How to use integration in Nonlinear Data-Fitting: Fsumsquares and then fminunc for parameter optimization

72 views Asked by At

I am able to run the code for any equations but when I introduce an integral the command won't run:

    t=dataset_TK1(:,1);
dataset_TK4=xlsread('Akis','Sheet1','AG491:AR725');
y_4=dataset_TK4(:,12);

Kg=1.76717865712934;
N0=1.08E+05;

fun1=@(Z) Z^(-1+(X(1)-Kg)/X(3))*exp(Z);

Ntotal=@(X,t)integral(fun1,X(2)*exp(-X(3)*t),X(2));

X0=[10,10,10];
Fsumsquares=@(X)sum((Ntotal(X,t)-y_4).^2);
opts = optimoptions('fminunc','Algorithm','quasi-newton');
[xunc,ressquared,eflag,outputu] =   fminunc(Fsumsquares,X0,opts)

Any suggestions?

Thank you

1

There are 1 answers

0
Giogre On

The MWE (minimum working example) code below works, in the sense it doesn't spurt out errors: to obtain it, I have substituted your excel data with dummy arrays.

I limited myself to remove unnecessary handles from functions in your snippet, and adjust operators to element-wise .^ and .* in fun1. Also, in the Ntotal integral, the limits should be scalars, not vectors. That is why I took only one element out of t:

% dummies, put your data back
t=ones(1,10);
y_4=[1,2,3,4,5,6,7,8,9,10];
X=[11,3,4,6,2,3,55,22,89,6];

Kg=1.76717865712934;
N0=1.08E+05;

fun1=@(Z) Z.^(-1+(X(1)-Kg)/X(3)).*exp(Z);               % changed
Ntotal=integral(fun1,X(2)*exp(-X(3)*t(1)),X(2));        % changed

X0=[10,10,10];
Fsumsquares=@(X) sum((Ntotal-y_4).^2);                  % changed
opts = optimoptions('fminunc','Algorithm','quasi-newton');
[xunc,ressquared,eflag,outputu] =   fminunc(Fsumsquares,X0,opts)