MATLAB: Variable name with variation

variable variable-name

I have a very basic question. I want to write a loop in MATLAB which creates 4 separate variables with "a" number "in the name" and put 22 in each of them. Something like this:
for a=1:4
star'{a}'=22
end
But this does not seem to identify "a" separately and not as a part of the variable name. How should I use syntax to do that?

Best Answer

What you're describing is called dynamic variable naming and it should be avoided. Instead, you can store the intended variable name and its value in a cell array as shown below.
star = cell(4,2);
for a=1:4
star{a,1} = 'a'; % in reality, this would vary across iterations

star{a,2} = 22; % in reality, this would vary across iterations
end
Or, you could store it in a structure,
star = struct();
for a=1:4
star.('a') = 22; % assuming 'a' and will vary across iterations
end
See this outline for reasons to avoid using dynamic variable names.