Is it possible to change the value of a variable to text and then execute that text as code?
for example, if I have two different functions, function1(t) and function2(t), and I have a variable x that can take on the values {1,2}, would it be possible to do something like
Y = function'num2code(x)'(t)
where 'num2code(x)' (an expression that I'm just making up) is evaluated as a text '1' or '2' and then executed as part of the code in order to call the appropriate function.
In other words I am looking for dynamically generated code. I realize that I could accomplish the same thing with a series of 'if' statements, but in my case it would make the code very verbose and difficult to maintain.

댓글 수: 1

José-Luis
José-Luis 2014년 6월 24일
편집: José-Luis 2014년 6월 24일
You could use eval(). I am afraid that would make your code a nightmare to maintain, though. eval() not only confuses the debugger, but also, parsing strings passed to eval() is a known source of headaches and frustration and causes the name of many mothers to be taken in vain.
The general consensus is that it is a bad idea to do so. A slightly better idea would be to use feval().

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

 채택된 답변

José-Luis
José-Luis 2014년 6월 24일

0 개 추천

doc feval

댓글 수: 2

Ryan
Ryan 2014년 6월 24일
thank you!
José-Luis
José-Luis 2014년 6월 24일
My pleasure. I would still recommend that you avoid using it though. Loops are not always evil.

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

추가 답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 MATLAB에 대해 자세히 알아보기

제품

질문:

2014년 6월 24일

댓글:

2014년 6월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by