Extract sub n-dimensional array from n-dimensional array

7 visualizaciones (últimos 30 días)
Koby Hayashi
Koby Hayashi el 10 de Sept. de 2020
Comentada: Koby Hayashi el 10 de Sept. de 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!

Respuesta aceptada

Bruno Luong
Bruno Luong el 10 de Sept. de 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)

Más respuestas (0)

Categorías

Más información sobre Resizing and Reshaping Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by