accumulate a matrix of counters

I'm keeping a matrix of counters m. The indices of the individual counters to add to are kept in a (large) vector indx. What I am trying to accomplish is the behavior of:
for ii = i:length(indx)
m(indx(ii)) = m(indx(ii)) + 1;
end;
but in a vectorized way. I tried:
m(indx) = m(indx) + 1
but that ignores multiple occurrences of the same index in 'indx' As an example, note the difference in outcome between:
m = zeros(5)
indx = [1 20 3 9 19 1 9 24 1 9];
m(indx) = m(indx) + 1
and
m = zeros(5);
indx = [1 20 3 9 19 1 9 24 1 9];
for ii = 1:length(indx)
m(indx(ii)) = m(indx(ii)) + 1;
end;
disp(m);
Any ideas?

 Accepted Answer

Matt J
Matt J on 28 Nov 2012
Edited: Matt J on 28 Nov 2012
m=reshape(accumarray(indx(:),1,[25,1]),[5,5])

More Answers (0)

Categories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!