help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: selecting 'first' element/vector/matrix of an arbitrary n-dim array


From: Nicholas Jankowski
Subject: Re: selecting 'first' element/vector/matrix of an arbitrary n-dim array
Date: Mon, 7 Dec 2020 13:15:14 -0500

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 <jankowskin@asme.org> 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)

reply via email to

[Prev in Thread] Current Thread [Next in Thread]