# NMath User's Guide

8.2 Creating Least Squares Solutions (.NET, C#, CSharp, VB, Visual Basic, F#)

Least squares solutions to the linear system Ax = y are constructed from a rectangular matrix A and a vector of values y. For instance:

Code Example – C# least squares

```var A =
```
```   new DoubleMatrix( "4x2[1.0 20.0 1.0 30.0 40.0 1.0 50.0 1.0]" );
```
```var y = new DoubleVector( "[.446 .601 .786 .928]" );

```

```var lsq = new DoubleLeastSquares( A, y );
```

Code Example – VB least squares

```Dim A =
```
```  New DoubleMatrix("4x2[1.0 20.0 1.0 30.0 40.0 1.0 50.0 1.0]")
```
```Dim Y = New DoubleVector("[.446 .601 .786 .928]")
```
```Dim LSQ = New DoubleLeastSquares(A, Y)
```

An optional Boolean parameter to the constructor can be used to add an intercept parameter to the model. If true, a column of ones is prepended to a deep copy of matrix A before solving for the least squares solution.

NOTE—The input matrix A is not changed.

For example:

Code Example – C# least squares

```var lsq = new FloatComplexLeastSquares ( A, y, true );
```

Code Example – VB least squares

```Dim LSQ As New FloatComplexLeastSquares(A, Y, True)
```

Finally, for advanced users, you can specify a non-default tolerance to be used in computing the effective rank. The effective rank of A is determined by treating as zero those singular values that are less than the tolerance times the largest singular value.

Thus:

Code Example – C# least squares

```double tolerance = 1e-5;
```
```var lsq =
```
```   new DoubleComplexLeastSquares( A, y, false, tolerance );
```

Code Example – VB least squares

```Dim Tolerance As Double = "1e-5"
```
```Dim LQS As New DoubleComplexLeastSquares(A, Y, False, Tolerance)
```

NOTE—For details of the effective rank computation, see the documentation for LAPACK routines sgelsy(), dgelsy(), zgelsy(), and cgelsy().

Top

Top