3

I have a matrix A of size nRows x nCols.

I have a nx2 matrix B which contains indices of the matrix A. I want to get the values of A at the indices given in B.

lets say,

B = [1, 2;
     2, 3;
     3, 4]

A(1,2) = 1
A(2,3) = 2
A(3,4) = 1

I want to know any Matlab command which gives the following, given A and B (I don't want to use loops):

[1 2 1] 
2
  • 1
    Ok I got it. I need to use sub2ind. A(sub2ind(size(A), B(:,1), B(:,2))) Commented Oct 27, 2012 at 10:00
  • general solution (for any-dimensional matrices) is here Commented Oct 27, 2012 at 11:56

2 Answers 2

6

I guess this is what you are looking for:

A(sub2ind(size(A),B(:,1),B(:,2)))
Sign up to request clarification or add additional context in comments.

1 Comment

...yes, thanks. I was not able to put an answer so I put it as comment.
2

This is what you want:

A = [1,2; 3, 4; 5, 6; 7,8; 9,0]; % this is your N by 2 matrix
B = [1,1; 1,2; 2,1; 3, 1; 4,2]; % these are your indexes
A(sub2ind(size(A), B(:,1), B(:,2)))

A =

 1     2
 3     4
 5     6
 7     8
 9     0



B =

 1     1
 1     2
 2     1
 3     1
 4     2

ans =

 1
 2
 3
 5
 8

1 Comment

what do you mean? I edit the answer to show you how general it is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.