jinawee
jinawee

Reputation: 510

How to convert string to function handle in 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.

Upvotes: 11

Views: 6750

Answers (1)

am304
am304

Reputation: 13876

Doesn't the following work?

str = 'x^2+3';
f = str2func(['@(x)' str]);

Upvotes: 13

Related Questions