### Line fitting in Matlab

I've been using this for several times but I always forget where I put the source code, so every time I have to rewrite it again. So, I think it would be better if I put the source code here so it will be easier for me to find if I need this again.

This is almost the same with the article that I wrote using GSL, I use Matlab because I need to show the 3D, I haven't finished my 3D visualization software yet.

So here we go:

- Assume that you have a line data, Y(1:540) which are changing with the X value, X(1:540).

- Then basically, you just have to call this polynomial fitting function in Matlab: p = polyfit(X,Y,n);

- The result from this function is an array p which has n+1 element and representing the coefficient of the polynomial equation p1*x^(n) + p2*x^(n-1) + ... + p(n+1). for example if n = 1, then the equation will be p(1).x - y2 + p(2) = 0.

- To generate the line, simply plot the equation to the X value, for example:

for col=1:1:540

y2(col) = p(1)*x(col) + p(2);

end

plot(x, y, x, y2);

- To get the difference between the line and the actual values, the distance from point to a line formula can be used.

for col=1:1:540

d(col) = (p(1)*x(col) - Y(col) + p(2)) / sqrt( (p(1)*p(1))+1 );

end

- Then you can show the deviation in another figure.

Hope it helps.

Good luck.

Labels: job, matlab, programming