All possible combinations of a number of an array
11 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2020-11-27
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 个评论
Walter Roberson
2020-12-3
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)))
更多回答(1 个)
KSSV
2020-11-27
v = 1:3 ;
iwant = npermute(v,3)
2 个评论
Jan
2020-11-27
编辑:Jan
2020-11-27
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');
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Large Files and Big Data 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!