I have to convert a string like str='x^2+3'
into a function. A solution is to obtain an inline function, f=inline(str)
, but it will be unsupported in future versions.
A workaround is f=eval(['@(x)',f])
but it doesn't seem a neat option.
The function str2func
doesn't work because it requires just the name of an existing function.
Function handles can represent either named or anonymous functions. To create a function handle, use the @ operator. For example, create a handle to an anonymous function that evaluates the expression x2 – y2: f = @(x,y) (x.
fh = str2func( str ) constructs a function handle, fh , from a function name or text representation of an anonymous function. Function handles created using str2func do not have access to variables outside of their local workspace or to nested functions.
function handle. Function to plot, specified as a function handle to a named or anonymous function. Specify a function of the form y = f(x) . The function must accept a vector input argument and return a vector output argument of the same size.
eval( expression ) evaluates the MATLAB® code in expression . Note. Security Considerations: When calling eval with untrusted user input, validate the input to avoid unexpected code execution. Examples of untrusted user input are data coming from a user you might not know or from a source you have no control over.
Doesn't the following work?
str = 'x^2+3';
f = str2func(['@(x)' str]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With