function r = ncx2rnd(v,delta,m,n)
%NCX2RND Random matrices from the noncentral chi-square distribution.
%   R = NCX2RND(V,DELTA) returns a matrix of random numbers chosen   
%   from the non-central chisquare distribution with parameters V and DELTA.
%
%   The size of R is the common size of V and DELTA if both are matrices.
%   If either parameter is a scalar, the size of R is the size of the other
%   parameter. Alternatively, R = NCX2RND(V,DELTA,M,N) returns an M by N  
%   matrix.

%   Reference:
%      [1]  Evans, Merran, Hastings, Nicholas and Peacock, Brian,
%      "Statistical Distributions, Second Edition", Wiley
%      1993 p. 50-51.

%   Copyright 1993-2000 The MathWorks, Inc. 
%   $Revision: 2.7 $  $Date: 2000/05/26 18:53:19 $

if nargin < 2, 
    error('Requires at least two input arguments.');
end
if (any(delta(:)<0)), error('Noncentrality parameter cannot be negative'); end

if nargin == 2
    [errorcode rows columns] = rndcheck(2,2,v,delta);
end

if nargin == 3
    [errorcode rows columns] = rndcheck(3,2,v,delta,m);
end

if nargin == 4
    [errorcode rows columns] = rndcheck(4,2,v,delta,m,n);
end

if errorcode > 0
    error('Size information is inconsistent.');
end

% Initialization.
elements = rows*columns;
if prod(size(delta)==1)
   delta = delta(ones(elements,1),1);
end
if prod(size(v)==1)
   v = v(ones(elements,1),1);
end

r = zeros(rows,columns);
r(:) = NaN;

% Sum the squares of the normal random numbers.
for k = 1:elements
   if (v(k)>0)
      r(k) = sum(normrnd(sqrt(delta(k)/v(k)),1,v(k),1).^2);
   end
end
