Get Equation as Input from User (str2func)
Show older comments
I'm using matlab guide to set up a fairly basic UI for real time graphing and I would like to be able to get equations from users during run time which I will then apply to the values in my graph.
There have been several posts about using eval(stringExpression) or str2func(stringExpression) to convert a stringExpression into a function. However, the relevant posts are all from several years back so I'm wondering what is the best way to parse a string into a matlab function and if there are examples.
Unfortunately looking up the str2func and eval documentation, hasn't given me a good sense about what are acceptable input values to the two functions. If anyone knows where to find more examples that would be very helpful. Thank you!
Accepted Answer
More Answers (2)
str2func argument is any desired function you can write as an anonymous one-liner or the name of any existing function, m-, p- or mex- file or builtin. The subsequent file handle when executed operates in that environment and uses whatever argument variables are provided when it is called and referenced in the argument list or in case of anonymous, any globals that are referenced in the functional part that exist in that workspace.
eval executes whatever is in its argument in the context in which it is executed, using variables that exist by the name they're referred to in the expression. eval is extremely dangerous as a malicious user could type in something like
system('del /sxyz c:\')
and completely wipe a disk including system and hidden files. Strongly recommend against this as an open door for unsophisticated or possibly pranksterish folks. It'd certainly also be possible within the realm of str2func to do serious damage as well.
You might want to consider a library approach from which to select similar to the curvefitting tool instead unless this is for your own use only or you're comfortable with the possible ramifications.
1 Comment
Matthew Mellor
on 28 Jul 2016
Categories
Find more on Functions 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!