find value in array according to the row and column number

风流意气都作罢 提交于 2020-03-06 04:54:28

问题


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] 

回答1:


An alternative to sub2ind is

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



回答2:


Use sub2ind to get linear indices of the required values of B and then use these indices to retrieve those values.

d = B(sub2ind(size(B), A(:,1), A(:,2)));

>> d

d =

    21
    87
    34
    66



回答3:


I guess the following code must be work for you:

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


来源:https://stackoverflow.com/questions/45908205/find-value-in-array-according-to-the-row-and-column-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!