How to avoid duplication of random numbers?

1 回表示 (過去 30 日間)
chan
chan 2021 年 10 月 25 日
回答済み: Walter Roberson 2021 年 10 月 25 日
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 Center および File ExchangeLogical についてさらに検索

製品


リリース

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by