Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

optimising matlab for loop

Tags:

matlab

I have this following loop for a code (that computes the histograms). I am writing in Matlab. As I am new to Matlab I don't know of any faster methods to do this. I am currently writing

for i=1:size(b)
    a(b(i)) = a(b(i)) + 1;
end

Are there any faster methods to do this, preferably those which do not require the for loop?

like image 712
anirudh Avatar asked Sep 28 '12 17:09

anirudh


2 Answers

You can simply vectorize it by a(b) = a(b) + 1. Check the following:

>> a = [1 2 3 4];
>> b = [2 4]; %# indices to modify. Be sure that they are in bounds.
>> a(b) = a(b) + 1

a =

     1     3     3     5

If you use some indices multiple times, then accumarray will help as follows:

>> a = [1 2 3 4];
>> b = [2 4 2];
>> a = accumarray([1:numel(a) b].',[a ones(size(b))])'

a =

     1     4     3     5

Alternatively, you can use:

>> a = [1 2 3 4];
>> b = [2 4 2];
>> b = accumarray(b.',ones(size(b)));
>> a(nzIndex) = a(nzIndex) + b(nzIndex)'

a =

     1     4     3     5

See this nice answer here for further details.

like image 111
petrichor Avatar answered Oct 24 '22 21:10

petrichor


If both a and b are vector, this should work.

a = 1:100;
b = 100:-1:1;

a(b) = a(b) + 1;
like image 37
Kavka Avatar answered Oct 24 '22 21:10

Kavka