필터 지우기
필터 지우기

Simpler way without for loops

조회 수: 1 (최근 30일)
Meghana Dinesh
Meghana Dinesh 2014년 12월 2일
답변: Andrei Bobrov 2014년 12월 2일
How can I implement this without using for loops?
for i = 1:i_rows
Mat_NX3(i,1) = (Mat_A_3D (idx(i,1), idx(i,2), 1) );
Mat_NX3(i,2) = (Mat_A_3D (idx(i,1), idx(i,2), 2) );
Mat_NX3(i,3) = (Mat_A_3D (idx(i,1), idx(i,2), 3) );
end
where:
  • Mat_NX3 is the output N X 3 matrix
  • Mat_A_3D is a 3D matrix
  • idx is a matrix with 2 columns, (index points) telling which co-ordinate values should be copied from Mat_A_3D into Mat_NX3. It has i_rows number of rows
Example if
Mat_A_3D (:,:,1) = [1 2 3
4 5 6
7 8 9];
Mat_A_3D (:,:,2) = [1 2 3
4 5 6
7 8 9];
Mat_A_3D (:,:,3) = [1 2 3
4 5 6
7 8 9];
and
idx = [1,1
3,3];
output
Mat_NX3 = [1 1 1;
9 9 9];

채택된 답변

Sean de Wolski
Sean de Wolski 2014년 12월 2일
편집: Andrei Bobrov 2014년 12월 2일
I would just keep the for-loops.
Alternatively, you could use sub2ind to build a linear index from the pieces and then index with it:
% Size
sz = size(Mat_A_3D);
% First page only
idx = sub2ind(sz,idx(:,1),idx(:,2));
% Add second and third pages:
idx3 = bsxfun(@plus,idx,(0:sz(3)-1)*sz(1)*sz(2));
MatNX3 = Mat_A_3D(idx3)
  댓글 수: 3
Meghana Dinesh
Meghana Dinesh 2014년 12월 2일
When I give
idx = [1,2; % elements in 1st row, 2nd column of Mat_A_3D
3,1; % elements in 3rd row, 1st column of Mat_A_3D
3,3] % elements in 3rd row, 3rd column of Mat_A_3D
I expect the output:
[2, 2, 2;
7, 7, 7;
9, 9, 9]
This is not what I am getting with
% Size
sz = size(Mat_A_3D);
% First page only
idx = sub2ind(sz,idx(:,1),idx(:,1));
% Add second and third pages:
idx3 = bsxfun(@plus,idx,(0:sz(3)-1)*sz(1)*sz(2));
MatNX3 = Mat_A_3D(idx3)
Andrei Bobrov
Andrei Bobrov 2014년 12월 2일
corrected

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Thorsten
Thorsten 2014년 12월 2일
sz = size(Mat_A_3D);
ind = sub2ind(sz(1:2), idx(:,1), idx(:, 2));
offset = repmat(cumsum(repmat(prod(sz(1:2)), [1 sz(3)-1])), [size(ind) 1]);
ind = [ind repmat(ind, [1 size(offset, 2) 1]) + offset];
Mat_NX3 = Mat_A_3D(ind)

Andrei Bobrov
Andrei Bobrov 2014년 12월 2일
n = size(M);
x = zeros(n);
x(sub2ind(n,idx(:,1),idx(:,2))) = 1;
out = reshape(M(cumsum(x,3) > 0),size(idx,1),[]);

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by