How can I extract a slice from a multidimensional array?

27 ビュー (過去 30 日間)
Uri Goldsztejn
Uri Goldsztejn 2021 年 2 月 26 日
コメント済み: Uri Goldsztejn 2021 年 3 月 1 日
I have an array of variable dimensions and want to extract a slice of it.
If I the size of the array was fixed I would like to do:
result = G(:,:,:,r,:,:);
But in my case, r is a variable and so are the dimensions of G and the dimension from which I want to extract the slice (in this case the 4th dimension).
-----------------------------------
I am able to costruct a cell array containing the indices that need to be extracted, but can't extract them.
N = ndims(G);
other_dimensions = [1:(n-1),(n+1):N];
sz = size(G);
inds = repmat({r},1,ndims(G));
for k = 1:length(other_dimensions)
inds{other_dimensions(k)} = 1:sz(other_dimensions(k));
end
result = A(inds) % (not working)

採用された回答

Stephen23
Stephen23 2021 年 2 月 27 日
編集済み: Stephen23 2021 年 2 月 27 日
The trick here is to define a cell array and then use a comma-separated list for the indices. For example:
G = rand(7,6,5,4,3,2); % any size
d = 4; % which dimension
r = 3; % index in that dim.
% define cell array:
C = repmat({':'},1,ndims(G));
C{d} = r;
% comma-separated list to supply indices:
S = G(C{:}); % get slice!
% check:
size(G) % original array
ans = 1×6
7 6 5 4 3 2
size(S) % slice
ans = 1×6
7 6 5 1 3 2
isequal(S,G(:,:,:,r,:,:))
ans = logical
1
  1 件のコメント
Uri Goldsztejn
Uri Goldsztejn 2021 年 3 月 1 日
Thank you for your answer! I realized I could change 1:sz(other_dimensions(k)) for ':' in my code and solve the problem as well. I.e.,
N = ndims(G);
other_dimensions = [1:(n-1),(n+1):N];
sz = size(G);
inds = repmat({r},1,ndims(G));
for k = 1:length(other_dimensions)
inds{other_dimensions(k)} = ':';
end
result = A(inds) % (now it works)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by