Finding the first order derivative of a data series using the Savitzky-Golay filter.

43 visualizzazioni (ultimi 30 giorni)
I am trying to rewrite some Python code into a Matlab script. The input data to this code in a 2-D array called 'spectra' with each row of 'spectra' corresponding to a different set of signal observations (i.e. a different spectrum) and with each column corresponding to the wavelengths at which the observations were made. For the purposes of this question, assume that the columns have unity spacing (i.e., the difference between successive wavelengths is '1').
I would like to smooth and differentiate the data using a Savtizky-Golay filter. To do this in Python, the code would include these lines:
# Read the signal values (first column is observation date)
y = (spectra.values[:,2:]).astype('float32'))
# Calculate first derivative applying a Savitzky-Golay filter
dy = savgol_filter(y, 25, polyorder = 5, deriv=1)
My understanding of the above is that, for each wavelength, the Savitzky Golay filter fits a fifth order polynomial to the signal values in a window encompassing 25 wavelengths (symmetric about the wavelength of interest). The filter then applies that polynomial to compute the first order derivative at that wavelength. You end up with a series of data points equal to the first order derivative at each wavelength.
My question is: How can I best achieve the same computation in Matlab? The sgolay function does not appear to have a derivative option.

Risposta accettata

Image Analyst
Image Analyst il 6 Giu 2022
Wouldn't you just smooth the data with sgolayfilt and then differentiate with diff?
  1 Commento
Steve Francis
Steve Francis il 7 Giu 2022
This answer seemed to work. I adopted the following code:
% y is source data (ie 'spectra', a 150 x 400 numeric array)
% Pre-allocate array sizes for efficiency
y_filtered = zeros(150,400); % The measured absorbance values will be smoothed.
dy = zeros(150,399); % The derivative has one less column due to the way it is calculated
% Use the Savitzky-Golay filter to smooth out the derivative data.
% sgolayfilt operates on each column so need to transpose twice.
y_filtered = (sgolayfilt(y',5,25))';
% Compute the first order differential by taking the difference between
% successive signal values. The spacing between points in each direction
% is assumed to be one.
dy(:,1:(size(y_filtered,2)-1)) = diff(y_filtered,1,2);
Thank you

Accedi per commentare.

Più risposte (0)

Prodotti


Release

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by