Sushil Surwase
Sushil Surwase

Reputation: 35

How to split the matrix based on the column entries in Matlab?

I have a dataset/Matrix A, with the following features:

A = [ 
      2 3 6 2 2;
      5 3 5 6 2;
      4 5 6 5 2;
      6 4 3 2 0;
      2 3 6 2 0;
      5 3 5 6 0;
      4 5 6 5 2;
      6 4 3 2 2;
      2 3 6 2 2;
      5 3 5 6 2
];

In the last column, I have entries with 2 and 0. I want to split the matrix A into 3 different junks depending on the last column entries 2, 0 and again 2.

Could you please suggest any efficient way to do that??

I would be highly obliged for your earliest response.

Upvotes: 0

Views: 43

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

I assume the desired result is a cell array of (sub)matrices:

B = mat2cell(A, diff([0; find([diff(A(:,end)); 1])]), size(A,2));

For your example A, this gives

>> celldisp(B)
B{1} =
     2     3     6     2     2
     5     3     5     6     2
     4     5     6     5     2
B{2} =
     6     4     3     2     0
     2     3     6     2     0
     5     3     5     6     0
B{3} =
     4     5     6     5     2
     6     4     3     2     2
     2     3     6     2     2
     5     3     5     6     2

Upvotes: 3

Related Questions