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?
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.
If both a
and b
are vector, this should work.
a = 1:100;
b = 100:-1:1;
a(b) = a(b) + 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With