Selecting array column elements using a vector..?

3 ビュー (過去 30 日間)
Bradley Stiritz
Bradley Stiritz 2011 年 9 月 7 日
Hi everyone,
I need to select elements from a 2D array. I have an index vector whose (i)'th value is the desired row to select from the array. Is there a good, simple method to do this..?
In the following code, I want to extract the following (row,column) array elements: (3,1), (2,2), (4,3), (1,4) : giving the vector: [9 11 15 13]
>> A = magic(4)
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
>> viRow = [3 2 4 1]
viRow =
3 2 4 1
Referring to the doc page on Matrix Indexing, I thought my solution would have been: A(viRow,:) However, this code applies the index vector to each column, which isn't what I want.
>> A(viRow,:)
ans =
9 7 6 12
5 11 10 8
4 14 15 1
16 2 3 13
Could someone please point me in the right direction?
Thanks, Brad

採用された回答

Fangjun Jiang
Fangjun Jiang 2011 年 9 月 7 日
Vi=[3 2 4 1];
A=magic(4);
Index=sub2ind(size(A),Vi,1:4);
B=A(Index)
  1 件のコメント
Bradley Stiritz
Bradley Stiritz 2011 年 9 月 7 日
this looks like the perfect, straightforward solution :) very appreciated, thank you very much. brad

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by