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
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
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

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by