How to get all possible combination With the total number of possible combination for "n" variables that can take different values

4 次查看(过去 30 天)
Hi Guys,
I have "n" variables that my take different values each. (e.g.: length of variable 1 = m1, 2 = m2, 3 = m3 , ...., n = mn)
how can i get the following:
1- what is the total number of possible combination for such problem? is that m1*m2*m3*.....*mn?
2- is there an easy way to get the totale possible combination as a table for those n variables? something like this:
Comb-1 Comb-2 .....................
Var(1) Val(Var(1)[1]) Val(Var(1)[2])
Var(2) Val(Var(2)[1]) Val(Var(2)[1])
Var(3) Val(Var(3)[1]) Val(Var(3)[1])
. . .
. . .
. . .
Var(n) Val(Var(n)[1]) Val(Var(n)[1])
Thanks in Advance

采纳的回答

Bruno Luong
Bruno Luong 2024-3-25

更多回答(1 个)

Voss
Voss 2024-3-25
a = [1 99];
b = [2 30 700];
c = [4 55 666 8888];
vars = {a,b,c};
n = numel(vars);
out = cell(1,n);
[out{:}] = ndgrid(vars{:});
result = reshape(cat(n+1,out{:}),[],n);
disp(result)
1 2 4 99 2 4 1 30 4 99 30 4 1 700 4 99 700 4 1 2 55 99 2 55 1 30 55 99 30 55 1 700 55 99 700 55 1 2 666 99 2 666 1 30 666 99 30 666 1 700 666 99 700 666 1 2 8888 99 2 8888 1 30 8888 99 30 8888 1 700 8888 99 700 8888
Transpose result if desired.
An option for R2023a or later is to use the combinations function:
result = combinations(a,b,c); % R2023a or later
disp(result)
a b c __ ___ ____ 1 2 4 1 2 55 1 2 666 1 2 8888 1 30 4 1 30 55 1 30 666 1 30 8888 1 700 4 1 700 55 1 700 666 1 700 8888 99 2 4 99 2 55 99 2 666 99 2 8888 99 30 4 99 30 55 99 30 666 99 30 8888 99 700 4 99 700 55 99 700 666 99 700 8888

类别

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

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by