Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Random generator with truncated gaussian distribution

532 views
Skip to first unread message

Tamer Saad

unread,
Sep 22, 2002, 9:52:33 AM9/22/02
to
Dear all
Is there a way to define a random variable with a truncated gaussian
distribution, i.e. in other words a normal distribution where the
maximum limits are defined. Also the number of the random elements in
the array is predefined.
Thanks in advance
Kind Regards.

John D'Errico

unread,
Sep 23, 2002, 6:25:14 PM9/23/02
to
In article <27c2265a.02092...@posting.google.com>,
tsaa...@yahoo.com (Tamer Saad) wrote:

Its quite easy. Do you have the statistics toolbox?

Here is a function which does it, but it uses
normcdf and norminv from the stats toolbox. If
you don't have this toolbox, then its easy enough
to replace those calls with ones to properly
scaled versions of erf, erfc and erfinv.

HTH,
John D'Errico


function z=truncnormrnd(N,mu,sig,xlo,xhi)
% truncnormrnd: truncated normal deviate generator
% usage:z=truncnormrnd(N,mu,sig,xlo,xhi)
%
% (assumes the statistics toolbox, its easy
% to do without that toolbox though)
%
% arguments: (input)
% N - size of the resulting array of deviates
% (note, if N is a scalar, then the result will be NxN.)
% mu - scalar - Mean of underlying normal distribution
% sig - scalar - Standard deviation of underlying normal distribution
% xlo - scalar - Low truncation point, if any
% xhi - scalar - High truncation point, if any
%
% arguments: (output)
% z - array of truncated normal deviates, size(z)==N

% defaults
if (nargin<2)|isempty(mu)
mu=0;
end

if (nargin<3)|isempty(sig)
sig=0;
end

if (nargin<4)|isempty(xlo)
xlo=-inf;
plo=0;
else
plo=normcdf((xlo-mu)/sig);
end

if (nargin<5)|isempty(xhi)
xhi=inf;
phi=1;
else
phi=normcdf((xhi-mu)/sig);
end

% test if trunation points are reversed
if xlo>xhi
error 'Must have xlo <= xhi if both provided'
end

% generate uniform [0,1] random deviates
r=rand(N);

% scale to [plo,phi]
r=plo+(phi-plo)*r;

% Invert through standard normal
z=norminv(r);

% apply shift and scale
z=mu+z*sig;

--

Li Xue

unread,
Feb 8, 2011, 11:21:04 AM2/8/11
to
What's the following code for?

> if (nargin<2)|isempty(mu)
> mu=0;
> end

John D'Errico <der...@flare.net> wrote in message <derrico-272C4F...@news.newsguy.com>...

Z

unread,
Oct 7, 2015, 7:28:20 PM10/7/15
to
tsaa...@yahoo.com (Tamer Saad) wrote in message <27c2265a.02092...@posting.google.com>...
There is a new algorithm to simulate from a truncated normal generator
on the Matab repository here:

http://www.mathworks.com/matlabcentral/fileexchange/53180-truncated-normal-generator

best of luck
0 new messages