How to use OutputFcn with fitnlm
4 views (last 30 days)
Show older comments
Hi all,
How do I execute an OutputFcn function in each iteration inside fitlm? I have tried to run the following code but it does not print anything or throw an exception.
load carbig
tbl = table(Horsepower,Weight,MPG);
modelfun = @(b,x)b(1) + b(2)*x(:,1).^b(3) + ...
b(4)*x(:,2).^b(5);
beta0 = [-50 500 -1 500 -1];
opts = statset("fitnlm");
opts.OutputFcn = @(x)disp(x);
mdl = fitnlm(tbl,modelfun,beta0,"Options",opts);
Answers (1)
Matt J
on 4 Aug 2024
Edited: Matt J
on 5 Aug 2024
Only Optimization Toolbox solvers have an OutputFcn option. Perhaps you are thinking of lsqcurvefit,
load carbig
tbl = table(Horsepower,Weight,MPG);
modelfun = @(b,x)b(1) + b(2)*x(:,1).^b(3) + ...
b(4)*x(:,2).^b(5);
beta0 = [-50 500 -1 500 -1];
opts = optimoptions('lsqcurvefit',OutputFcn=@outfun);
beta1 = lsqcurvefit(modelfun,tbl{:,1:2},tbl{:,3},beta0,"Options",opts);
function stop = outfun(x,optimValues,state)
stop = false;
% Check whether directional derivative norm is less than .01.
if strcmp(state,'iter')
disp(x)
end
end
3 Comments
Torsten
on 5 Aug 2024
If statistics for the fitted parameter were accessible when using "lsqcurvefit", it would be mentionned on the documentation page as possible output from the solver:
But it isn't.
Matt J
on 5 Aug 2024
once you have solved with lsqcurvefit, you can take the solution beta1 and use it for beta0 with fitnlm:
load carbig
tbl = table(Horsepower,Weight,MPG);
modelfun = @(b,x)b(1) + b(2)*x(:,1).^b(3) + ...
b(4)*x(:,2).^b(5);
beta0 = [-50 500 -1 500 -1];
opts = optimoptions('lsqcurvefit',OutputFcn=@outfun);
beta1 = lsqcurvefit(modelfun,tbl{:,1:2},tbl{:,3},beta0,"Options",opts);
mdl = fitnlm(tbl,modelfun,beta1,"Options",statset("fitnlm"));
You can then use mdl for whatever statistical analysis you had originally planned.
See Also
Categories
Find more on Nonlinear Regression in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!