All possible combinations of a number of an array
12 views (last 30 days)
Show older comments
Swati Sarangi
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 ; .........]
Please help me with its code.
Thanks in advance!
0 Comments
Accepted Answer
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)))
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
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)))
More Answers (1)
KSSV
on 27 Nov 2020
v = 1:3 ;
iwant = npermute(v,3)
2 Comments
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');
See Also
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!