n dimensional array section
Afficher commentaires plus anciens
Ok, lets say that I have a code where I can have an array:
A = randi([0,9],4,4);
and I want to access the last two columns and rows:
B = A(2:end,2:end);
Now I have the same thing but with 3 dimensions:
A = randi([0,9],4,4,4);
B = A(2:end,2:end,2:end);
Is there any way that I can write both cases in a single generic one?, I was trying to do something like:
n = 2; % or 3 or whatever
dims = 4*ones(1,n);
A = randi([0,9],dims);
B = A( 2*ones(1,n):end); % THIS WONT WORK.
I don't know if I explained what I wan't. Please let me know if you need more precise explanation. Thank you
Réponses (2)
KSSV
le 22 Oct 2018
Read about sub2ind
n = 2; % or 3 or whatever
dims = 4*ones(1,n);
A = randi([0,9],dims);
[I,J] = meshgrid(2:4,2:4) ;
idx = sub2ind(size(A),I,J)' ;
B = A(idx);
1 commentaire
Manuel Pena
le 22 Oct 2018
Use a comma-separated list.
n = 2; % or 3 or whatever
dims = 4*ones(1,n);
A = randi([0,9],dims) % Leaving the semicolon off for checking purposes
inds = cell(1, n);
for dim = 1:n
inds{dim} = (size(A, dim))+(-1:0); % [end-1, end] in that dimension
end
B = A(inds{:})
Catégories
En savoir plus sur Programming dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!