create all possible combinations of numbers

5 views (last 30 days)
I have this code for creating a matrix that shows all possible combinations of numbers
function pathcomb=allcombinations(a, b, c, d)
sets = {a, b, c, d};
[a, b, c, d] = ndgrid(sets{:});
pathcomb = [a(:) b(:) c(:) d(:)];
Can I change it more flexible with the number of input variables?
I was trying to input 11 times of [0 1], but it is onerous to write [0 1] 11 times, and I also realized that I need to change the code when the number of inputs varies. Let us assume that I am working only with [0 1] matrix as an input. Then, how can I make it simple?
For example, if I have five [0 1] matrix, the outcome will [0 0 0 0 0;0 0 0 0 1;0 0 0 1 0;0 0 0 1 1,...,1 1 1 1 1]. It would be better if the function requires the number of [0 1], 5 in this example, as an input.

Answers (1)

Walter Roberson
Walter Roberson on 23 Sep 2016
N = 5;
repmat([0 1], 1, N)
this would produce [0 1 0 1 0 1 0 1 0 1]
You might also in future be interested in repelem() repelem([0 1], 5) would produce [0 0 0 0 0 1 1 1 1 1]
  2 Comments
SANG GYU LEE
SANG GYU LEE on 23 Sep 2016
Well.. it does not create all possible combinations. I need an output matrix of [0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 1 0 0 1 0 0 0 0 1 0 1 0 0 1 1 1 .... 1 1 1 1 1] in case the input is 5
Walter Roberson
Walter Roberson on 23 Sep 2016
I misread your question, sorry.
function pathcomb = allcombinationsN(a, N)
[t1{1:N}] = ndgrid(a);
t2 = cellfun(@(M) M(:), t1, 'Uniform', 0);
pathcomb = horzcat(t2{:});

Sign in to comment.

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!