San*_*har 6 arrays matlab multidimensional-array
在Matlab中,我们可以像这样折叠数组的维度:
M = rand(3,4,5);
myvec = M(:); % gives a 60-element vector
Run Code Online (Sandbox Code Playgroud)
我认为它被称为序列化或扁平化.元素的顺序首先是dim1,然后是dim2,然后是dim3 - 所以你得到了[M(1,1,1); M(2,1,1); M(3,1,1); M(1,2,1); ...].
但我想要做的就是沿着前两个维度崩溃:
mymatrix = M( :: , : ); % something that works like this?
Run Code Online (Sandbox Code Playgroud)
给出12 x 5矩阵.所以,例如,你得到
[M(1,1,1) M(1,1,2) M(1,1,3) M(1,1,4) M(1,1,5)
M(2,1,1) M(2,1,2) M(2,1,3) M(2,1,4) M(2,1,5)
M(3,1,1) M(3,1,2) M(3,1,3) M(3,1,4) M(3,1,5)
M(1,2,1) M(1,2,2) M(1,2,3) M(1,2,4) M(1,2,5)
...
]
Run Code Online (Sandbox Code Playgroud)
因此第一个维度mymatrix是原件的"扁平"第一和第二维M,但保留了任何其他尺寸.
我实际上需要为5维数组的"中间3维"做这个,所以一般的解决方案会很棒!例如,W=rand(N,N,N,N,N); mymatrix = W( :, :::, : )应该给N x N^3 x N,如果你明白我的意思矩阵.
谢谢
使用reshape方括号([])作为其中一个维度长度参数的占位符:
sz = size( M );
mymatrix = reshape( M, [], sz(end) ); % # Collapse first two dimensions
Run Code Online (Sandbox Code Playgroud)
要么
mymatrix = reshape( M, sz(1), [], sz(end) ); % # Collapse middle dimensions
Run Code Online (Sandbox Code Playgroud)
占位符[]告诉reshape您自动计算大小.请注意,您只能使用一次[].必须明确指定所有其他尺寸长度.