# Is there a way to make matlab create variables of any number on its own?

47 views (last 30 days)
Voula on 7 Sep 2015
Answered: Walter Roberson on 7 Sep 2015
I was making a programm that has some numbers that each time change because every time are generated random and I don't know the exact number of the variables I have to set due to this fact, so I was wondering if there is any command or function in matlab that helps me to create variables of any number, depending on the numbers that I get each time from an other variable. For example if a=10, I want matlab to create 10 new different variables, but the next time that I will run that programm and a=25, I want to be created 25 variables automatic without having to interfere myself.

John D'Errico on 7 Sep 2015
DON'T DO IT. This is just bad programming style, even if you do figure out a way to do it. (Yes there are ways to do so. They are not efficient. They are great ways to create buggy code.)
Learn to use arrays. The fact is, it is nearly as simple to type a(1) or a{1} as it is to type a1. Your code will be far better for it.

### More Answers (3)

the cyclist on 7 Sep 2015
One thing that might be useful for you is a cell array:
a = 10;
for na = 1:a
avar{na} = rand(na)
end

Hamoon on 7 Sep 2015
you don't need to define 10 variables, just define one and use its dimensions as different variables. If new variables are in the same "size" and "type" you can easily use an array with 10 rows and suitable columns. But if your new variables are arrays or strings in different sizes and types you can use cells:
b=cell(a,1);
and then use each cell as one variable.
b{1}='Hello';
b{2}=[1 2 3];
b{3}=[1 2 3; 4 5 6];
...
b{a}= 'anything';

Walter Roberson on 7 Sep 2015