Random number multiple of 5 generation

조회 수: 2 (최근 30일)
Vincent TORRELLI
Vincent TORRELLI 2019년 10월 31일
댓글: AMJR21 2023년 1월 9일
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