MATLAB: Double indexing of matrix / help with vectorizing

matrix vectorizing double index

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 1000×1000 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

Best Answer

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.