Question about array alternating between positive and negative

조회 수: 4 (최근 30일)
William Fantin
William Fantin 2019년 5월 15일
댓글: James Tursa 2019년 5월 15일
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!

채택된 답변

James Tursa
James Tursa 2019년 5월 15일
편집: James Tursa 2019년 5월 15일
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.
  댓글 수: 2
William Fantin
William Fantin 2019년 5월 15일
IT WORKED!!!! THANK YOU!!! i had sunusoidal motion about the x-axis and it crossed 6 times and your method gave me 6! what did you mean it wont exactly count zeros correctly?
THanks again
James Tursa
James Tursa 2019년 5월 15일
E.g.,
>> a = [-2 -3 0 1 2 -3 5]
a =
-2 -3 0 1 2 -3 5
>> sum(logical(diff(sign(a))))
ans =
4
There's really only three 0 crossings, but the calculation above gave a result of 4. The 0 crossing from -3 --> 0 --> 1 got double booked because the sign changed twice even though it was only one crossing. So if you expect you might get exact 0's you will need a more sophisticated method to detect them and check for 0 crossings vs 0 peaks etc and adjust the answer accordingly.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by