Search code examples
matlabmatlab-figurenormal-distribution

Normally distributed points within a square in matlab


How can I create N normally distributed points within a N x N square with the mean at the centre (More points concentrated at the centre). I would appreciate an approach in which the coordinates of each points could be stored in a struct. I have tried the code below

 for i=1:200
 S(i).x=randn*200;
 S(i).y=randn*200;
 plot(S(i).x,S(i).y,'.');
 axis([0 200 0 200]); 
 end

However, I observed I got negative values. Using a centre [mean] of (100,100) in a square, I want to store normally distributed points between 0-200 for a 200x200 square. Thanks


Solution

  • The following would require the Statistics Toolbox in MATLAB. You can create a truncated normal distribution, which by definition would only generate normally distributed random numbers within the range [0, N].

    % Create a normal distribution
    N = 200;
    pd = makedist('Normal', 'mu', N/2, 'sigma', 60)
    
    % Truncate the normal distribution to [0,N]
    t = truncate(pd, 0, N)
    
    % Samples from normal distribution
    x = pd.random(N,1);
    y = pd.random(N,1);
    subplot(211)
    plot(x,y,'bx')
    title('Normal Distribution')
    
    % Samples from truncated distribution
    x = t.random(N,1);
    y = t.random(N,1);
    subplot(212)
    plot(x,y,'ro')
    title('Truncated Normal Distribution')
    

    This would result in something like the following:

    enter image description here