Hi Xingwang,
Despite support for the optimoptions function, the objects it generates are not supported for code generation. In the generated code, optimoptions generates structs of options.
As a workaround, I can suggest 2 alternatives, both of which require you to call optimoptions in the function that is being codegened:
- The most simple, which will work for this case but won't scale well is to pass the individual options you want set as inputs to your function. This won't be as easy to update as you add more options.
function ab_fitted = my_fit_ab_2(x0, xdata, ydata, maxiter)
Opt = optimoptions('lsqcurvefit','Algorithm','levenberg-marquardt','MaxIterations',maxiter);
simple_exp_func = @(x, xdata) x(1)*exp(-x(2)*xdata);
ab_fitted = lsqcurvefit(simple_exp_func, x0, xdata, ydata, [],[], Opt);
end
2. If you anticipate wanting to toggle different options in the future, then try passing a struct of options that can be copied over into the optimoptions:
function ab_fitted = my_fit_ab_2(x0, xdata, ydata, optIn)
f = fieldnames(optIn);
Opt = optimoptions('lsqcurvefit','Algorithm','levenberg-marquardt');
for k = 1:numel(f)
thisOption = f{k};
Opt.(thisOption) = optIn.(thisOption);
end
simple_exp_func = @(x, xdata) x(1)*exp(-x(2)*xdata);
ab_fitted = lsqcurvefit(simple_exp_func, x0, xdata, ydata, [],[], Opt);
end
To generate code for this, try this script:
dblMatType = coder.typeof(double(1), [8, 1], [1, 1]);
dblVecType = coder.typeof(double(1), [2, 1], [1, 1]);
dblScalarType = coder.typeof(double(1), [1, 1], [1, 1]);
optsType = struct('Algorithm', 'levenberg-marquardt', 'MaxIterations', dblScalarType);
cfg = coder.config('mex');
cArgs = {dblVecType, dblMatType, dblMatType, optsType};
codegen -config cfg my_fit_ab_2 -args cArgs
Note that the 4th input is a struct of "typeof" objects that you can add to as needed.