function [sys,x0,str,ts] = S_PMsync_obs(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  = 14;
sizes.NumDiscStates  = 0;
sizes.NumOutputs     = 4;
sizes.NumInputs      = 3;
sizes.DirFeedthrough = 0;
sizes.NumSampleTimes = 1;   % at least one sample time is needed
sys = simsizes(sizes);
x0  = [1;0;1;1;SymReshape(eye(4))];
str = [];
ts  = [0 0];

function sys=mdlDerivatives(t,x,u)
id=x(1);
iq=x(2);
omega=x(3);
theta=x(4);
P=SymReshape(x(5:14));
Ld=21;
Lq=8;
R=10;
np=1;
Km=0;
J=37;
thetames=u(1);
vd=u(2);
vq=u(3);
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;
A=[-R/Ld -np*omega*Lq/Ld -np*Lq*iq/Ld 0;
    -np*omega*Ld/Lq -R/Lq -np*(Ld*id+Km)/Lq 0;
    np*(Ld-Lq)*iq/J np*(Km+(Ld-Lq)*id)/J 0 0;
    0 0 1 0];
C=[0,0,0,1];
Q=eye(4);
xdot = [iddot;iqdot;omegadot;thetadot]+P*C'*(thetames-theta);
Pdot=A*P+P*A'+Q-P*C'*C*P;
sys = [xdot;SymReshape(Pdot)];

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

function sys=mdlOutputs(t,x,u)
sys = x(1:4);

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 = [];
