- Home /
How would I find multiple peaks and valleys in an array of values?
I know how to get the maximum and minimum values- I just set a variable to zero and then loop through the whole array and change the variable to Mathf.Max(theMax,theArray[i]). Now I'm trying to find the second highest or lowest points, which obviously would be one of the two points immediately on either side of the peak or valley, but that's not what I mean - I'm trying to find peaks and valleys in a sequence, but only the biggest 2 or 3. And it's getting messy.
I know this is more a general programming problem than a Unity-specific one; and there seem to be several approaches to it, but my application is analyzing Input.acceleration data to make tilt controls that don't suck. Could someone who's already got this stuff figured out point me to some example code on the interwebs of an elegant way to go about it?
I'm presu$$anonymous$$g your trying to get a significant "Input" pulse from this array to smooth out tilting. If that is what you want then I have a solution which did work for me.
Can you provide an example of what some data in the array might look like? and point out which data are the ones you would like to find
Answer by Julien-Lynge · Jun 07, 2012 at 08:19 PM
How about taking the differential of the sequence? For each point, do something like
difference = Mathf.Sign(newVal - prevVal);
When the sign changes from positive to negative, you've hit a peak. When it changes from negative to positive you're at a valley. You can then save out and iterate through the points associated with each peak/valley, or just put them in a SortedList that will automatically sort them from the highest peak to lowest valley.
Thanks- that's simpler than what I was thinking, and I didn't even know such thing as a SortedList existed.
Your answer
Follow this Question
Related Questions
mathf.min and mathf.max 3 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Clarification on how RangeAttribute works 1 Answer
A problem with intersection detection 1 Answer
getting a sum from two scripts 1 Answer