连接第n行 [英] Concatenate every n-th row

查看:61
本文介绍了连接第n行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了如下所示的矩阵中的数据集(从Excel导入):

I got a data set in a matrix like the following (imported from Excel):

matrix =
    Cat1   1  2  3  4
    Cat2   9 10 11 12
    Cat3  17 18 19 20
    Cat1   5  6  7  8
    Cat2  13 14 15 16
    Cat3  21 22 23 24

我想将其重塑为3个大小相同的向量(每个类别一个),以进行堆积的条形图.整形操作后,矢量应该看起来像这样(如果矢量具有第一列的名称并且矩阵可以是任意大小,那将是很好的选择):

I would like to reshape it into 3 vectors (one for every category) of the same size to do a stacked bar plot. Vectors should look like this after reshape operation (It would be nice if the vector had the name of the first column and the matrix could be of any size):

cat1 = [ 1  2  3  4  5  6  7  8]
cat2 = [ 9 10 11 12 13 14 15 16]
cat3 = [17 18 19 20 21 22 23 24]

我衷心希望这不是重复的.在其他重塑问题的帮助下,我无法提供可行的解决方案.

I sincerely hope this is not duplicate. I couldn't produce a working solution with the help of the other reshape questions.

推荐答案

如果数据是矩阵,则可以在建立索引时操纵行的顺序,因此可以执行以下操作:

If your data is a matrix, you can manipulate the order of the rows when indexing, so you can do something like this:

rows = reshape(1:size(matrix, 1), n, []).';
res = reshape(matrix(rows, :).', [], n).';

结果矩阵res由串联的行组成.

The resulting matrix res is composed of the concatenated rows.

该解决方案也适用于单元阵列,但是您需要附加的cell2mat才能将结果转换为矩阵.

This solution holds for cell arrays as well, but you'll need an additional cell2mat to turn the result into a matrix.

matrix = [1:4; 9:12; 17:20; 5:8; 13:16; 21:24];
n = 3;

rows = reshape(1:size(matrix, 1), n, []).';
res = reshape(matrix(rows, :).', [], n).';

结果是:

res =
     1     2     3     4     5     6     7     8
     9    10    11    12    13    14    15    16
    17    18    19    20    21    22    23    24

这篇关于连接第n行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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