Create all unique combination with a vector array
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
cht
el 8 de Jul. de 2020
Comentada: Bas van Dorp
el 28 de Abr. de 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 comentarios
madhan ravi
el 8 de Jul. de 2020
What do you mean mean by lots of redundancies, you are the ones asking for unique combinations?
Respuesta aceptada
Bruno Luong
el 9 de Jul. de 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 comentario
Bas van Dorp
el 28 de Abr. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!