How to generate random variable X over [2,5] using MATLAB?

727 views Asked by At

I have to create a random variable X distributed uniformly over [2,5] and generate more than 10000 samples.

Then I have to estimate the probability density function of X using histc() or hist() functions, and plot estimated PDF with theoretic curve.

I have no idea how to solve it with MATLAB.

2

There are 2 answers

0
SecretAgentMan On

Generate the Uniform random variable using rand() for the [0,1] interval. Then shift it with a and scale (stretch) it with b-a.

N = 10000;
a = 2;      % lower bound
b = 5;      % upper bound
X = a + (b-a)*rand(N,1);    % X ~ Uniform(a,b)

Then plot the sample distribution & the theoretical distribution (Wiki).

figure, hold on, box on
histogram(X,'normalization','pdf','DisplayName','Sample')
xRng = 2:.1:5;
plot(xRng,(1/(b-a))*ones(size(xRng)),'r--','LineWidth',2.8,...
    'DisplayName','Theoretical')
legend('show','Location','north','Orientation','horizontal')
xlabel('X')
ylabel('Probability Density')

Uniform Distribution

0
bas On

Here are links to useful functions and resources:

  • RAND : Look up the first example for getting random numbers between two arbitrary limits. You can specify the number of random samples you desire in the function itself.
  • The normalized HISTC should give you a probability distribution function.
  • If you have the statistics toolbox, you can do MLE to get the best fit uniform distribution.

Happy data fitting!