All possible combinations of a number of an array

12 views (last 30 days)
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 ; .........]
Please help me with its code.
Thanks in advance!

Accepted Answer

Walter Roberson
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 ™
  3 Comments
Swati Sarangi
Swati Sarangi 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
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)))

Sign in to comment.

More Answers (1)

KSSV
KSSV on 27 Nov 2020
  2 Comments
Swati Sarangi
Swati Sarangi 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
Jan on 27 Nov 2020
Edited: Jan on 27 Nov 2020
You have to download the function from the link KSSV has provided.
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');

Sign in to comment.

Categories

Find more on Large Files and Big Data in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!