Department of Engineering

IT Services

Find local min and max values of experimental data with Matlab

Suppose you have some data in a vector y and you want to find the local maxima and minima. There are 2 main methods depending on the nature of the data

Number crunching

You can check each y value to see if it's greater than (or less than) both neighbouring values. You could use an explicit for loop to do this, but there are quicker ways. Below are 2 functions and an example of how to use them.

function minima = findminima(x)
%FINDMINIMA  Find location of local minima
%  From David Sampson
%  See also FINDMAXIMA

minima = findmaxima(-x);

function maxima = findmaxima(x)
%FINDMAXIMA  Find location of local maxima
%  From David Sampson
%  See also FINDMINIMA

% Unwrap to vector
x = x(:);
% Identify whether signal is rising or falling
upordown = sign(diff(x));
% Find points where signal is rising before, falling after
maxflags = [upordown(1)<0; diff(upordown)<0; upordown(end)>0];
maxima   = find(maxflags);


y=randn(10,1)*10
%find the indices of the local maxima
k=maxima(x)
%list the y values 
x(k)
%find the indices of the local mimima
k=mimima(x)
%list the y values 
x(k)

Differentiation

If the data is relatively smooth and could be approximated well by a function (and if you have the Symbolic Toolbox) you could use the methods on the curve fitting page then differentiate the resulting function to find the minima and maxima. This is likely to produce values that don't belong to your original data set. The following example uses a polynomial approximation.

 x=1:10;
 y=sin(x);
 [P,S] = polyfit(x,y,5); 
 d=polyder(P);
 % now find where d is 0
 roots(d)