Double indexing of matrix / help with vectorizing
16 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Jan
on 28 Mar 2012
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.
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!