我正在将 3d 矩阵转换为 2d 矩阵。这是形状变换:[n x m x o] -> [n*o x m]。
矩阵的元素与行相关。因此,要求在结果矩阵中具有相同的行。
A = rand(2,2,3);
这样做:
C = reshape(A, 2*3, 2);
不保留 A 中的行。
所以我这样做:
B = zeros(size(A,1)*size(A,3),size(A,2));
first_indice = 1;
for i = 1:size(A,3)
B(first_indice:size(A,1)*i,:)=A(:,:,i);
first_indice = first_indice + size(A,1);
end
是否有更有效的方法使用 reshape ?
非常感谢!
最佳答案
reshape 组合从第一维开始的矩阵元素。因此,解决方案是在 reshape 之前置换尺寸。在您的情况下,它应该如下所示:
% A is the input matrix of dimensions (n x m x o).
B = ipermute(A, [1 3 2]);
C = reshape(B, n*o, m);
关于performance - 将矩阵从 3d reshape 为 2d 保持行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8655878/