## Loren on the Art of MATLABTurn ideas into MATLAB

Note

Loren on the Art of MATLAB has been archived and will not be updated.

# More on eval

I recently wrote an article on Evading eval. A couple of users asked me how to avoid using eval in the case post under Code Clarity / Readability. The answer is you can't, unless you rethink the code altogether.

Where did the variables come from and who established the naming convention? If it was you the programmer, then you have some great options for avoiding the hard-to-understand code.

### First option: structures

You can create names that you want as fields of a structure and use fieldnames and dynamic field references.

### Second option: cell arrays

You can use cell arrays to hold the variables and use cell indexing to get the contents for any particular array. See the FAQ for more information which I will quote here:

Now, if you still really want to create variables with dynamically generated names, you need to use eval. With eval, you use MATLAB commands to generate the string that will perform the operation you intend. For example, eval('A=10') has the same effect as A=10, and eval(['A' 'B' '=10']) has the same effect as AB=10, only the eval method executes much more slowly. So in a loop, you could use:

for i=1:10
eval(sprintf('A%d = [1:i]', i));
end


Notice how much more obfuscated this is. Repeat: don't do this unless you have a very good reason (such as someone gives you a MAT file with 2000 variables named A1428, for example).

The only thing I would add to this is that you could indeed load the variables in the MAT-file into a structure, by writing something like this:

                      MyData=load('data.mat');


The variable MyData is a struct with the variable names in the MAT-file as the field names. So once again, you can use dynamic field references to rescue your code.

### コメント

コメントを残すには、ここ をクリックして MathWorks アカウントにサインインするか新しい MathWorks アカウントを作成します。