Closed Form Solution

%
%   Mass-Spring system 
%   Closed form solution 
%

%
%   constant inputs
%

m = 1;                      %  mass of the system in meter
k = 50;                     %  stiffness of the spring (N/m)
wn = sqrt(k/m);             %  natural frequency (rad/sec)

t_final = 2;                     %  calculation time
n = 500;                    %  number of data points

%
%   initial conditions
%

x_0 = 1;                    %  initial displacement
x_dot_0 = 0;                %  initial velocity

%
%   calculation of amplitude and phase angle
%

X_0 = sqrt(x_0^2+(x_dot_0/wn)^2);
phi = acos(x_0/X_0);

%
%   x(t)
%

t = 0:t_final/n:t_final;
x = X_0*cos(wn*t+phi);           %  displacement x(t)
x_dot = -wn*x_0*sin(wn*t+phi);   %  velocity x_dot(t)

%
%   plotting the results 
%

figure(1); clf; orient tall;
subplot(2,1,1),plot(t,x);
xlabel('Time (sec.)');
ylabel('Displacement (m)');
title('Mass-Spring system : Closed form result')

subplot(2,1,2),plot(t,x_dot);
xlabel('Time (sec.)');
ylabel('Velocity (m/sec.)');