Clear Filters
Clear Filters

How to use OutputFcn with fitnlm

33 views (last 30 days)
Adrian Batista Planas
Adrian Batista Planas on 4 Aug 2024 at 16:19
Commented: Matt J on 5 Aug 2024 at 18:47
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);
  1 Comment
dpb
dpb on 4 Aug 2024 at 16:46
fitnlm doesn't document the 'OutputFcn' field in the options list; I'm guessing it's being ignored.
Try nlinfit instead.
This penchant for multiple nearly identical functions is maddening, indeed...
which -all fitnlm
/MATLAB/toolbox/stats/classreg/fitnlm.m
which -all nlinfit
/MATLAB/toolbox/stats/stats/nlinfit.m

Sign in to comment.

Answers (1)

Matt J
Matt J on 4 Aug 2024 at 20:50
Edited: Matt J on 5 Aug 2024 at 18:45
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
Torsten on 5 Aug 2024 at 17:12
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
Matt J on 5 Aug 2024 at 18:47
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.

Sign in to comment.

Products


Release

R2024a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!