
Administrator

i'm sure there's a compact, efficient way to do this, but it's eluding me and my googlefu is failing:
give a ndimensional matrix A (n unknown apriori), and a user specified dimension to operate on, return the first 'part' of the array for that dimension, preserving shape:
e.g, for a 3D array, dim 2:
B = A(:,1,:)
for dim 3:
B = A(:,1,:)
for a 4D array, dim 2:
B = A(:,1,:,:)
for dim 4:
etc.
what's an efficient way to extract that subarray for any number of dimensions? i assume I could do something clever directly with subsasgn and expanding a cell array of some number of ':' with {:}, but i'm sure I'm missing something cleaner, no?
(does not need to be matlab compatible)

Administrator

Always, 5 minutes after I put the question together I find a good solution I missed the first dozen times.
>> A = magic(3); >> dim = 2; >> v = repmat({':'},ndims(A),1);
>> v{dim} = 1; >> firsts = A(v{:})
firsts =
ans(:,:,1) =
8 3 4
ans(:,:,2) =
8 3 4
ans(:,:,3) =
8 3 4
>> dim = 3; v = repmat({':'},ndims(A),1); v{dim} = 1 v = { [1,1] = : [2,1] = : [3,1] = 1 }
>> firsts = A(v{:}) firsts =
8 1 6 3 5 7 4 9 2
i'm sure there's some code golf to be played here, but that seems to do the trick. Thanks for the sounding board!
On Mon, Dec 7, 2020 at 1:06 PM Nicholas Jankowski < [hidden email]> wrote: i'm sure there's a compact, efficient way to do this, but it's eluding me and my googlefu is failing:
give a ndimensional matrix A (n unknown apriori), and a user specified dimension to operate on, return the first 'part' of the array for that dimension, preserving shape:
e.g, for a 3D array, dim 2:
B = A(:,1,:)
for dim 3:
B = A(:,1,:)
for a 4D array, dim 2:
B = A(:,1,:,:)
for dim 4:
etc.
what's an efficient way to extract that subarray for any number of dimensions? i assume I could do something clever directly with subsasgn and expanding a cell array of some number of ':' with {:}, but i'm sure I'm missing something cleaner, no?
(does not need to be matlab compatible)

