假设我有一个可变大小的三维矩阵A
。是否有一个易于使用的命令,堆栈矩阵像B = [squeeze(A(1,:,:)); squeeze(A(2,:,:)); ...; squeeze(A(n,:,:))]
?
现在我使用下面的代码,但是很麻烦:
if(length(A(:,1,1))==1)
B =squeeze(A);
else
B = zeros(length(A(:,1,1)*length(A(1,:,1)), length(A(1,1,:)));
B(1:length(A(1,:,1)),:) = squeeze(A(1,:,:));
for i=2:length(A(1,:,1)
B(1:i*length(A(1,:,1)),:)=...
vertcat(B, squeeze(A(i,:,:)));
end
end
这将做相同的B = [squeeze(A(1,:,:)); squeeze(A(2,:,:)); ...; squeeze(n,:,:))]
。不确定它是否比循环快:
B = num2cell(A, [2 3]); % split along first dimension into cells
B = permute([B{:}], [2 3 1]); % concatenate the cells along second dimension
% and remove first dimension, which is a singleton
您可以将reshape
与矩阵维度的排列和转置一起使用:
C = reshape(permute(A,[3,2,1]),size(A,3),[]).';
将优雅地适应任意行数。一个小测试:
A = rand([3,4,4]);
B = [squeeze(A(1,:,:)); squeeze(A(2,:,:)); squeeze(A(3,:,:))];
C = reshape(permute(A,[3,2,1]),size(A,3),[]).';
all(B(:)==C(:)) % should be true/1
这是另一个使用permute
和reshape
-
B = reshape(permute(A,[2,1,3]),[],size(A,3))