How to create all possible matrices of zeros and ones without having more than one '1' in the same column?
조회 수: 6 (최근 30일)
이전 댓글 표시
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
Steven Lord
2023년 1월 12일
You're missing several possibilities. One such example is
z = zeros(2, 3)
This has no more than one 1 in the same column. Is this a valid matrix you want your function to generate?
Bruno Luong
2023년 1월 12일
편집: Bruno Luong
2023년 1월 12일
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
채택된 답변
Bruno Luong
2023년 1월 12일
편집: Bruno Luong
2023년 1월 12일
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)
추가 답변 (1개)
Jan
2023년 1월 12일
편집: Jan
2023년 1월 12일
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
Jan
2023년 1월 12일
@Bruno Luong: You are right - this is instable. I've taken it from dec2bin (it was an m-file in former Matlab versions), but hier n=2 is less susceptible to rounding artifacts.
This is better to produce the column indices:
function I = PermRepOrder(n, m)
a = 1;
b = n^m;
I = zeros(b, m);
v = (1:n).';
for k = 1:m
b = b / n;
I(:, k) = repmat(repelem(v, b, 1), a, 1);
a = a * n;
end
end
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!