Random Numbers with Gaussian and Uniform Distributions in matlab

前端 未结 6 1805
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 07:12

I want generate a number in Gaussian and Uniform distributions in matlab. I know this function randi and rand() but all of them are in normal (Gau

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-09 07:32

    It is true you can generate just about anything from rand but that it isn't always convenient, especially for some complicated distributions.

    MATLAB has introduced Probability Distribution Objects which make this a lot easier and allow you to seamless access mean, var, truncate, pdf, cdf, icdf (inverse transform), median, and other functions.

    You can fit a distribution to data. In this case, we use makedist to define the probability distribution object. Then we can generate using random.

    % Parameters
    mu = 10; 
    sigma = 3;
    a = 5; b = 15;
    N = 5000;
    
    % Older Approaches Still Work
    rng(1775)
    Z = randn(N,1);    % Standard Normal  Z~N(0,1)
    X = mu + Z*sigma;  % X ~ Normal(mu,sigma)
    
    U = rand(N,1);     % U ~ Uniform(0,1)
    V = a + (b-a)*U;   % V ~ Uniform(a,b)
    
    % New Approaches Are Convenient
    rng(1775)
    pdX = makedist('Normal',mu,sigma);
    X2 = random(pdX,N,1);
    
    pdV = makedist('Uniform',a,b);
    V2 = random(pdV,N,1);
    

    A reproducible example:

    Support = (0:0.01:20)';
    figure 
    s(1) = subplot(2,2,1)
    h(1) = histogram(X,'Normalization','pdf')
    xlabel('Normal')
    s(2) = subplot(2,2,2)
    h(2) = histogram(V,'Normalization','pdf')
    xlabel('Uniform')
    s(3) = subplot(2,2,3), hold on, box on
    h(3) = histogram(X2,'Normalization','pdf')
    plot(Support,pdf(pdX,Support),'r-','LineWidth',1.2)
    xlabel('Normal (new)')
    s(4) = subplot(2,2,4), hold on, box on
    h(4) = histogram(V2,'Normalization','pdf')
    plot(Support,pdf(pdV,Support),'r-','LineWidth',1.2)
    xlabel('Uniform (new)')
    xlim(s,[0 20])  
    

    References:
    Uniform Distribution
    Normal (Gaussian) Distribution

提交回复
热议问题