Error in fzero for solving numerical inverse function

6 views (last 30 days)
Hello
I am trying to find the inverse of an function, g, numerically, as the explicit form of it is complex. Here I wrote the inverse function by solving through the fzero command, however, I don't know why it is giving me this error:
Error using fzero (line 328)
Function value at starting guess must be finite and real.
I really appreciate your help,
Thank you
syms x
g = 1.02*x + 0.6*exp(-8.7*x)-0.292
gx = @(x) g
gval = 0.1 % or 0.2 or...0.6
guess = 0.5
inv_fun = @(x) (gx(x) - gval)
S = fzero (@(x) inv_fun(x) , guess)

Accepted Answer

Benjamin
Benjamin on 11 Dec 2020
I think I was able to figure it out. it seems fzero can only solve functions in the form of function handle, which matlabFunction can be used for the functions defined as symbolic
syms x
g = 1.02*x + 0.6*exp(-8.7*x)-0.292
gx = matlabFunction(g)
gval = 0.1 % or 0.2 or...0.6
guess = 0.5
inv_fun = @(x) (gx(x) - gval)
S = fzero (@(x) inv_fun(x) , guess)

More Answers (2)

James Tursa
James Tursa on 11 Dec 2020
Edited: James Tursa on 11 Dec 2020
These lines don't do what you think they do
syms x
g = 1.02*x + 0.6*exp(-8.7*x)-0.292
gx = @(x) g
The x in g is symbolic. The x in gx is a dummy input argument that is ignored because it isn't used in g. That is, the x dummy input argument in gx is different from the symbolic x in g.
It looks like you really want just a simple function handle:
gx = @(x) 1.02*x + 0.6*exp(-8.7*x)-0.292
E.g.,
>> gx = @(x) 1.02*x + 0.6*exp(-8.7*x)-0.292
gx =
function_handle with value:
@(x)1.02*x+0.6*exp(-8.7*x)-0.292
>> gval = 0.1;
>> guess = 0.5;
>> inv_fun = @(x) (gx(x) - gval)
inv_fun =
function_handle with value:
@(x)(gx(x)-gval)
>> S = fzero (@(x) inv_fun(x) , guess)
S =
0.3583
>> inv_fun(S)
ans =
-2.7756e-17
>> gx(S)
ans =
0.1000
If you insist on starting with a symbolic expression then you need to convert it to a function handle properly. E.g.,
>> gx = matlabFunction(g)
gx =
function_handle with value:
@(x)x.*(5.1e+1./5.0e+1)+exp(x.*(-8.7e+1./1.0e+1)).*(3.0./5.0)-7.3e+1./2.5e+2

Walter Roberson
Walter Roberson on 11 Dec 2020
gx = matlabFunction(g);
or change your solving method
syms gval x
g = 1.02*x + 0.6*exp(-8.7*x)-0.292
inv_formula = solve(g == gval, x);
inv_fun = matlabFunction(inv_formula);
inv_fun(0.1)

Tags

Community Treasure Hunt

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

Start Hunting!