Extract sub n-dimensional array from n-dimensional array

7 Ansichten (letzte 30 Tage)
Koby Hayashi
Koby Hayashi am 10 Sep. 2020
Kommentiert: Koby Hayashi am 10 Sep. 2020
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!

Akzeptierte Antwort

Bruno Luong
Bruno Luong am 10 Sep. 2020
% 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)

Weitere Antworten (0)

Kategorien

Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by