Feed on
Posts ## use linear algebra to fit a line in matlab

let’s say you’ve got 2 vectors (x,y) who are linearly related according to the relation: y = mx + b. you’d like to use matlab to find m and b.

this can be done with one line of linear algebra in matlab.

first, consider the equation y = mx + b: you can imagine rewriting this in linear algebra as [X_i 1_i]*[m b] = y_i, where _i denotes a vector with i items. If we let A = [m b], r = [X 1], and s = y, we have the familiar linear algebra form: Ar = s. To solve, all we need is A = r^-1*s.

In matlab-speak:

>> A = pinv([x ones(size(x))])*y

[note that since r is usually not square, we need to use matlab's pseudo-inverse function.] ### if that was helpful ...

check out the other tips and tricks i've compiled on these pages. you might learn something else interesting!

### One Response to “use linear algebra to fit a line in matlab”

1. on 14 Nov 2007 at 7:53 am Will Dwinnell

It is even simpler to construct a least-squares fit using MATLAB’s backslash operator, ‘\’. See, for instance:

Linear Regression in MATLAB
http://matlabdatamining.blogspot.com/2007/04/linear-regression-in-matlab.html

Also: Alternatives to the least-squares fit may be of interest, such as the least absolute errors (also called “L-1″) fit:

L-1 Linear Regression
http://matlabdatamining.blogspot.com/2007/10/l-1-linear-regression.html

-Will Dwinnell 