MATLAB: Generating all possible products from set of values

multiplevariablesvector

Hi!
I have some variables that can have different values:
X1 can be 1, 2 or 3
X2 can be 4 or 5
X3 can be 6 or 7 or 8 or 9
I need to multiply the values of the variables, and generate all possible combinations. I mean as a result, I need a vector, that contains:
1*4*6; 1*4*7; 1*4*8; 1*4*9; 1*5*6; 1*5*7; 1*5*8; 1*5*9; 2*4*6; 2*4*7; 2*4*8; 2*4*9; 2*5*6; 2*5*7; 2*5*8; 2*5*9; 3*4*6; 3*4*7; 3*4*8; 3*4*9; 3*5*6; 3*5*7; 3*5*8; 3*5*9; 3*4*6; 3*4*7; 3*4*8; 3*4*9; 3*5*6; 3*5*7; 3*5*8; 3*5*9. (in this case 24 elements, because 3*2*4=24).
In this small example I can calculate it by hand, but in reality, I have much more variables with more possible values, so I need a way to automatize this task.
Thank you guys for help 🙂

Best Answer

One simple solution (although it does change the size of A on each iteration).
C = {[1,2,3],[4,5],[6,7,8,9]}; % much better in a cell array than as separate variables.
A = C{1}(:);
for k = 2:numel(C)
V = shiftdim(C{k}(:),1-k);
A = A.*V; % requires >= R2016b
end
B = A(:); % optional
or to get the order you requested:
>> B = reshape(permute(A,numel(A):-1:1),[],1)
B =
24
28
32
36
30
35
40
45
48
56
64
72
60
70
80
90
72
84
96
108
90
105
120
135
For earlier MATLAB versions replace the .* with bsxfun.