Reading Notes for Qian Xin

Culture, Economics, Political... after reading something on internet, i will try to write down some notes. this is the place for me to record these notes.

Wednesday, April 11, 2007

Cambridge University Engineering Department - Matlab: curve fitting

Cambridge University Engineering Department - Matlab: curve fitting

If you know the form of the required function you can use fminsearch to find the best coefficients. Suppose that you think that some data should conform to a relation of the form a*x+b*sin(x)+c. To be able to use fminsearch you need to write a matlab function that for given values of a, b and c, calculates the square of the disparity. Its first argument is a vector of coefficients, its last argument is a vector of the given data values. The other arguments (in this case, just one) are vectors of free variables. You can put this function into its own file or (as here) make it into a subfunction. If you put the following code into a file called fitting.m, then run it, you should see how good to fit is.

function fitting
x=1:10;
y=sin(x);
bestcoeffs=fminsearch(@fun,[1 1 1],[],x,y);
yfit=bestcoeffs(1)*x +bestcoeffs(2)*sin(x) + bestcoeffs(3);
%Now compare y with yfit
plot(x,y,x,yfit);

function out=fun(coeff,X,Y)
a = coeff(1);
b = coeff(2);
c = coeff(3);
Y_fun = a .* X + b .* sin(X)+c;
DIFF = Y_fun - Y;
SQ_DIFF = DIFF.^2;

out = sum(SQ_DIFF);

Note that the [1 1 1] argument to fminsearch provides the starting values for a, b and c. The choice of starting values can affect the speed of the search.

An example of fitting a function of 2 values is in Mathworks' Solution Search (Solution 1484)

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home