MATLAB: Matrix linear indexing: how to add more than once to the same index

linear indexingMATLAB

Here is my question. Let's imagine we have this matrix:
A = [1 2 ; 3 4];
So if I use linear indexing to add 1 to, for instance, positions 1 and 3:
A([1 3]) = A([1 3]) + 1
A =
2 3
3 4
Now, let's imagine that, having the initial A matrix, I have an index vector in which some indices are repeated. For example, I need to add twice 1 to the first position, and once to the index 3:
A([1 3 1])=A([1 3 1])+1
A =
2 3
3 4
And surprisingly I get A(1,1)=2, instead of A(1,1)=3. How can I make it work?
The first idea was to put it inside a loop, but the matrix is normally big and this operation runs many times, and it becomes very slow. Any ideas?
Thank you very much in advance!

Best Answer

Another option, possibly faster than a loop or unique + histc:
A = [10 20;30 40];
idx = [1 3 1];
A(:) = A(:) + accumarray(idx(:), 1, [numel(A), 1]);