Extract sub n-dimensional array from n-dimensional array

11 ビュー (過去 30 日間)
Koby Hayashi
Koby Hayashi 2020 年 9 月 10 日
コメント済み: Koby Hayashi 2020 年 9 月 10 日
Hello,
I have an n-dimensial array A (such that n = numel(size(A)) ).
I want to randomly select a subblock of the array.
To this end I have generated n random vectors of indices along each dimension.
For example for a 3 dimensional array I could have something like:
rows = [1,2,3]; % but randomly generated
cols = [1,3];
pages = [2];
% A 3x3x3 array, note that A may not always be square
A = [1 2 3; 4 5 6; 7 8 9];
A(:,:,2) = [10 11 12; 13 14 15; 16 17 18];
A(:,:,3) = [19 20 21; 22 23 24; 25 26 27];
subA = A(rows,cols,pages);
My issue is that I want to generalize this to arbiratry n dimensions. It is easy to statically code this for any n as you can just list them in the A(index1, index2, ..., indexn) but how would one write a code robust to the choice of n?
Thanks!

採用された回答

Bruno Luong
Bruno Luong 2020 年 9 月 10 日
% Testt matrix
A=randi(10,[2,3,4])
n = ndims(A);
s = size(A);
i = repelem({':'}, 1, n) ;
i{end} = 3 % whatever page
s(end) = 1
A(i{:}) = rand(s)

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSparse Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by