Curve fitting

Spread the word!

One of my preferred task I like to see solved by the powerful computational skills of calculators is the curve fitting: we have some measured values and we want to find a function which describe the trend of this values against time. The key question is: what kind of function to optimize should we choose? I will call it model function and this will be given to the Matlab/Octave script in order to be fitted to our measured values.

Before going on: about linearisation
If our model function is non-linear we would maybe first linearise it, because some Matlab functions are working better with linear model functions. I take a practical example of linearisation from a project done at the University:

linearisation

Here the x values are the coefficients to be set and the t are the measured values converted after the linearisation.

Now we have a lot of solutions. The most easy way is to use the fitlm function, which will do all the job, but while this will work perfectly with Matlab, I could not make it work on Gnu Octave:

Note: don’t forget to convert back the parameters found by your Matlab script!

General method in details
Let’s discuss now some other way to find the fitting curve by using a general method which should work also with Gnu Octave. The following code was written with Gnu  Octave 3.8.1. For simplicity I will not consider here a multi-variable function as before, but just a set of values as function of the time.

Example:

The scatter function will let us visualize this set of fictitious points:
pointplot

Now the question is about which criterion we want to apply for the curve fitting starting from a model equation: what do we want to minimize? In this case I chose to minimize the distance between the model function and the “y” of every point. The Matlab/Octave function used for the minimization is fminsearch. Since it depends on some given initial values for the x-parameters (because it use the Nelder & Mead Simplex algorithm which is a derivative-free method) I just used the for loop in order to repeat the computation with different random initial values and at the end I just selected the set of parameters which fit better to my criterion.

Here is the full code:

This is the result:
fittingcurve

Now it’s up to you to play with the choice of the model function and its x-parameters to use for the curve fitting optimization.

Be the first to comment

Leave a Reply

Your email address will not be published.


*