function r = frnd(v1,v2,m,n);
%FRND   Random matrices from the F distribution.
%   R = FRND(V1,V2) returns a matrix of random numbers chosen   
%   from the F distribution with parameters V1 and V2.
%   The size of R is the common size of V1 and V2 if both are matrices.
%   If either parameter is a scalar, the size of R is the size of the other
%   parameter. Alternatively, R = FRND(V1,V2,M,N) returns an M by N matrix. 

%   FRND calls BETARND.
%   See Devroye, Theorem 4.1 on page 430, case D.

%   References:
%      [1]  L. Devroye, "Non-Uniform Random Variate Generation", 
%      Springer-Verlag, 1986

%   Copyright 1993-2000 The MathWorks, Inc. 
%   $Revision: 2.8 $  $Date: 2000/05/26 18:52:52 $

if nargin < 2, 
    error('Requires at least two input arguments.'); 
end

if nargin == 2
    [errorcode rows columns] = rndcheck(2,2,v1,v2);
end

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

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

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

r = zeros(rows,columns);
if prod(size(v1) == 1)
    v1 = v1(ones(rows,columns));
end
if prod(size(v2) == 1)
    v2 = v2(ones(rows,columns));
end

% Return NaN if either of V1 and V2 is not positive.
k = (v1<=0 | v2<=0);
if any(k(:))
   r(k) = NaN;
end
if any(~k(:))
   v1 = v1(~k);
   v2 = v2(~k);
   num = chi2rnd(v1) ./ v1;
   den = chi2rnd(v2) ./ v2;
   r(~k) = num ./ den;
end

