假设我有矩阵A,在MATLAB中定义为:
A = zeros(2,2,2,2,2);
A(1,1,1,1,1) = 1;
A(1,1,1,1,2) = 2;
A(1,1,1,2,1) = 3;
A(1,1,1,2,2) = 4;
A(1,1,2,1,1) = 5;
A(1,1,2,1,2) = 6;
A(1,1,2,2,1) = 7;
A(1,1,2,2,2) = 8;
A(1,2,1,1,1) = 9;
A(1,2,1,1,2) = 10;
A(1,2,1,2,1) = 11;
A(1,2,1,2,2) = 12;
A(1,2,2,1,1) = 13;
A(1,2,2,1,2) = 14;
A(1,2,2,2,1) = 15;
A(1,2,2,2,2) = 16;
A(2,1,1,1,1) = 17;
A(2,1,1,1,2) = 18;
A(2,1,1,2,1) = 19;
A(2,1,1,2,2) = 20;
A(2,1,2,1,1) = 21;
A(2,1,2,1,2) = 22;
A(2,1,2,2,1) = 23;
A(2,1,2,2,2) = 24;
A(2,2,1,1,1) = 25;
A(2,2,1,1,2) = 26;
A(2,2,1,2,1) = 27;
A(2,2,1,2,2) = 28;
A(2,2,2,1,1) = 29;
A(2,2,2,1,2) = 30;
A(2,2,2,2,1) = 31;
A(2,2,2,2,2) = 32;
如何将此矩阵转换为新的矩阵B,使得矩阵B是一个向量,使得B = [1,2,3,4 ... 32]?
重塑功能不起作用,我在网上找不到任何帮助。
提前致谢!
答案 0 :(得分:4)
您的尺寸方向相反,以达到您想要的效果。所以:只需置换维度(使用permute
),然后线性化(使用:
):
B = permute(A, [5 4 3 2 1]);
B = B(:);
如果您想将它放在一行中,请使用reshape
进行线性化:
B = reshape(permute(A, [5 4 3 2 1]), [],1);
如果你定义了(注意指数的反转)
A(1,1,1,1,1) = 1;
A(2,1,1,1,1) = 2;
A(1,2,1,1,1) = 3;
A(2,2,1,1,1) = 4;
A(1,1,2,1,1) = 5;
A(2,1,2,1,1) = 6;
A(1,2,2,1,1) = 7;
A(2,2,2,1,1) = 8;
...
维度将采用“正确”的顺序,然后您不需要permute
:
B = A(:);
或
B = reshape(A, [],1);