How to index the matrix only the first dimension of the rest
23 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(4 个)
Bruno Luong
2022-8-31
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 个评论
Stephen23
2022-9-1
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
2022-8-31
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 个评论
Bruno Luong
2022-9-1
@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
2022-8-31
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!