function [sys,x0,str,ts] = S_PMsync(t,x,u,flag)
% PM Synchronous motor
switch flag,
  case 0,
    [sys,x0,str,ts]=mdlInitializeSizes;
  case 1,
    sys=mdlDerivatives(t,x,u);
  case 2,
    sys=mdlUpdate(t,x,u);
  case 3,
    sys=mdlOutputs(t,x,u);
  case 4,
    sys=mdlGetTimeOfNextVarHit(t,x,u);
  case 9,
    sys=mdlTerminate(t,x,u);
  otherwise
    error(['Unhandled flag = ',num2str(flag)]);
end

function [sys,x0,str,ts]=mdlInitializeSizes
sizes = simsizes;
sizes.NumContStates  = 4;
sizes.NumDiscStates  = 0;
sizes.NumOutputs     = 4;
sizes.NumInputs      = 2;
sizes.DirFeedthrough = 0;
sizes.NumSampleTimes = 1;   % at least one sample time is needed
sys = simsizes(sizes);
x0  = [0,1,0,0];
str = [];
ts  = [0 0];

function sys=mdlDerivatives(t,x,u)
id=x(1);
iq=x(2);
omega=x(3);
theta=x(4);
Ld=21;
Lq=8;
R=10;
np=1;
Km=0;
J=37;
vd=u(1);
vq=u(2);
iddot=(-R*id-np*omega*Lq*iq+vd)/Ld;
iqdot=(-R*iq-np*omega*Ld*id-np*omega*Km+vq)/Lq;
omegadot=np*(Km*iq+(Ld-Lq)*iq*id)/J;
thetadot=omega;
sys = [iddot;iqdot;omegadot;thetadot];

function sys=mdlUpdate(t,x,u)
sys = [];

function sys=mdlOutputs(t,x,u)
sys = x;

function sys=mdlGetTimeOfNextVarHit(t,x,u)
sampleTime = 1;    %  Example, set the next hit to be one second later.
sys = t + sampleTime;

function sys=mdlTerminate(t,x,u)
sys = [];
