Consider matrix A that has 2 for each diagonal entry 1s on e
Consider matrix A that has -2 for each diagonal entry, 1\'s on each of the
1st upper and lower diagonals, and the rest of the matrix is all 0\'s. Such a matrix
is encountered in numerically solving differential equations. It is considered to be
sparse because is consists of mostly 0\'s.
Let b be a vector of all ones. For n=10, 100, 1000, 2000, 4000, 8000:
a) Create the matrix A by rst creating a matrix of all 0\'s, then putting in the
-2\'s on the main diagonal and 1\'s on the 1st upper and lower diagonals. Solve
Ax = b using backslash, and time it using `tic\' and `toc\'. Hint: Using the `diag\'
command can help here.
b) Repeat the process, but using the sparse matrix format for A. You can do
this inefficiently using the `sparse\' command to turn your matrices from part
a) into sparse format. A much better way to do this is to create the matrix
using the `spdiags\' command. The syntax to do this can be found in the help
documentation of `spdiags\' (type \\help spdiags\" on the command line). Is there a
timing difference between solving sparse and full matrices using backslash? How
much?
PLEASE SHOW ALL MATLAB CODE FOR PART B
Solution
n = [10000];
% Normal method (a)
A = zeros(n);
c1 = -2*ones(n,1);
c2 = ones(n-1,1);
c3 = ones(n-1,1);
d1 = diag(c1);
d2 = diag(c2,-1);
d3 = diag(c3,1);
A = A + d1 + d2 + d3;
b = ones(n,1);
tic;A\\b;toc
% Sparse matrix method with spdiag (b)
m = ones(n,1)*[1 -2 1];
A1 = spdiags(m,[-1 0 1],n,n);
tic; A1\\b;toc
