# Writing a MATLAB .m File to Generate a Plot of Absolute Error as a Function of h (step-size)

This is the question I am to solve:

Given the function $f(x)=\ln(3x+1)$, compute approximations to $f'(0)$ using the centered 3-point formula:

$f'(x_0)\approx\frac{f(x_0+h)-f(x_0-h)}{2h}$.

Use Matlab to generate a plot of the absolute error as a function of the step-size h for the centered 3-point formula approximation to f′(0). At what values of h is the error minimized, that is, what step-sizes yield the maximum accuracy for this problem? (The magnitude of this number will be quite small.)

I have written the following MATLAB .m script file to generate the matrix of values $x, f(x), f'(x),$ and $\approx f'(x)$. However, I cannot figure out how to evaluate the error at more than one value for $h$ at a time, if there is a way.

h = 0.1;

x = -0.3:h:0.3;

f = @(x)(log(3.*x+1));

fp = @(x)((3)./(3.*x+1));

N = length(x);

A = zeros(N,4);

for i=1:N

for j = 1:3

A(i,1) = x(i);

A(i,2) = f(A(i,1));

A(i,3) = fp(A(i,1));

end%j

end%i

for i=2:N-1

for j = 4

A(i,j) = (A(i+1,j-2)-A(i-1,j-2))./(2.*h);

end%j

end%i

mdpt = ceil(N/2);

pt = A(mdpt,4);

err = abs(pt-fp(0));

scatter(h,err)

There are probably a few ways to answer this question. Perhaps you could generate the approximations of $f'(0)$ using the following code:

x0 = 0;

n = 1000;

h = logspace(-16, -1, n); % Generates n numbers logarithmically spaced between 10^(-16) and 10^(-1)

fp_approx = (f(x0 + h) - f(x0 - h)) ./ (2*h); % The approximations of f'(x_0)

Then compute the error as

fp_exact = fp(x0)*ones(size(fp_approx));

err = abs(fp_approx - fp_exact);

You could take $n$ much larger (say, $n = 10^6$), then find the minimum $h$ using min:

[min_err, idx] = min(err);

h(idx)

• Thank you for the help. I took away my for loops and basically pasted what you had suggested into my script file, so I have my assigned functions followed by the pasted material. To complete the question, would adding the line "plot(err,h)" be correct? If so, the plot generated is i43.tinypic.com/1628tb6.png Which shows both a blue line at the bottom and one going toward the top middle. – Khori Wood Oct 22 '13 at 21:44
• Glad to help. I get that plot as well when I type plot(err, h). Since you are interested in the absolute error as a function of h, you might want to swap the order of h and err: plot(h, err). One caveat though -- because of the very small numbers involved (recall that some of the numbers are on the order of $10^{-16}$), the plot doesn't show the graph of the absolute error very clearly. Instead you could use a log-log plot, loglog(h, err), which shows the absolute error as a function of $h$ much more clearly (on a log-log scale). – Kyle Oct 23 '13 at 2:23