How to avoid "doubling up" in a RNG?
Afficher commentaires plus anciens
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 commentaires
David Fletcher
le 3 Avr 2021
Didn't someone say it would be a better idea to use a while loop earlier? If you use a while loop it doesn't matter if you select the same square twice - you just continue until you have six ones.
x = zeros(10,10);
while sum(x,'All')<6
m = randi(10)
n = randi(10)
x(m,n) = 1;
end
Connor K Riggs
le 3 Avr 2021
David Fletcher
le 3 Avr 2021
Modifié(e) : David Fletcher
le 3 Avr 2021
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
Réponses (1)
the cyclist
le 3 Avr 2021
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 commentaires
Walter Roberson
le 3 Avr 2021
??
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
le 3 Avr 2021
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.
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!