MATLAB Answers

string to calculation algorithm ?

13 views (last 30 days)
Hey Guys, Imagine u have a GUI which hold the variable x = 1:10 (doubble). Now I want to create an Editbox which allows the user to enter a calculation algorithm.
for example: x*3.
Is it possible to convert this string (x*3) into an actual calculation algorithm ?

  1 Comment

Stephen Cobeldick
Stephen Cobeldick on 16 Sep 2014
The answers below give some solutions, including using eval and str2func , but keep in mind these could be dangerous as this allows the user to run arbitrary code, including system calls via MATLAB.

Sign in to comment.

Accepted Answer

Michael Haderlein
Michael Haderlein on 16 Sep 2014
eval(string)

  0 Comments

Sign in to comment.

More Answers (1)

Adam
Adam on 16 Sep 2014
You can also create a function handle if you want, something like:
s = 'x*3';
s = ['@(x)' s];
f = str2func(s);
f(x);

  1 Comment

Sign in to comment.

Sign in to answer this question.