Below is a code, which works fine without function/function handles. However, I have to write a function so that I can use optimization function of "lsqcurvefit" in MATLAB and optimize parameters constant(1) and constant(2).
L=zeros(n,length(S)); % Height of elements
L(:,1)=Linitial; % Height of elements for day zero
for jj=1:length(S)
if jj==1
continue
end
for j=1:n % n is 101 (previously defined...)
L(j,jj) = @(constant, i_dt) L(j,jj-1) - (i_dt(j,jj).*constant(1).*((L(j,jj-1)./hs)-1)^constant(2)); %*****
end
end
height_pred = @(constant,i_dt) sum(L); %heigh_pred(1) is known and previously defined
options = optimoptions('lsqcurvefit','FinDiffType','central',...
'TolFun',1e-10);
constant = lsqcurvefit(height_pred,constant0,i_dt,height_meas,lb,ub,options);
When I run above code, I receive the error "Conversion to double from function_handle is not possible" for line with 5 stars (*****).
If I remove function handle and instead write a function at the end of my code like below:
L=zeros(n,length(S)); % Height of elements
L(:,1)=Linitial; % Height of elements for day zero
for jj=1:length(S)
for j=1:n % n is 101 (previously defined...)
L(j,jj) = Nelfun(j,jj);
end
end
height_pred = @(constant,i_dt) sum(L); %heigh_pred(1) is known and previously defined
options = optimoptions('lsqcurvefit','FinDiffType','central',...
'TolFun',1e-10);
constant = lsqcurvefit(height_pred,constant0,i_dt,height_meas,lb,ub,options);
function L = Nelfun(constant,i_dt)
for jj=1:145
if jj==1
L(:,1)=0.0187600000000000;
continue
end
for j=1:101
L(j,jj-1);
L(j,jj) = L(j,jj-1) - (i_dt(j,jj).*constant(1).*((L(j,jj-1)./hs)-1)^constant(2)); %*****
end
end
end
I receive the error
"Index exceeds matrix dimensions" for line with (*****).
Size of matrix i_dt is (101,145), L is (101,145), height_meas(1,145), and height_pred(1,145).
L(j,jj) for jj==1 is known but then should be calculated and optimized for L(:,2) to L(:,145).
***
Thanks to Praveen, "Index exceeds matrix dimensions" issue is resolved, but now I receive the error
"Error using snls (line 183)
Finite difference Jacobian at initial point contains Inf or NaN values. lsqcurvefit cannot continue."
for below code:
lb = [0.000000000001,0.05]; ub = [1,50]; constant0 = [1.06e-09,15.2];
height_pred = @(constant,i_dt) sum(Nelfun(constant,i_dt));
options = optimoptions('lsqcurvefit','FinDiffType','central',...
'TolFun',1e-10);
constant = lsqcurvefit(height_pred,constant0,i_dt,height_meas,lb,ub,options);
function L = Nelfun(constant,i_dt)
L=zeros(size(i_dt));
n=101; % number of nodes
ei=2.05613504572765;
e0=ei.*ones(n,1);
Hsolid=0.613847219422639;
hs = Hsolid./(n-1);
for JJ=1:size(i_dt,2)
if JJ==1
for j=1:n
Linitial0=hs.*(1+e0);
Linitial0(1)=0;
end
L(:,JJ) = Linitial0;
continue
end
for J=1:size(i_dt,1)
L(J,JJ) = L(J,JJ-1) - (i_dt(J,JJ).*constant(1).*((L(J,JJ-1)./hs)-1)^constant(2));
end
end
end