How can I generate all possible combinations of a given number of vectors?
3 次查看(过去 30 天)
显示 更早的评论
Hello, I'm currently trying to generate all possible combinations of given vectors in all possible matrices.
If n=2 the possible vectors are [1 0;0 1;2 0;0 2] If n=3 the possible vectors are [1 0 0;0 1 0;0 0 1;2 0 0;0 2 0;0 0 2]
I generate a matrix with the possible vectors: In this case n=3
B=3;
D_possibilities1=diag(ones(1,B),0);
D_possibilities2=diag(2*ones(1,B),0);
D_possibilities=zeros(B*2,B);
for i=1:B
D_possibilities(i,:)=D_possibilities1(i,:);
D_possibilities(B+i,:)=D_possibilities2(i,:);
end
Now I'm struggling to generate all possible matrices with all possible combinations
Any help is welcome, thanks
0 个评论
回答(2 个)
Karsten Reuß
2018-3-13
编辑:Karsten Reuß
2018-3-13
There are several commands you may try, depending on if you want replacement/no replacement/ ordering matters or not,
One command is "perms":
perms(0:2)
If the ordering does not matter, you have fewer combinations. In this case the command "combnk" will help
combnk(0:3,3)
Another interesting command that may help you is "nchoosek". In this code you combine the command with "perms", so the ordering matters:
n = 6; k = 2;
nk = nchoosek(1:n,k);
p=zeros(0,k);
for i=1:size(nk,1),
pi = perms(nk(i,:));
p = unique([p; pi],'rows');
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!