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

1 Ansicht (letzte 30 Tage)
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 Kommentare
per isakson
per isakson am 29 Jul. 2018
" 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 am 29 Jul. 2018
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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Titus Edelhofer
Titus Edelhofer am 30 Jul. 2018
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

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Produkte


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by