Custom Sorting Arrays in Matlab

arrays, matlab

Solution

Here's one way to do it:

>> A = [-2.5 -4 -6 0 1 -2.4 3 7.1 5 -1];
>> cellSizes = diff([0 find(diff(A >= 0)) numel(A)]);
>> B = mat2cell(A, 1, cellSizes)

B = 

    [1x3 double]    [1x2 double]    [-2.4000]    [1x3 double]    [-1]

You first get a logical array where `A` is greater than or equal to 0. Then using DIFF and FIND you get the indices where the logical array changes from 0 to 1 or 1 to 0. Add a zero to the front of that array, the length of `A` to the end, then take the difference again to get the size of each positive or negative segment. Finally, you can break the array up into a cell array of smaller arrays using the function MAT2CELL.

Problem

I have an array of double values containing negative and positive numbers (eg. `-2.5 -4 -6 0 1 -2.4 3 7.1 5 -1`). I want to sort this into smaller arrays of continuous positive and negative numbers so from the array above, i d like to create `[-2.5 -4 -6 ] [1] [-2.4] [3 7.1 5] [-1]`. How do i implement this in Matlab

Original source