How do I calculate Savitzky-Golay 1st Derivative?

76 ビュー (過去 30 日間)
Hannah
Hannah 2024 年 7 月 1 日
コメント済み: Hannah 2024 年 7 月 1 日
Hi, I'm quite new to MATLAB.
I want to use Savitzky-Golay 1st Derivative over a 5-point window and second polynomial order, to smooth my NIR data.
Could I simply use the sgolayfilt function and compute it like this:
dx1 = sgolayfilt(x1, 2, 5)
Or do I need a different code?

採用された回答

Abhishek Kumar Singh
Abhishek Kumar Singh 2024 年 7 月 1 日
I don't think you can use sgolayfilt to compute the first derivative. It is used to apply the Savitzky-Golay filter to smoothen it. The output you get is a filtered signal, not any derivative. Refer to the documentation: https://www.mathworks.com/help/signal/ref/sgolayfilt.html
To compute the first derivative, you need to use the sgolay function to get the filter coefficients and then apply them to your data using convolution.
Refer to a sample code here:
% Generate sample data: a noisy sine wave
x = linspace(0, 2*pi, 100); % 100 points from 0 to 2*pi
y = sin(x) + 0.1*randn(size(x)); % sine wave with added noise
% Parameters for Savitzky-Golay filter
polynomialOrder = 2; % Second polynomial order
frameSize = 5; % 5-point window (should be odd)
% Calculate Savitzky-Golay filter coefficients
[b, g] = sgolay(polynomialOrder, frameSize);
% Compute the sampling interval
dt = x(2) - x(1); % Sampling interval
% Compute the first derivative
p = 1; % First derivative
dy = conv(y, factorial(p) / -1*dt^p * g(:, p+1), 'same');
% Plot the original data and the first derivative
figure;
subplot(2, 1, 1);
plot(x, y, 'b.-');
title('Original Data (Noisy Sine Wave)');
xlabel('x');
ylabel('y');
subplot(2, 1, 2);
plot(x, dy, 'r.-');
title('First Derivative (Savitzky-Golay)');
xlabel('x');
ylabel('dy/dx');
Refer to this example for more accurate implementation and understanding of sgolay function for your use case: https://www.mathworks.com/help/signal/ref/sgolay.html#mw_564d68d7-239a-4145-9508-eb6dfcfaf8ae
  1 件のコメント
Hannah
Hannah 2024 年 7 月 1 日
Thank you so much!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSmoothing and Denoising についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by