← All NMath Code Examples
using System;
using System.Globalization;
using System.Threading;
using CenterSpace.NMath.Core;
namespace CenterSpace.NMath.Examples.CSharp
{
/// <summary>
/// A .NET example in C# showing how to use the Savitzky-Golay filtering class.
/// </summary>
class SavitzkyGolayFilteringExample
{
static void Main( string[] args )
{
#region Savitzky-Golay Smoothing
// Build a Savitzky-Golay filter with a window width of 7, and a 4th degree smoothing polynomial.
var sgf = new SavitzkyGolayFilter( 3, 3, 4 );
// Make some random noise.
RandomNumberGenerator rnd = new RandGenUniform();
var data = new DoubleVector( 100, rnd );
// Build a noisy sinusoidal signal to filter.
double step_size = 0.1;
var x = new DoubleVector( 100, 0, step_size );
var sin_x = new DoubleVector( NMathFunctions.Sin( x ) + data.Scale( 0.1 ) );
// Filter the signal function
DoubleVector z = sgf.Filter( sin_x );
#endregion
#region Savitzky-Golay Derivatives
// Build a vector of a sampled sinc() function and its derivative.
x = new DoubleVector( 100, 0.01, step_size );
var sinc = new DoubleVector( NMathFunctions.Sin( x ) / x );
var derivative_sinc = new DoubleVector( NMathFunctions.Cos( x ) / x - NMathFunctions.Sin( x ) / ( x * x ) );
// Create a Savitzky-Golay filter for computing the first derivative using a 5th degree polynomial.
// By default the boundaries are smoothed to the edges, if this is not necessary,
// other faster boundary handling options are available.
sgf = new SavitzkyGolayFilter( 3, 3, 5, 1 );
// Find the S-G derivatives.
DoubleVector sg_d_sinc = sgf.Filter( sinc );
// Scale the raw derivatives.
sgf.ScaleDerivative( step_size, ref sg_d_sinc );
// Look at the mean squared error over the 100 samples, of the SG derivatives.
Double mean_sqrd_error = NMathFunctions.Mean( NMathFunctions.Pow( derivative_sinc - sg_d_sinc, 2.0 ) );
Console.WriteLine();
Console.WriteLine( "The mean squared error of the Savitzky-Golay derivative estimate of the sinc() function = {0}", mean_sqrd_error );
#endregion
Console.WriteLine();
Console.WriteLine( "Press Enter Key" );
Console.Read();
}
}
}
← All NMath Code Examples