Search code examples
matlabsortingmatrixsumdivide

Divide Matrix into Higher and Lower Value than Scalar Value Input


I have some problem in matlab since I was new in this programming language. Okay here it is :

I have Matrix and I have sorted it ascending, for example :

1
1
1
3
4
4
4
5
6
6
7
7
9
9
9
9
9

It's only 1 column matrix. I want to divide the matrix into two groups with some scalar value. Is I choose 5 as the scalar so my matrix will be divide into two groups higher than 5 and lower than 5 :

Expected result :

Lower Matrix :

1
1
1
3
4
4
4
5

Higher Matrix :

6
6
7
7
9
9
9
9
9

I have tried using max and min command but this command keep the matrix size and replace all lower number than scalar (5) into 5. Its a problem since for the next step I want to sum each lower and higher matrix.

Could you suggest me some trick? Many thanks


Solution

  • You can use logical addressing to do this:

    LowValuesMatrix = Matrix(Matrix <= 5);
    HighValuesMatrix = Matrix(Matrix > 5);
    
    LowValuesMatrix =
     1
     1
     1
     3
     4
     4
     4
     5
    
    HighValuesMatrix =
     6
     6
     7
     7
     9
     9
     9
     9
     9