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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by