In: Computer Science
function dMat = numdiff(f,h,a)
syms x
df = diff(f(x));
trueValue = eval(subs(df,x,a));
dMat=zeros(3,9);
dMat(1,1)=trueValue;
dMat(1,2)=(f(h+a)-f(a))/h;
dMat(1,3)=(f(a)-f(a-h))/h;
dMat(1,4)=(f(h+a)-f(a-h))/(2*h);
dMat(1,5)=(-f(a+2*h)+4*f(a+h)-3*f(a))/(2*h);
dMat(1,6)=(f(a-2*h)-4*f(a-h)+3*f(a))/(2*h);
dMat(1,7)=(f(a-2*h)-8*f(a-h)+8*f(a+h)-f(a+2*h))/(12*h);
dMat(1,8)=(-25*f(a)+48*f(a+h)-36*f(a+2*h)+16*f(a+3*h)-3*f(a+4*h))/(12*h);
dMat(1,9)=(25*f(a)-48*f(a-h)+36*f(a-2*h)-16*f(a-3*h)+3*f(a-4*h))/(12*h);
dMat(2,:)=abs(trueValue-dMat(1,:));
if trueValue~=0%relative error will be calculated only if
derivativeis not 0
dMat(3,:)=dMat(2,:)/trueValue;
end