MATLAB: All possible n-length combinations of two numbers

combinationspermutations

Suppose I have two numbers, u and v, and a length n. I want to create all possible combinations of u and v that give me a vector length n, with repeats allowed. This gives different combinations. It is easier to show how this works with a couple of examples:
gives: [u u; u v; v u; v v], which is a matrix of length x n = 2 x 2.
gives: [u u u; u u v; u v u; u v v; v u u; v u v; v v u; v v v], which is a matrix of length 8 x 3.
There should be a pretty simple solution to this, but I'm having trouble using functions like perm or nchoosek to accomplish this. Thank you in advance!

Best Answer

Use ndgrid: (in these examples I used u=5, v=7):
>> [X,Y] = ndgrid([5,7]); % n = 2
>> M = [X(:),Y(:)]
M =
5 5
7 5
5 7
7 7
>> [X,Y,Z] = ndgrid([5,7]); % n =3
>> M = [X(:),Y(:),Z(:)]
M =
5 5 5
7 5 5
5 7 5
7 7 5
5 5 7
7 5 7
5 7 7
7 7 7
General solution for any n:
>> n = 4;
>> C = cell(1,n);
>> [C{:}] = ndgrid([5,7]);
>> C = cellfun(@(a)a(:),C,'Uni',0);
>> M = [C{:}]
M =
5 5 5 5
7 5 5 5
5 7 5 5
7 7 5 5
5 5 7 5
7 5 7 5
5 7 7 5
7 7 7 5
5 5 5 7
7 5 5 7
5 7 5 7
7 7 5 7
5 5 7 7
7 5 7 7
5 7 7 7
7 7 7 7
See also: