How to avoid "doubling up" in a RNG?

2 ビュー (過去 30 日間)
Connor K Riggs
Connor K Riggs 2021 年 4 月 3 日
コメント済み: the cyclist 2021 年 4 月 3 日
So, I've found a way to get my code to run 6 times through, but I've encountered a different problem. Since I'm using a random number generator to select which squares to turn the 0 to a 1, it's possible for my random number generator to select the same square twice. I want to ensure that the squares selected are unique. Once again, any help would be appreciated. EDIT: I have to use a for loop, not a while loop
x = zeros(10,10);
for i = 1:6
m = randi(10)
n = randi(10)
if x(m,n) == 0
x(m,n) = 1;
elseif x(m,n) == 1
end
end
  3 件のコメント
Connor K Riggs
Connor K Riggs 2021 年 4 月 3 日
Unfortunately, I have to use a for loop, not a while loop.
David Fletcher
David Fletcher 2021 年 4 月 3 日
編集済み: David Fletcher 2021 年 4 月 3 日
Ahh, the vagaries of education. You could always break the for loop on the six ones condition, if only to highlight the asinine.
x = zeros(10,10);
for iter=1:inf
m = randi(10)
n = randi(10)
x(m,n) = 1;
if sum(x,'All')>5
break
end
end

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

回答 (1 件)

the cyclist
the cyclist 2021 年 4 月 3 日
Here is one way to do what I think you mean:
x = zeros(10,10);
% For M and N, select 6 random integers from 1:10.
M = randperm(10,6);
N = randperm(10,6);
for i = 1:6
% Select each (m,n) in order from (M,N)
m = M(i);
n = N(i);
if x(m,n) == 0
GB(m,n) = 1;
elseif x(m,n) == 1
end
end
  2 件のコメント
Walter Roberson
Walter Roberson 2021 年 4 月 3 日
??
What is GB here?
The code you used cannot set two values in the same row (or the same column), so it does not need to do the test. However, the original homework seems to have the possibility that multiple values in the same row could occur.
the cyclist
the cyclist 2021 年 4 月 3 日
sigh
I'm guessing that @Connor K Riggs changed the code in their question. I copy/pasted the original, and did nothing other than change it so that there would be no repeated (m,n) values.
Caveat emptor my answer.

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by