Home > Net >  How do I separate an array depending on values in a column?
How do I separate an array depending on values in a column?

Time:02-10

Say I have an Mx4 array A where the values in the first column are a number 1 to 12. Now I want to gather the rest of the columns in 12 separate Mx3 arrays depending on which number is in column 1. How would I go about doing that?

CodePudding user response:

You can use unique and splitapply as follows. The result is a cell array of arrays.

M = [2 11 41 51;
     1 10 20 30;
     1 62 83 22;
     4 73 53 53;
     2 84 94 14]; % example data
L = 5; % Group labels are 1:L (L=12 in your case)
[u,~,w] = unique(M(:,1));
result = cell(L,1);
result(u) = splitapply(@(x){x}, M(:,2:end), w);

This gives

>> celldisp(result)
result{1} =
    10    20    30
    62    83    22
result{2} =
    11    41    51
    84    94    14
result{3} =
     []
result{4} =
    73    53    53
result{5} =
     []
  • Related