Randomly convert exact number of 1 to 0 in binary matrix

2 ビュー (過去 30 日間)
mnemonix
mnemonix 2020 年 5 月 22 日
コメント済み: mnemonix 2020 年 5 月 23 日
Hi.
I have binary matrix 3x3.
0 1 0
1 0 1
1 1 1
Let say, it includes six "1" values on random positions. I need to convert two "1" to "0", but randomly.
0 1 0
1 0 0
1 0 1
one of the possible outcomes.
Thank you for your help!

採用された回答

per isakson
per isakson 2020 年 5 月 22 日
Try
%%
x = [ 0 1 0
1 0 1
1 1 1];
%%
ix_one = find( x == 1 );
ix_set_zero = randi( numel(ix_one), 1,2 );
x( ix_one( ix_set_zero ) ) = 0
  3 件のコメント
per isakson
per isakson 2020 年 5 月 23 日
Thanks for accepting, however, there is a flaw in my answer. randi() may return two equal numbers, which leads to that only one 1 is replaced by 0.
>> randi( 6, 1,2 )
ans =
6 6
>>
>> m = 1:8;
>> m([6,6])=0
m =
1 2 3 4 5 0 7 8
>>
With or without replacement, the statement
ix_set_zero = randi( numel(ix_one), 1,2 );
needs to be replaced by
ix_set_zero = randperm( numel(ix_one), 2 );
mnemonix
mnemonix 2020 年 5 月 23 日
Thanks for warning.

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

その他の回答 (1 件)

Stephen23
Stephen23 2020 年 5 月 22 日
>> M = [0,1,0;1,0,1;1,1,1]
M =
0 1 0
1 0 1
1 1 1
>> X = find(M);
>> M(X(randperm(numel(X),2))) = 0
M =
0 0 0
1 0 1
1 1 0

カテゴリ

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

製品


リリース

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by