MATLAB Answers


How can I turn a string into a function and obtain the result?

Brent King さんによって質問されました 2018 年 7 月 29 日
最新アクティビティ Titus Edelhofer
さんによって 回答されました 2018 年 7 月 30 日
To be more precise I have a sequence of functions that result in several outputs that all look similar to this:
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.
>> foo = str2func('@() ((5/5)+5)+(5*((5*5)-5))');
>> foo()
ans =
Brent King 2018 年 7 月 29 日
Thank you that seems to have done the trick.
I do apologize for the lack of detail, this is my first time posting a question.

サインイン to comment.




1 件の回答

回答者: 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 件のコメント

サインイン to comment.

Translated by