Building Big Matrices: sparse matrix
Let's consider the matrices associated to a Poisson problem:
in a square domain 
Using finite differences you obtain a linear system of equations with a matrix A of the form:
Build by hand the blockMatrix
One possibility is to build the matrix step by step:
Amd=2*c*eye(N); %main diagonal block matrix
Better using idiag function (not in Matlab distribution)
Amd(idiag(size(Amd),0))=4;
Amd(idiag(size(Amd),-1))=a;
Amd(idiag(size(Amd),1))=a;
Aupp(idiag(size(Aupp),0))=b;
Alow(idiag(size(Alow),0))=b;
spy(A) %notice that they are sparse matrices
Sparse Matrices
Automatic blockMatrix using blktridiag function (not in Matlab distribution)
% define the matrix blocks
Amd = blktridiag(c,a,a,N);
Alow =blktridiag(b,0,0,N);
Aupp =blktridiag(b,0,0,N);
A = blktridiag(Amd,Alow,Aupp,N);
Poisson's equation: Finitte Differences solution
Let's the Poisson's problem:
in a square domain
with homogeneous Dirichlet boundary conditions: and
The analytical solution is
In this case:
Linear system
with
, where
is the domain grid size.In this exemple the number of subdivisions is N+1 (here 8), so the total grid, including the boundaries, has (N+2)x(N+2) points (here 9x9). The number of unknowns per row is N (here 7), which is the size of each bock matrix and finally, the global matrix A has size
(here 49x49). N = 7; %dimension of the block matrices (correspond to the number of unknowns in each row)
% define the matrix blocks
Amd = blktridiag(c,a,a,N);
Alow = blktridiag(b,0,0,N);
Aupp = blktridiag(b,0,0,N);
A = blktridiag(Amd,Alow,Aupp,N);
f = @(x,y) -2*pi^2*(cos(2*pi*x).*sin(pi*y).^2+cos(2*pi*y).*sin(pi*x).^2);
u = @(x,y) (sin(pi*x).^2).*sin(pi*y).^2;
h = 1/(N+1); % corresponds to N+1 subdivisions
rhs = f(X(2:end-1,2:end-1),Y(2:end-1,2:end-1));
solExact = u(X(2:end-1,2:end-1),Y(2:end-1,2:end-1));
bb = h^2*rhs(:); %independent vector
xini = zeros(size(A,1),1);
sol = conjgrad(A,bb,xini,1.e-14);
Comparing efficiency with the solution using full matrices
N = 128; %bigger dimensions
% define the matrix blocks
Amd = blktridiag(c,a,a,N);
Alow = blktridiag(b,0,0,N);
Aupp = blktridiag(b,0,0,N);
A = blktridiag(Amd,Alow,Aupp,N);
h = 1/(N+1); % corresponds to N+1 subdivisions
% substitute all grid points but the boundary ones
rhs = f(X(2:end-1,2:end-1),Y(2:end-1,2:end-1));
bb = h^2*rhs(:); %independent vector
solSparse = A\bb; %solution using sparse matrices
toc
Elapsed time is 0.020963 seconds.
solExact = u(X(2:end-1,2:end-1),Y(2:end-1,2:end-1));
norm(solSparse-solExact,inf)
solFull = Cf\bb; %solution using full matrices
toc
Elapsed time is 8.254292 seconds.
© Numerical Factory 2021