How do I index into a matrix with a vector to extract the jth column for each row?

2 次查看(过去 30 天)
Is there an easy way to index into a matrix with a vector to extract the jth column of the matrix for each row? As an example, lets take the 4 x 4 matrix created by
A = magic(4);
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
I have a vector which describes which columns I'd like to extract:
ii = [1; 2; 1; 2]
ii =
1
2
1
2
Is there a straightforward way of indexing into the matrix to return the vector:
result =
16
11
9
14

采纳的回答

Star Strider
Star Strider 2016-5-3
There is. Use the sub2ind function:
A = magic(4);
ii = [1; 2; 1; 2];
ix = sub2ind(size(A), [1:4]', ii);
result = A(ix)
result =
16
11
9
14

更多回答(1 个)

dpb
dpb 2016-5-3
>> A(sub2ind(size(A),[1:size(A,1)],ii))
ans =
16 11 9 14
>>

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by