How to part a Matrix into submatrices based on the data

I have a 30.000x5 Matrix, in the third column of each row i have an integer comprised between 1 and 5 and i don't know how many rows there are with each value. I want to divide my matrix into five smaller matrices (Nx5) each of which has into the third column the same value. How do i proceed?

Answers (3)

A=magic(5)
a=A(A(:,3)==1,:)
b=A(A(:,3)==13,:)
c=A(A(:,3)>=10,:)
E.g., with results in a cell array:
X = the 30000 x 5 matrix
n = number limit for 3rd column
result = cell(n,1);
for k=1:n
result{k} = X(X(:,3)==k,:);
end
If you have R2015b or later, use the splitapply (link) function:
Result = splitapply(@(x){x}, M, M(:,3));

4 Comments

What function should i put in splitapply in place of "@(x){x}"?
If you just want your ‘M’ matrix separated into sub-matrices for each group identified by an integer in column 3, the anonymous function ‘@(x){x}’ will do what you want. It creates a cell array of sub-matrices with different numbers of rows, each defined by — and with — the integer in column 3.
This is what comes out. I am not sure what should i do at this point. P.s. I made a mistake earlier: the coloumn whit the data from 0 to 5 is the second, not the third.
I thought they were positive integers. If any are <=0, you need to add a findgroups call first:
[G,ID] = findgroups(Matrix_Dati(:,2));
Result = splitapply(@(x){x}, Matrix_Dati, G);
That should work.

Sign in to comment.

Categories

Asked:

on 21 Jul 2017

Commented:

on 23 Jul 2017

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!