Concatenate every n-th row

左心房为你撑大大i 提交于 2020-02-03 20:51:10

问题


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

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.


回答1:


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).';

The resulting matrix res is composed of the concatenated rows.

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

Example

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).';

The result is:

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



回答2:


EDIT:

Try the following:

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

Now you can access the i-th "cat" vector as: 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

Note that the matching "cat" labels are stored in L{i} (the mapping keys)



来源:https://stackoverflow.com/questions/16437937/concatenate-every-n-th-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!