MATLAB: How to create variables and then use them in loops

create variables

I have 2 variables K and C, which I want a user to be able to enter values for. Once I have values for K and C, I want to create KC variables ie A1, A2, A3,… AKC (I think I can do this bit). I then want to create KC for loops where each variable A1…AKC takes values between 1 and x,
eg:
B=[ ]
for A1=1:x
for A2=1:x
for A3=1:x
(and so on)
Q=[A1,A2,A3..]
B=[B;Q]
end
end
end
So that I end up with a matrix where each row is a different combination of the variables A1…AKC, and I have all possible combinations.
Thanks,
Erin

Best Answer

So... you want to create a program that is going to write a program that consist of a bazillion nested for loops that are going to calculate something. A better idea would be to write the first program so that it calculates something directly.
Creating dynamic variables is an extremely bad idea. Unless you've got years of experience writing code, don't do it. If you start numbering variables, you're doing something very wrong. There's already something in matlab that allows you to simply access things by number, it's called a matrix / vector / cell array. Instead of A1, A2, A3, ... you use A(1), A(2), A(3), etc.
Now, if I understood correctly, what you want to generate does not even require a single for loop:
x = 4;
KC = 6;
C = cell(1, KC);
[C{:}] = ndgrid(1:x);
C = cell2mat(cellfun(@(c) c(:), C, 'UniformOutput', false))