How to use str2func to replace eval command?

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);

 채택된 답변

Walter Roberson
Walter Roberson 2013년 12월 4일
편집: Walter Roberson 2013년 12월 4일

0 개 추천

fx = str2func(['@(t) ', x_e]);
x = fx(t);

댓글 수: 3

Matthew
Matthew 2013년 12월 4일
편집: Walter Roberson 2013년 12월 4일
I tried your way and it gave me an error
This is my code
t = linspace(0.001,2,1000);
T = t;
x_e = input ('x_e');
y_e = input ('y_e');
z_e = input ('z_e');
fx = str2func(['@(t) ', x_e], 't');
x = fx(t);
fy = str2func(['@(t) ', y_e], 't');
y = fy(t);
fz = str2func(['@(t) ', z_e], 't');
z = fz(t);
and this is what the command window said
Error using str2func
Too many input arguments.
Error in test (line 6)
fx = str2func(['@(t) ', x_e], 't');
Thx
Sorry, corrected. After I put in the bad code I checked the documentation and then forgot to fix the mistake before sending.
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{:};

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

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2013년 12월 4일

0 개 추천

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

Walter Roberson
Walter Roberson 2013년 12월 4일
편집: Walter Roberson 2013년 12월 4일
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 2013년 12월 4일
Thanks I tried both of your ways and both of them work.

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

태그

질문:

2013년 12월 4일

댓글:

2013년 12월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by