0

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] 
Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
abbas
  • 57
  • 6
  • None of the above solutions work when size(A,1) is too large. The reason behind is that all of the solutions above imply creating a matrix of dimensions size(A,1) x size(A,1). See https://stackoverflow.com/questions/60477249/get-matrix-values-at-millions-of-index-pairs-efficiently-matlab – Karpov Mar 01 '20 at 16:38

3 Answers3

4

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
Sardar Usama
  • 19,536
  • 9
  • 36
  • 58
3

An alternative to sub2ind is

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

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)))
Salman
  • 924
  • 1
  • 7
  • 20