function  [sys, x0]  = mixedm(t,x,u,flag)
% MIXEDM M-file implementation of hybrid system consisting
%        of a continuous integrator (1/s) in series with a 
%        a unit delay (1/z).  Note that because the step time of
%        the SIMULINK integrator is much smaller than the sampling
%        interval of the discrete block, there is an implicit zero-order
%        hold on the output of the unit delay.

%	Copyright (c) 1990-94 by The MathWorks, Inc.

if nargin~=4
  if nargin==0
    flag = 0;
  else
    error('??? Wrong number of input arguments.');
  end
end

% Sample and offset times
offset = 0;
ts = 1.0;

if abs(flag) == 1  % Return derivatives
  
  sys = u(1); 
  
elseif abs(flag) == 2  % Return discrete states in sys
  
  % Is it a sample hit (within a tolerance of 1e-8) ?
  if abs(round((t - offset)/ts) - (t - offset)/ts) < 1e-8
    
    % When it is a sample hit, set the first discrete state equal to the
    % the output of the 1/s block, i.e. sample the integrator.
    
    sys(1) = x(1);
    
  end
  
elseif flag == 3  % Return outputs
  
  % Is it a sample hit (within a tolerance of 1e-8) ?
  % If it is not a discrete sample hit, the output should not change,
  % so just return an empty matrix.
  if abs(round((t - offset)/ts) - (t - offset)/ts) < 1e-8
    sys(1) = x(2);
  else
    sys = [];
  end
  
elseif flag == 4 % Return next sample hit
  
  % ns stores the number of samples
  ns = (t - offset)/ts;
  
  % This is the time of the next sample hit.
  sys = offset + (1 + floor(ns + 1e-13*(1+ns)))*ts;
  
elseif flag  == 0,  % Initial conditions and size information
  
  sys=zeros(6,1);
  sys(1) = 1;       % 1 continuous state
  sys(2) = 1;       % 1 discrete state
  sys(3) = 1;       % 1 output
  sys(4) = 1;       % 1 input
  sys(5) = 0;       % no roots (unsupported)
  sys(6) = 0;       % no direct feedthrough
  
  x0 = ones(2,1);
  
else 
  
  sys = [];
  
end

% Note: this file has changed since the manual was printed. 
% See the SIMULINK system: MIXEDS for an equivalent of this M-file.

