필터 지우기
필터 지우기

How do I index an array with varying dimension?

조회 수: 5 (최근 30일)
runtime_error
runtime_error 2024년 2월 9일
댓글: Stephen23 2024년 2월 9일
I have a function Y = func(X)
X can be any dimension >=2. Inside the function, I need to index X by the first dimension. X(index, :) or X(index, :, :) depending on the dimension. I know I can check the dimension like this:
if ndims(X) == 2
X(index, :) = ....
elseif ndims(x) == 3
X(index, :, :) = ..
end
Is there a more efficient way?

채택된 답변

Walter Roberson
Walter Roberson 2024년 2월 9일
If you use a trailing dimension of : to index, then the result has the proper size but with the dimension "unwrapped"
A = ones(3,4,5);
B = A(2,:);
size(B)
ans = 1×2
1 20
You can leave it like that for computations, or you can reshape() it
sz = size(A);
sz(1) = 1;
C = reshape(B,sz);
size(C)
ans = 1×3
1 4 5
Alternately....
indx = repmat({':'}, 1, ndims(A));
indx{1} = 2;
D = A(indx{:});
size(D)
ans = 1×3
1 4 5

추가 답변 (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