필터 지우기
필터 지우기

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by