How to index the matrix only the first dimension of the rest

18 views (last 30 days)
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?

Answers (4)

Bruno Luong
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{:});

Stephen23
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);
  1 Comment
Stephen23
Stephen23 on 1 Sep 2022
Edited: Stephen23 on 1 Sep 2022
format compact
A = rand(5,4,3)
A =
A(:,:,1) = 0.9656 0.6497 0.2581 0.7417 0.5392 0.6739 0.5440 0.5115 0.7184 0.7770 0.1037 0.1437 0.0460 0.8504 0.7329 0.6772 0.5472 0.3287 0.3364 0.2696 A(:,:,2) = 0.0271 0.2944 0.1932 0.9287 0.1086 0.7801 0.5014 0.3357 0.5984 0.8400 0.6211 0.6933 0.0673 0.5048 0.7611 0.2261 0.9548 0.6398 0.8557 0.5052 A(:,:,3) = 0.8824 0.8974 0.9947 0.4210 0.0417 0.5307 0.0642 0.1385 0.7882 0.7552 0.9825 0.7442 0.5414 0.1979 0.8633 0.4881 0.7751 0.2920 0.6514 0.4335
X = 3;
B = A(X,:);
S = size(A);
S(1) = size(B,1);
B = reshape(B,S)
B =
B(:,:,1) = 0.7184 0.7770 0.1037 0.1437 B(:,:,2) = 0.5984 0.8400 0.6211 0.6933 B(:,:,3) = 0.7882 0.7552 0.9825 0.7442

Sign in to comment.


Walter Roberson
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
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.

Sign in to comment.


Cris LaPierre
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 =
A(:,:,1) = 0.8151 0.1142 0.4037 0.5967 0.0920 0.2222 0.8144 0.6967 0.1565 0.9195 0.4080 0.7906 0.1481 0.9235 0.4610 0.4404 0.6894 0.7504 0.8451 0.0283 A(:,:,2) = 0.6298 0.0226 0.3653 0.7651 0.3858 0.3005 0.2023 0.8461 0.2826 0.2151 0.7336 0.5432 0.4013 0.0399 0.1543 0.5064 0.6406 0.9716 0.4377 0.8008 A(:,:,3) = 0.4181 0.4029 0.7620 0.6040 0.7262 0.1018 0.3144 0.6743 0.1473 0.6745 0.5357 0.1704 0.5709 0.9167 0.0451 0.7542 0.9045 0.3479 0.7617 0.6889
A(1,:)
ans = 1×12
0.8151 0.1142 0.4037 0.5967 0.6298 0.0226 0.3653 0.7651 0.4181 0.4029 0.7620 0.6040

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!