% Unit 1 (MATLAB Course @ UAM)
% numerical derivative exercise #1
% (c) Alexander Knebe

%===============================
% differentiation of function
%==============================
echo on
clear all
close all
clc

% parameters
a = 1.5;
b = 15.6;
N = 10;

% the function
x = linspace(a,b,N);
f = x.^2+5.*x;

% the derivative
il = 1:N-1;

dx = x(il+1)-x(il);
df = f(il+1)-f(il);

fderiv = df./dx;
xmid   = a+(il-1).*dx+dx./2;

% plot numerical derivative
plot(xmid,fderiv,'r'), hold on

% and compare to analytical result
plot(xmid,2.*xmid+5,'bo')

xlabel('x')
ylabel('y')
legend('numerical derivate (tabulated)','analytical derivative','Location','NorthWest')
