function [sys,x0,str,ts] = S_StepperMotor(t,x,u,flag)
%
% Dispatch the flag.
%
switch flag,
  case 0
    [sys,x0,str,ts]=mdlInitializeSizes; % Initialization
  case 1
    sys = mdlDerivatives(t,x,u); % Calculate derivatives
  case 3
    sys = mdlOutputs(t,x,u); % Calculate outputs  
  case 9
    mdlTerminate(t);
  case { 2, 4 } % Unused flags
    sys = [];
  otherwise
    error(['Unhandled flag = ',num2str(flag)]); % Error handling
end
% End of csfunc.
%==============================================================
% mdlInitializeSizes
% Return the sizes, initial conditions, and sample times for the 
% S-function.
%==============================================================
%
function [sys,x0,str,ts] = mdlInitializeSizes()
%
% Call simsizes for a sizes structure, fill it in and convert it 
% to a sizes array.
%
sizes = simsizes;
sizes.NumContStates  = 4;
sizes.NumDiscStates  = 0;
sizes.NumOutputs     = 4;
sizes.NumInputs      = 3;
sizes.DirFeedthrough = 0;
sizes.NumSampleTimes = 1;
sys = simsizes(sizes);
%
% Initialize the initial conditions.
%
x0 = [1;1;1;1];
%
% str is an empty matrix.
%
str = [];
%
% Initialize the array of sample times; in this example the sample 
% time is continuous, so set ts to 0 and its offset to 0.
%
ts = [0 0];
% End of mdlInitializeSizes.
%
%==============================================================
% mdlDerivatives
% Return the derivatives for the continuous states.
%==============================================================
function sys = mdlDerivatives(t,x,u)
K1=1;
K2=1;
K3=1;
K4=1;
K5=1;
K6=1;
J=1;
sys = [-K1*x(1)+K2*x(3)*sin(K5*x(4))+u(1),
       -K1*x(2)-K2*x(3)*cos(K5*x(4))+u(2),
       -K3*x(1)*sin(K5*x(4))+K3*x(2)*cos(K5*x(4))-K4*x(3)+K6*sin(4*K5*x(4))-u(3)/J,
       x(3)];
% End of mdlDerivatives.
%
%==============================================================
% mdlOutputs
% Return the block outputs.
%==============================================================
%
function sys = mdlOutputs(t,x,u)
sys = [x];
% End of mdlOutputs.

function mdlTerminate(t)
disp('done')