Random number multiple of 5 generation

1 Ansicht (letzte 30 Tage)
Vincent TORRELLI
Vincent TORRELLI am 31 Okt. 2019
Kommentiert: AMJR21 am 9 Jan. 2023
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 Kommentar
AMJR21
AMJR21 am 9 Jan. 2023
I'm over 3 years late but you could just make it generate a random number and multiply it by 5 after

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Daniel M
Daniel M am 31 Okt. 2019
Bearbeitet: Daniel M am 31 Okt. 2019
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

Kategorien

Mehr zu Random Number Generation finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by