How do I find the (x,y) coordinates of the peaks and valleys of a graph?

I am new to Matlab and I am not sure how to find the coordinates of the peaks or valleys of my graph. After looking online, I tried using findpeaks() which did give me the y-values of the local maxima of my function ((e^(−at))*cos(2πft), where t is time and a and f are constants). However, I have not been able to find the corresponding x-values (and findpeaks() omits a local max at the y-intercept). I am also not at all sure how to find the coordinates for the valleys (minima or "troughs").

 Akzeptierte Antwort

The x values are the second return argument of findpeaks(). It's the index number. Your formula does not have an x by name so you have to go with the index number. If you have a second array for t, then to get the t values you'd do
[peakValues, indexes] = findpeaks(y);
tValues = t(indexes);
To get valleys, you invert the signal, so that now what used to be valleys are now peaks, and use findpeaks() again
invertedY = max(y) - y;
[peakValues, indexes] = findpeaks(invertedY);
tValues = t(indexes);

5 Kommentare

Thank you! A few quick follow-up questions: 1. Is "inverted" a matlab function? or do I have to invert the function somehow? 2. Also, the coordinate results seem off from what the graph has. Am I missing something with my code here? (See below)
y=((exp(-1.83*x)).*(cos(4*pi*x)));
[peakValues, indexes]=findpeaks(y);
xValues = x(indexes)
fprintf('The coordinates of peaks are:\n');
fprintf('(%g,%g)\n',peakValues,indexes);
No, invertedY is a variable that is constructed by
invertedY = max(y) - y;
You could call it something else like
upsidedownY = max(y) - y;
Personally I favour the simpler
upsidedownY = -y;
Alright, that makes sense. One last thing. The graph has a y-intercept of (0,1) that I am supposed to include as a local max, but the findpeaks function disregards it. Is there anyway to get the function to find/include (0,1)?
You could try appending -inf to the data so that the adjacent value is seen as a local maximum.
An alternative could be to take the absolute value of your vector to find only the indexes of both peaks and values.. Would need to go back and evaluate the original function to get the y-values, though.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Sergio Yanez-Pagans
Sergio Yanez-Pagans am 28 Mär. 2021

0 Stimmen

You can use my MATLAB file exchange function, it's really easy to implement and use:
Hope you find this useful!

Community Treasure Hunt

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

Start Hunting!

Translated by