function x = logn_rnd( medX , covX ,  r, c )
% x = logn_rnd( medX , covX ,  r, c )
%
% generate a matrix of a random variable distribued according to the 
% lognormal distribution with parameters  medX  and  covX
%
%  INPUT         DESCRIPTION
%   medX         median of the lognormal distribution         1 x 1   or  r x c
%   covX         c.o.v. of the lognormal distribution         1 x 1   or  r x c
%   r            number of rows in x                                      1 x 1
%                sample of standard normal variables, possibly correlated r x c
%   c            number of cols in x                                      1 x 1
%
%    Values of  medX  and  covX  must be greater than zero.  
%
%  OUTPUT
%   x            sample of the lognormal distribution                r x c
%
%    If X is a lognormal random variable, then the log of X is normally 
%    distributed with a mean of  log(medX) and a variance of log(1+covX^2)
%
%  EXAMPLE 
%    To plot the PDF of a single lognormal random variable, ... 
%    n=10000; x=logn_rnd(1,0.5,1,n); hist(x,n/100,1); avg_x = sum(x)/n
 
%    Reference: http://en.wikipedia.org/wiki/Log-normal_distribution

 if any(medX<=0), error(' logn_rnd:  medX must be greater than zero'); end
 if any(covX<=0), error(' logn_rnd:  covX must be greater than zero'); end

 if nargin == 3
   z = r;
   [r,c] = size(z);
 end
 if nargin == 4
   z = randn(r,c);
 end
 
 if (prod(size(medX)) == 1), medX = medX * ones(r,c); end
 if (prod(size(covX)) == 1), covX = covX * ones(r,c); end

 VlnX = log(1+covX.^2);	% the variance of log(X)

 x = exp ( log(medX) + z.*sqrt(VlnX) );

% ----------------------------------------------------------------- logn_rnd
% HP Gavin  2016-04-28, 2021-04-21
