# Creating a matrix of all possible combinations of an array - MATLAB

40 vues (au cours des 30 derniers jours)
Guy Lawrence le 2 Mar 2020
Hi!
I am looking to create a matrix that contains all possible combinations of elements in an array of size n, but to a smaller number size of matrix
For example, if x = [1,2,3,4,5], I might want to produce a [4x(5^4)] matrix that contains 625 combinations of 4 numbers from x, or a [(3x5^3)] matrix that contains 125 combinations of 3 numbers.
Is there a MATLAB function that would assist with this, as opposed to making many for loops?
Any help would be much appreciated!
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Réponse acceptée

Guillaume le 2 Mar 2020
" as opposed to making many for loops"
Why would you use loops for this?
%x: a vector of numbers
x = 1:5;
%n: number of elements to pick (with repetetition) from x. n must be less than or equal to numel(x)
n = 4;
assert(n < numel(x), 'n can''t be greater than numel(x)')
combs = cell(1, n);
[combs{:}] = ndgrid(x);
combs = reshape(cat(n+1, combs{:}), [], n); %a numel(x)^n X n matrix of combinations
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

R2019b

### Community Treasure Hunt

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

Start Hunting!

Translated by