Extract sub n-dimensional array from n-dimensional array
7 views (last 30 days)
Show older comments
Koby Hayashi
on 10 Sep 2020
Commented: Koby Hayashi
on 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!
0 Comments
Accepted Answer
Bruno Luong
on 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)
More Answers (0)
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!