TridisolveDemo.m

Contents

Overview

This script demonstrates the difference in using dense and sparse code to solve a tridiagonal linear system. The function tridisolve is taken from Numerical Computing with MATLAB by Cleve Moler

for n = [10 100 1000 10000 100000]
    a = -ones(n-1,1);
    b = 2*ones(n,1);
    c = a;
    % Create a tridiagonal matrix with 2's on the diagonal and -1's on the
    % sub- and superdiagonal.
    A = gallery('tridiag',a,b,c);
    % A random vector for the right-hand side
    d = rand(n,1);
    fprintf('Time to solve %dx%d system\n', n,n)
    if n < 5000     % larger matrices will use too much memory
        % Turn $A$ into a dense matrix and solve with built-in backslash
        % solver
        Afull = full(A);
        tic;
        x = Afull\d;
        tend = toc;
        fprintf('Dense code:         %f seconds.\n', tend)
    end
    % Use the specialized algorithm from |tridisolve.m|
    tic;
    x = tridisolve(a,b,c,d);
    tend = toc;
    fprintf('Tridiagonal solver: %f seconds.\n', tend)
    tic;
    % Use the built-in backslash solver's capability to handle the sparse
    % format
    x = A\d;
    tend = toc;
    fprintf('Built-in code       %f seconds.\n\n', tend)
end
Time to solve 10x10 system
Dense code:         0.000184 seconds.
Tridiagonal solver: 0.001985 seconds.
Built-in code       0.000024 seconds.

Time to solve 100x100 system
Dense code:         0.000619 seconds.
Tridiagonal solver: 0.000042 seconds.
Built-in code       0.000023 seconds.

Time to solve 1000x1000 system
Dense code:         0.072084 seconds.
Tridiagonal solver: 0.000162 seconds.
Built-in code       0.000091 seconds.

Time to solve 10000x10000 system
Tridiagonal solver: 0.001170 seconds.
Built-in code       0.000800 seconds.

Time to solve 100000x100000 system
Tridiagonal solver: 0.012326 seconds.
Built-in code       0.008189 seconds.