[Scilab-users] Fitting correlations to measured data. Write-ups of leastsq is messy ...

Heinz Nabielek heinznabielek at me.com
Thu Jan 30 23:25:06 CET 2020


Scilab is a great and powerful mathematical tool that can be used for fitting correlations to measured data.

For me, the help functions and literature write-ups for least-squares fitting in Scilab were tedious and I found them difficult to follow.

At an elementary level, I have sorted out my problems. I would like to report on it, but I am grateful for any further suggestions.

First: linear least-squares fitting: with measurement data x=[2 7 12]'; y=[2 4.5  6.5]'; 
it is easy, to fit a straight line and plot it:
M=[ones(x) x]; a=M\y; plot2d(x,M*a); plot(x,y,'r.');

Strangely, you find the recipe under "backslash" and this is not very straightforward. The method is really neat, because you can easily fit a polynomial of 25th order or any correlation that is linear in the parameters.

Correlations not linear in the parameters need non-linear least-squares fitting, e.g. with "leastsq", where the Scilab help function is terribly complex.

In my case, I wanted to simultaneously fit three straight lines through three measurement series with the condition that all 3 lines start at the same point on the x-axis. So the following worked well for me:

x=[2 7 12]'; y=[2 4.5  6.5]'; y1=[1 2 3]'; y2=[0 1 1.4]'; par0 = [.5 .15 .09 -5];
function e=err(par, x,y,y1,y2)
   e= [y-par(1)*(x+par(4)); y1-par(2)*(x+par(4)); y2-par(3)*(x+par(4))]
endfunction
 [f,paropt] = leastsq ( list(err,x,y,y1,y2), par0);

plot(x,[y y1 y2],'.');
xx=-5:15;
plot(xx,paropt(1)*(xx+paropt(4)),'b--');
plot(xx,paropt(2)*(xx+paropt(4)),'g--');
plot(xx,paropt(3)*(xx+paropt(4)),'r--');

I guess there are more elegant ways to write this code, are they?

I find write-ups of leastsq in the help function and in Scilab books terribly messy....
Greetings
Heinz


PS: Why do I need "list" in the leastsq function call?





More information about the users mailing list