Create binary matrix with some conditions (Matlab)

1 回表示 (過去 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.
  1 件のコメント
high speed
high speed 2021 年 4 月 9 日
It works. Thank you so much

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by