The least squares method is commonly used in data fitting. The solution to a least squares problem is the coefficient or set of coefficients that minimises the sum of the squared residuals. Residuals are the difference between the actual value and the fitted value.

Scientists and engineers use Matlab, a software application developed by MathWorks, to perform least squares analysis. You can use the "fminsearch" function -- but this can be very complicated and time consuming -- or the Curve Fitting toolbox -- which is expensive. Alternatively, you can use Ezyfit. Ezyfit is free, fast and easy-to-use Matlab toolbox.

- Skill level:
- Moderate

### Other People Are Reading

## Instructions

- 1
Download Ezyfit. Extract it to a folder on your computer. Do not add it to your Matlab directory ("Program Files/Matlab").

- 2
Select "File > Set Path ..." from the menu bar and then select the folder containing Ezyfit to add Ezyfit to your Matlab path.

- 3
Restart Matlab to load Ezyfit for the first time. Subsequently, Ezyfit will automatically load when you start Matlab.

- 1
Type "x = 0:1:100" in the Command window to generate a series of x values.

- 2
Type "y = rand(1,length(x))" to randomly generate a y value for each x value.

- 3
Type "y = y .

*(x * 2)" to create a gradient of 2. Take care to use array multiplication ".*" after the second y rather than matrix multiplication "*" otherwise you will generate a matrix multiplication error. - 4
Type "plot(x,y,'kx')" to plot the points on a scatter plot.

- 1
Type "showfit('a*x + b')" to perform a linear least squares fit. Ezyfit prints the solution, i.e. the values of the fitting coefficients "a" and "b" and correlation coefficient "R".

- 2
Type "showfit('a

*exp(b*x) + c')" to perform a exponential least squares fit. - 3
Check that the correlation coefficient "R" for the exponential fit is less than the "R" value for the linear fit. This means the linear fit is a better fit of the data, as expected.