% Simulation of a damped spring dynamic system by using the explicit Euler
% method for integration

clear

g=9.81;
k=2;
mu=0.5;
m=5;

x10=1.5;     % Initial value for the position of the object
x20=0;       % Initial value for the velocity

h=0.01;
t0=0;
t1=100;
t=t0:h:t1;          % a vector of time instants
N=length(t);

%N=ceil(t1-t0)/h+1;

x=[x10;x20]; % Initial state vector
for i=1:N
    
    f1=x(2);
    f2=-k*(x(1)-x10)/m-mu*x(2)/m-g;
    f=[f1;f2];
    
    X(i,1:2)=x';
    
    x=x+h*f
end

plot(t,X), grid
xlabel('Time  0 \leq t \leq 100')
title('Simulation of damped spring system')
legend('Position','velocity')