List of indexes for each row of a matrix without a for loop
1 回表示 (過去 30 日間)
古いコメントを表示
Matrix DATA contains some data, and matrix INDSETS contains the indexes to be extracted from each row of DATA.
Example:
DATA = [8 9 3 1 2; 4 5 8 7 6; 1 5 9 7 3]
DATA =
8 9 3 1 2
4 5 8 7 6
1 5 9 7 3
INDSETS = [2 4 3; 1 3 5; 5 2 1; 5 4 2]
INDSETS =
2 4 3
1 3 5
5 2 1
5 4 2
For EACH row of DATA, I would like to extract its N subsets as given by each row of INDSETS (where N = number of rows in INDSETS). For instance, for the first row of DATA, its subsets are:
DATA(1, :)(INDSETS)
ans =
9 1 3
8 3 2
2 9 8
2 1 9
For the 2nd row of DATA, its subsets are:
DATA(2, :)(INDSETS)
ans =
5 7 8
4 8 6
6 5 4
6 7 5
and so on. A possible slow solution would be to preallocate a 3D array C to store the results, and run a for loop row by row, saving the results of each iteration on the 3rd dimension of C:
Slow solution:
C = zeros(size(INDSETS, 1), size(INDSETS, 2), size(DATA, 1));
for i = 1:size(DATA, 1)
C(:, :, i) = DATA(i, :)(INDSETS);
end
Is there a more efficient way to do this without a for loop, perhaps a vectorized solution?
0 件のコメント
採用された回答
Stephen23
2016 年 2 月 24 日
編集済み: Stephen23
2016 年 2 月 24 日
>> S = size(INDSETS);
>> reshape(DATA(:,INDSETS).',S(1),S(2),[])
or on one line:
>> reshape(DATA(:,INDSETS).',[size(INDSETS),size(DATA,1)])
both produce this output:
ans(:,:,1) =
9 1 3
8 3 2
2 9 8
2 1 9
ans(:,:,2) =
5 7 8
4 8 6
6 5 4
6 7 5
ans(:,:,3) =
5 7 9
1 9 3
3 5 1
3 7 5
その他の回答 (0 件)
参考
カテゴリ
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!