Search code examples
arraysmatlabloopsmatrixmatrix-indexing

find value in array according to the row and column number


I have two matrix A and B,the first row of matrix A(1,:)=[1 2] refer to the number of row and column matrix B(1,2)=21,now I want to do this work for another rows of matrix A without loops?

A=[1 2;2 3;1 3;3 3];
B=[1 21 34;45 65 87;4 55 66];
for i=1:4
d(i,:)=B(A(i,1),A(i,2))
end
d =[21; 87;34;66] 

Solution

  • An alternative to sub2ind is

    d = B(A(:,1)+ (A(:,2)-1)*size(B,1));