Search code examples
matlabrandomprobabilityuniform-distribution

Number series with uniform distribution for a given variance and a mean in matlab


I want to generate n number of points using a uniform distribution for a specific variance (v) and mean (m).

I'm currently using MATLAB to achieve this task. This can be done for a normal distribution using y = v.*randn(n,1) + m;

Is there any straightforward method to do this in MATLAB?


Solution

  • For uniform distribution use rand (randn is for normal distribution).

    rand generates numbers uniformly distributed on the interval (0,1), so the mean is 0.5 and the variance is 1/12. To get different mean or variance you need to shift and scale:

    desired_mean = 3;
    desired_var = 5;
    N = 1e6; % number of samples
    x = sqrt(12*desired_var) * (rand(1,N)-0.5) + desired_mean;
    

    Check:

    >> mean(x)
    ans =
       3.003083912414557
    >> var(x)
    ans =
       4.998928353933906