フィルターのクリア

List of indexes for each row of a matrix without a for loop

2 ビュー (過去 30 日間)
George Aipal
George Aipal 2016 年 2 月 24 日
コメント済み: George Aipal 2016 年 2 月 24 日
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?

採用された回答

Stephen23
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
  1 件のコメント
George Aipal
George Aipal 2016 年 2 月 24 日
Thanks Stephen, that works! I have a lot to work from you

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by