The use of eval in Matlab
Published by Kasper D. Fischer on December 8th, 2013
I just came across the a Matlab® script which used the
eval function to evaluate and execute an expression in a text string. Of Course there are a few, limited situations where the use of eval is necessary, but for all uses I came across in the last 10 years there are better solutions than using the eval function. For example in a function to calculate the Gutenberg-Richter Magnitude I found:eval(sprintf('disp(''Ml=%3.1f'')',Ml_net));and
eval(sprintf('load %s',datfile));These are two typical use cases for which Mathworks (the creators of Matlab) do not recommend to use
eval and also provide solutions which don't use it.Let's first have a look on why the
eval function should be avoided and then on what alternatives exists. Code that calls eval is often less efficient and more difficult to read and debug than code that uses other functions (Matlab online documentation):- Matlab compiles code the first time you run it to enhance performance. Code in an eval statement can change at run time and therefore can't be compiled.
- The eval statement can unexpectedly create or assign to a variable already in the current workspace, overwriting existing data. This can not be detected by the syntax checker of the Matlab editor.
- Concatenating strings within an eval statement is often difficult to read and to debug.
disp(sprintf('Ml=%3.1f', Ml_net));or even shorter
fprintf('Ml=%3.1f', Ml_net);The solution for the second example is even simpler:
load(datfile);Remember: There are (almost) always alternatives to using
eval. Eval is evil!