Random number multiple of 5 generation

4 visualizzazioni (ultimi 30 giorni)
Vincent TORRELLI
Vincent TORRELLI il 31 Ott 2019
Commentato: AMJR21 il 9 Gen 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 Commento
AMJR21
AMJR21 il 9 Gen 2023
I'm over 3 years late but you could just make it generate a random number and multiply it by 5 after

Accedi per commentare.

Risposte (1)

Daniel M
Daniel M il 31 Ott 2019
Modificato: Daniel M il 31 Ott 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

Categorie

Scopri di più su Random Number Generation in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by