Create all unique combination with a vector array

11 次查看(过去 30 天)
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 个评论
madhan ravi
madhan ravi 2020-7-8
What do you mean mean by lots of redundancies, you are the ones asking for unique combinations?
cht
cht 2020-7-8
If I use perms, they are a lot of combination that are the same. This is the meaning of redundancy.

请先登录,再进行评论。

采纳的回答

Bruno Luong
Bruno Luong 2020-7-9
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 个评论
Bas van Dorp
Bas van Dorp 2021-4-28
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by