How can I extract data from fsolve results?
Show older comments
If I use fsolve and ('Display','iter') to display the function count, function value, norm of step, first-order optimality, and trust region radius, is there a way to create a vector containing values from this list?
options = optimoptions('fsolve','Display','iter')
fsolve(fun,x0,options)
Answers (1)
Ameer Hamza
on 20 Apr 2020
Edited: Ameer Hamza
on 20 Apr 2020
You can use OutputFcn property to get information from each iteration. The following code shows a simple example. It records the value of the variable and the function value. Check here for more details: https://www.mathworks.com/help/releases/R2020a/optim/ug/output-function.html
opts = optimoptions('fsolve', 'OutputFcn', @myOutFcn, 'Display', 'off');
global X f_val
X = [];
f_val = [];
fsolve(@(x) x.^3-5, rand, opts);
function stop = myOutFcn(x, optimValues, state)
global X
global f_val
X = [X; x];
f_val = [f_val; optimValues.fval];
stop = 0;
end
I wrote the above code using a global variable for a quick demonstration. Global variables are somewhat unrecommended in MATLAB. You can look at John's answer here for alternate approaches: https://www.mathworks.com/matlabcentral/answers/510713-is-it-possible-to-store-the-intermediate-values-of-fmincon#answer_420002
1 Comment
Ameer Hamza
on 20 Apr 2020
Yes, this is the simplest possible way to get the information for each iteration of the fsolve().
Categories
Find more on Solver Outputs and Iterative Display 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!