How do I generate a random number between two numbers with using a distribution

조회 수: 4 (최근 30일)
I I know that we can define distribution in the random command, but the random numbers I generate with the random command are integers. I'm using the rand command for decimal random numbers and this time I can't define a distribution. In short, how can I create a normal distribution or triangular distribution of 100 random numbers consisting of decimal numbers?

채택된 답변

Bruno Luong
Bruno Luong 2022년 3월 22일
% define the siscrete value and their relative pdf
xval=(-10:10);
p=exp(-(xval/5).^2); % Gaussian function, triangular whatever you like
n = 1e6; % number of samples
c=cumsum(p);
c=c/c(end);
xrand=xval(discretize(rand(1,n ),[0; c(:)])); % here is the random
% Check graphically
p = p/sum(p);
figure
subplot(2,1,1);
plot(xval,p)
subplot(2,1,2);
histogram(xrand)
  댓글 수: 3
Bruno Luong
Bruno Luong 2022년 3월 22일
If you want continuous distribution (and not discrete, I don't know what means "decimal" and the computer is the same as me)
% define the siscrete value and their relative pdf
xval=(-10:10);
xmid = (xval(1:end-1) + xval(2:end))/2;
p=exp(-((xmid-3)/5).^2); % Gaussian function, triangular whatever you like
n = 1e6; % number of samples
c=cumsum(p);
c=c/c(end);
xrand=interp1([0 c], xval, rand(1,n));
% Check graphically
p = p/sum(p);
figure
ax1=subplot(2,1,1);
plot(xmid,p)
ax2=subplot(2,1,2);
histogram(xrand,100)
linkaxes([ax1 ax2], 'x')
Emre Can Yilmaz
Emre Can Yilmaz 2022년 3월 22일
What I was talking about was xrand values. When I looked at your first example, the xrand values were showing as integers like 1-2-3-4. I asked how this would become a decimal number. In your second example, xrand values became decimal numbers like 0.657. I got the answer I wanted, thank you.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Paul
Paul 2022년 3월 22일
Emre,
The statement that the the random() command only generates integers doesn't sound correct. The doc page shows an an example of generating random numbers from a Weibull diistribution which are not integers. Can you post an example that illustrates the behavior?
For a standard normal distribution you can use randn(), and then adjust the outputs for whatever mean and variance is desired. Or use normrnd() in the Statistics and Machine Learning Toolbox, or other options in that toolbox. That toolbox supports many distributions, including the Triangular distribution, for which you can get the pdf, cdf, random numbers, and lots of other interesting things.
  댓글 수: 2
Paul
Paul 2022년 3월 22일
Here's an example using Stats Toolbox functionality
pd = makedist('Triangular',0,20,100)
pd =
TriangularDistribution A = 0, B = 20, C = 100
rng(100);
v = random(pd,100000,1);
histogram(v,'Normalization','pdf')

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Exploration and Visualization에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by