function z = mod(x,y)
%MOD    Modulus (signed remainder after division).
%   MOD(x,y) is x - y.*floor(x./y) if y ~= 0.  By convention, MOD(x,0) is x.
%   The input x and y must be real arrays of the same size, or real scalars.
%
%   The statement "x and y are congruent mod m" means mod(x,m) == mod(y,m).
%
%   MOD(x,y) has the same sign as y while REM(x,y) has the same sign as x.
%   MOD(x,y) and REM(x,y) are equal if x and y have the same sign, but
%   differ by y if x and y have different signs.
%
%   See also REM.

%   Copyright (c) 1984-98 by The MathWorks, Inc.
%   $Revision: 1.10 $  $Date: 1997/11/21 23:28:26 $

% Check for nonreal arguments.

if ~isreal(x) | ~isreal(y)
    error('Arguments must be real.')
end

% Make arguments the same size.

if length(y) == 1
   y = y(ones(size(x)));
elseif length(x) == 1
   x = x(ones(size(y)));
end
z = zeros(size(x));

if ~isequal(size(x),size(y)), 
  error('X and Y must be the same size.'); 
end
if isempty(x) | isempty(y), return, end

% Integer denominator.
% Use the conventional formula.

m = (y == fix(y)) & (y ~= 0);
z(m) = x(m) - floor(x(m)./y(m)).*y(m);

% Noninteger denominator.
% Adjust any quotient within roundoff error of an integer.

m = (y ~= fix(y));
q = x(m)./y(m);
r = abs(q - round(q)) <= eps*abs(q);
q(r) = round(q(r));
z(m) = (q - floor(q)).*y(m);

% Zero denominator.

m = (y == 0);
z(m) = x(m);
