How to use str2func to replace eval command?

1 view (last 30 days)
I want user to enter a parametrized function in terms of t. Is there a way that I can have an input function instead of using '' and eval?
t = linspace(0.001,2,1000);
T = t;
x_e = 't.^3';
y_e = 'exp(t)';
z_e = 'cos(10*t)';
x = eval(x_e);
y = eval(y_e);
z = eval(z_e);

Accepted Answer

Walter Roberson
Walter Roberson on 4 Dec 2013
Edited: Walter Roberson on 4 Dec 2013
fx = str2func(['@(t) ', x_e]);
x = fx(t);
  3 Comments
Walter Roberson
Walter Roberson on 4 Dec 2013
Sorry, corrected. After I put in the bad code I checked the documentation and then forgot to fix the mistake before sending.
Andrei Bobrov
Andrei Bobrov on 4 Dec 2013
Hi Matthew and Walter!
t = linspace(0.001,2,1000);
x_e = 't.^3';
y_e = 'exp(t)';
z_e = 'cos(10*t)';
funs = cellfun(@str2func,strcat('@(t),{x_e,y_e,z_e}),'un',0);
rez = cellfun(@(q)q(t),funs,'un',0);
[x,y,z] = rez{:};

Sign in to comment.

More Answers (1)

Andrei Bobrov
Andrei Bobrov on 4 Dec 2013
t = linspace(0.001,2,1000);
x_e = 't^3';
y_e = 'exp(t)';
z_e = 'cos(10*t)';
funs = arrayfun(@matlabFunction,sym({x_e,y_e,z_e}),'un',0);
rez = cellfun(@(q)q(t),funs,'un',0);
[x,y,z] = rez{:};
  2 Comments
Walter Roberson
Walter Roberson on 4 Dec 2013
Edited: Walter Roberson on 4 Dec 2013
Notice here that Andrei had to change
x_e = 't.^3';
to
x_e = 't^3';
This is because sym() interprets strings as being in MuPAD language, which is slightly different than MATLAB itself. str2func() uses MATLAB language. matlabFunction() knows to convert MuPAD symbols into MATLAB language.
Matthew
Matthew on 4 Dec 2013
Thanks I tried both of your ways and both of them work.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!