Re: selecting 'first' element/vector/matrix of an arbitrary n-dim array
Nicholas Jankowski <[email protected]>
| Newsgroups | gmane.comp.gnu.octave.general |
|---|---|
| Message-ID | <CABNpfR_=8FXC_j=hYfTxm6wmPTn0XK_S9Z2QRHdC76vS9qwHLw@mail.gmail.com> |
Always, 5 minutes after I put the question together I find a good solution
I missed the first dozen times.
see:
https://www.mathworks.com/matlabcentral/answers/344423-index-slice-of-nd-array-of-unknown-dimension#comment_814098
>> 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 <[email protected]>
wrote:
> i'm sure there's a compact, efficient way to do this, but it's eluding me
> and my google-fu is failing:
>
> give a n-dimensional 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:
>
> B = A(:,:,:,1)
>
> 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)
>