Thursday, November 15, 2012

Easy Curve Fitting with MATLAB



Basically this exercise is about an easy and common curve fitting, which is used on a set of raw data points. The book 'Mathematische Formelsammlung' by Lothar Papula was referred for this exercise and its particular chapter is 'Ausgleichs- oder Regressionsparabel'.

Your mission, should you choose to accept it, is to fit a parabolic curve of the form y(x) = a*x^2 + b*x + c, to the given set of raw data points.

At the end of this post, I've included the link to download the M-script file.

Raw data
x = [-3:1:5]';
y = [-3.94 -1.47 -4.66 -3.21 0.84 7.24 15.58 27.94 42.59]';
[n,m] = size(x);
Calculation
The curve parameter a, b and c can be determined from the method of least squares (German- Methode der kleinsten Quadrate), which uses linear equation system with 3 equations and 3 unknowns.

x4 = x.^4;
x3 = x.^3;
x2 = x.^2;

sx4 = sum(x4);
sx3 = sum(x3);
sx2 = sum(x2);

sx = sum(x);
sy = sum(y);

x2y = x2.*y;
xy = x.*y;
sx2y = sum(x2y);
sxy = sum(xy);
Formation of the known matrices
The targetted matrix equation is as follows: A*K = vekb. Out of those 3 matrices, A and vekb are known.


A = [sx4 sx3 sx2;...
    sx3 sx2 sx;...
    sx2 sx n];

vekb = [sx2y; sxy; sy];
Determination of the curve parameter
The matrix K consists of the parameters - a, b and c, that we sought after. Simply multiply the inverse of A and vekb, both gained from the previous step.
K = inv(A)*vekb;
Generation of new data points
By using the gained parameters in K, new points can now be plotted.


yneu = K(1)*x.*x + K(2)*x + K(3);

Plotting

The displaying of the result.

M-Script code:
MV_Blatt_1_Aufgb5.m
p/s: just in case that you're not using MATLAB or Octave, that file can also be viewed in normal text editor =P

No comments: