Reputation: 6670
Supposing I have this matrix:
>> m = magic(4)
m =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
and I want do access these positions x1 = [1;3]
and x2 = [4;3]
, I mean, I want a result like this: [13; 6]
, the [x1(1); x2(1)]
and [x1(2); x2(2)]
positions. x1
and x2
can have any size. I tried doing m(x1, x2)
, but did not work... Is there a way to achieve this with one command?
Upvotes: 0
Views: 46
Reputation: 1390
You can get multiple values with linear indices, say in your case m([13, 6]);
To get linear indices, use sub2ind(size(m), x1, x2);
which will generate [13,6] in your case.
Now just glue them together to get the one-liner:
out = m(sub2ind(size(m), x1, x2));
Upvotes: 1