How to avoid "doubling up" in a RNG?
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
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
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
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
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 Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!