分割长2D矩阵入第三维(split long 2D matrix into the third di

2019-07-05 12:05发布

说我有以下矩阵:

A = randi(10, [6 3])
     7    10     3
     5     5     7
    10     5     1
     6     5    10
     4     9     1
     4    10     1

我想提取每个2行,放到第三个层面,所以结果会是这样:

B(:,:,1) =
     7    10     3
     5     5     7
B(:,:,2) =
    10     5     1
     6     5    10
B(:,:,3) =
     4     9     1
     4    10     1

我可以明显地做到这一点有一个for循环,只是不知道如何使用作为一个班轮置换 / 重塑做到这一点更优雅/ ..(注意矩阵大小和步骤必须是参数)

% params
step = 5;
r = 15;
c = 3;

% data
A = randi(10, [r c]);
B = zeros(step, c, r/step); % assuming step evenly divides r

% fill
counter = 1;
for i=1:step:r
    B(:,:,counter) = A(i:i+step-1, :);
    counter = counter + 1;
end

Answer 1:

下面是一个使用一个在线解决方案RESHAPE和置换 :

C = 3;          % Number of columns
R = 6;          % Number of rows
newR = 2;       % New number of rows
A = randi(10,[R C]);  % 6-by-3 array of random integers
B = permute(reshape(A',[C newR R/newR]),[2 1 3]);

当然,这需要newR整除R



Answer 2:

这里有一个一行与reshapepermute ,但没有调换输入数组-

out = permute(reshape(A,newR,size(A,1)/newR,[]),[1 3 2]);

其中newR处于行数3D阵列输出。


标杆

本节建议的形式给出在这个岗位比较反对other solution with reshape, permute & transpose性能。 该datasizes充气比例在问题中列出的那些。 因此, A60000 x 300大小,我们将它分开,使得3D输出将具有200 rows ,因此变暗-3将具有300的条目。

基准测试代码 -

%// Input
A = randi(10, [60000 300]); %// 2D matrix
newR = 200;                 %// New number of rows

%// Warm up tic/toc.
for k = 1:50000
    tic(); elapsed = toc();
end

N_iter = 5; %// Number of iterations for each approach to run with

disp('---------------------- With PERMUTE, RESHAPE & TRANSPOSE')
tic
for iter = 1:N_iter
    [R,C] = size(A);
    B = permute(reshape(A',[C newR R/newR]),[2 1 3]); %//'
end
toc, clear B R C iter

disp('---------------------- With PERMUTE & RESHAPE')
tic
for iter = 1:N_iter
    out = permute(reshape(A,newR,size(A,1)/newR,[]),[1 3 2]);
end
toc

输出 -

---------------------- With PERMUTE, RESHAPE & TRANSPOSE
Elapsed time is 2.236350 seconds.
---------------------- With PERMUTE & RESHAPE
Elapsed time is 1.049184 seconds.


文章来源: split long 2D matrix into the third dimension