n dimensional array section

Ok, lets say that I have a code where I can have an array:
A = randi([0,9],4,4);
and I want to access the last two columns and rows:
B = A(2:end,2:end);
Now I have the same thing but with 3 dimensions:
A = randi([0,9],4,4,4);
B = A(2:end,2:end,2:end);
Is there any way that I can write both cases in a single generic one?, I was trying to do something like:
n = 2; % or 3 or whatever
dims = 4*ones(1,n);
A = randi([0,9],dims);
B = A( 2*ones(1,n):end); % THIS WONT WORK.
I don't know if I explained what I wan't. Please let me know if you need more precise explanation. Thank you

回答 (2 件)

KSSV
KSSV 2018 年 10 月 22 日

0 投票

Read about sub2ind
n = 2; % or 3 or whatever
dims = 4*ones(1,n);
A = randi([0,9],dims);
[I,J] = meshgrid(2:4,2:4) ;
idx = sub2ind(size(A),I,J)' ;
B = A(idx);

1 件のコメント

Manuel Pena
Manuel Pena 2018 年 10 月 22 日
Would sub2ind work with 3 dimensions? Besides that, your code doesn't solve my problem as you are explicitly using the fact that you know that n = 2, when you do the meshgrid call.

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

Steven Lord
Steven Lord 2022 年 2 月 4 日

0 投票

Use a comma-separated list.
n = 2; % or 3 or whatever
dims = 4*ones(1,n);
A = randi([0,9],dims) % Leaving the semicolon off for checking purposes
A = 4×4
9 3 8 7 3 1 6 7 6 1 6 2 0 8 8 4
inds = cell(1, n);
for dim = 1:n
inds{dim} = (size(A, dim))+(-1:0); % [end-1, end] in that dimension
end
B = A(inds{:})
B = 2×2
6 2 8 4

カテゴリ

ヘルプ センター および File ExchangeProgramming についてさらに検索

タグ

質問済み:

2018 年 10 月 22 日

回答済み:

2022 年 2 月 4 日

Community Treasure Hunt

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

Start Hunting!

Translated by