Creating multiple variables with consecutive names using a for loop

I want to create several variables with consecutive names. For instance, I want to create 100 variables like variable_1, variable_2, … , variable_100, and maybe assign a random vector to each of them, e.g. variable_1 = rand(1,10). Then I want to iterate through each of them and change some elements inside them. How can I do it using a for loop? Thanks in advance.

1 Like

Is there a specific reason why you don’t want to use an array for this?

1 Like

You can’t do it. You should use an array.

Or if it’s something static, then you can write a loop to generate the code…

2 Likes

Do you mean an array of arrays? That’s a good idea. I am coming from MATLAB and was thinking about this problem with MATLAB perspective, where you can do something like 'variable_num2str(i)'. So you’re saying that’s not possible in Julia?

Even in MATLAB you should probably use a cell array. I have not tested it but I highly suspect using a cell array is faster.

1 Like

Yes, an array of array (or a Matrix, if that’s an option) would be the standard way to achieve this in Julia.

1 Like

Although you should use an array as was suggested, you could technically create and modify variables in the global scope using something like this (maybe it can be written more nicely, but anyway you probably shouldn’t use it):

# create the arrays
for i in 1:100
    eval(:($(Symbol(:v,"_",i)) = rand(1,10) ))
end

# modify the first element of each array
for i in 1:100
    eval( :($(Symbol(:v,"_",i))[1] = 0 ))
end

You can find more info on this in the meta-programming section of the manual. But once again let me emphasize that I don’t think it is necessary for your current use case.

3 Likes

I am also a Matlab user. You should never do this in Matlab either, or in any language. In Matlab you could use a cell array of arrays, for example.

1 Like

I wouldn’t say “any language”. I’ve done variance of this in bash and cmake for example. Both of which are very much string processors and lack support for storing nested/structured information. For anything that has truely generic array and map support this shouldn’t be necessary.