Rik
Rik

Reputation: 1977

index matrix with array

I'd like to index matrix

x=[1:5;6:10]

x =

1    2    3    4    5
6    7    8    9   10

using array

 [1,2,1,2,1]

to get

1 7 3 9 5

I tried this:

x([1,2,1,2,1],:)

ans =

    1    2    3    4    5
    6    7    8    9   10
    1    2    3    4    5
    6    7    8    9   10
    1    2    3    4    5

but that is not what I want. Please help

Upvotes: 1

Views: 58

Answers (2)

TroyHaskin
TroyHaskin

Reputation: 8401

I'd use linear indexing with sub2ind:

>> v = x(sub2ind(size(x),a,1:5))
v =
     1     7     3     9     5

Upvotes: 5

zeeMonkeez
zeeMonkeez

Reputation: 5157

Let

ind = [1, 2, 1, 2, 1];
offset = [1:size(x, 1):numel(x)] - 1;

then

x(ind + offset)

returns what you want. This assumes that your index vector has an entry for every column of x and uses linear indexing to add a column offset to every in-column index.

Upvotes: 2

Related Questions