% This is a short tutorial with a few examples on linear systems

%% start with an empty sheet
clear all   % remove all variables form the workspace
close all   % close all figure windows
clc         % clear all text from the command window

%% Defining linear systems
s = tf('s')             % the Laplace variable
T = 2                   % time constant
K = 3                   % gain
G = K/(s*T+1)           % transfer function

G2 = tf(1,[5 1])      % a more compact way of writing

exp(-s*3)               % a pure delay system

A = [-2 -2; 1 0]
B = [1;0]
C = [0 1]
D = 0
G3 = ss(A,B,C,D)        % this is how to construct a state space system

%% differnt representations
G3                      % state space
G3 = tf(G3)             % transfer function
G3 = ss(G3)             % back to state space (Matlab assigns states)

%% interconnecting systems
G*G2                    % series interconnection
G+G2                    % parallel interconnection

G4 = (G+G2)/G           % division (inverse) is also defined
G4 = minreal(G4)

%% transient responses
figure()
step(G2)                % step response

help impulse            % to find out more
% doc impulse           % to find out even more

figure()
impulse(G,G2,20)        % an example

%% frequency domain plots
figure()
bode(G,G2)              % bode plots of two processes

nyquist(G)              % nyquist curve of a process (also negative w)

%% poles and zeros
zpk(G4)
zero(G4)
pole(G4)

%% simulate linear system
t = 0:0.1:60;                           % time vector corresp. to 60 s
u = sin(2*pi*0.1*t);                    % input signal

G2                                      % the system we want to simulate
y = lsim(G2,u,t);                       % system response

figure()
subplot(211)
plot(t,y)
subplot(212)
plot(t,u)                   % plot input blue, output red