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)
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
Raquel Preciado
Raquel Preciado on 3 May 2019
I thought by putting that within the while loop it will compare the last n value with the next one to make sure they dont repeat. I tried what you suggested but still getting the same result...
Walter Roberson
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.

Sign in to comment.

Answers (2)

Image Analyst
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
  1 Comment
Raquel Preciado
Raquel Preciado on 3 May 2019
Just to be clear, the matrix is a character array. Looks like:
I'm not dealing with numerical values.
----------
----------
----------
----------
----------
----------
----------
----------
----------
----------

Sign in to comment.


Walter Roberson
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

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!