How to Use Matlab to Solve Least Squares Solutions

Written by eric smith
  • Share
  • Tweet
  • Share
  • Pin
  • Email
How to Use Matlab to Solve Least Squares Solutions
Least squares analysis is used to fit a model to data. (John Foxx/Stockbyte/Getty Images)

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:


  1. 1

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

  2. 2

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

  3. 3

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

  1. 1

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

  2. 2

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

  3. 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. 4

    Type "plot(x,y,'kx')" to plot the points on a scatter plot.

  1. 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. 2

    Type "showfit('aexp(bx) + c')" to perform a exponential least squares fit.

  3. 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.

Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.