% MATLAB script to model spring-mass-damper system and find response to
% pulse position input (as shown in class).

m = 1;  % mass (kg)
b = 0.0175;  % viscous damping constant (N-s/m)
k = 3;  % stiffness (N/m)

% Define system, input, output, and feed-thru matrices

A = [0 1; -k/m -b/m];   % System matrix
B = [0; k/m];   % Input matrix
C = [100 0; 0 39.37];   % Output matrix to produce pos (cm), vel (in/s)
D = [0; 0]; % Feed-thru matrix zero (true for physical systems)

% Define the SS LTI system

mass = ss(A,B,C,D); % Define the LTI spring-mass-damper system

% Next construct the input: a 0.1-meter 0.5-second pulse, followed by 9.5
% seconds of "zeros" to give a 10 second duration.

dt = 0.01;  % Use a 0.01-second stepsize (should be plenty small)
u1 = ones(51,1)*0.1;    % 51x1 column vector of 0.1
u2 = zeros(950,1);      % 950x1 column vector of zeros
u = [u1;u2];    % Stack them on top of each other

% Now make up a 10-sec time vector and perform the simulation

t = [0:dt:10]'; % 0 to 10 sec with dt stepsize; transpose to make column

y = lsim(mass,u,t); % Use lsim function to perform simulation

plot(t,u,'r',t,y(:,1),'k-',t,y(:,2),'k--'); grid;  % Plot results
legend('Input (m)','Position (cm)','Velocity (in/s)');
title('Response of Class Example System');
xlabel('Time (sec)');
ylabel('Displacement (cm), velocity (in/s)');