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

조회 수: 1 (최근 30일)
Brent King
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:
'((5/5)+5)+(5*((5*5)-5))'
I tried using str2func but that didn't seem to work.
  댓글 수: 2
per isakson
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
>>
Brent King
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Titus Edelhofer
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개)

카테고리

Help CenterFile Exchange에서 String에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by