index previous 

List of downloadable functions, scripts and spreadsheets

for "A Pragmatic Introduction to Signal Processing"

[Peak shape functions]  [Signal processing functions]  [Demonstration scripts]  [Interactive tools]  [MAT files]  [Spreadsheets]

You can click or click on these links to inspect the code, or you can right-click and select "Save link as..." to download them to your computer. Place the Matlab/Octave functions and scripts into the Matlab or Octave "path", so you can use them just like any other built-in function. Type "help <name>" at the command prompt (where "<name>" is the name of the script) to display the built-in help for these functions and scripts. The complete set of all these functions, scripts, tools, spreadsheets and documentation files are included in the site archive ZIP file (approx. 82 MBytes).

Peak shape functions (for Matlab and Octave)

Most of these shape function take three required input arguments: the independent variable ("x") vector, the peak position, and the peak width  (usually the full width at half maximum). The functions marked 'variable shape' require an additional fourth input argument that determines the exact peak shape.

Gaussian
exponentially-broadened Gaussian (variable shape)
bifurcated Gaussian (variable shape)
Flattened Gaussian (variable shape)
Clipped Gaussian (variable shape)
Lorentzian (aka 'Cauchy')
exponentially-broadened Lorentzian (variable shape)
Clipped Lorentzian (variable shape)
Gaussian/Lorentzian blend (variable shape)
Voigt profile (variable shape)
lognormal
logistic distribution
Pearson 5 (variable shape)
alpha function
exponential pulse
up-sigmoid (logistic function or "S-shaped")
down-sigmoid ("Z-shaped")
Breit-Wigner-Fano resonance (BWF) (variable shape)
triangle
peakfunction.m, a function that generates any of the above peak types specified by number.
tsallis distribution (variable shape, similar to Pearson 5)

Note:

modelpeaks, a function that simulates multi-peak time-series signal data consisting of any number of  peaks of the same shape. Syntax is model=modelpeaks(x, NumPeaks, peakshape, Heights, Positions, Widths, extra), where 'x' is the independent variable vector, 'NumPeaks' in the number of peaks, 'peakshape' is the peak shape number, 'Heights' is the vector of peak heights, 'Positions' is the vector of peak positions,'Widths' is the vector of peak widths, and 'extra' is the additional shape parameter required by the exponentially broadened, Pearson, Gaussian/Lorentzian blend, BiGaussian and BiLorentzian shapes. Type 'help modelpeaks'.  To create noisy peaks, use one of the following noise functions to create some random noise to add to the modelpeaks array.

  modelpeaks2, a function that simulates multi-peak time-series signal data consisting of any number of  peaks of different shapes. Syntax is y=modelpeaks2(t,Shape,Height,Position,Width,extra)where 'shape' is a vector of peak type numbers and the other input arguments are the same as for modelpeaks.m. Type 'help modelpeaks2'

  ShapeDemo demonstrates the 16 basic peak shapes graphically, showing the variable-shape peaks as multiple lines.

Signal processing functions (for Matlab and Octave)

whitenoise, pinknoise, bluenoise  propnoise, sqrtnoise, bimodal: different types of random noise that might be encountered in physical measurements. Type "help whitenoise", etc, for help and examples.

IQrange, computes the “interquartile range” (IQR), an alternative to standard deviation for computing the dispersion (spread) of a data set that contains outliers. For a normal distribution, the interquartile range is equal to 1.34896 times the standard deviation. Syntax is b = IQrange(a)

fastsmooth, fast data smoothing. The syntax is SmoothY=fastsmooth(Y,w,type,ends). See Smoothing.html#Matlab

medianfilter, median-based filter for eliminating narrow spike artifacts. The syntax is mY=medianfilter(y,Width), where "Width" is the number of points in the spikes that you wish to eliminate. Type "help medianfilter" at the command prompt.

deriv, deriv2, deriv3, deriv4, derivxy and secderivxy, simple functions for computing the derivatives of time-series data.  See Differentiation.html#Matlab

enhance, Resolution enhancement (peak sharpening) by the even-derivative method. Syntax is Enhancedsignal=enhance(signal, factor1, factor2, SmoothWidth). See ResolutionEnhancement.html

ProcessSignal, a Matlab/Octave command-line function that performs smoothing, differentiation, peak sharpening, and median filtering on the time-series data set x,y (column or row vectors). Similar to iSignal, without the plotting and interactive keystroke controls. Type "help ProcessSignal". Returns the processed signal as a vector that has the same shape as x, regardless of the shape of y. The syntax is Processed=ProcessSignal(x,y,DerivativeMode,w,type,ends,Sharpen,factor1,factor2,SlewRate,MedianWidth). See Smoothing.html#Matlab.

PlotFrequencySpectrum.m can plot the frequency spectrum or periodogram of the signal x,y on linear or log coordinates. The syntax is  PowerSpectrum=PlotFrequencySpectrum(x,y,plotmode,XMODE,LabelPeaks). Type "help PlotFrequencySpectrum" for details. Try this example: x=[0:.01:2*pi]';y=sin(200*x)+randn(size(x));subplot(2,1,1);plot(x,y);subplot(2,1,2);PowerSpectrum=PlotFrequencySpectrum(x,y,1,0,1);

FouFilter, Fourier filter function, with variable band-pass, low-pass, high-pass, or notch (band reject). The syntax is ry=FouFilter(y, samplingtime, centerfrequency, frequencywidth, shape, mode. See FourierFilter.html

ExpBroaden, exponential broadening.  Syntax is yb = ExpBroaden(y,t). Convolutes the vector y with an exponential decay of time constant t. Mentioned on SignalsAndNoise.html and InteractivePeakFitter.htm

plotit, (previous named 'plotfit'), a function for plotting x,y data in matrices or in separate vectors. Optionally fits the data with a polynomial of order n if n is included as the third input argument. In version 5 the syntax is  [coef, RSquared, StdDevs] = plotit(x,y) or plotit(x,y,n). It returns the best-fit coefficients 'coeff', in decreasing powers of x, the standard deviations of those coefficients 'StdDevs' in the same order, and the R-squared value.  Type "help plotit" at the command prompt for syntax options. See SignalsAndNoise.html. This function works in Matlab or Octave and has a built-in bootstrap routine that computes coefficient error estimates by the bootstrap method and returns the results in the matrix "BootResults" (of size 5 x polyorder+1). The calculation is triggered by including a 4th output argument, e.g. [coef, RSquared, StdDevs, BootResults]= plotit(x,y,polyorder). This works for any positive integer polynomial order. See CurveFitting.html#Matlab. The variation plotfita animates the bootstrap process for instructional purposes.  The variation logplotfit plots and fits log(x) vs log(y), for data that follows a power law relationship or that covers a very wide numerical range.

trypoly(x,y) fits the data in x,y with a series of polynomials of degree 1 through length(x)-1 and returns the coefficients of determination (R2) of each fit as a vector, allowing you to evaluate how polynomials of various orders fit your data. To plot as a bar graph, write bar(trypoly(x,y)); xlabel('Polynomial Order'); ylabel('Coefficient of Determination (R2)'). Here's an example.

trydatatrans(x,y,polyorder) tries 8 different simple data transformations on the data x,y, fits the transformed data to a polynomial of order 'polyorder', displays results graphically in 3 x 3 array of small plots and returns the R2 values in a vector.

condense(y,n), function to reduce the length of  vector y by replacing each group of n successive values by their average. condensem.m works for matrices. Mentioned on Smoothing.html and iSignal.html

val2ind(x,val), returns the index and the value of the element of vector x that is closest to val. Example:  if x=[1 2 4 3 5 9 6 4 5 3 1], then val2ind(x,6)=7 and val2ind(x,5.1)=[5 9]. For some example of how this is used, see PeakFindingandMeasurement.htm#UsingP.

findpeaksG and findvalleys, automatically find the peaks or valleys in a signal and and measure their position, height, width and area by curve fitting. The syntax is P= findpeaksG(x, y, SlopeThreshold, AmpThreshold, SmoothWidth, FitWidth, smoothtype). Returns a matrix containing the peak parameters for each detected peak. For peak of Lorentzian shape, use findpeaksL.m instead. See PeakFindingandMeasurement.htm#findpeaks.

findpeaksplot.m is a simple variant of findpeaksG.m that also plots the x,y data and numbers the peaks on the graph (if any are found).

 findpeaksT.m and findpeaksTplot.m are variants of findpeaks that measure the peak parameters by constructing a triangle around each peak with sides tangent to the sides of the peak. Graphic example.

findpeaksb.m is a variant of findpeaksG.m that more accurately measures peak parameters by using iterative least-square curve fitting based on peakfit.m. This yields better peak parameter values that findpeaks alone, because it fits the entire peak, not just the top part, and because it has provision for a large number of different peak shapes and for background subtraction (linear or quadratic). Works best with isolated peaks that do not overlap. Syntax is P = findpeaksb(x,y, SlopeThreshold, AmpThreshold, smoothwidth, peakgroup, smoothtype, window, PeakShape, extra, AUTOZERO). The first seven input arguments are exactly the same as for the findpeaksG.m function; if you have been using findpeaks or iPeak to find and measure peaks in your signals, you can use those same input argument values for findpeaksb.m. Type "help findpeaksb" at the command prompt. See PeakFindingandMeasurement.htm. Compare this to the related findpeaksfit.m and findpeaksb3, next.

findpeaksb3.m is a variant of findpeaksb.m that fits each detected peak together with the previous and following peaks found by findpeaksG.m. It deals better with overlapping peaks than findpeaksb.m does, and it handles larger numbers of peaks better than findpeaksfit.m, but it fits only those peaks that are found by findpeaks. The syntax is function P=findpeaksb3(x,y, SlopeThreshold, AmpThreshold, smoothwidth, peakgroup, smoothtype, PeakShape, extra, NumTrials, AUTOZERO, ShowPlots). The first seven input arguments are exactly the same as for the findpeaksG.m function; if you have been using findpeaks or iPeak to find and measure peaks in your signals, you can use those same input argument values for findpeaksb3.m. The demonstration script DemoFindPeaksb3.m shows how findpeaksb3 works with multiple overlapping peaks. 

findpeaksfit.m is essentially a serial combination of findpeaksG.m and peakfit.m. It uses the number of peaks found by findpeaks and their peak positions and widths as input for the peakfit.m function, which then fits the entire signal with the specified peak model. This deals with non-Gaussian and overlapped peaks better than findpeaks alone. However, it fits only those peaks that are found by findpeaks. The syntax is [P, FitResults, LowestError, BestStart, xi, yi] = findpeaksfit(x,y, SlopeThreshold, AmpThreshold, smoothwidth, peakgroup, smoothtype, peakshape, extra, NumTrials, autozero, fixedparameters, plots). The first seven input arguments are exactly the same as for the findpeaksG.m function; if you have been using findpeaks or iPeak to find and measure peaks in your signals, you can use those same input argument values for findpeaksfit.m. The remaining six input arguments of findpeaksfit.m are for the peakfit function; if you have been using peakfit.m or ipf.m to fit peaks in your signals, you can use those same input argument values for findpeaksfit.m. Type "help findpeaksfit" for more information. See PeakFindingandMeasurement.htm#findpeaksfit.

peakstats.m uses the same algorithm as findpeaksG.m, but it computes and returns a table of summary statistics of the peak intervals (the x-axis interval between adjacent detected peaks), heights, widths, and areas, listing the maximum, minimum, average, and percent standard deviation of each, and optionally displaying the x,t data plot with numbered peaks in figure window 1, the table of peak statistics in the command window, and the histograms of the peak intervals, heights, widths, and areas in figure window 2. Type "help peakstats". See PeakFindingandMeasurement.htm

findpeaksnr.m is a variant of findpeaksG.m that additionally computes the signal-to-noise ratio (SNR) of each peak and returns it in the 5th column of the peak table. The SNR is computed as the ratio of the peak height to the root-mean-square residual (difference between the actual data and the least-squares fit over the top part of the peak). See PeakFindingandMeasurement.htm

FindpeaksE.m is a variant of findpeaksG.m that additionally estimates the percent relative fitting error of each peak (assuming a Gaussian peak shape) and returns it in the 6th column of the peak table. 

findpeaksGSS.m and findpeaksLSS.m, for Gaussian and Lorentzian peaks respectively, are variants of findpeaksG.m and findpeaksL.m that additionally compute the 1% start and end positions return them in the 6th and 7th columns of the peak table.  See PeakFindingandMeasurement.htm

findsquarepulse.m (syntax S=findsquarepulse(t,y,threshold) locates the rectangular pulses in the signal t,y that exceed a y-value of "threshold" and determines their start time, average height (relative to the adjacent baseline) and width. DemoFindsquare.m creates a test signal and calls findsquarepulse.m to demonstrate.

findsteps.m P=findpulses(x,y,SlopeThreshold,AmpThreshold,SmoothWidth,peakgroup) locates positive transient steps in noisy x-y time series data, by computing the first derivative of y that exceed SlopeThreshold, computes the step height as the difference between the maximum and minimum y values over a number of data point equal to "Peakgroup". Returns list (P) with step number, x and y positions of the bottom and top of each step, and the step height of each step detected; "SlopeThreshold" and "AmpThreshold" control step sensitivity; higher values will neglect smaller features. Increasing "SmoothWidth" ignores small sharp false steps caused by random noise or by "glitches" in the data acquisition. See findsteps.png for a real example. findstepsplot.m plots the signal and numbers the peaks.

idpeaks, peak identification function. The syntax is [IdentifiedPeaks,AllPeaks]= idpeaks(DataMatrix, AmpT, SlopeT, sw, fw, maxerror, Positions, Names). Locates and identifies peaks in DataMatrix that match the position of peaks in the array "Positions" with matching names "Names".  Type "help idpeaks" for more information. Download and extract idpeaks.zip for a working example, or see Example 8 on PeakFindingandMeasurement.htm

cls.m is a classical least-squares function that you can use to fit a computer-generated model, consisting of any number of peaks of known shape, width, and position, but of unknown height, to a noisy x,y signal.  The syntax is heights= cls(x,y,NumPeaks,PeakShape,Positions,Widths,extra) where x and y are the vectors of measured signal (e.g. x might be wavelength and y might be the absorbance at each wavelength), 'NumPeaks' is the number of peaks, 'PeakShape' is the peak shape number (1=Gaussian, 2=Lorentzian, 3=logistic, 4=Pearson, 5=exponentially broadened Gaussian; 6=equal-width Gaussians; 7=Equal-width Lorentzians; 8=exponentially broadened equal-width Gaussian, 9=exponential pulse, 10=sigmoid, 11=Fixed-width Gaussian, 12=Fixed-width Lorentzian; 13=Gaussian/Lorentzian blend; 14=BiGaussian, 15=BiLorentzian), 'Positions' is the vector of peak positions on the x axis (one entry per peak), 'Widths' is the vector of peak widths in x units (one entry per peak), and 'extra' is the additional shape parameter required by the exponentially broadened, Pearson, Gaussian/Lorentzian blend, BiGaussian and BiLorentzian shapes. cls.m returns a vector of measured peak heights for each peak. See clsdemo.m

gaussfit, function that performs least-squares fit of a single Gaussian function to an x,y data set, returning the height, position, and width of the best-fit Gaussian. Syntax is [Height,Position,Width] = gaussfit(x,y). The similar function lorentzfit.m performs the calculation for a Lorentzian peak shape. See CurveFitting.html#Transforming. The similar function plotgaussfit does the same thing as gaussfit.m but also plots the data and the fit. The data set can not contain any zero or negative values.

bootgaussfit is an expanded version of gaussfit that provides optional plotting and error estimation. The syntax is [Height,Position,Width,BootResults] = bootgaussfit(x,y,plots). If plots=1, plots the raw data as red dots and the best-fit Gaussian as a line. If the 4th output argument (BootResults) is supplied, computes peak parameter error estimates by the bootstrap method.

peakfit, command-line function for multiple peak fitting by iterative non-linear least-squares. The syntax is peakfit(signal, center, window, NumPeaks, peakshape, extra, NumTrials, start, AUTOZERO, fixedwidth, plots, bipolar, minwidth). Type "help peakfit". See InteractivePeakFitter.htm#command.  Test the installation by running testpeakfit.m script.

isignal, can be used as a command-line function in Octave, but its interactive features currently work only in Matlab. The syntax is isignal(DataMatrix, xcenter, xrange, SmoothMode, SmoothWidth, ends, DerivativeMode, Sharpen, Sharp1, Sharp2, SlewRate, MedianWidth). See iSignal.

Demonstration scripts and functions (for Matlab and Octave)

noisetest.m is a self-contained Matlab/Octave function for demonstrating different noise types. It plots Gaussian peaks with four different types of added noise with the same standard deviation: constant white noise; constant pink (1/f) noise; proportional white noise; and square-root white noise, then fits a Gaussian model to each noisy data set and computes the average and the standard deviation of the peak height, position, width and area for each noise type. See SignalsAndNoise.html.

NoiseColorTest.m, a function that demonstrates the effect of smoothing white, pink, and blue noise.

CurvefitNoiseColorTest.m, a function that demonstrates the effect of white, pink, and blue noise on curve fitting a single Gaussian peak.

RANDtoRANDN.m is a script that demonstrates how the expression 1.73*(RAND()-RAND()+RAND()-RAND()) approximates normally-distributed random numbers with zero mean and a standard deviation of 1.
See SignalsAndNoise.html.

CentralLimitDemo.m, script that demonstrates that the more independent uniform random variables are combined, the probability distribution becomes closer and closer to normal (Gaussian). See SignalsAndNoise.html.

SmoothExperiment.m, simple script that demonstrates the effect of smoothing on the position, width, and height of a single Gaussian peak. Requires that the fastsmooth.m and peakfit.m functions be installed.  See Smoothing.html#Matlab

smoothdemo.m, self-contained function that compares the performance and speed of four types of smooth operations: (1) sliding-average, (2) triangular, (3) pseudo-Gaussian (equivalent to three passes of a sliding-average), and (4) Savitzky-Golay. These smooth operations are applied to a single noisy Gaussian peak. The peak height of the smoothed peak, the standard deviation of the smoothed noise, and the signal-to-noise ratio are all measured as a function of smooth width. See Smoothing.html#Matlab

SmoothOptimization.m, script that shows why you don't need to smooth data prior to least-squares curve fitting; it compares the effect of smoothing on the signal-to-noise ratio of peak height of a noisy Gaussian peak, using three different measurement methods. Requires that the fitgauss2.m, gaussfit.m, gaussian.m, and fminsearch.m functions be installed. See CurveFittingC.html#Smoothing.

derivdemo1.m, a function that demonstrates the basic shapes of derivatives. See Differentiation.html#BasicProperties

derivdemo2.m, a function that demonstrates the effect of peak width on the amplitude of derivatives. See Differentiation.html#BasicProperties

derivdemo3.m, a function that demonstrates the effect of smoothing on the first derivative of a noisy signal. See Differentiation.html#Smoothing

derivdemo4.m, a function that demonstrates the effect of smoothing on the second derivative of a noisy signal. See Differentiation.html#Smoothing

DerivativeDemo.m is a self-contained Matlab/Octave demo function that uses ProcessSignal.m and plotit.m to demonstrate an application of differentiation to the quantitative analysis of a peak buried in an unstable background (e.g. as in various forms of spectroscopy). The object is to derive a measure of peak amplitude that varies linearly with the actual peak amplitude and is minimally effected by the background and the noise. To run it, just type DerivativeDemo at the command prompt. You can change several of the internal variables (e.g. Noise, BackgroundAmplitude) to make the problem harder or easier. Note that, despite the fact that the magnitude of the derivative is numerically smaller than the original signal (because it has different units), the signal-to-noise ratio of the derivative is better, and the derivative signal is linearly proportional to the actual peak height, despite the interference of large background variations and random noise. See Differentiation.html

deconvolutionexample.m, a simple example script that demonstrates the use of the Matlab Fourier deconvolution 'deconv' function. See Deconvolution.html.

DeconvDemo.m, a Fourier deconvolution demo script with a signal containing four Gaussians broadened by an exponential function.

LinearFiMC.m, a script that compares standard deviation of slope and intercept for a first-order least-squares fit computed by random-number simulation of 1000 repeats to predictions made by closed-form algebraic equations. See CurveFitting.html#Reliability

  TestLinearFit.m, a script that compares standard deviation of slope and intercept for a first-order least-squares fit computed by random-number simulation of 1000 repeats to predictions made by closed-form algebraic equations and to the bootstrap sampling method. Several different noise models can be selected by commenting/uncommenting the code in lines 20-26. See CurveFitting.html#Reliability

GaussFitMC.m, a function that demonstrates Monte Carlo simulation of the measurement of the peak height, position, and width of a noisy x,y Gaussian peak. See CurveFitting.html

GaussFitMC2.m, a function that demonstrates measurement of the peak height, position, and width of a noisy x,y Gaussian peak, comparing the gaussfit parabolic fit to the fitgaussian iterative fit. See CurveFitting.html

RegressionDemo.m, script that demonstrates the classical least squares procedure for a simulated absorption spectrum of a 5-component mixture at 100 wavelengths. Requires that gaussian.m be installed. See CurveFittingB.html

clsdemo.m is a demonstration script that creates a noisy signal, fits it with cls.m, computes the accuracy of the measured heights, then repeats the calculation using iterative least-squares for comparison.

SmoothVsFit.m is a demonstration script that compares iterative least-square fitting to two simpler methods for the measurement of the peak height of a single peak of uncertain width and position and with a very poor signal-to-noise ratio of 1. The accuracy and precision of the methods are compared. SmoothVsFitArea.m does the same thing for the measurement of peak area. See CurveFittingC.html#Fitting_peaks.

CLSvsINLS.m is a script that compares the classical least-squares (CLS) method with three different variations of the iterative method (INLS) method for measuring the peak heights of three Gaussian peaks in a noisy test signal, demonstrating that the fewer the number of unknown parameters, the faster and more accurate is the peak height calculation.

BlackbodyDataFit.m, a script that demonstrates iterative least-squares fitting of the blackbody equation to a measured spectrum of an incandescent body, for the purpose of estimating its color temperature. See CurveFittingC.html#Matlab
   
Demofitgauss.m a script that demonstrates iterative fitting a single Gaussian function to a set of data, using the fminsearch function. Requires that gaussian.m and fmsearch.m (in the "Optim 1.2.1" package) be installed. Demofitgaussb.m and fitgauss2b.m illustrate a modification of this technique to accommodate shifting baseline (Demofitlorentzianb.m and fitlorentzianb.m for Lorentzian peaks). This modification is now incorporated to peakfit.m (version 4.2 and later), ipf.m (version 9.7 amd later), findpeaksb.m (version 3 and later), and findpeaksfit, (version 3 and later)See CurveFittingC.html#Matlab

Demofitgauss2.m a script that demonstrates iterative fitting of two overlapping Gaussian functions to a set of data, using the fminsearch function. Requires that gaussian.m and fmsearch.m (in the "Optim 1.2.1" package) be installed. Demofitgauss2b.m is the baseline-corrected extension. See CurveFittingC.html#Matlab

VoigtFixedAlpha.m and VoigtVariableAlpha.m demonstrate two different ways to fit peaks with variable shapes, such as the Voigt profile, Pearson, Gauss-Lorentz blend, and the bifurcated and exponentially-broadened shapes, which are defined not only by a peak position, height, and width, but also by an additional "shape" parameter that fine-tunes the shape of the peak. If that parameter is equal for all peaks in a group, it can be passed as an additional input argument to the shape function, as shown in VoigtFixedAlpha.m. If the shape parameter is allowed to be different for each peak in the group and is to be determined by iteration (just as is position and width), then the routine must be modified to accommodate three, rather than two, iterated variables, as shown in VoigtVariableAlpha.m. Although the fitting error is lower with variable alphas, the execution time is longer and the alphas values so determined are not very stable, with respect to noise in the data and the starting guess values, especially for multiple peaks. See CurveFittingC.html#Fitting_peaks

 Demofitmultiple.m.  Demonstrates an iterative fit to sets of computer-generated noisy peaks of different types, knowing only the shape types and variable shape parameters of each peak. Iterated parameters are shape, height, position, and width of all peaks. Requires the fitmultiple.m and peakfunction.m functions. View screen shot. See CurveFittingC.html#Fitting_peaks

BootstrapIterativeFit.m, a function that demonstrates bootstrap estimation of the variability of an iterative least-squares fit to a single noisy Gaussian peak. Form is: BootstrapIterativeFit(TrueHeight, TruePosition, TrueWidth, NumPoints, Noise, NumTrials). See CurveFitting.html#Bootstrap

BootstrapIterativeFit2.m, a function that demonstrates bootstrap estimation of the variability of an iterative least-squares fit to two noisy Gaussian peaks. Form is: BootstrapIterativeFit2(TrueHeight1, TruePosition1, TrueWidth1, TrueHeight2, TruePosition2, TrueWidth2, NumPoints, Noise, NumTrials). See CurveFitting.html#Bootstrap

DemoPeakfitBootstrap.m. Self-contained demonstration function for peakfit.m, with built-in signal generator. Demonstrates bootstrap error estimation. See CurveFitting.html#Bootstrap

DemoPeakfit.m, Demonstration script (for peakfit.m) that generates an overlapping peak signal, adds noise, fits it with peakfit.m, then computes the accuracy and precision of peak parameter measurements. Requires that peakfit.m be installed. See InteractivePeakFitter.htm#peakfitdemos

DemoPeakFitTime.m is a simple script that demonstrates how to use peakfit.m to apply multiple curve fits to a signal that is changing with time. The signal contains two noisy Gaussian peaks in which the peak position of the second peak increases with time and the other parameters remain constant (except for the noise). The script creates a set of 100 noisy signals (on line 5) containing two Gaussian peaks where the position of the second peak changes with time (from x=6 to 8) and the first peak remains the same. Then it fits a 2-Gaussian model to each of those signals (on line 8), displays the signals and the fits graphically with time as a kind of animation, then plots the measured peak position of the two peaks vs time on line 12.

demoipeak.m is a simple demo script that generates a noisy signal with peaks, calls iPeak, and then prints out a table of the actual peak parameters and a list of the peaks detected and measured by iPeak for comparison. Before running this demo, ipeak.m must be downloaded and placed in the Matlab path.


DemoFindPeak.m, a demonstration script using the findpeaks function on noisy synthetic data. Numbers the peaks and prints out the peak parameters  in the command window. Requires that gaussian.m and findpeaksG.m be installed. See PeakFindingandMeasurement.htm#findpeaks.

DemoFindPeakSNR is a variant of DemoFindPeak.m that uses findpeaksnr.m to compute the signal-to-noise ratio (SNR) of each peak and returns it in the 5th column. 

triangulation.m is a demo that compares findpeaksG, which determines peak parameters by curve-fitting a Gaussian to the center of each peak, to findpeaksT, which determines peak parameters by drawing a triangle around each peak with sides that are tangent to the sides of the peak.

  testpeakfit.m, a test script that demonstrates 26 different examples on InteractivePeakFitter.htm#Examples.  Use for testing that peakfit and related functions are properly installed. Updated for peakfit 6.

iPeakEnsembleAverageDemo.m is  a demonstration of iPeak's ensemble average function. In this example, the signal contains a repeated pattern of two overlapping Gaussian peaks, 12 points apart, both of width 12, with a 2:1 height ratio. These patterns occur a random intervals throughout the recorded signal, and the random noise level is about 10% of the average peak height. Using iPeak's ensemble average function (Shift-E), the patterns can be averaged and the signal-to-noise ratio significantly improved.

ShapeTest.m creates a test signal consisting of a single (asymmetrical) peak, adds random white noise, fits it with six different candidate model peak shapes using peakfit.m, plots each fit in a separate figure window, and prints out a table of fitting errors in the command window. In this particular case, the last two model shapes almost equally well.

Peakfit Time Tests. These are a series of scripts that demonstrate how the execution time of the peakfit.m function varies with the peak shape (PeakfitTimeTest2.m and PeakfitTimeTest2a.m, with number of peaks in the model (PeakfitTimeTest.m), and with the number of data points in the fitted region (PeakfitTimeTest3.m). This issue is discussed on InteractivePeakFitter.htm#time.

  peakfitVSfindpeaks.m  performs a direct comparison of the accuracy of findpeaksG vs peakfit. This script generates four very noisy peaks of different heights and widths, then applies findpeaksG.m and peakfit.m to measure the peaks and compares the results. The peaks detected by findpeaks are labeled "Peak 1", "Peak 2", etc. If you run this script several times, you'll find that both methods work well most of the time, with peakfit giving smaller errors in most cases, but occasionally findpeaks will miss the first (lowest) peak and rarely it will detect an extra peak that is not there if the signal is very noisy.

tfit.m, a self-contained command-line Matlab/Octave function that demonstrates a computational method for quantitative analysis by multiwavelength absorption spectroscopy which uses convolution and iterative curve fitting to correct for spectroscopic non-linearity. The syntax is tfit(TrueAbsorbance). TFitStats.m is a script that demonstrates the reproducibility of the method. TFitCalCurve.m compares the calibration curves for single-wavelength, simple regression, weighted regression, and TFit methods. TFit3.m is a demo function for a mixture of 3 absorbing components; the syntax is TFit3(TrueAbsorbanceVector), e.g. TFit3([3 .2 5]). Download all these as a ZIP file.

CaseStudyC.m is a self-contained Matlab/Octave demo function that demonstrates the application of several techniques described on this site to the quantitative measurement of a peak buried in an unstable background, a situation that can occur in the quantitative analysis applications of various forms of spectroscopy and remote sensing. See Case Studies C.

Keystroke-operated interactive signal processing tools (for Matlab)

  iSignal performs smoothing, median filtering, differentiation, peak sharpening, least-squares measurements of peak position, height, width, and area, signal and noise amplitudes, frequency spectra in selected regions of the signal, and signal-to-noise ratio of peaks. (m-file link: isignal.m)Click here to download the ZIP file "iSignal4.zip"

iPeak automatically finds and measures multiple peaks in a signal. (m-file link: ipeak.m). Check out the Animated step-by-step instructions. The ZIP file ipeak6.zip contains several demo scripts (ipeakdemo.m, ipeakdemo1.m, etc) that illustrate various aspects of the iPeak function and how it can be used effectively. testipeak.m is a script that tests for the proper installation and operation of iPeak by running quickly through all eight examples and six demos for iPeak on http://terpconnect.umd.edu/~toh/spectrum/PeakFindingandMeasurement.htm#ipeak. Assumes that ipeakdata.mat has been loaded into the Matlab workspace.

ipf, is an interactive multiple peak fitter (m-file link: ipf.m). It uses iterative nonlinear least-squares to fit any number of overlapping peaks of the same or different peak shapes to x-y data sets. Demoipf.m is a demonstration script for ipf.m, with a built-in simulated signal generator. The true values of the simulated peak positions, heights, and widths are displayed in the Matlab command window, for comparison to the FitResults obtained by peak fitting.  Animated step-by-step instructions . You can also download a ZIP file containing ipf.m plus some examples and demos.

Note: These last three interactive functions, iPeak, iSignal, and ipf, all have several keystroke commands in common: all share the same set of pan and zoom keys (cursor arrow keys, < and > keys, [ and ] keys, etc) to adjust the portion of the signal that is displayed in the upper panel. All use the K key to display the list of keystroke commands. All use the T key to cycle through the four baseline connection modes. All use the Shift-Ctrl-S, Shift-Ctrl-F, and Shift-Ctrl-P keys to transfer the current signal between iSignal, ipf, and iPeak, respectively. To make it easier to transfer settings from one of these functions to other related functions, all use the W key to print out the syntax of other related functions, with the pan and zoom settings and other numerical input arguments specified, ready for you to Copy, Paste and edit into your own scripts or back into the command window. For example, you can convert a curve fitting operation performed in ipf.m into the command-line peakfit.m function; or you can convert a peak finding operation performed in ipeak.m into a command-line findpeaksG.m or findpeaksb.m functions.

 iFilter, interactive Fourier filter. (m-file link: ifilter.m), which uses the pan and zoom keys to control the center frequency and the filter width. Select from low-pass, high-pass, band-pass, band-reject, harmonic comb-pass, or harmonic comb-reject filters.

TFit, a method for quantitative absorption spectroscopy. (m-file links: TFitDemo.m demonstrates the application for a single component; TFit3Demo.m demonstrates the application to a three-component mixture). Download all these as a ZIP file. Animated example.

iPower, interactive power spectrum demonstrator. (m-file link: ipower.m). Slideshow of examples.

Which to use: iPeak or Peakfit?  Try these Matlab demo functions that compare iPeak.m with Peakfit.m for signals with a few peaks and signals with many peaks and that shows how to adjust iPeak to detect broad or narrow peaks. These are self-contained demos that include all required sub-functions. Just place them in your path and type their name at the command prompt.  You can download all these demos together in idemos.zip.

MAT files (for Matlab and Octave)

DataMatrix2 is a computer-generated test signal consisting of 16 symmetrical Gaussian peaks with random white noise added. Can be used to test the peakfit.m function. See CurveFittingC.html#Exponential_broadening

DataMatrix3 is a computer-generated test signal consisting of 16 Gaussian peaks with random white noise that have been exponentially broadened with a time constant of 33 x-axis units. See CurveFittingC.html#Exponential_broadening

ipeakdata.mat, data set for demonstrating idpeaks.m or the peak identification function of iPeak; includes a high-resolution atomic spectrum and a table of known atomic emission wavelenghs. See PeakFindingandMeasurement.htm#ipeak

udx.txt: a text file containing the 2 x 1091 matrix that consists of two Gaussian peaks with different sampling intervals.  It's used as an example in Smoothing and in Curve Fitting

Spreadsheets (for Excel or OpenOffice Calc)

Note 1: If you see a yellow bar at the top of the spreadsheet window, click the "Enable Editing" button.
Note 2: Some browsers change the file extension of these spreadsheets to .zip when they are downloaded; if that happens, rename the files to their original file extensions (.ods, .xls, or .xlsx) before running them. 

Random numbers and noise.
The spreadsheets RandomNumbers.xls (for Excel) and RandomNumbers.ods (for OpenOffice) demonstrate how to create a column of normally-distributed random numbers (like white noise) in a spreadsheet that has only a uniformly-distributed random number function. Also shows how to compute the interquartile range and the peak-to-peak value and how they compare to the standard deviation. See SignalsAndNoise.html

Smoothing.
The spreadsheets smoothing.ods (for Open office Calc) and smoothing.xls (for Microsoft Excel) demonstrate a 7-point rectangular (sliding average) in column C and a 7-point triangular smooth in column E, applied to the data in column A. You can type in (or Copy and Paste) any data you like into column A. You can extend the spreadsheet to longer columns of data by dragging the last row of columns A, C, and E down as needed. You can change the smooth width by changing the equations in columns C or E. The spreadsheet MultipleSmoothing.xls for Excel or Calc demonstrates a more flexible method that allows you to define various types of smooths by typing a few integer numbers.  UnitGainSmooths.xls and UnitGainSmooths.ods  contain a collection of unit-gain convolution coefficients for rectangular and triangular smooths of width 3 to 29 that you can Copy and Paste into your own spreadsheets. Convolution.txt lists some simple whole-number coefficient sets for performing single and multipass smoothing.See Smoothing.html

Differentiation. DerivativeSmoothingOO.ods (for OpenOffice Calc) and DerivativeSmoothing.xls (for Excel) demonstrate the application of differentiation for measuring the amplitude of a peak that is buried in a broad curved background. Differentiation and smoothing are both performed together. Higher order derivatives are computed by taking the derivatives of previously computed derivatives. SecondDerivativeXY2.xlsx, demonstrates locating and measuring changes in the second derivative (a measure of curvature or acceleration) of a time-changing signal, showing the apparent increase in noise caused by differentiation and the extent to which the noise can be reduced by smoothing (in this case by two passes of a 5-point triangular smooth). The smoothed second derivative shows a large peak at the point where the acceleration changes and plateaus on either side showing the magnitude of the acceleration before and after the change (2 and 4, respectively). Convolution.txt lists simple whole-number coefficient sets for performing differentiation and smoothing.  CombinedDerivativesAndSmooths.txt lists the sets of unit-gain coefficients that perform 1st through 4th derivatives with various degrees of smoothing.  See Differentiation.html

Convolution. Spreadsheets can be used to perform "shift-and-multiply" convolution for small data sets (for example, MultipleConvolution.xls or MultipleConvolution.xlsx for Excel and MultipleConvolutionOO.ods for Calc), which is essentially the same technique as the above spreadsheets for smoothing and differentiation. Use this spreadsheet to investigate convolution, smoothing, differentiation, and the effect of those operations on noise and signal-to-noise ratio. (For larger data sets the performance is slower that Fourier convolution, which is much easier done in Matlab or Octave than in spreadsheets). Convolution.txt lists simple whole-number coefficient sets for performing differentiation and smoothing.

Peak detection and measurement. These spreadsheets implement the "findpeaks" peak finding and measurement method. The input x,y data are contained in Sheet1, column A and B, rows 8 to 263. You can Copy and Paste your own data there. The amplitude threshold and slope threshold are set in cells B3 and E3, respectively.  The Smooth Width and the Fit Width are both controlled by the number of non-zero convolution coefficients in row 5, columns J through Z. Sheets 2 - 11 perform the least-squares measurements. The spreadsheet is available in OpenOffice (.ods) and in Excel (.xls) and (.xlsx) formats. They are functionally equivalent and differ only in minor cosmetic aspects. An example spreadsheet, with data, is available.  A demo version, with a calculated noisy waveform that you can modify, is also available.  See PeakFindingandMeasurement.htm#Spreadsheet

Gaussian and Lorentzian fitting. GaussianLeastSquares.odt, is an OpenOffice spreadsheet that fits a quadratic function to the natural log of y(x) and computes the height, position, and width of the Gaussian that is a best fit to y(x).  There is also an Excel version (GaussianLeastSquares.xls). See Fitting Gaussian Peaks.  LorentzianLeastSquares.ods and LorentzianLeastSquares.xls fits a quadratic function to the reciprocal of y(x) and computes the height, position, and width of the Lorentzian that is a best fit to y(x). Note that the data may not contain zeros or negative points, and the baseline (value that y approaches far from the peak center) must be zero. See CurveFitting.html#Transforming.  

Straight-line and quadratic fitting. S
preadsheets in Excel .xls format and in OpenOffice Calc .ods format (see CurveFitting.html#spreadsheets) that automate the computation of those equations and plot the data and the best-fit line, requiring only that you type in (or paste in) the x-y data. There is one spreadsheet for linear fits (LeastSquares.xls and LeastSquares.odt) and also a version for quadratic (parabolic) fits (QuadraticLeastSquares.xls and QuadraticLeastSquares.ods).  For the applications of polynomial curve fitting to calibration, see Worksheets for Analytical Calibration Curves and Error propagation in Analytical Calibration.

Multicomponent spectroscopy by classical least-squares multilinear regression. The spreadsheets RegressionDemo.xls and  RegressionDemo.ods (for Excel and Calc, respectively) demonstrate the classical least squares procedure for a simulated spectrum of a 5-component mixture measured at 100 wavelengths.  See CurveFittingB.html. The spreadsheet uses both the matrix method and the LINEST function methods.

Worksheets for Analytical Calibration Curves.
A growing collection of fill-in-the-blanks spreadsheet templates for performing calibration curve fitting and concentration calculations for analytical methods. Covers linear, quadratic, and cubic least-squares methods, interpolation, plus some log/log-based methods for wide dynamic range calibrations and a drift-corrected method for unstable calibrations. Available in Open Office Calc (.ods) and in Excel (.xls or .xlsx) formats.  Download the complete collection in a ZIP file: CalibrationSpreadsheets.zip.

index previous
Copyright (c) 2014, Thomas C. O'Haver
 
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

This page is maintained by Prof. Tom O'Haver , Department of Chemistry and Biochemistry, The University of Maryland at College Park. Comments, suggestions and questions should be directed to Prof. O'Haver at toh@umd.edu. Updated November, 2014.
Unique visits to this site since June 17, 2008: