MATLAB: Matrix evaluation at a collection of indices

matrix evaluation

Hello,
I would like to do multiple matrix evaluations without the use of a loop. In particular, suppose Z is a p-by-q matrix, and X and Y are m-by-n integer-valued matrices.
I would like to construct an m-by-n matrix U defined as
U(i,j) = Z(X(i,j),Y(i,j))
Is there a simple way to do this without using the loop? Thanks a lot!

Best Answer

idx = sub2ind([m n],i1,j1);
U = zeros([m n]);
U(idx) = Z(X(idx),Y(idx));