Generating all possible products from set of values

2 次查看(过去 30 天)
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 :)
  1 个评论
Stephen23
Stephen23 2020-4-17
Your example output repeats the 3*4*X and 3*5*X groups, giving 32 elements. The 24 elements should be:
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

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2020-4-17
编辑:Stephen23 2020-4-17
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by