将长2D矩阵分割成第三维

时间:2009-09-07 20:50:27

标签: matlab matrix multidimensional-array vectorization

说我有以下矩阵:

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

我想提取每两行并将它们放入第三维,因此结果如下:

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

2 个答案:

答案 0 :(得分:11)

以下是使用RESHAPEPERMUTE的单行解决方案:

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

答案 1 :(得分:0)

这里是reshapepermute的单行,但没有转置输入数组 -

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

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

基准

本节将此帖中提议的方法与other solution with reshape, permute & transpose的效果进行比较。数据集与问题中列出的数据集成比例。因此,A的大小为60000 x 300,我们会将其拆分,以使3D输出具有200 rows,因此dim-3会有300个条目。< / p>

基准代码 -

%// 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.