Create binary matrix with some conditions (Matlab)

조회 수: 2 (최근 30일)
high speed
high speed 2021년 4월 8일
댓글: high speed 2021년 4월 9일
I have this matrix of dimensions (6x12)
H=[1 1 1 1 1 1 0 0 0 0 0 0;
0 0 0 1 0 0 0 0 0 0 0 0;
0 0 0 0 0 1 0 0 0 0 0 0;
0 0 0 0 0 0 0 1 0 0 0 0;
0 0 0 0 0 0 0 0 0 1 0 0;
0 0 0 0 0 0 0 0 0 0 0 1]
The first row must still as it is (1 1 1 1 1 1 0 0 0 0 0 0)
1) As a first condition, I want change the second row in order to get it (0 0 0 1 0 0 0 1 1 1 1 1) it means we change the zeros from 8 to 12 column of the second row to ones.
2) As a second condition, from the third to sixth row I must add ones in order to get a matrix with 6 ones in each row and 3 ones in each column without changing the place of ones of this initially matrix.
Anyone can help please

채택된 답변

DGM
DGM 2021년 4월 9일
Well, I'm not exactly the guy to ask for elegant solutions to anything, but I'll take a stab at it.
clc
H=[1 1 1 1 1 1 0 0 0 0 0 0;
0 0 0 1 0 0 0 0 0 0 0 0;
0 0 0 0 0 1 0 0 0 0 0 0;
0 0 0 0 0 0 0 1 0 0 0 0;
0 0 0 0 0 0 0 0 0 1 0 0;
0 0 0 0 0 0 0 0 0 0 0 1];
H(2,8:end)=1;
% H(1:2,:) can't change
% remaining rows to be arranged
% such that all(sum(H,1)==3) && all(sum(H,2)==6)
% i'm going to assume no further rules apply
% blindly just fill the bulk of the area
for r=3:size(H,1)
hasroom=((3-sum(H,1))>0) & ~H(r,:);
H(r,find(hasroom,5))=1;
end
% clean up any underruns
% for other initial conditions or more general use, i can't guarantee that
% this won't need to become an iterative process
leancol = find(sum(H,1)<3,1);
leanrow = find(sum(H,2)<6,1);
openrows = [0; 0; ~H(3:end,leancol)]; % these are places in leancol where a 1 can be placed
opencols = ~H(leanrow,:); % these are places in leanrow where a 1 can be placed
swappable = bsxfun(@and,openrows,opencols) & H; % these are ones that can be moved
[r c] = find(swappable,1);
H([r leanrow],[leancol c])=1;
H(r,c)=0;
% dump the result and show the criteria are met
H
all(sum(H,1)==3) && all(sum(H,2)==6)
Make of that what you will. I have a feeling that this problem is intended to be solved generally with an iterative process, so my simplistic single-pass code may not work for other scenarios. I'm not sure of anything except that someone else can find a better way.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Sources에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by