MATLAB Answers

0

How to create the combination of zeros and ones matrix in matlab?

Asked by Dong Jun Jung on 12 Nov 2019 at 8:24
Latest activity Commented on by Dong Jun Jung on 13 Nov 2019 at 6:21
Hi
I want to create N X n_C_k matrix using combination function C about 0, 1. The 'k' means the number of '1' and all other elements in matrix are '0'.
For example, if N=4 and k=2, the combination shows the results '1100','1010','1001','0110','0101','0011'. And I want to create the matrix like
A=[1 1 1 0 0 0
1 0 0 1 1 0
0 1 0 1 0 1
0 0 1 0 1 1]
How could i do?

  0 Comments

Sign in to comment.

1 Answer

Answer by Rik
on 12 Nov 2019 at 9:09
Edited by Rik
on 12 Nov 2019 at 10:19
 Accepted Answer

Although I have the feeling this might be homework, I'm going to give a complete answer anyway. By a happy coincidence, this code happens to reproduce your column order.
N=4;k=2;
v=1:N;
C1=nchoosek(v,k);%find rows that should be 1
C2=repmat((1:size(C1,1))',1,size(C1,2));%find the column indices
out=accumarray([C1(:) C2(:)],ones(numel(C1),1));%fill a zero matrix
Or similarly, as Stephen suggested:
R = nchoosek(1:N,k);
C = ndgrid(1:size(R,1),1:size(R,2));
out = accumarray([R(:),C(:)],1);

  3 Comments

Nice. Note accumarray's second input can be scalar:
>> N = 4;
>> k = 2;
>> R = nchoosek(1:N,k);
>> C = ndgrid(1:size(R,1),1:size(R,2));
>> M = accumarray([R(:),C(:)],1)
M =
1 1 1 0 0 0
1 0 0 1 1 0
0 1 0 1 0 1
0 0 1 0 1 1
Thank you, good catch. I've edited it into my answer so it doesn't get hidden in the comments.

Sign in to comment.