how to use the randi function to perform random numbers provided that no random number results are repeated or are not the same?
6 views (last 30 days)
Show older comments
i want to do random numbers
phi = 1: 4 looping using the randi function.
I want each iteration not to come out the same number
so
iteration 1
randi (phi) = 3
iteration 2
randi (phi) = 1
iteration 3
randi (phi) = 4
iteration 4
randi (phi) = 2
I don't use the randperm function because what I want the output of the random result is one number.
how is the solution?
0 Comments
Answers (1)
Walter Roberson
on 3 Oct 2020
so_far = [];
for count = 1 : 4
trial = randi(4);
while ismember(trial, so_far)
trial = randi(4);
end
randi_phi(count) = trial;
do something with trial
end
However, there is seldom a good reason to do this. Instead do
randi_phi = randperm(4);
for count = 1 : 4
trial = randi_phi(count);
do something with trial
end
3 Comments
Walter Roberson
on 3 Oct 2020
There is another method:
available = 1:4;
for count = 1 : length(available)
used_idx = randi(length(available));
trial = available(used_idx);
available(used_idx) = [];
randi_phi(count) = trial;
do something with trial
end
See Also
Categories
Find more on Loops and Conditional Statements 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!