Double indexing of matrix / help with vectorizing

16 views (last 30 days)
Hi all,
Suppose I have 3 vectors x,y,z of the same length, and a matrix A. The vectors x and y refer to the row and column element of that matrix. z can be anything e.g.
x=[2 1 3 4 2 2]; y=[4 2 3 4 2 2]; z=[100 -5 0 0 2 3];
A=rand(4,4);
now I would like to write something like
A(x,y)=A(x,y)+z;
so that A(2,4)=A(2,4)+100, A(1,2)=A(1,2)-5 etc.. but this is not allowed. In reality, A is 1000x1000 matrix and x and y can have lengths >1e+6, so I would like to avoid using a for loop.
Does anyone know how to vectorize this?
Thanks a lot in advance

Accepted Answer

Jan
Jan on 28 Mar 2012
See sub2ind.
x = [2 1 3 4 2 2]; y=[4 2 3 4 2 2]; z=[100 -5 0 0 2 3];
A = rand(4,4);
index = sub2ind(size(A), x, y);
A(index) = A(index) + z;
I cannot test this currently.
  1 Comment
Christine A.
Christine A. on 28 Mar 2012
Thanks a lot, exactly what I was looking for!
The duplicate index at the end doesn't work though, but I can fix that by removing duplicates first. Thanks again.

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!