Create all unique combination with a vector array
11 views (last 30 days)
Show older comments
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 Comments
madhan ravi
on 8 Jul 2020
What do you mean mean by lots of redundancies, you are the ones asking for unique combinations?
Accepted Answer
Bruno Luong
on 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 Comment
Bas van Dorp
on 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.
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!