How to use subs() instead of eval()?
6 views (last 30 days)
Show older comments
I've got some code where the user enters a string form of a function (like "z*z+5) in complex variable z, takes a symbolic derivative, and evalutes iteratively it for some different values of z. Like a root-finding method:
for (k=1:50)
z = z - eval(formula)/eval(derivative) / (1 - ...
(eval(formula)*eval(derivative2))/(2*power(eval(derivative),2.0)));
I'm seeing a number of discussions on-line that ssuggest that I need to use subs() instead of eval(). But I'm having trouble seeing how to use them the same way:
with z=z-evalI(...) the eval returns a number and everything is cool with the expression. But subs() returns an expression, not the number, so how do I feed it into the math wihout having to use eval() on it? I tried it just using subs in the place of eval and it gives an error about the variable z being inaccessible. What am I missing?
0 Comments
Answers (1)
Stephen23
on 25 Apr 2020
Edited: Stephen23
on 25 Apr 2020
Following the Symbolic Toolbox documentation, you need to use double:
val = double(subs(...))
This page took me three seconds to find using [name of a major internet search engine]:
(note that eval is NOT listed on that page or anywhere else in the Symbolic Toolbox documentation (but double is). The undocumented side-effect of eval doing something with your symbolic expressions could be removed tomorrow without any change to the documentation at all. Use of undocumented "features" is entirely at your own risk).
2 Comments
Stephen23
on 25 Apr 2020
"Is it plausible that double(subs()) is way slower than eval()?"
Yes, because it invokes the symbolic engine to correctly parse the symbolic expression (whereas eval evaluates the expression as if it were MATLAB code (which it isn't)).
Is it really required to evaluate this symbolically? I would approach this numerically if at all possible.
See Also
Categories
Find more on Code Execution 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!