convergence rate in matlab

To analyze the convergence rate of a numerical method in Matlab, we need to calculate the error at each iteration and compare it to some known error bound or to the error at the previous iteration. This allows us to estimate the rate at which the method is converging.

Here's an example for the bisection method to find the root of a function f(x) within the interval [a,b], with a known error tolerance eps:

main.m
a = ...; % set initial bounds
b = ...;
eps = ...; % set error tolerance
nmax = ...; % set maximum number of iterations

% initialize variables
n = 0;
err = (b-a)/2;
xn = (a+b)/2;
error_history = zeros(nmax,1); % to store the error at each iteration

while n < nmax && err > eps
    % bisect the interval
    if f(a)*f(xn) < 0
        b = xn;
    else
        a = xn;
    end
    % update variables
    n = n+1;
    xn = (a+b)/2;
    err = abs(xn-a);
    error_history(n) = err; % store the error at this iteration
end

% plot the error versus iteration number
plot(1:n,error_history(1:n),'-o');
xlabel('iteration');
ylabel('error');
title('Convergence rate of bisection method');
680 chars
31 lines

This code will plot the error versus iteration number, allowing us to visually inspect the convergence rate. We could also calculate the rate more precisely by fitting a line to the logarithm of the error history and finding its slope. This would give us an estimate of the order of convergence of the method.

gistlibby LogSnag