酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

请用C#写一份完整的Savitzky-Golay filter算法

Savitzky-Golay滤波器是一种数字滤波器,常用于平滑数据,同时保留数据的原始形状和特征。以下是一个用C#实现的Savitzky-Golay滤波器的完整示例: ```csharp using System; using System.Linq; public class SavitzkyGolayFilter { private int windowSize; private int polynomialOrder; private double[] coefficients; public SavitzkyGolayFilter(int windowSize, int polynomialOrder) { if (windowSize % 2 == 0) throw new ArgumentException("Window size must be odd."); if (polynomialOrder >= windowSize) throw new ArgumentException("Polynomial order must be less than window size."); this.windowSize = windowSize; this.polynomialOrder = polynomialOrder; this.coefficients = CalculateCoefficients(); } private double[] CalculateCoefficients() { int halfWindow = windowSize / 2; double[,] designMatrix = new double[windowSize, polynomialOrder + 1]; for (int i = -halfWindow; i <= halfWindow; i++) { for (int j = 0; j <= polynomialOrder; j++) { designMatrix[i + halfWindow, j] = Math.Pow(i, j); } } var pseudoInverse = PseudoInverse(designMatrix); return pseudoInverse.GetColumn(0); // Return the first column for smoothing } private double[,] PseudoInverse(double[,] matrix) { var svd = new MathNet.Numerics.LinearAlgebra.Double.Matrix(matrix).Svd(); var s = svd.S; var u = svd.U; var vt = svd.VT; var sInv = s.Map(x => x == 0 ? 0 : 1 / x, Zeros.AllowSkip); return (vt.Transpose() * sInv.ToColumnMatrix() * u.Transpose()).ToArray(); } public double[] ApplyFilter(double[] data) { int halfWindow = windowSize / 2; double[] smoothedData = new double[data.Length]; for (int i = 0; i < data.Length; i++) { double sum = 0; for (int j = -halfWindow; j <= halfWindow; j++) { int index = i + j; if (index < 0) index = 0; if (index >= data.Length) index = data.Length - 1; sum += data[index] * coefficients[j + halfWindow]; } smoothedData[i] = sum; } return smoothedData; } } // Example usage public class Program { public static void Main() { double[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var filter = new SavitzkyGolayFilter(5, 2); double[] smoothedData = filter.ApplyFilter(data); Console.WriteLine("Smoothed Data:"); foreach (var value in smoothedData) { Console.WriteLine(value); } } } ``` 代码说明: 1. SavitzkyGolayFilter类:这个类实现了Savitzky-Golay滤波器。构造函数接受窗口大小和多项式阶数作为参数,并计算滤波器的系数。 2. CalculateCoefficients方法:计算Savitzky-Golay滤波器的系数。使用设计矩阵和伪逆矩阵来计算系数。 3. PseudoInverse方法:计算矩阵的伪逆矩阵。使用SVD分解来实现。 4. ApplyFilter方法:应用滤波器到输入数据上,返回平滑后的数据。 额外需要注意的逻辑点: 1. 窗口大小必须是奇数,以确保滤波器对称。 2. 多项式阶数必须小于窗口大小,以避免过拟合。 3. 在应用滤波器时,边界处理是必要的,以避免数组越界。 [2025-03-16 19:04:42 | AI写代码神器 | 866点数解答]

相关提问