How to avoid duplication of random numbers?

2 次查看(过去 30 天)
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

回答(1 个)

Walter Roberson
Walter Roberson 2021-10-25
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)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by