function ShowSparse3()
% Comments on data structures and implementations
clc
clear
% Suppose A is an nxn symmetric tridiagonal matrix, e.g.,
A = [1 2 0 0 0;...
2 3 4 0 0;...
0 4 5 6 0;...
0 0 6 7 8;...
0 0 0 8 9]
% Serious random example...
n = 1000000;
d = randn(n,1); % encodes the diagonal of A
e = randn(n-1,1); % encodes the superdiagonal of A(and therefore, itssubdiagonal)
A = struct('d',d,'e',e);
% With this 2-vector data structure, let's compute y = A*x where
x = randn(n,1);

% Scalar-level implementation...
tic
y = zeros(n,1);
y(1) = A.d(1)*x(1)+A.e(1)*x(2);
for i=2:n-1
y(i) = A.e(i-1)*x(i-1) + A.d(i)*x(i) + A.e(i)*x(i+1);
end
y(n) = A.e(n-1)*x(n-1)+A.d(n)*x(n);
tScalar = toc

% Vector-level implementation...
tic
y = zeros(n,1);
y(1) = A.d(1)*x(1)+A.e(1)*x(2);
y(2:n-1) = A.e(1:n-2).*x(1:n-2) + A.d(2:n-1).*x(2:n-1) + A.e(2:n-1).*x(3:n);
y(n) = A.e(n-1)*x(n-1)+A.d(n)*x(n);
tVector = toc

% Using the sparse format...
i = [1:n 1:n-1 2:n]';
j = [1:n 2:n 1:n-1]';
s = [d ; e ; e];
A = sparse(i,j,s);
tic
y = A*x;
tSparse = toc