Using a vector as an index to a matrix

조회 수: 1 (최근 30일)
ceinem
ceinem 2018년 12월 1일
댓글: ceinem 2018년 12월 1일
Hi,
I have a rather large Matrix A with the dimensions 100x100x3 as well as a vector b of dimensions 100x1 with values from 1 to 3.
Now I want to get a out of Matrix A a Matrix C with the dimensions 100x100x1 where b defines which elements along the third dimension of A should be used.
I was thinking of something along the lines of
C = A(:,:,b(:))
but this does not work the way I want.
This code does exactly what I want, but I would prefer to do it without a For-Loop:
for i = 1:100
C(i,:) = A(i,:,b(i));
end
Is it even possible to do without a for-Loop? I had a look at the sub2ind function, but could not get it to work in the way I wanted.
Thank you very much for any help.
  댓글 수: 1
madhan ravi
madhan ravi 2018년 12월 1일
can you post a short numerical example so that we know what your goal is?

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

채택된 답변

Bruno Luong
Bruno Luong 2018년 12월 1일
편집: Bruno Luong 2018년 12월 1일
[m,n,p] = size(A);
[I,J] = ndgrid(1:m,1:n);
C = A(sub2ind([m,n,p],I,J,b(I)))
  댓글 수: 1
ceinem
ceinem 2018년 12월 1일
Awesome! This worked! Thanks a lot!

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

추가 답변 (0개)

카테고리

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