Why eval() and evalin() are not recommended?

12 views (last 30 days)
I have read so many times that functions eval() and evalin() are not recommended. What is the reason?
I have a situation where i want to evaluate the value of a parameter whose name is stored in string.
I obtained parameter name as
CostName=get_param(cblk,'Name');
Now i want value of this parameter from workspace so i wrote
CostVal=eval(strcat(CostName,'.Value'));
Is there any alternative for above line instead of using eval();

Accepted Answer

Daniel Shub
Daniel Shub on 22 Sep 2011
See the FAQ and TMW for reasons to avoid eval and evalin
As your code is written now, you probably cannot avoid eval. One possible work around would be if all of your "parameters" (i.e., anything that could be returned by get_param) were saved in a structure. Then you could do
param.(CostName).Value
You really need to show us how the variable that the string in CostName points to was created in order for us to give you ideas about how to avoid eval.
  7 Comments
TAB
TAB on 26 Sep 2011
I think, there is no alternative of eval() in this case.
K E
K E on 3 Apr 2012
Simulink coding seems to rely on many practices that Matlab experts recommend against, such as frequent use of eval and evalin; or populating the workspace with many variables without tracking where they came from. See #6, 7 and 9 on http://blogs.mathworks.com/loren/2012/01/13/best-practices-for-programming-matlab/ . Perhaps these two departments of Mathworks could benefit from talking more often.

Sign in to comment.

More Answers (0)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!