我有一个250 × -200的大矩阵。其中有50-by-50较小的5-by-4矩阵。
什么是重塑矩阵的最佳方法,使2500 5 × 4较小的矩阵彼此水平对齐?所以大矩阵的末端维数应该是5-by-10000
Matlab的reshape
函数非常方便(并且快速),但总是读取和写入完整的列。因此,针对您的问题,需要采取一些额外的步骤。
你可以这样做:
m = 5 % columns of submatrix
n = 4 % rows of submatrix
k = 50 % num submatrixes in matrix column
l = 50 % num submatrixes in matrix row
A = rand(m*k,n*l); % rand(250,200)
将矩阵重塑为四维矩阵(维度x1,x2,x3,x4),其中每个子矩阵位于x1-x3平面。然后原矩阵的子矩阵列在x2方向,子矩阵行在x4方向。
B = reshape(A,[m,k,n,l]); % [4,50,5,50]
对四维矩阵进行置换('转置'),使每个子矩阵位于x1-x2平面。(reshape
首先读取列,然后是行,然后是三维,等等)
C = permute(B,[1,3,4,2]); % For column-wise reshaping, use [1,3,2,4]
将4D矩阵重塑为所需的2D输出矩阵。
D = reshape(C,m,[]);
你可以先用mat2cell
,然后用reshape
,最后用cell2mat
得到矩阵。出于演示目的,我使用了变量n
和m
。对于你的矩阵,它们都是50。
下面的代码按行执行,正如您在注释中说明的那样:
n = 3; % rows
m = 2; % columns
A = reshape(1:20,[5,4]); % generate some data
M = repmat(A,n,m); % create the large matrix
X = mat2cell(M,repmat(5,1,n),repmat(4,1,m))
X = reshape(X.',1,[])
X = cell2mat(X)
注意: reshape
按列操作。因此,在使用reshape
之前,我们需要将X
转换为.'
或transpose
,如上面的代码所示。
我想我会添加另一种方法,使用索引和一个内置函数zeros
。也许这种方式不会有任何不必要的错误检查或重塑操作。事实证明,它更有效率(见下文)。
%submatrix size
m = 5;
n = 4;
%repeated submatrix rows and cols
rep_rows = 50;
rep_cols = 50;
% big matrix
A = rand(m * rep_rows, n * rep_cols);
% create new matrix
C = zeros(m, (n * rep_cols) * rep_rows);
for k = 1:rep_rows
ind_cols = (n * rep_cols) * (k - 1) + 1: (n * rep_cols) * k;
ind_rows = m * (k - 1) + 1: m * k;
C(:, ind_cols) = A(ind_rows, :);
end
我决定在这里计算三个答案的时间,发现这种方法要快得多。下面是测试代码:
% Bastian's approach
m = 5; % columns of submatrix
n = 4; % rows of submatrix
k = 50; % num submatrixes in matrix column
l = 50; % num submatrixes in matrix row
A = rand(m*k,n*l); % rand(250,200)
% start timing
tic
B = reshape(A,[m,k,n,l]); % [4,50,5,50]
C = permute(B,[1,3,4,2]); % For column-wise reshaping, use [1,3,2,4]
D = reshape(C,m,[]);
toc
% stop timing
disp(' ^^^ Bastian');
% Matt's approach
n = 50; % rows
m = 50; % columns
% start timing
tic
X = mat2cell(A,repmat(5,1,n),repmat(4,1,m));
X = reshape(X.',1,[]);
X = cell2mat(X);
toc
% stop timing
disp(' ^^^ Matt');
% ChisholmKyle
m = 5;
n = 4;
rep_rows = 50;
rep_cols = 50;
% start timing
tic
C = zeros(m, (n * rep_cols) * rep_rows);
for k = 1:rep_rows
ind_cols = (n * rep_cols) * (k - 1) + 1: (n * rep_cols) * k;
ind_rows = m * (k - 1) + 1: m * k;
C(:,ind_cols) = A(ind_rows, :);
end
toc
% stop timing
disp(' ^^^ this approach');
下面是我的机器上的输出:
Elapsed time is 0.004038 seconds.
^^^ Bastian
Elapsed time is 0.020217 seconds.
^^^ Matt
Elapsed time is 0.000604 seconds.
^^^ this approach