How to index the matrix only the first dimension of the rest
19 views (last 30 days)
Show older comments
For example, I have an matrix A=zeros(5,4,3)
And B=A(1,:,:)
Is there any way that I don't have to use the latter two ':'?
Something simple like B=A(1,?) that takes whatever from the second dimension onwards?
0 Comments
Answers (4)
Bruno Luong
on 31 Aug 2022
A = rand(2,3,4,5);
C=repmat({':'},1,ndims(A)-1);
% C=repmat({:},1,100); if you don't want to be depend on A
B = A(1,C{:});
0 Comments
Stephen23
on 1 Sep 2022
This will be quite efficient because none of the data in memory is moved around, only the array header is accessed.
It also works for non-scalar X.
B = A(X,:);
S = size(A);
S(1) = size(B,1);
B = reshape(B,S);
Walter Roberson
on 31 Aug 2022
B=A(1,:);
However this will treat it like
temp = reshape(A, size(A, 1), []);
B = temp(1,:);
which would give you a 1 x 12 not a 1 x 4 x 3
2 Comments
Bruno Luong
on 1 Sep 2022
@Xuze Liu Walter explains the RHS of
B=A(1,:)
is like reshaping A with all the traling dimension grouped. You don't have to.
Cris LaPierre
on 31 Aug 2022
It depends what you want the ouput dimensions to be. If you just want them in a vector, then you can just use a single colon.
A=rand(5,4,3)
A(1,:)
0 Comments
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!