MATLAB: Question about array alternating between positive and negative

graphguiMATLABMATLAB and Simulink Student Suite

Hello,
I have solved a differential equation symbolically and then evaulated it based on user input. The result is different every time. Each time I obtain an array from the graph. For example, lets say I get an array, a=[-1,1,2,-2,1,5,-4,1]. Is there a way to find out how many times the sign of an array changes from positive to negative? The reason I am trying to do this is I need to know how many times the curve crosses the origin.
Thanks!

Best Answer

Seems like there should be a shorter way, but assuming you are looking for all 0 crossings and not just the positive to negative ones:
sum(logical(diff(sign(a))))
This will double book the exact 0's, however. So if you expect you might get those, you will need something more sophisticated.