# Metoda najmanjih kvadrata

podaci: [[1,2],[2,3],[2.5,2.5],[4,4],[5.5,7],[6,8]];

wxplot2d([discrete,podaci],[x,0,8],[y,0,10],[style,points]);

sum((y[i]-f(x[i]))^2,i,1,n);

f(t):=a*t+b;

sk: sum((podaci[i][2]-f(podaci[i][1]))^2,i,1,6);

expand(sk);

diff(sk,a);
diff(sk,b);

expand(diff(sk,a));
expand(diff(sk,b));

solve([diff(sk,a)=0,diff(sk,b)=0],[a,b]);

ff: f(t), %;

wxplot2d([[discrete,podaci],ff],[t,0,8],[y,0,10],[style,points,lines],
    [legend,"podaci","model"],[gnuplot_preamble,"set key left"]);

podaci2: [[1,0.5],[2,1],[3,2],[4,4.5],[5,6],[7,8.5],[8,9.1],[9,9.3]];

wxplot2d([discrete,podaci2],[x,0,10],[y,0,10],[style,points]);

mat2: apply(matrix,podaci2);

lsquares_estimates(mat2, [x,y], y=f(x), [a,b],initial=[1,1]);

ff: f(t), %;

wxplot2d([[discrete,podaci2],ff],[t,0,10],[y,0,10],[style,points,lines],
    [legend,"podaci","model"],[gnuplot_preamble,"set key left"]);

sum((podaci2[i][2]-subst(podaci2[i][1],t,ff))^2,i,1,8);

f(t):=K/(1+C*exp(-r*t));

lsquares_estimates(mat2, [x,y], y=f(x), [K,C,r],initial=[10,1,1]);

ff: f(t), %;

wxplot2d([[discrete,podaci2],ff],[t,0,10],[y,0,10],[style,points,lines],
    [legend,"podaci","model"],[gnuplot_preamble,"set key left"]);

sum((podaci2[i][2]-subst(podaci2[i][1],t,ff))^2,i,1,8);

f(t):=K*exp(-a*exp(-b*t));

lsquares_estimates(mat2, [x,y], y=f(x), [K,a,b],initial=[10,1,1]);

ff: f(t), %;

wxplot2d([[discrete,podaci2],ff],[t,0,10],[y,0,10],[style,points,lines],
    [legend,"podaci","model"],[gnuplot_preamble,"set key left"]);

sum((podaci2[i][2]-subst(podaci2[i][1],t,ff))^2,i,1,8);

f(t):=a*(t/(b+t))^c;

lsquares_estimates(mat2, [x,y], y=f(x), [a,b,c],initial=[10,1,3]);

ff: f(t), %;

wxplot2d([[discrete,podaci2],ff],[t,0,10],[y,0,10],[style,points,lines],
    [legend,"podaci","model"],[gnuplot_preamble,"set key left"]);

sum((podaci2[i][2]-subst(podaci2[i][1],t,ff))^2,i,1,8);