Fitting a function with lsqcurvefit

342 views Asked by At

I use lsqcurvefit to fit my function. My function is:

C_PET (t)=(k_1/(α_2+α_1 ) [(k_3+k_4-α_1 )  e^((-α_1   t) )+(α_2-k_3-k_4 ) e^((-α_2   t) ) ]* C_P (t))+vC_b (t)

I went to find the solution, meaning the best fit for my K parametres. The problem is that the solution that my code give is the initial point. this is the code (vb is constant , cp,ydata,t are a vector

    k0 = 1*ones(1,4);
    k0(4) = 0;
    k0 = [0.8,0.1,0.5,0.07]
    a1=[k0(2)+k0(3)+k0(4)+sqrt(((k0(2)+k0(3)+k0(4)).^2) -4*k0(2)*k0(4))]/2;
    a2=[k0(2)+k0(3)+k0(4)-sqrt(((k0(2)+k0(3)+k0(4)).^2) -4*k0(2)*k0(4))]/2;
    l1=(k0(1)/(a2+a1))*(k0(3)+k0(4)-a1) l2=(a2-k0(3)-k0(4))
    l2=(a2-k0(3)-k0(4))
     y=conv((l1*exp(-a1*t)+l2*exp(-a2*t)),cp);

    y=(y(1:numel(t)));
    CPET=@(k,t) y+(vb*cp);
    [xfitted,errorfitted] = lsqcurvefit(CPET,k0,t,ydata)

%

So please can you hep me.

1

There are 1 answers

14
Dan On

Your objective function CPET is a constant:

CPET=@(k,t) y+(vb*cp);

You have declared it as a function of k and t but neither y, vb nor cp change when k or t change. That's why your solver isn't changing the answer. No matter what values of k or t lsqcurvefit feeds to CPET, the answer is always the same, which is wrong.

Your objective function is very long, so lets consider a much simpler one, say fitting a quadratic model that has another function of t as another term (i.e. in the same way that your C_P works) something like:

O = k1 + k2*t + k3*t2 + CP(t)

To write this objective function into the form expected by lsqcurvefit do:

O = @(k,t) k(1) + k(2).*t + k(3).*t.^2 + CP(t)

Now CP above can be a vector, CP, if and only if t will always be a natural number. It would make far more sense however to create a function called CP that takes t in as an input. For example maybe all CP does is take the sine of t then

CP = @(t)sin(t);  %// This needs to be declared before O

You need to write your CPET similary as a function of k and t and it needs to use both k and t in it's definition.