Contents

%program to generate Gaussian random variates
%input parameters are n, mu, sigma (which you can set in the program)
%output is an ascii file with one variate per line
%lines with "%" are "header lines"
%Plot histogram and compute mean, median and rms for the generated sample
%If you wish to "strip" the headers for your program then
% $ sed '/^%/d' Gaussian.dat > NoHeader.dat

Gaussian Probability Density Function

$$P(x)=\frac{1}{\sqrt{2\pi}}\exp\Big[-\frac{1}{2}\frac{(x-\mu)^2}{\sigma^2}\Big]$$

%setting the three basic parameters
    n=1000;    %number of variates to generate
    mu=0;   %mean value
    sigma=1; %rms

    outfile='Gaussian.dat';  %Name of output file
    fid=fopen(outfile,'w');  %open file

% write header lines
    x=normrnd(mu,sigma,1,n);
    fprintf(fid,'%% Gaussian variates\n');
    fprintf(fid,'%% number of variates: %d\n',n);
    fprintf(fid,'%% mean, mu=%5.3f\n',mu);
    fprintf(fid,'%% rms, sigma=%5.4f\n',sigma);

%write data
    fprintf(fid,'%1.4f \n',x);
    fclose(fid);    %close file
%Histogram the data
    h=histogram(x,50);
    xlabel('x')
    ylabel('#')
    title('Histogram of Gaussian variates')
    xlim([-5*sigma+mu 5*sigma+mu]);
    legend(['\mu=' num2str(mu) ',  '  '\sigma=' num2str(sigma) ', n=' num2str(n)])
%compute the mean, median and rms
    xmean=mean(x);
    xmed=median(x);
    xrms=sqrt(var(x));
    fprintf('mean: %f median %f rms: %f\n',xmean,xmed,xrms);
mean: 0.017265 median -0.005890 rms: 0.977377