MATLAB: multi-value matrix division

I am 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 the submatrices where the values ​​in the first and second columns can be grouped so 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'm trying to think about how to index the matrix for this, and I have an available matrix:

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

which I could use for indexing. I was wondering if I can use it, but I'm not 100% sure. I do not want to use a for loop, since matrices can be quite large and the complexity order can become very large.

Thanks for reading!

+6
source share
1 answer

This is easy to do 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 an array of cells containing 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 
+12
source

All Articles