% numdiff.m % This code is a script that performs numerical % differentiation. It is currently implementing % a centered difference algorithm. % NOTE: The step size is currently decreased % by a factor of 10 each time through the % following loop. % NOTE: This driver requires you to define the % name of the function that you want to evaluate % for the difference approximation. (string format) % Initialize variables clear; nam='ex2'; %Name of the function to be evaluated. % Notice that it is entered as a string-- % that is, it is in apostrophes. x0 = 0.8; %x value where we are approximating % the derivative h = 0.1; %Step size M = 4; %Number of iterations tru= cos(0.8); %True value of the derivative % necessary for error output. % Making a table for output fprintf(1,' It# Step Diff Approx. Error \n'); fprintf(1,'-----------------------------------------------\n'); for i = 1:M d(i) = (feval(nam,x0+h)-feval(nam,x0-h))/2/h; %output results fprintf(1,' %2d %5.4f %10.9e %10.9e\n',i,h,d(i),abs(tru-d(i))); % Calculate the new value of h for the next iteration. h = h/10; end; %end-i-loop