Create all unique combination with a vector array

8 Ansichten (letzte 30 Tage)
cht
cht am 8 Jul. 2020
Kommentiert: Bas van Dorp am 28 Apr. 2021
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 Kommentare
madhan ravi
madhan ravi am 8 Jul. 2020
What do you mean mean by lots of redundancies, you are the ones asking for unique combinations?
cht
cht am 8 Jul. 2020
If I use perms, they are a lot of combination that are the same. This is the meaning of redundancy.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Bruno Luong
Bruno Luong am 9 Jul. 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 Kommentar
Bas van Dorp
Bas van Dorp am 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by