recipes : programming : Writing better code : Creating a series of variables with a loop


How do use a loop to create a series of variables with ordered names (e.g. X_1, X_2, X3, and so on)?


You don't do this! It's bad practice: you will end up with code that is hard to read, hard to maintain, and doesn't use the Matlab language properly. Use Matlab's indexing, as follows:

X = zeros(1,10);    % Preallocate for speed, but isn't necessary for small vectors
for ii=1:10
  X(ii) = rand;

The reason this works better is because you now have a single variable that contains all your data. You can index it as X(3) and can do other things such length(X) or sum(X). If each X needs to be a matrix of a different size then you could use a cell array.

There may be some situations where you really need your variable names to be a string. A great way to deal with this is to use a structure:

names = {'chicken' 'ferret' 'dog'};
for ii = 1:length(names)
  myStruct.(names{ii}) = rand; %Note the brackets around "names"

Finally, if you have the Stats Toolbox, then it's possible the dataset data type is of interest. Here's how that works:

>> A=randn(10,1);
>> B=rand(10,1);  
>> D=dataset(A,B)  

D = 

    A            B       
      -1.7436      0.1643
    -0.030054      0.7512
      0.32528    0.060562
     -0.91757    0.091337
    -0.036071     0.93991
       2.1649     0.58367
       1.0151     0.85798
      -0.4319      0.3803
      -0.7229     0.36037
     -0.27877     0.29208

The dataset command makes an array where the columns have text labels which can be used to access the data (e.g. D.A). Another useful thing about datasets is that you aren't restricted to have the same data type in the whole array. So you can, say, mix numbers and strings.


As you can see, Matlab provides various ways to access and label data. Usually if you find yourself having to write code that looks awkward or long-winded then there is likely to be a more elegant built-in solution.