How to avoid duplication of random numbers?

2 views (last 30 days)
chan
chan on 25 Oct 2021
Answered: Walter Roberson on 25 Oct 2021
clc;
clear all;
n=10;
rng(1);
reply_timer=randi(10);
fprintf('The reply_timer is %i\n',reply_timer);
i=1;
t=15;
while(1)
if(reply_timer<t)
rng 'shuffle'
node=randi(n);
fprintf('The node %d is selected for simulation\n',node);
reply_timer=reply_timer+1;
else
break;
end
end
Output:
The reply_timer is 5
The node 8 is selected for simulation
The node 1 is selected for simulation
The node 3 is selected for simulation
The node 1 is selected for simulation
The node 5 is selected for simulation
The node 7 is selected for simulation
The node 7 is selected for simulation
The node 7 is selected for simulation
The node 10 is selected for simulation
The node 2 is selected for simulation
>>
Here in the output i got 1,7 repeated. I used 'shuffle ' to avoid the duplication still in the result some duplication occur. How can i avoid this problem. Can anyone suggest me some hint to sort this problem? Thank you

Answers (1)

Walter Roberson
Walter Roberson on 25 Oct 2021
node_sequence = randperm(n, t-reply_timer);
Now use the elements of node_sequence, in that order.
You will quickly get an error if reply_timer is generated as 1, 2, 3, or 4. That is because it is impossible to generate 11 or more different numbers in the range 1 to 10 (n)

Products


Release

R2016a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!