Effacer les filtres
Effacer les filtres

How to obtain all possible combinations from a set of values without nested for loops ?

3 vues (au cours des 30 derniers jours)
Hi people! I wanted to know if there is an elegant and general approach to generate all possible vectors of a given length where the components are being taken from a known set of values. In my example I have:
set={-1,0,1}; %set of possible values for vector components
n=10; % length of vector
A possible combination for a vector could be
[0,0,0,0,0,0,0,0,0,0]
or
[0,0,0,0,0,0,0,0,0,1]
or
[1,0,0,0,0,0,0,0,0,-1]
So there are 3^10=59049 possible combinations for the components of the vector. I would like to have a method where my result is a 59049-by-10 matrix, each row being a unique combination of the values {-1,0,1}.
The only way I found is extremly inefficient and not parametric, simply nesting 10 for loops, so I would be really thankful for a "real" method. I already tried different matlab functions such as combvec, combnk, but they didn't do what I wanted. Maybe I just used them wrongly.

Réponse acceptée

Matt J
Matt J le 29 Août 2017
Modifié(e) : Matt J le 29 Août 2017
n=10;
[combs{1:n}]=ndgrid([-1,0,1]);
result=reshape( cat(n+1,combs{:}) ,[],n);
  6 commentaires
Vivek kumar
Vivek kumar le 25 Août 2020
Could u suggest anything better?
Matt J
Matt J le 25 Août 2020
I think the loop-free approach in my last comment would be faster, if that matters...

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by