Matlab重塑水平连接

6

嗨,我想重塑一个矩阵,但是reshape命令没有按照我想要的顺序排序元素。 我有一个包含元素的矩阵:

A B
C D
E F
G H
I K
L M

并且想要重新塑造它为:

A B E F I K
C D G H L M

我知道我想要有多少行(在这种情况下是2行),所有2行的“组”应该横向添加。是否可以不使用for循环来完成此操作?

2个回答

4

您可以使用两个reshape和一个permute来完成。让 n 表示每组的行数:

y = reshape(permute(reshape(x.',size(x,2),n,[]),[2 1 3]),n,[]);

使用3列的示例,n=2

>> x = [1 2 3; 4 5 6; 7 8 9; 10 11 12]
x =
     1     2     3
     4     5     6
     7     8     9
    10    11    12
>> y = reshape(permute(reshape(x.',size(x,2),n,[]),[2 1 3]),n,[])
y =
     1     2     3     7     8     9
     4     5     6    10    11    12

哇,那真是太复杂了,但却有效!谢谢 :) - Stefan
1
@Stefan 如果你将三个步骤分开进行,它看起来就不会那么复杂了:首先执行 reshape(x.',size(x,2),n,[]) 等操作。这样你就可以看到中间结果,并理解其逻辑。 - Luis Mendo
此外,这仅适用于正方形框。要推广到任意行数,我认为您必须更改它,即: numRows = 3; y = reshape(permute(reshape(x.',size(x,2),numRows,[]),[2 1 3]),numRows,[]) 您能将其添加到答案中吗? - Stefan
1
@Stefan 我已经进行了泛化。你看到我的修改后的代码和示例了吗? - Luis Mendo
是的,我按照步骤操作了,现在更有意义了。通过转换成3D等方式进行重塑,概念上仍然有点复杂,呵呵。但这很棒。 - Stefan

1

单元数组方法 -

mat1 = rand(6,2) %// Input matrix
nrows = 3; %// Number of rows in the output

[m,n] = size(mat1);

%// Create a cell array each cell of which is a (nrows x n) block from the input
cell_array1 = mat2cell(mat1,nrows.*ones(1,m/nrows),n);  

%// Horizontally concatenate the double arrays obtained from each cell
out = horzcat(cell_array1{:})

代码运行时的输出 -

mat1 =
    0.5133    0.2916
    0.6188    0.6829
    0.5651    0.2413
    0.2083    0.7860
    0.8576    0.3032
    0.1489    0.4494
out =
    0.5133    0.2916    0.5651    0.2413    0.8576    0.3032
    0.6188    0.6829    0.2083    0.7860    0.1489    0.4494

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接