How is f(x) evaluated for each iteration using fsolve?
Show older comments
I'm using fsolve for an unconstrained non-linear function. And I notice that fval is much different than f(x) for the last iteration. How exactly is f(x) calculated?
13 Comments
Torsten
on 14 Jan 2019
Did you compare the x-vectors that led to fval and f(x) ?
"And I notice that fval is much different than f(x) for the last iteration."
Why should the last function call necessarily use the fsolve output x value? I don't see why this would have to be the case, nor do I see anything in the documentation to support this.
"How exactly is f(x) calculated?"
Using the function that you provide, and whatever algorithm that fsolve uses. There are many algorithms:
TS
on 14 Jan 2019
Torsten
on 14 Jan 2019
Of course. If you write "f" as a MATLAB function, you can output x every time the function is called.
Example:
function main
fun = @root2d;
x0 = [0,0];
x = fsolve(fun,x0,options)
end
function F = root2d(x)
F(1) = exp(-exp(-(x(1)+x(2)))) - x(2)*(1+x(1)^2);
F(2) = x(1)*cos(x(2)) + x(2)*sin(x(1)) - 0.5;
x
end
"So can I see the vaule of x at each iteration?"
Of course, here are some options:
- inside your function either print/display the current x value to the command window or to a file (simple).
- add persistent and an input flag to your function to allow you to reset, collect the values into an array, and return them afterwards (complex).
- plot the values using PlotFcn and any of the inbuilt plot functions, or write your own custom plot function:
- define an OutputFcn, which can do anything you want and is called on each iteration:
- display the f(x) values using the inbuilt Display option:
Which would you prefer?
TS
on 14 Jan 2019
Here is an option how to show x together with f(x):
https://de.mathworks.com/matlabcentral/answers/178244-how-to-show-value-after-every-fsolve-iteration
I guess that 0.0540317 is the function value after the first Newton step, not when the function has been called two times.
Torsten
on 14 Jan 2019
Square the function values, and you arrive at the f(x) values. Don't know why f(x)^2 is shown in the convergence monitor.
TS
on 14 Jan 2019
Accepted Answer
More Answers (1)
RANJEET YADAV
on 14 Jan 2019
0 votes
f(x)=fsolve(@(x) funname(x),x=1);
Categories
Find more on Solver-Based Nonlinear Optimization 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!