Generating all possible products from set of values

2 ビュー (過去 30 日間)
Gabor Pauer
Gabor Pauer 2020 年 4 月 17 日
コメント済み: Gabor Pauer 2020 年 4 月 17 日
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.
  1 件のコメント
Gabor Pauer
Gabor Pauer 2020 年 4 月 17 日
Thank you Sir, it works :) the order is not important for me :)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by