Loren on the Art of MATLAB

Turn ideas into MATLAB

More on eval 2

Posted by Loren Shure,

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.

Note

Comments are closed.

2 CommentsOldest to Newest

Hiroshi Furutani replied on : 1 of 2
Hi Loren, I understand why creating variable with dynamically-assigned name should be avoided. It will be very complex on Matlab. But I have to admit that variables with specific names are really useful to understand the content later and further data analysis. Just looking at the workspace, one can understand the content. Is there any better and practical way to make both sides happy?
Loren replied on : 2 of 2
Hiroshi- I recommend using dynamic field names with structures. Here's an example:
label = 'loren'
d.([label] str2int(4) = data{4};
%% now there's a struct with field 'loren4'
--Loren