重塑矩阵从3d到2d保持行 [英] Reshape matrix from 3d to 2d keeping rows
本文介绍了重塑矩阵从3d到2d保持行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在将3d矩阵转换为2d矩阵。这是形状变换:[n x m x o] - > [n * o x m]。
I am transforming a 3d matrix into a 2d matrix. This is the shape transformation: [n x m x o] -> [n*o x m].
矩阵的元素与行有关。因此,需要在结果矩阵中具有相同的行。
The elements of the matrices are row-related. Thus, it is required to have the same rows in the resulting matrix.
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
是否有更有效的方式可能使用重塑?
Is there a more efficient way maybe using reshape?
非常感谢!
推荐答案
reshape结合了从第一维开始的矩阵元素。因此,解决方案是在重塑之前置换尺寸。在您的情况下,它应如下所示:
reshape combines the matrix elements starting from the first dimension. Thus, the solution would be to permute the dimensions prior to reshaping. In your case it should be as follows:
% A is the input matrix of dimensions (n x m x o).
B = ipermute(A, [1 3 2]);
C = reshape(B, n*o, m);
这篇关于重塑矩阵从3d到2d保持行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文