将2D长矩阵分解为三维 [英] split long 2D matrix into the third dimension

查看:83
本文介绍了将2D长矩阵分解为三维的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下矩阵:

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

我想提取每两行并将它们放入第三维,所以结果将是:

And I would like to extract each 2 rows and put them into the third dimension, so the result would be like:

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 /.作为一个衬套更优雅地完成它.(请注意矩阵大小并且step必须是参数)

I can obviously do this with a for loop, just wondering how to do it more elegantly as one-liner using permute/reshape/.. (note matrix size and step must be parameters)

% 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

推荐答案

这里是使用 reshape permute :

Here's a one-line solution using 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.

This of course requires that newR divides evenly into R.

这篇关于将2D长矩阵分解为三维的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆