The following code runs fine and gives the accurate result.
c1...c5 are known constants, and x(1)...x(5) (anonymous vector) are unknown variables which to be fitted by fminsearch
using the least square method. (t,y) is the given data (curve) to fit the equation, myfunc
is a ode45
function saved in a separate .m file.
% run the solver
options = optimset('MaxFunEvals',10000,'MaxIter',10000,'Display','iter');
[x,fval,exitflag,output] = fminsearch(@(x) Obj(x,initial_p,c1,c2,c3,c4,c5,c6,t,y),x0,options);
function F = Obj(x,initial_p,c1,c2,c3,c4,c5,c6,t,y)
p = myfunc(x(2:end),initial_p,t,c1,c4);
yt = mainfunc(x,p,c1,c2,c3,c4,c5,c6);
F = sqrt(sum((yt-y).^2));
disp(x);
end
function yt = mainfunc(x,p,c1,c2,c3,c4,~,~)
yf = c1*c2*c3*c4*sqrt(p);
yt = x(1)+yf;
end
But error occurs (Assignment has more non-singleton rhs dimensions than non-singleton subscripts
) when I rewrite mainfunc
(all else being same):
function yt = mainfunc(x,p,c1,c2,c3,c4,c5,c6)
ys = c1*c3*(c5/(c6*sqrt(p)));
yf = c1*c2*c3*c4*sqrt(p);
yt = x(1)+ys+yf;
end
p is a curve (t,p) coming from ode45
in myfunc
, it is working fine in the first version of code so no problem there. Is having two terms with sqrt(p) in mainfunc
causing the problem?