assiging values to matrix accrding to indexes using sub2ind

I have 3 data sets, two with coordinates and one with data with the length of n
with a loop I would assign the data in this way
MAT=zeros(m,n);
for i=1:n
MAT(Z(i),X(i))=MAT(Z(i),X(i))+DATA(i);
end
I want to do it without a loop since
what I am trying to do is something like
MAT=zeros(m,n);
mn=size(MAT);
MAT(sub2ind(mn,Z,X))=MAT(sub2ind(mn,Z,X))+DATA;
any one has an idea how to make it properly and efficiently?
cheers

 Accepted Answer

Try accumarray
MAT = accumarray([Z X],DATA)

4 Comments

I would suggest
MAT = accumarray([Z X],DATA, [m n]);
as this version will create the correct output size even if the outermost indices do not happen to be used.
Thanks Walter, you are absolutely right. That's a good catch.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!