camdroid
camdroid

Reputation: 524

Matlab find Series of First Negative Number

With a matrix of numbers in Matlab, how would you find the first negative number after a series of positive numbers?

So far, the only answer I could come up with was to write a loop to check for the first negative number, then record it, then look for the first positive number, and truncate the array there, then start over. Is there a vectorized way to do this?

e.g., I have x = [ -1 -5 -2 3 4 8 -2 -3 1 9], and I want this function or script to give me an array of y = [1 7].

Upvotes: 2

Views: 1991

Answers (2)

Acorbe
Acorbe

Reputation: 8391

This is a quite home made solution, check it out

x = [ -1 -5 -2 3 4 8 -2 -3 1 9]

neg_idx = find(x < 0)     % // negative values
z = [0 diff(neg_idx)]     % // increments among indices of successive values;
                          % // consecutive indices return a difference of 1 whereas
                          % // non consecutive return a value greater than 1.
                          % // because the first element must be distinguished 
                          % // we put the zero in front
id = find(z ~= 1)         % // Every time there is a jump, a non consecutive neg.
                          % // value appears 

% // thus the solution is in                     
y = neg_idx(id)           

 ans =

 1     7

If neg_idx is empty (i.e. no negative value is involved) you will get an Index exceeds matrix dimensions, although the condition is immediate to check.

Upvotes: 1

High Performance Mark
High Performance Mark

Reputation: 78316

or

find(diff(sign([1 x]))<0)

that is to say: find the locations in x where the difference in sign between successive elements is negative, oh and pushing a 1 onto the front of x to take care of the case where the 1st element is already negative

Upvotes: 3

Related Questions