Change language

Findpeaks Matlab function

| |

pks = findpeaks(data) returns a vector with local maxima (peaks) of the input signal vector, data. A local peak is a sample of the data that is either greater than its two adjacent samples or equal to Inf. Non-Inf endpoints of the signal are excluded. If the peak is flat, the function returns only the point with the lowest index.

Findpeaks Matlab

Syntax

pks = findpeaks(data)
[pks,locs] = findpeaks(data)
[pks,locs,w,p] = findpeaks(data)
[___] = findpeaks(data,x)
[___] = findpeaks(data,Fs)
[___] = findpeaks(___,Name,Value)
findpeaks(___)

pks = findpeaks(data) returns a vector with local maxima (peaks) of the input signal vector, data. A local peak is a sample of the data that is either greater than its two adjacent samples or equal to Inf. Non-Inf endpoints of the signal are excluded. If a peak is flat, the function will only return the point with the lowest index.

[pks,locs] = findpeaks(data) additionally returns indices where peaks occur.

[pks,locs,w,p] = findpeaks(data) additionally returns widths of peaks as vector w and prominent positions of peaks as vector p.

[___] = findpeaks(data,x) sets x as a location vector and returns any of the output arguments from the previous syntaxes. locs and w are described in terms of x.

[___] = findpeaks(data,Fs) specifies the sampling rate, Fs, from the data. The first sample of data is taken to be taken at the starting point in time. locs and w are converted to time units.

[___] = findpeaks(___,Name,Value) specifies the name-value pair arguments to use in addition to any of the input parameters in the previous syntaxes.

findpeaks(___) without output arguments builds a signal and imposes peak values.

FindPeaks Matlab examples

Find Peaks in a vector

Define a vector with three peaks and build it.

data = [25 8 15 5 6 10 10 3 1 20 7];
plot(data)
Figure contains an axes object. The axes object contains an object of type line.

Find local maxima. Peaks are output in order of occurrence. The first sample is not included despite being a maximum. For a flat peak, the function returns only the point with the lowest index.

pks = findpeaks(data)
pks = 1×3

    15    10    20

Use findpeaks without output arguments to display peaks.

findpeaks(data)
Figure contains an axes object. The axes object contains 2 objects of type line.

Find Peaks and their locations

Create a signal that consists of the sum of the curves of a normal distribution. Set the location, height and width of each curve.

x = linspace(0,1,1000);

Pos = [1 2 3 5 7 8]/10;
Hgt = [3 4 4 2 2 3];
Wdt = [2 6 3 3 4 6]/100;

for n = 1:length(Pos)
    Gauss(n,:) = Hgt(n)*exp(-((x - Pos(n))/Wdt(n)).^2);
end

PeakSig = sum(Gauss);

Construct the individual curves and their sum.

plot(x,Gauss,'--',x,PeakSig)
Figure contains an axes object. The axes object contains 7 objects of type line.

Use findpeaks with default settings to find peaks of the signal and their locations.

[pks,locs] = findpeaks(PeakSig,x);

Build peaks using findpeaks and mark them.

findpeaks(PeakSig,x)

text(locs+.02,pks,num2str((1:numel(pks))'))
Figure contains an axes object. The axes object contains 8 objects of type line, text.

Sort peaks from highest to shortest.

[psor,lsor] = findpeaks(PeakSig,x,'SortStr','descend');

findpeaks(PeakSig,x)

text(lsor+.02,psor,num2str((1:numel(psor))'))
Figure contains an axes object. The axes object contains 8 objects of type line, text.

Peaks of prominence

Create a signal that consists of a sum of normal distribution curves riding the full cosine period. Set the location, height and width of each curve.

x = linspace(0,1,1000);

base = 4*cos(2*pi*x);

Pos = [1 2 3 5 7 8]/10;
Hgt = [3 7 5 5 4 5];
Wdt = [1 3 3 4 2 3]/100;

for n = 1:length(Pos)
    Gauss(n,:) =  Hgt(n)*exp(-((x - Pos(n))/Wdt(n)).^2);
end

PeakSig = sum(Gauss)+base;

Plot the individual curves and their sum.

plot(x,Gauss,'--',x,PeakSig,x,base)
Figure contains an axes object. The axes object contains 8 objects of type line.

Use findpeaks to determine the location and build peaks that have an outstanding position of at least 4.

findpeaks(PeakSig,x,'MinPeakProminence',4,'Annotate','extents')
Figure contains an axes object. The axes object contains 4 objects of type line. These objects represent signal, peak, prominence, width (half-prominence).

The highest and lowest peaks are the only units that satisfy the condition.

Display the prominent positions and widths in half the prominent position of all peaks.

[pks,locs,widths,proms] = findpeaks(PeakSig,x);
widths
widths = 1×6

    0.0154    0.0431    0.0377    0.0625    0.0274    0.0409

proms
proms = 1×6

    2.6816    5.5773    3.1448    4.4171    2.9191    3.6363

Find Peaks with minimum separation

Sunspots are cyclic phenomena. Their number is known to peak about every 11 years.

Download sunspot.dat, which contains the average number of sunspots observed each year from 1 700 to 1987. Find and plot the maxima.

load sunspot.dat

year = sunspot(:,1);
avSpots = sunspot(:,2);

findpeaks(avSpots,year)
Figure contains an axes object. The axes object contains 2 objects of type line.

Improve your estimation of the cycle length by ignoring the peaks, which are very close to each other. Find and construct peaks again, but now limit the acceptable peak-to-peak separations to values greater than six years.

findpeaks(avSpots,year,'MinPeakDistance',6)
Figure contains an axes object. The axes object contains 2 objects of type line.

Use the peak locations returned by findpeaks to calculate the average interval between peaks.

[pks,locs] = findpeaks(avSpots,year,'MinPeakDistance',6);

meanCycle = mean(diff(locs))
meanCycle = 10.9600

Create a datetime array using year data. Assume that sunspots were counted every year on March 20th, close to the vernal equinox. Find the peak years of the sunspot. Use the years function to specify the minimum peak year as the duration.

ty = datetime(year,3,20);

[pk,lk] = findpeaks(avSpots,ty,'MinPeakDistance',years(6));

plot(ty,avSpots,lk,pk,'o')
Figure contains an axes object. The axes object contains 2 objects of type line.

Calculate the average cycle of solar activity using the datetime functionality.

dttmCycle = years(mean(diff(lk)))
dttmCycle = 10.9600

Create a schedule with the data. Set time variable in years. Display the data on a graph. Show the last five schedule entries.

TT = timetable(years(year),avSpots);
plot(TT.Time,TT.Variables)
Figure contains an axes object. The axes object contains an object of type line.
entries = TT(end-4:end,:)
entries=5×1 timetable
      Time      avSpots
    ________    _______

    1983 yrs     66.6  
    1984 yrs     45.9  
    1985 yrs     17.9  
    1986 yrs     13.4  
    1987 yrs     29.3  

Limit peak functions

Load an audio signal produced at 7,418 Hz. Select 200 samples.

load mtlb
select = mtlb(1001:1200);

Find peaks that are separated by at least 5ms.

Applying this limitation, findpeaks selects the highest peak in the signal and removes all peaks within 5 ms from it. The function then repeats the procedure for the highest remaining peak and iterates until this has exhausted the peaks to consider.

findpeaks(select,Fs,'MinPeakDistance',0.005)
Figure contains an axes object. The axes object contains 2 objects of type line.

Find the peaks that have an amplitude of at least 1 V.

findpeaks(select,Fs,'MinPeakHeight',1)
Figure contains an axes object. The axes object contains 2 objects of type line.

Find peaks which are at least 1 V higher than their neighbouring samples.

findpeaks(select,Fs,'Threshold',1)
Figure contains an axes object. The axes object contains 2 objects of type line.

Find peaks that are decreasing by at least 1 V on both sides before the signal reaches a higher value.

findpeaks(select,Fs,'MinPeakProminence',1)
Figure contains an axes object. The axes object contains 2 objects of type line.

Peaks wet signal

Sensors can return cut-off readings if the data is greater than the given saturation point. You may decide to ignore these peaks as meaningless or include them in the analysis.

Generate a signal that consists of a product of trigonometric frequency functions of 5 Hz and 3 Hz embedded in a white Gaussian noise deviation of 0.1 ². The signal is produced for one second at 100 Hz. Reset the random number generator for the reconstructed results.

rng default

fs = 1e2;
t = 0:1/fs:1-1/fs;

s = sin(2*pi*5*t).*sin(2*pi*3*t)+randn(size(t))/10;

Simulate the wet measurement by truncating each reading that is greater than the set, bound 0.32. Construct the wet signal.

bnd = 0.32;
s(s>bnd) = bnd;

plot(t,s)
xlabel('Time (s)')
Figure contains an axes object. The axes object contains an object of type line.

Find peaks of the signal. findpeaks reports only the rising edge of each flat peak.

[pk,lc] = findpeaks(s,t);

hold on
plot(lc,pk,'x')
Figure contains an axes object. The axes object contains 2 objects of type line.

Use a 'Threshold' name-value pair to exclude flat peaks. Require a minimum amplitude difference of 10

[pkt,lct] = findpeaks(s,t,'Threshold',1e-4);

plot(lct,pkt,'o','MarkerSize',12)
Figure contains an axes object. The axes object contains 3 objects of type line.

Findpeaks input parameters

Findpeaks Matlab

data - input data

vector

Input data as a vector. data must be valid and must have at least three elements.

Data types: double | single

x - locations

vector | datetime array

Locations as a vector or datetime array. x must increment monotonically and have the same length as data. If x is not used, then the data indexes are used as locations.

Data types: double | single | datetime

Fs - sample rate

positive scalar value

Sampling rate is a positive scalar quantity. Sampling rate is the number of samples per unit time. If time modulus is seconds, the sampling rate is a Hertz modulus.

Data types: double | single

FindPeaks Matlab name-value arguments

Define additional comma-separated Name,Value arguments. Name is the name of the argument and Value the corresponding value. Name must appear in quotes. You can specify multiple arguments as name and value pairs in any order, e.g.: Name1, Value1, …, NameN, ValueN.

Example: 'SortStr','descend','NPeaks',3 finds the three highest peaks of the signal.

NPeaks - Maximum number of peaks

positive integer scalar

Npeaks in FindPeaks Matlab is Maximum number of peaks to return as a comma-separated pair consisting of 'NPeaks' and a positive integer scalar. findpeaks acts from the first element of the input data and terminates when the number of peaks reaches the value of 'NPeaks'.

Data types: double | single

SortStr - Peaks sorting

'none' (default value) | 'ascend' | 'descend'

SortStr in FindPeaks Matlab function is peak sorting as a comma-separated pair consisting of 'SortStr' and one of these values:

  • 'none' returns peaks in the order in which they occur in the input data.
  • 'ascend' returns peaks in ascending or ascending order, from smallest to largest value.
  • 'descend' returns peaks in descending order, from largest to smallest value.

MinPeakHeight - Minimum peak height

-Inf (default value) | valid scalar

MinPeakHeight is minimum peak height in FindPeaks Matlab function as a comma-separated pair consisting of 'MinPeakHeight' and a valid scalar. Use this argument to have findpeaks return only that peaks higher than 'MinPeakHeight'. Defining a minimum peak height can reduce computation time.

Data types: double | single

MinPeakProminence - MinPeakHeight

0 (default value) | valid scalar

MinPeakProminence in FindPeaks Matlab function is a comma-separated pair consisting of 'MinPeakProminence' and a valid scalar. Use this argument to have findpeaks return only peaks that have a relative importance of at least 'MinPeakProminence'. For more information, see outstanding position.

Data types: double | single

Threshold - Minimum height difference

0 (default values) | non-negative real scalar

Threshold in FindPeaks Matlab function is minimum height difference between a peak and its neighbours as a comma-separated pair consisting of 'Threshold' and a non-negative real scalar. Use this argument to have findpeaks return only peaks that exceed their instantaneous neighbouring values by at least the value of 'Threshold'.

Data types: double | single

MinPeakDistance - Minimum peak distance

0 (default value) | positive real scalar

MinPeakDistance in FindPeaks Matlab function is the minimum peak distance as a comma-separated pair consisting of 'MinPeakDistance' and a positive real scalar. When you set a value for 'MinPeakDistance', the algorithm selects the highest peak in the signal and ignores all peaks in 'MinPeakDistance' from it. The function then repeats the procedure for the highest remaining peak and iterates until it has exhausted the peaks to consider.

If you specify a location vector, x, then 'MinPeakDistance' must be described in terms of x. If x is a datetime array, then specify 'MinPeakDistance' as a duration scalar or as a number described in days.

If you specify a sampling rate, Fs, then 'MinPeakDistance' should be described in terms of time.

If you do not specify any x or Fs, then 'MinPeakDistance' must be described in the sampling modules.

Use this argument to have findpeaks ignore the small peaks that occur around the larger peaks.

Data types: double | single | duration

WidthReference - Reference height for width measurements

'halfprom' (default value) | 'halfheight'

WidthReference in FindPeaks Matlab function is the reference height for width measurements as a comma-separated pair consisting of 'WidthReference' and any 'halfprom' or 'halfheight'. findpeaks estimates the width of the peak as the distance between the points where the descending signal interrupts the horizontal reference line. The height of the line is selected using the criterion specified in 'WidthReference':

  • 'halfprom' places the reference line below the peak at a vertical distance equal to half the peak outstanding position. See Eminent Position for more information.
  • 'halfheight' places the reference line at half the peak height. A line is truncated if any of its intersection points lies outside the boundary of the peaks selected by setting 'MinPeakHeight', 'MinPeakProminence', and 'Threshold'. The boundary between peaks is set by the horizontal position of the lowest gully between them. Peaks with a height less than zero are discarded.

The locations of the intersection points are calculated by linear interpolation.

MinPeakWidth - Minimum peak width

0 (default values) | positive real scalar

MinPeakWidth in FindPeaks Matlab function is the minimum peaks width as a comma-separated pair consisting of 'MinPeakWidth' and a positive valid scalar. Use this argument to select only peaks that have a width of at least 'MinPeakWidth'.

If you specify a location vector, x, then 'MinPeakWidth' must be described in terms of x. If x is a datetime array, then specify 'MinPeakWidth' as a duration scalar or as a number described in terms of days.

If you specify a sampling rate, Fs, then 'MinPeakWidth' must be described in terms of time.

If you do not specify any x or Fs, then 'MinPeakWidth' should be described in the sampling modules.

Data types: double | single | duration

MaxPeakWidth - Maximum peak width

Inf (default value) | positive real scalar

MaxPeakWidth in FindPeaks Matlab function is the maximum peak width as a comma-separated pair consisting of 'MaxPeakWidth' and a positive real scalar. Use this argument to select only peaks that have widths in the greater part of 'MaxPeakWidth'.

If you are specifying a location vector, x, then 'MaxPeakWidth' must be described in terms of x. If x is a datetime array, then specify 'MaxPeakWidth' as a duration scalar or as a number described in terms of days.

If you specify a sampling rate, Fs, then 'MaxPeakWidth' must be described in terms of time.

If you do not specify any x or Fs, then 'MaxPeakWidth' should be described in the sample modules.

Data types: double | single | duration

Annotate - The style of the graph

'peaks' (default value) | 'extents'

Annotate in FindPeaks Matlab function defines the style the graph as a comma-separated pair consisting of 'Annotate' and one of these values:

  • 'peaks' builds the signal and annotates the location and value of each peak.
  • 'extents' constructs the signal and annotates the location, value, width and prominence of each peak.

This argument is ignored if you call findpeaks with output arguments.

Findpeaks Matlab

FindPeaks output parameters

pks - Local maxima

vector

pks in FindPeaks Matlab function is the local maxima returned as a vector of signal values. If there are no local maxima, pks isempty.

locs - Peak locations

vector

locs in FindPeaks Matlab function returns peak locations returned as a vector.

If you specify a location vector, x, then locs contains x values in peak indices.

If you specify a sampling rate, Fs, then locs a numeric vector of time moments with a 1/Fs time difference between successive samples.

If you specify no x nor Fs, then locs a vector of integer indices.

w - Peak widths

vector

w in in FindPeaks Matlab function represents peak widths returned as a vector of real numbers. The width of each peak is calculated as the distance between the points to the left and right of the peak where the signal interrupts the reference line whose height is given by WidthReference. The points themselves are found by linear interpolation.

If you specify a location vector, x, then the widths are described in terms of x.

If you specify a sampling rate, Fs, then the widths are described in terms of time.

If you do not specify any x or Fs, then the widths are described in terms of sampling modules.

p - Peak prominences

vector

Peak outstanding positions returned as a vector of real numbers. The outstanding position of a peak is the minimum vertical distance that the signal must decrease on either side of the peak before or go back up a level higher than the peak or reach the endpoint. See Eminent Position for more information.

More on FindPeaks in Matlab

Overhanging position

The prominence of a peak is measured by how much a peak stands out because of its internal height and its position in relation to other peaks. A low isolated peak may be more prominent than one which is higher, but is otherwise a normal member of a high value area.

Measure the prominent position of the peak:

  • Place a marker at the peak.
  • Extend the horizontal line from the peak to the left and straight until the line does one of the following
  • Crosses the signal because there is a higher peak
  • Reaches the left or right end of the signal
  • Find the minimum of the signal in each of the two intervals given in Step 2. This point is either the gully or one of the signal endpoints.

Above the two interval minima sets the reference level. The height of the peak above this level is its outstanding position.

findpeaks makes no assumptions about the behaviour of the signal outside its endpoints, irrespective of their height. This is reflected in Steps 2 and 4 and often affects the value of the reference level. Consider, for example, the peaks of this signal: