Random number multiple of 5 generation
6 ビュー (過去 30 日間)
古いコメントを表示
Hello everyone,
I want to generate a random number which is a multiple of 5 (number that finish either by 0 or 5) and which is bound in an interval: [interMin; interMax].
example:
interMin=20; % lower bound
interMax=150;% upper bound
I know that I can generate a random number as shown below:
NUMBER=randi([interMin interMax],1,1);
But I want this number "NUMBER" to be a multiple of 5.
Do you know how to do this ?
Thank you in advance.
Vincent
1 件のコメント
AMJR21
2023 年 1 月 9 日
I'm over 3 years late but you could just make it generate a random number and multiply it by 5 after
回答 (1 件)
Daniel M
2019 年 10 月 31 日
編集済み: Daniel M
2019 年 10 月 31 日
First find out how many possibilities there are:
interMin = 20;
interMax = 150;
n = sum(~mod(interMin:interMax,5));
% n = 27
% or just, n = (interMax-interMin)/5 + 1;
That means there are 27 multiples of 5 from interMin to interMax.
Now pick a random one.
var = (randi(n)-1)*5 + interMin;
You can test that it works properly like this:
isequal((1-1)*5 + interMin, interMin) % ans = 1
isequal((n-1)*5 + interMin, interMax) % ans = 1
Here is a handy way to generate as many values as you want, using an anonymous function:
pickN = @(N) (randi(n,N,1)-1)*5 + interMin;
vals = pickN(10000); % vals is [10000x1]
% visually check if it works
figure
histogram(vals,n)
% all bins should be roughly equal
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Data Preprocessing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!