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

4 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Bruno Luong
Bruno Luong el 25 de Mzo. de 2024

Más respuestas (1)

Voss
Voss el 25 de Mzo. de 2024
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

Categorías

Más información sobre MATLAB en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by