% berlabnoisegen.m 
% generate normally distributed sample values for Rigol AWG
% Ed Casas 2015-11-2

% N-1 is the number of samples generated

N=1000000+1 ;

% Calculate N-1 evenly spaced values corresponding to
% probabilities probabilities from 1/N to (N-1)/N.

p=[1/N:1/N:1-1/N];

% Compute the voltages (normalized threshold or 't' values)
% corresponding to these probabilities for a Gaussian random
% variable.

t=sqrt(2)*erfinv(2*p-1);

% Scale the voltages into the range of integers accepted by the
% Rigol AWG (14-bit unsigned).

mint=min(t) ;
maxt=max(t) ;

x=floor((2^14-1)/(maxt-mint)*(t-mint)) ;

% Print the values corresponding to the maximum and minimum AWG
% output voltages.  Setting the AWG peak-to-peak voltage setting
% to this should result in a standard deviation (RMS output
% voltage) of 1.

maxt-mint

% Generate N-1 random values and find the indices required to
% sort them into ascending order.

[s,i]=sort(rand(size(x))) ;

% Randomize the order of the noise samples by sorting them using
% this same sort order.

x=x(i) ;

% (optional) replicate each sample value to check the effect of
% comparator hysteresis
% x=ones(4,1)*x ;

% Write out in the Rigol AWG '.RAF' binary file in the format:
% unsigned 16-bit values in LittleEndian byte order.

fid = fopen ( 'awgn.raf', 'w' ) ;
fwrite(fid, x, 'uint16' ) ;
fclose(fid) ;

