% -----------------------------------------------------
% velocityaccnusingdiff.m
% -----------------------------------------------------
% A program that computes velocity and acceleration and plots them vs time
% -----------------------------------------------------
% Notes: Use the difference formulae. 
% -----------------------------------------------------
% Copyright and license details available at matlabmarina.com
%------------------------------------------------------

clear;
clc;
close all;

% define time in seconds and distance in meters
t = [0, 0.1, 2, 2.5, 4, 6.2, 7, 8, 8.5, 9.5];
x = [10, 13, 14.6, 17.8, 20, 25, 36.6, 41.2, 44.2, 45];

% compute velocity using numerical differentiation
vel = diff(x) ./ diff(t);
tVel = t(2:end);

% compute acceleration using numerical differentiation
acc = diff(vel) ./ diff(tVel);
tAcc = tVel(2:end);

% plot distance, velocity and acceleration vs time
figure(1)
subplot(3,1,1);
plot(t,x,'bo-');
grid;
ylabel('distance (m)');
xlim([0 10]);

subplot(3,1,2);
plot(tVel,vel,'gx-');
grid;
ylabel('velocity (m/s)');
xlim([0 10]);

subplot(3,1,3);
plot(tAcc,acc,'r*-');
grid;
ylabel('acceleration (m/s^2)');
xlabel('time (s)');
xlim([0 10]);
