MyFunc=@(x) x.^2.*cos(x)
MyDeriv=@(x)x.*(2.*cos(x)-x.*sin(x))
% Define the vector of Delta values
DeltaVec=[0.001 0.002 0.005 0.01 0.1 0.2 0.4 1.0] ;
%Defining data point
xi=2.0;
for k=1:length(DeltaVec)
Delta=DeltaVec(k)
xim2=xi-2*Delta
xim1=xi-Delta;
xip1=xi+Delta;
xip2=xi+2*Delta;
%2nd order centred
dfdx2ndCentered=(1./(2*Delta))*(-MyFunc(xim1)+MyFunc(xip1));
error2ndCentered(k)=abs(MyDeriv(xi)-dfdx2ndCentered);
%4th order centred
dfdx4thCentered=(1./(12*Delta))*(MyFunc(xim2)-8*MyFunc(xim1)+8*MyFunc(xip1)-MyFunc(xip2));
error4thCentered(k)=abs(MyDeriv(xi)-dfdx4thCentered);
end
hold off
plot(log10(DeltaVec),log10(error2ndCentered),’ko-‘)
hold on
plot(log10(DeltaVec),log10(error4thCentered),’go-‘)
xlabel(‘log(\Delta)’,’FontSize’,14)
ylabel(‘log(Error)’,’FontSize’,14)