嗨,我想重塑一个矩阵,但是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循环来完成此操作?
您可以使用两个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
单元数组方法 -
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
reshape(x.',size(x,2),n,[])
等操作。这样你就可以看到中间结果,并理解其逻辑。 - Luis Mendoy = reshape(permute(reshape(x.',size(x,2),numRows,[]),[2 1 3]),numRows,[])
您能将其添加到答案中吗? - Stefan