Example: Regression with User-supplied Basis Functions

In this example, we fit the function 1 + sin(x) + 7 * sin(3x) with no error introduced. The function is evaluated at 90 equally spaced points on the interval [0, 6]. Four basis functions are used, sin(kx) for k = 1,...,4 with no intercept.
using System;
using Imsl.Stat;
using Imsl.Math;

public class UserBasisRegressionEx1 : IRegressionBasis
{
	public double Basis(int index, double x)
	{
		return System.Math.Sin((index + 1) * x);
	}

	public static void Main(string[] args)
	{
		double[] coef = new double[4];
		IRegressionBasis basis = new UserBasisRegressionEx1();
		UserBasisRegression ubr = 
			new UserBasisRegression(basis, 4, false);
		
		for (int k = 0; k < 90; k++)
		{
			double x = 6.0 * k / 89.0;
			double y = 1.0 + Math.Sin(x) + 7.0 * Math.Sin(3.0 * x);
			ubr.Update(x, y, 1.0);
		}
		coef = ubr.GetCoefficients();
		PrintMatrix pm = new PrintMatrix("The regression coefficients are:");
		PrintMatrixFormat pmf = new PrintMatrixFormat();
		pmf.NumberFormat = "0.000";
		pm.Print(pmf, coef);
	}
}

Output

The regression coefficients are:
     0    
0  1.010  
1  0.020  
2  7.029  
3  0.037  


Link to C# source.