size(matrixA)=[b,n,m]
size(matrixB)=[n,m]
how can I create
matrixC(i,j)=matrixA(matrixB(i,j),i,j)
without using for-loops? What is this kind of indexing called? Thanks!

 채택된 답변

Stephen23
Stephen23 2018년 10월 3일
편집: Stephen23 2018년 10월 3일
Use sub2ind to get the linear indices:
A = reshape(1:6*3*2,6,3,2);
B = [6,1;4,3,;5,2];
% Solution with loops:
for ii = 1:size(B,1)
for jj = 1:size(B,2)
C(ii,jj) = A(B(ii,jj),ii,jj);
end
end
% Solution with SUB2IND:
S = size(B);
[I,J] = ndgrid(1:S(1),1:S(2));
X = sub2ind(size(A),B,I,J);
D = A(X)
% Compare:
isequal(C,D)

댓글 수: 1

Stephen you're awesome thanks! I knew there was something like that... it's been a while!

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

추가 답변 (1개)

Bruno Luong
Bruno Luong 2018년 10월 3일
편집: Bruno Luong 2018년 10월 3일
C = A(B+reshape(0:numel(B)-1,size(B))*size(A,1))

댓글 수: 1

Awesome I'll check this one, cannot even wrap my head around it!!

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

태그

질문:

2018년 10월 2일

댓글:

2018년 10월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by