MATLAB: Assignin and eval functions

assigninbeginnerbuggycomplexdynamic variable namesevalevalcevalinloadMATLABmatlab functionobfuscatedslow

Hi everyone,
I have a question that really tangles my mind. The experienced contributors to the forum always emphasize avoiding usage of assignin and eval functions due to many reasons. I now know the reason for it thanks to Walter Roberson especially. Then why MATLAB does not stop their usage? I really need to be enlightened about this issue.

Best Answer

You totally misunderstand the issue if you think that eval, evalin or assignin are faulty.
There is nothing wrong with eval, evalin, or assignin, in the sense that they work exactly as documented and do exactly what they are supposed to do. Sometimes these functions are useful. But...
The problem is that what they do lets many beginners use them totally inappropriately, to solve tasks that would be much better solved using simpler, faster, neater, more efficient, easier to debug and much more robust methods (usually indexing is the simpler solution). Simply put, those beginners design their code in such a way that they force themselves to write bad code: slow, buggy, hard to debug, insecure, complex, ugly code. By deciding to write such bad code they remove all of the inbuilt code checking and code helper tools. They also remove any ability for the JIT compiler to speed up their code. They remove the ability to search for and locate variables. The list goes on. Even if all other things were equal, any one of these disadvantages would be reason enough to avoid dynamic variable names.
Or, to put it another way, the problem is not using eval in particular, the main problem is dynamically accessing variable names. It just happens that magically defining or accessing variable names is most commonly achieved using eval and assignin, but the problem actually occurs regardless of what tool or method is used to access them: it also applies to load, for example, when load is called without an output variable.
You need to stop asking "what is the problem with eval?", and start asking yourself "why is it so inefficient to dynamically access variable names?". To help understand some of the issues that is causes, read this thread:
You are not the first beginner to ask this question. Some of them get really confused, because they think that there is a problem with eval. For example, read this discussion, including all of the answers and comments:
"The experienced contributors to the forum always emphasize avoiding usage of assignin and eval functions due to many reasons."
You will notice that the title of my tutorial is actually "TUTORIAL: Why Variables Should Not Be Named Dynamically (eval)". All of the discussions and links within that tutorial are focused on one topic: dynamically accessing variable names. You need to start reading about this topic if you really want to understand it.