Create binary matrix with some conditions (Matlab)

2 次查看(过去 30 天)
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 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by