How to create all possible matrices of zeros and ones without having more than one '1' in the same column?
4 views (last 30 days)
Show older comments
I want to create all possible matrices of zeros and ones without having more than one '1' in the same column and then save each combination individually
For Example n=number of rows and m= number of column. So the possible combination number is C=n^m. Assuming n=2 and m=3 so C=8. And I need the output to be in a matrix form for each combination as shown below.
X1 = [1 1 1
0 0 0]
X2 = [0 0 0
1 1 1]
X3 = [1 0 0
0 1 1]
X4 = [0 1 1
1 0 0]
X5 = [1 1 0
0 0 1]
X6 = [0 0 1
1 1 0]
X7 = [1 0 1
0 1 0]
X8 = [0 1 0
1 0 1]
2 Comments
Bruno Luong
on 12 Jan 2023
Edited: Bruno Luong
on 12 Jan 2023
Simply generate for all possible (m+1) x n matrix with exactly one 1 by column; then thow away one row, as the last row.
m = 2;
n = 3;
c = cell(1,n);
[c{:}] = ndgrid(1:m+1); % change here
i = reshape(cat(n+1,c{:}),[],n);
[j,k] = meshgrid(1:n,1:size(i,1));
X = accumarray([i(:) j(:) k(:)],1);
X(end,:,:) = []; % new here
X
Accepted Answer
Bruno Luong
on 12 Jan 2023
Edited: Bruno Luong
on 12 Jan 2023
m = 2;
n = 3;
c = cell(1,n);
[c{:}] = ndgrid(1:m);
i = reshape(cat(n+1,c{:}),[],n);
[j,k] = meshgrid(1:n,1:size(i,1));
X = accumarray([i(:) j(:) k(:)],1)
More Answers (1)
Jan
on 12 Jan 2023
Edited: Jan
on 12 Jan 2023
n = 3;
m = 4;
c = n^m;
X = cell(1, c); % List of outputs
v = n .^ (1-m:0); % Calculate expensive power operation once
for ic = 0:c - 1
index = rem(floor(ic .* v), n); % Column indices of 1s
XX = zeros(n, m);
XX(sub2ind([n, m], index + 1, 1:m)) = 1;
X{ic + 1} = XX;
end
X{1}, X{2}, X{end-1}, X{end}
This chooses m numbers from 1:n as column index of 1s in a nxm matrix of 0s.
4 Comments
See Also
Categories
Find more on Operating on Diagonal 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!