在我的脚本中,我生成了一个矩阵,其中每一列至少与另一列耦合。例如,第 1 列与第 2 列耦合,第 3 列与第 4 列耦合,等等......但我也可以将 3 乘 3 或 4 乘 4 或任何其他数字耦合。
目前这只是脑海中的一个图像,但我想在它们自己的行上移动耦合的列,这样我就可以使用 any() 或 sum() 轻松地将它们混合起来。
这个例子会更清楚:
A = reshape(1:12, 3, []) % A is the matrix I start with, this reshape is OK
A =
1 4 7 10
2 5 8 11
3 6 9 12
reshape(A, [], 2) % this reshape is not OK
ans =
1 7
2 8
3 9
4 10
5 11
6 12
但是,我希望答案是:
ans =
1 4
2 5
3 6
7 10
8 11
9 12
正如我所说,此示例仅适用于 2 列,但在我的用例中,我还需要支持任意数量的列对。这里有 3 列:
B = reshape(1:18, 3, [])
B =
1 4 7 10 13 16
2 5 8 11 14 17
3 6 9 12 15 18
reshape(B, [], 3)
ans =
1 7 13
2 8 14
3 9 15
4 10 16
5 11 17
6 12 18
我想要什么:
ans =
1 4 7
2 5 8
3 6 9
10 13 16
11 14 17
12 15 18
有没有办法以矢量化的方式做到这一点?
最佳答案
假设 M
是输入矩阵,看看这是否适合你 -
ncols = 2; %// number of columns (needs to be edited)
[m,n] = size(M) %// get size of input matrix for later usage
r = numel(M)/(m*ncols);
out = reshape(permute(reshape(M,m,ncols,[]),[1 3 2]),m*r,[])
样本运行-
M =
1 4 7 10
2 5 8 11
3 6 9 12
ncols =
2
out =
1 4
2 5
3 6
7 10
8 11
9 12
和
M =
1 4 7 10 13 16
2 5 8 11 14 17
3 6 9 12 15 18
ncols =
3
out =
1 4 7
2 5 8
3 6 9
10 13 16
11 14 17
12 15 18
涵盖另一个可能的预期问题
按照您的说法 - “第 1 列与第 2 列耦合,第 3 列与第 4 列耦合,等等......但我也可以将 3 乘 3 或 4 乘 4 或任何其他数字耦合”
,我感觉您实际上可能希望形成输入矩阵列的所有可能组合,并将它们垂直连接以形成一个细长矩阵作为输出。解决方案的这一部分将涵盖该基础。实现这样一个目标的代码(如果这就是你希望的意思)
会是这样的-
ncols = 2; %// number of columns (needs to be edited)
[m,n] = size(M) %// get size of input matrix for later usage
combs = dec2base(0:n^2-1,n,ncols)-'0'+1 %// find combinations
combsp = permute(combs,[3 2 1]) %// make a 3D array of those combinations
idx = bsxfun(@plus,[1:m]',(combsp-1)*m) %//'# Indices as a 3D array
idx1 = reshape(permute(idx,[1 3 2]),m*size(idx,3),[]) %// vertically concatenate
%// 3D indices array into a 2D array
out = M(idx1) %// desired output
一次 sample 运行 -
M =
6 7 3 6
3 1 6 3
5 1 4 2
ncols = 2
out =
6 6
3 3
5 5
6 7
3 1
5 1
6 3
3 6
5 4
6 6
3 3 ....
关于matlab - reshape 以垂直平铺列 block 低于先前的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26917249/