How can I turn a string into a function and obtain the result?
1 次查看(过去 30 天)
显示 更早的评论
To be more precise I have a sequence of functions that result in several outputs that all look similar to this:
'((5/5)+5)+(5*((5*5)-5))'
I tried using str2func but that didn't seem to work.
2 个评论
per isakson
2018-7-29
" that didn't seem to work." Always describe exactly what you did and what error message was returned.
Try
>> foo = str2func('@() ((5/5)+5)+(5*((5*5)-5))');
>> foo()
ans =
106
>>
采纳的回答
Titus Edelhofer
2018-7-30
Hi Brent,
maybe you can describe a little more what you are trying to achieve? Your "function" has no input, so you could basically evaluate the string:
str = '((5/5)+5)+(5*((5*5)-5))';
value = eval(str);
If you indeed have a function, e.g.
str = '2*exp(x)';
then Per's suggestion of using the "@" and str2func works fine:
fcn = str2func(['@(x) ' str]);
Regards, Titus
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!