How can I use a WHILE loop to pick an element in an array at random but not pick the same element more than once?
2 views (last 30 days)
Show older comments
So far this is the code I have. Not too good at this, please keep codes simple (for, while loops, if statements, etc.)! Any help is appreciated!!
a=1;
while a~=10
a=a+1;
n=floor(10*rand+1);
m=floor(10*rand+1);
if n==n
n=floor(10*rand+1);
if m==m
m=floor(10*rand+1);
end
end
if board(n,m)~='1'
board(n,m)='1';
if board(n,m)~='1'
board(n,m)='1';
end
end
end
3 Comments
Walter Roberson
on 3 May 2019
The first time through, there is no "last" value to compare against. And if there were, then you would have the risk of going back to the first element, such as [5 3 5] -- since the second 5 is not the same as the 3 previous, it would pass the test you were thinking of.
Answers (2)
Image Analyst
on 3 May 2019
I'm not sure what this uncommented code does, but presumably you do. All I can say is that if you want to pick a number from 1 to N but have no chance to repeat the number you need to make up a vector in advance and then pick the values in your loop. For example:
indexes = randperm(N); % Values from 1 to N all scrambled up.
while k < N
thisNumber = indexes(k);
% Now do whatever.....
k = k + 1;
end
Walter Roberson
on 3 May 2019
remaining = 1:10;
while ~isempty(remaining);
idx = randi(length(remaining));
n = remaining(idx);
remaining(idx) = [];
do something with n
end
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!