How can I generate all possible combinations of a given number of vectors?

1 view (last 30 days)
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

Answers (2)

Karsten Reuß
Karsten Reuß on 13 Mar 2018
Edited: Karsten Reuß on 13 Mar 2018
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

Birdman
Birdman on 13 Mar 2018
Edited: Birdman on 13 Mar 2018
Hope this is what you want:
clear C;
n=3;
for i=1:n
C{i,1}=unique(perms([zeros(1,n-1) i]),'rows');
end
C=fliplr(cell2mat(C));
C(any(C>2,2),:)=[]
Change n and observe the result you want.

Categories

Find more on Creating and Concatenating Matrices 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!