连接每第n行

时间:2013-05-08 10:08:04

标签: matlab vector matrix

我在矩阵中得到了一个数据集,如下所示(从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个向量(每个类别一个)来进行叠加条形图。重塑操作后,矢量应如下所示(如果矢量具有第一列的名称且矩阵可以是任何大小,那将是很好的):

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]

我真诚地希望这不重复。在其他重塑问题的帮助下,我无法提供有效的解决方案。

2 个答案:

答案 0 :(得分:2)

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

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

结果矩阵res由连接的行组成。

此解决方案也适用于单元格数组,但您需要额外的cell2mat才能将结果转换为矩阵。

实施例

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

答案 1 :(得分:1)

编辑:

尝试以下方法:

%# dataset stored in a cell array
data = {
    '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
};

%# get all possible values of first column,
%# and map them to integer indices
[L,~,IDX] = unique(data(:,1));

%# for each possible "category"
groups = cell(max(IDX),1);
for i=1:max(IDX)
    %# get the rows of numeric data matching current category
    M = data(IDX==i, 2:end)';

    %# flatten matrix into a vector and store in cell (row-major order)
    groups{i} = [M{:}];
end

现在您可以访问第i个“cat”向量:groups{i}

>> [cat1,cat2,cat3] = deal(groups{:})
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

请注意,匹配的“cat”标签存储在L{i}(映射键)