13

假设我有以下矩阵:

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 循环来做到这一点,只是想知道如何使用permute / reshape /..更优雅地作为单行来做到这一点(注意矩阵大小和步长必须是参数)

% 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
4

2 回答 2

13

reshape这是使用and的单线解决方案permute

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

于 2009-09-07T20:59:41.350 回答
2

reshape这是一个带有and的单行代码permute,但没有转置输入数组 -

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

,其中newR3D数组输出中的行数。


基准测试

本节将本文中提出的方法与other solution with reshape, permute & transposeon 性能进行比较。数据大小与问题中列出的数据大小成比例。因此,A60000 x 300大小,我们将拆分它,以便3D输出将具有200 rows,因此 dim-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.
于 2016-01-01T09:13:42.610 回答