Create all unique combination with a vector array

10 visualizzazioni (ultimi 30 giorni)
Hello,
let`s say I have a vector a=[1 1 0 0 0]. I want to build all possible combinations with the values within that vector. I`m looking for such result:
[1 0 1 0 0]
[1 0 0 1 0]
[1 0 0 0 1]
[0 1 1 0 0]
[0 1 0 1 0]
and so on till [ 0 0 0 1 1]
With the function perms there is quite a lot of redundancy and the order of the sigles arrays is not the one I would like
  2 Commenti
madhan ravi
madhan ravi il 8 Lug 2020
What do you mean mean by lots of redundancies, you are the ones asking for unique combinations?
cht
cht il 8 Lug 2020
If I use perms, they are a lot of combination that are the same. This is the meaning of redundancy.

Accedi per commentare.

Risposta accettata

Bruno Luong
Bruno Luong il 9 Lug 2020
Try this, no redundancy created. However the number of combinations still grow very quick so be awared. Where as it gives the order you expect, who knows since you never specify the order you want.
function c = vperm(v)
[u,~,J] = unique(v);
n = accumarray(J(:),1);
c = vpengine(u,n).';
end
function c = vpengine(u,n)
if length(u)==1
c = u + zeros(n,1);
else
k = n(1);
i = nchoosek(1:sum(n),k);
p = size(i,1);
j = repmat((1:p)',1,k);
c = accumarray([i(:),j(:)],1);
d = vpengine(u(2:end),n(2:end));
c = repelem(c,1,size(d,2));
b = c==0;
d = repmat(d,1,p);
c(b) = d(:);
c(~b) = u(1);
end
end
Test:
>> vperm([1 1 0 0 0])
ans =
0 0 0 1 1
0 0 1 0 1
0 0 1 1 0
0 1 0 0 1
0 1 0 1 0
0 1 1 0 0
1 0 0 0 1
1 0 0 1 0
1 0 1 0 0
1 1 0 0 0
  1 Commento
Bas van Dorp
Bas van Dorp il 28 Apr 2021
Nice work!
I first used unique(perms(a),'rows'). For my purposes that does the same, but it gets very slow and runs out of memory when a is too long. This was limiting my program but with your script it works!
Thanks for this.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by