%% Time Response of Continuous Plant with Discrete Controller
% To illustrate the use of sdlsim, consider the application of a discrete controller to a plant with an integrator and near integrator. A continuous plant and a discrete controller are created. A sample-and-hold equivalent of the plant is formed and the discrete closed-loop system is calculated. Simulating this gives the system response at the sample points.  sdlsim is then used to calculate the intersample behavior.

P = tf(1,[1, 1e-5,0]); 
T = 1.0/20; 
C = ss([-1.5 T/4; -2/T -.5],[ .5 2;1/T 1/T],... 
   [-1/T^2  -1.5/T], [1/T^2  0],T); 
Pd = c2d(P,T,'zoh');

%
% The closed-loop digital system is now set up. You can use sysic to construct the interconnected feedback system.

systemnames = 'Pd C'; 
inputvar = '[ref]'; 
outputvar = '[Pd]'; 
input_to_Pd = '[C]'; 
input_to_C = '[ref ; Pd]'; 
sysoutname = 'dclp'; 
cleanupsysic = 'yes'; 
sysic;

%
% Use step to simulate the digital step response.

[yd,td] = step(dclp,20*T);

%
% Set up the continuous interconnection and calculate the sampled data response with sdlsim.

M = [0,1;1,0;0,1]*blkdiag(1,P); 
t = [0:.01:1]'; 
u = ones(size(t)); 
y1 = sdlsim(M,C,u,t); 
plot(td,yd,'r*',y1{:},'b-') 
axis([0,1,0,1.5]) 
xlabel('Time: seconds') 
title('Step response: discrete (*) and continuous')

%
% You can see the effect of a nonzero initial condition in the continuous-time system. Note how examining the system at only the sample points will underestimate the amplitude of the overshoot.

y2 = sdlsim(M,C,u,t,1,0,[0.25;0]); 
plot(td,yd,'r*',y1{:},'b-',y2{:},'g--') 
axis([0,1,0,1.5]) 
xlabel('Time: seconds') 
title('Step response: nonzero initial condition')

%
% Finally, you can examine the effect of a sinusoidal disturbance at the continuous-time plant output. This controller is not designed to reject such a disturbance and the system does not contain antialiasing filters. Simulating the effect of antialiasing filters is easily accomplished by including them in the continuous interconnection structure.

M2 = [0,1,1;1,0,0;0,1,1]*blkdiag(1,1,P); 
t = [0:.001:1]'; 
dist = 0.1*sin(41*t); 
u = ones(size(t)); 
[y3,meas,act] = sdlsim(M2,C,[u dist],t,1); 
plot(y3{:},'-',t,dist,'b--',t,u,'g-.') 
xlabel('Time: seconds') 
title('Step response: disturbance (dashed) and  output (solid)')

%
% Copyright 2015 The MathWorks, Inc.