MATLAB: Need help in creating matrix…..please

combinationcreate matrixmatrix manipulation

I wanna create matrix like this A(m,n), which n defined by user input. matrix A is consist of combination between number 1,2,3. then the form of this matrix if n=3: A=[1 1 1; 2 1 1; 1 2 1; 1 1 2; 2 2 1; 2 1 2; 1 2 2; 2 2 2; 3 1 1; 1 3 1; 1 1 3; 3 3 1; 3 1 3; 1 3 3; 3 2 2; 2 3 2; 2 2 3; 1 2 3; 1 3 2; 2 1 3; 2 3 1; 3 2 1; 3 1 2; 3 3 3] please help me to create this matrix.
thanks in advance.

Best Answer

a = 1:3;
n = 3;
k = perms(reshape(ones(n,1)*a,1,[]));
aout1=unique(k(:,1:n),'rows');
OR
a2 = cell(1,n);
[a2{:}] = ndgrid(a);
aout2 = cell2mat(cellfun(@(x)x(:),a2,'un',0));