4

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

1
  • What happened to "0" and "-1"? Commented Apr 12, 2012 at 21:43

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Probably you should remove 0s first.
@yuk: I thought maybe that was an accidental omission in the question, since there is also a -1 missing at the end. I just treated 0 as positive.
thanks for your help guys, sorry about the confusion. i dint know whether 0 was positive or negative and missed -1 by chance

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.