6

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?

4
  • 3
    general comment: size isn't the right function for what you are doing now, rather use length or numel. Commented Sep 28, 2012 at 17:45
  • 2
    The idea that for-loops are inefficient/slow and should be replaced if possible is unsubstantiated. Even though you could replace this code with something that is faster, you would probably save only a fraction of a second. This is not the level of code optimization you should be worried about. Commented Sep 28, 2012 at 17:58
  • @Kavka Concerning this type of for loop, I would agree. A more complex for loop that manipulates large matrices would be worth vectorizing, right? Matlab was designed to work with Matrices -- all of its matrix operations are supposed to be optimized. Commented Sep 28, 2012 at 18:32
  • See also mathworks.com/matlabcentral/newsreader/view_thread/10055 Commented Sep 28, 2012 at 18:47

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

In my case b may be [2 4 2], so that I need to increment a(2) twice. This method updates a(2) only once.
1

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

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

a(b) = a(b) + 1;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.