Evading eval
If you are a regular reader of the MATLAB Usenet newsgroup, comp.soft-sys.matlab, found on the MathWorks User Community page, you are probably familiar with repeated advice to not use the MATLAB function eval . Today I plan to tell you more about why this is generally good advice.
Code Clarity / Readability
Statements containing a call to eval have a way of obscuring the underlying intent of the code though this is rarely a goal of the author. What do I mean by this? Well, in under 3 seconds, can you discern what the following code means?
a = who ; a = a(~cellfun('isempty',regexp(a,'2$'))) ; str = sprintf('%s,',a{:}) ; str = sprintf('B = cat(1,%s) ;',str(1:end-1)) ; eval(str) ;
Unless you are one of the proponents of this code pattern (see this newsgroup post, for example), you likely couldn't tell that the code is saying
Concatenate all variables that have '_2' in their name, i.e. a_2, b_2, c_2
Efficiency
When a function M-file is run in MATLAB for the first time in a session, MATLAB reads in the file, translates it into an internal representation, analyzes the contents, and executes the code. The next time you use this function in the same MATLAB session, assuming the file hasn't changed, MATLAB doesn't need to reread and translate the file.
However, if the M-file contains any calls to the function eval, at least those lines of code will need to be reinterpreted each time the function is run. Why? Because there is no guarantee, and it is generally not true, that the expression that was executed in the first instance is the same as subsequent ones. The expression may require different MATLAB functions or variables. In any case, to be sure MATLAB gets the right answer, at least the lines of code containing eval statements need to be re-analyzed with each invocation.
Analyzability
In an M-file, if the functions being called are coded into strings so they can be placed into eval statements, it is very difficult to build up a complete understanding of the functions and files that your M-file depends upon, especially in a static way. It might be possible, though probably difficult and perhaps error-prone, to scan through an M-file to see where strings are used in eval statements and to try to pull out the possible function and file names from these.
Techniques to evade eval
- Use structs and have fields with the chosen names (using dynamic field references) instead of naming variables with those names
- str2func
- Category:
- Readability
Comments
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.