%% Mass-Spring System
% A one-dimensional discrete-time oscillating system consists of a unit mass, m, attached to a wall by a spring of unit elastic constant. A sensor measures the acceleration, a, of the mass.
%
% The system is sampled at F_s=5 Hz. Generate 50 time samples. Define the sampling interval \Delta t=1/F_s.

Fs = 5;
dt = 1/Fs;
N = 50;
t = dt*(0:N-1);

%
% The oscillator can be described by the state-space equations
% \matrix{x(k+1)=Ax(k)+Bu(k),\cr y(k)=Cx(k)+Du(k),\cr}
% where x=\pmatrix{r&v}^T is the state vector, r and v are respectively the position and velocity of the mass, and the matrices
% A=\pmatrix{\cos\Delta t&\sin\Delta t\cr-\sin\Delta t&\cos\Delta
% t\cr},\quad B=\pmatrix{1-\cos\Delta t\cr\sin\Delta t\cr},\quad
% C=\pmatrix{-1&0\cr},\quad D=\pmatrix{1\cr}.

A = [cos(dt) sin(dt);-sin(dt) cos(dt)];
B = [1-cos(dt);sin(dt)];
C = [-1 0];
D = 1;

%
% The system is excited with a unit impulse in the positive direction. Use the state-space model to compute the time evolution of the system starting from an all-zero initial state.

u = [1 zeros(1,N-1)];

x = [0;0];
for k = 1:N
    y(k) = C*x + D*u(k);
    x = A*x + B*u(k);
end

%
% Plot the acceleration of the mass as a function of time.

stem(t,y,'filled')

%
% Compute the time-dependent acceleration using the transfer function to filter the input. Express the transfer function as second-order sections. Plot the result.

sos = ss2sos(A,B,C,D);
yt = sosfilt(sos,u);
stem(t,yt,'filled')

% The result is the same in both cases.
% Copyright 2015 The MathWorks, Inc.