# All possible combinations of a number of an array

3 views (last 30 days)
Swati on 27 Nov 2020
Commented: Walter Roberson on 3 Dec 2020
Hi ,
I've a vector , a =[ 1 2 3]. I want to have all possible combinations of elements of a as belows ; 27 in total
o/p : a_o = [ 1 1 1 ; 1 1 2; 1 1 3; 1 2 1; 1 2 2 ; 1 2 3; 1 3 1 ; 1 3 2 ; 1 3 3 ; .........]

Walter Roberson on 27 Nov 2020
a = [ 1 2 3];
ua = unique(a);
nua = length(ua);
assert(nua <= 36, 'Sorry, this code only supports up to 36 elements in the vector')
mapa(dec2base(0:nua-1, nua)) = 0:nua-1;
o_a = a(1 + mapa(dec2base(0:nua.^nua-1, nua)))
o_a = 27×3
1 1 1 1 1 2 1 1 3 1 2 1 1 2 2 1 2 3 1 3 1 1 3 2 1 3 3 2 1 1
The code can be made more efficient if you can be sure that there are no more than 9 elements in the vector (which would be over 350 million rows of output).
The code as designed has a limitation of supporting no more than 36 elements in the vector. If that is a problem, then I can point you to some of my other postings that have code that can deal with longer vectors. However... all entries with 36 elements would require using more memory than can be constructed out of all atoms in the Solar System, so chances are excellent that if you need more than 36 elements that you should start with an extra-large dose of Not Gonna Do That ™

Bruno Luong on 27 Nov 2020
mapa(dec2base(0:nua-1, nua)) = 0:nua-1;
o_a = a(1 + mapa(dec2base(0:nua.^nua-1, nua)))
You can group 2 mappings together
mapa(dec2base(0:nua-1, nua)) = a;
o_a = mapa(dec2base(0:nua.^nua-1, nua))
Swati on 3 Dec 2020
I've, a = [ 3 9 15 21 27]. I applied this code and got o_a of size 3125 x 5 whereas I want to get o_a of size 125 x 3.
Walter Roberson on 3 Dec 2020
You have 5 positions. Each one can be any of 5 different values. Therefore there are 5^5 results.
Getting 125 results would be consistent with taking only 3 output positions, but we have no reason to expect that to be the case. Your only input is a, and your sample wanted all choices in all positions. If you had had a second input that was the number of positions to fill then that would have been different.
o_a = a(1 + mapa(dec2base(0:nua.^positions-1, positions)))

KSSV on 27 Nov 2020
v = 1:3 ;
iwant = npermute(v,3)

Swati on 27 Nov 2020
Hi,
Thanks for responding.
The MATLAB in my laptop does not support this command.
However, through permute I can get all unique combinations by using the elements only once.
Jan on 27 Nov 2020
But this submission produces only permutations without repititions, while the OP asks for e.g. [1 1 1] also. Then this will work: https://www.mathworks.com/matlabcentral/fileexchange/24325-combinator-combinations-and-permutations
index = combinator(3, 3, 'p', 'r');