Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to function handle in Matlab?

Tags:

matlab

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.

like image 659
jinawee Avatar asked Mar 02 '15 10:03

jinawee


People also ask

How do you create a handle function in MATLAB?

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.

What is str2func MATLAB?

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.

Can you plot a function handle in MATLAB?

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.

What is eval MATLAB?

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.


1 Answers

Doesn't the following work?

str = 'x^2+3';
f = str2func(['@(x)' str]);
like image 155
am304 Avatar answered Oct 13 '22 20:10

am304