Skip to content

Instantly share code, notes, and snippets.

@tonyfast
Last active July 23, 2019 21:38
Show Gist options
  • Select an option

  • Save tonyfast/d7f6212f86ee004a4d2b to your computer and use it in GitHub Desktop.

Select an option

Save tonyfast/d7f6212f86ee004a4d2b to your computer and use it in GitHub Desktop.
Generalized Peak and Valley Finding function in Matlab using the Image Processing Toolbox
%% Motivation
% This Matlab function is motivated by http://tonyfast.com/nsf-goali/2014/08/29/Peak-Finding/
%% Example use of Find_Peaks on a 2-D array
N = 100;
% Example Dataset
T = peaks( N );
%% Find Peaks using the default filter
Peaks_default = Find_Peaks( T );
%% Find Valleys using the default filter
Valleys_default = Find_Peaks( T, 'valley', true );
%% Change the size of the neighborhood to find Peaks
% Changing the size of the neighborhood can be effective for noisey datasets.
Peaks_Neighborhood = Find_Peaks( T, 'neighborhood', 11 );
%% Indices of Valleys and Peaks
% Use the ``find`` function to find the positions of the peaks or valleys
id = find( Peaks_Neighborhood );
[x y z] = ind2sub( size( T ), id );
function P = Find_Peaks( T, varargin )
% Finds Peaks or Valleys in an N-D matrix T.
% Requires the Image Processing Toolbox.
%
% Options
% 'neighborhood', an integer to design a cuboidal filter with edges of length ``r``
% default: r = 5
% 'valley', boolean value ``true`` and ``false`` find valleys and peaks respectively.
% default: false; % Find Peaks
%
% Returns Boolean matrix with dimensions equal to T. ``true`` entries indicate a peak or valley
% depending upon the flag used to call this function.
% Finds the peaks or valleys in the spatial correlation functions.
param = setparam( varargin, numel(T),size(T) );
% Design the filter
F = ones( param.neighborhood);
F( ceil(numel(F)./2) ) = 0;
if ~param.valley
P = T > imdilate( T, F );
else
P = T < imerode( T, F );
end
function param = setparam( varargin, N, sz )
if sz(2) == 1 & N == sz(1)
r = 1;
else
r = numel( sz );
end
param = struct( 'neighborhood', 5*ones(1,r),...
'valley', false);
if numel( varargin ) > 0
for ii = 1 : 2 :numel( varargin )
param = setfield( param, varargin{ii}, varargin{ii+1});
end
end
end %setparam
end %Find_Peaks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment