Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB: Splitting a matrix based on multiple values

I'm dealing with matrices of this format:

M =
1    1    3
1    1    1
1    2    2
1    2    1
1    2    2
2    1    5
2    1    1
2    2    3
2    2    4
2    2    2
...

What I want to do is extract sub matrices where the values in the first and second column can be grouped such that:

M1 =
1    1    3
1    1    1

M2 =
1    2    2
1    2    1
1    2    2

M3 =
2    1    5
2    1    1

...

I have been trying to think hard about how to index the matrix for this and I have a matrix available:

I =
1    1
1    2
2    1
2    2
...

that I could use for indexing. I was wondering if I could use it but I'm not 100% sure how. I don't want to use a for loop since the matrixes can be rather large and the order of complexity can become very large.

Thank you for reading!

like image 335
Joe Hesketh Avatar asked Feb 03 '16 17:02

Joe Hesketh


People also ask

How do you split a matrix row in Matlab?

For Splitting a matrix in a loop You can use the colon operator. M(3:4, :) % 3rd and 4th row of M and all columns. If you want to split any number of columns in multiple matrices of two colums, You can use a for loop to do so.

How do you split a matrix into Submatrices in Matlab?

c = mat2cell(x, m, n) divides the two-dimensional matrix x into adjacent submatrices, each contained in a cell of the returned cell array c . Vectors m and n specify the number of rows and columns, respectively, to be assigned to the submatrices in c .


1 Answers

This is easily done with unique and accumarray:

M = [ 1    1    3
      1    1    1
      1    2    2
      1    2    1
      1    2    2
      2    1    5
      2    1    1
      2    2    3
      2    2    4
      2    2    2 ]; %// data
[~, ~, u] = unique(M(:,1:2), 'rows'); %// unique labels of rows based on columns 1 and 2
M_split = accumarray(u(:), (1:size(M,1)).', [], @(x){M(sort(x),:)}); %'// group rows 
                                                                     % // based on labels

This gives a cell array containing the partial matrices. In your example,

M_split{1} =
     1     1     3
     1     1     1
M_split{2} =
     1     2     2
     1     2     1
     1     2     2
M_split{3} =
     2     1     5
     2     1     1
M_split{4} =
     2     2     3
     2     2     4
     2     2     2
like image 164
Luis Mendo Avatar answered Nov 15 '22 05:11

Luis Mendo