Leo
Leo

Reputation: 583

How to catch elements from a m*n matrix by an n array in MATLAB

For example, I have A matrix and an array B:

A = [1 2 3 4
     4 5 6 7
     7 8 9 10];

B = [2 1 3 2]

B represents a list of indices of A, which means I want to get the result like this:

[4 2 9 7]

(the 2nd element of [1 4 7] is 4; the 1st element of [2 5 8] is 2...)

Upvotes: 0

Views: 40

Answers (1)

Suever
Suever

Reputation: 65430

You could use sub2ind to get this. We use B as the row indices and 1:size(A,2) as the column indices. sub2ind then converts these to linear indices which we can use to index into A.

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

You could also compute the linear indices directly without using sub2ind for a performance improvement.

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

Upvotes: 2

Related Questions