我有一个250乘200的大矩阵。里面是50乘50小的5乘4矩阵.
怎样才能最好地重塑矩阵,使2500个5乘4的小矩阵水平对齐?因此,大矩阵的最终尺寸应该是5乘-10000。
发布于 2015-07-29 09:46:30
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]置换4D矩阵,使每个子矩阵位于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,[]);发布于 2015-07-29 09:46:10
您可以使用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按列操作.因此,在使用X之前,我们需要将.'或transpose转换为reshape,如上面的代码所示。
发布于 2015-07-29 13:16:01
我想添加另一种使用索引和内置函数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 approachhttps://stackoverflow.com/questions/31695877
复制相似问题