Use Indexing for more than 1 dimension of array simultaneously
4 ビュー (過去 30 日間)
古いコメントを表示
I have a 10 by 3 matrix:
matrix = rand(10, 3);
I have an indexing array which selects a column number for each row:
idx = [1; 2; 2; 3; 1; 2; 1; 2; 3; 3];
I want to produce a 10x1 array which uses the above index array to extract the respective column number element at each row. Without using a for loop.
I have tried:
output = matrix(1:10, idx)
This produces a 10x10 matrix.
0 件のコメント
回答 (3 件)
Fangjun Jiang
2023 年 7 月 25 日
編集済み: Fangjun Jiang
2023 年 7 月 25 日
matrix(sub2ind(size(matrix),(1:10)',idx))
0 件のコメント
the cyclist
2023 年 7 月 25 日
matrix = rand(10, 3);
idx = [1; 2; 2; 3; 1; 2; 1; 2; 3; 3];
linearIndex = sub2ind(size(matrix),1:10,idx');
matrix(linearIndex)
0 件のコメント
James Tursa
2023 年 7 月 25 日
編集済み: James Tursa
2023 年 7 月 25 日
Yet another way using linear indexing (showing what sub2ind( ) does internally):
matrix = rand(10, 3);
idx = [1; 2; 2; 3; 1; 2; 1; 2; 3; 3];
m = size(matrix,1);
matrix( (1:m)' + m*(idx-1) )
And to show that it is the same as other solutions:
matrix(sub2ind(size(matrix),(1:m)',idx))
1 件のコメント
Walter Roberson
2023 年 7 月 25 日
Note that linear indexing is what happens internally when you use sub2ind: sub2ind is a helper function to make it easier to calculate the correct linear indexing.
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!