Swagatika
Swagatika

Reputation: 885

how to get values of a matrix in MATLAB where the indices are given in a nx2 array

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] 

Upvotes: 3

Views: 2987

Answers (2)

Ali
Ali

Reputation: 19722

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

Upvotes: 2

mola
mola

Reputation: 1150

I guess this is what you are looking for:

A(sub2ind(size(A),B(:,1),B(:,2)))

Upvotes: 6

Related Questions