Extract sub n-dimensional array from n-dimensional array

조회 수: 7 (최근 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 CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by