Skip to content

Instantly share code, notes, and snippets.

@rygorous
Created October 12, 2013 00:14
Embed
What would you like to do?
How to fit polynomials using Matlab.
Fit polynomial:
a*x^2 + b*x + c
to a bunch of data points (x,y).
Stuff the x into a vector. Let's just use a bunch of random points between 0 and 1:
octave-3.6.2.exe:1> x = rand(10,1)
x =
0.94838
0.10026
0.68927
0.98075
0.24579
0.29140
0.98766
0.54006
0.31093
0.12693
Now we need some y's. I'm just gonna cheat and use a quadratic function with some noise so we can see how good the fit is:
octave-3.6.2.exe:2> y = (x.^2 + 2*x + 1) + 0.1*(rand(size(x)) - 1)
y =
3.7093
1.1602
2.7584
3.9070
1.4842
1.5913
3.8757
2.2748
1.6543
1.1742
The ".^" there is pointwise exponentiation, the rest should be fairly self-explanatory. There's
".*" (pointwise multiply), "./" (pointwise divide) and so forth too.
Now here's how you solve the over-complete linear system for them:
octave-3.6.2.exe:3> [x.^2 x.^1 x.^0] \ y
ans =
1.15039
1.84023
0.95267
Note how we got our original values, plus some noise, back.
The stuff in square brackets is a matrix with the elements of x squared in the first column,
x in the second column, and x to the 0'th power (i.e. 1) in the third. The "\" is just "right
divide": "A / b" = A * inverse(b), "A \ b" = inverse(A) * b.
If the matrix is over-complete, Matlab/Octave will automatically give you a (linear) least-squares
solution.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment