n dimensional array section

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

Answers (2)

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 Comment

Would sub2ind work with 3 dimensions? Besides that, your code doesn't solve my problem as you are explicitly using the fact that you know that n = 2, when you do the meshgrid call.

Sign in to comment.

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
A = 4×4
9 3 8 7 3 1 6 7 6 1 6 2 0 8 8 4
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{:})
B = 2×2
6 2 8 4

Categories

Find more on Programming in Help Center and File Exchange

Tags

Asked:

on 22 Oct 2018

Answered:

on 4 Feb 2022

Community Treasure Hunt

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

Start Hunting!