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!

采纳的回答

Walter Roberson
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)))
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 个评论
Swati Sarangi
Swati Sarangi 2020-12-3
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 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
KSSV 2020-11-27
  2 个评论
Swati Sarangi
Swati Sarangi 2020-11-27
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 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 CenterFile 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!

Translated by