How to part a Matrix into submatrices based on the data
Show older comments
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)
Fangjun Jiang
on 21 Jul 2017
A=magic(5)
a=A(A(:,3)==1,:)
b=A(A(:,3)==13,:)
c=A(A(:,3)>=10,:)
James Tursa
on 21 Jul 2017
Edited: James Tursa
on 21 Jul 2017
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
Star Strider
on 21 Jul 2017
Result = splitapply(@(x){x}, M, M(:,3));
4 Comments
Matteo Castelli
on 22 Jul 2017
Star Strider
on 22 Jul 2017
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.
Matteo Castelli
on 23 Jul 2017
Star Strider
on 23 Jul 2017
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.
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!