%% TridisolveDemo.m

%% 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.^(1:6)
    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 < 15000     % 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