在一个矩阵中堆叠子矩阵3d矩阵

时间:2016-08-15 16:30:56

标签: matlab matrix multidimensional-array vectorization

所以我想说我有一个可变大小的3d矩阵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

2 个答案:

答案 0 :(得分:4)

您可以将reshapepermutation矩阵的尺寸和转置一起使用:

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

答案 1 :(得分:3)

此处还有一个使用permutereshape -

B = reshape(permute(A,[2,1,3]),[],size(A,3))