1
function A = meshsparse (G, stencil)
2
%MESHSPARSE convert a 2D or 3D mesh into a sparse matrix matrix.
6
% A = meshsparse (G,5) % 2D 5-point stencil (default for 2D case)
7
% A = meshsparse (G,9) % 2D 9-point stencil
8
% A = meshsparse (G,7) % 3D 7-point stencil (default for 3D case)
9
% A = meshsparse (G,27) % 3D 27-point stencil
10
% A = meshsparse (G,stencil) % user-provided stencil
12
% To create a sparse matrix for an m-by-n 2D mesh or m-by-n-by-k 3D mesh, use
14
% A = meshsparse (meshnd (m,n)) ;
15
% A = meshsparse (meshnd (m,n,k)) ;
17
% G is an m-by-n-by-k matrix, with entries numbered 1 to m*n*k (with k=1 for
18
% the 2D case). The entries in G can appear in any order, but no duplicate
19
% entries can appear. That is sort(G(:))' must equal 1:m*n*k. A is returned as
20
% a sparse matrix with m*n*k rows and columns whose pattern depends on the
21
% stencil. The number of nonzeros in most rows/columns of A is equal to the
22
% number of points in the stencil. For examples on how to specify your own
23
% stencil, see the contents of meshsparse.m.
27
% Copyright 2007, Timothy A. Davis, Univ. of Florida
32
stencil = 5 ; % 2D default is a 5-point stencil
34
stencil = 7 ; % 3D default is a 7-point stencil
38
if (numel (stencil) == 1)
44
% 5-point stencil (2D)
53
% 9-point stencil (2D)
66
% 7-point stencil (3D)
75
elseif (stencil == 27)
77
% 27-point stencil (3D)
78
stencil = zeros (26, 3) ;
83
if (~(i == 0 & j == 0 & k == 0)) %#ok
85
stencil (t,:) = [i j k] ;
93
stencil = fix (stencil) ;
94
[npoints d] = size (stencil) ;
96
% append zeros onto a 2D stencil to make it "3D"
97
stencil = [stencil zeros(npoints,1)] ;
99
[npoints d] = size (stencil) ;
101
error ('invalid stencil') ;
109
Ti = zeros (npoints*m*n*k, 1) ;
110
Tj = zeros (npoints*m*n*k, 1) ;
113
for point = 1:npoints
115
% find the overlapping rows of G
116
idelta = stencil (point,1) ;
118
ki = find (i2 >= 1 & i2 <= m) ;
120
% find the overlapping columns of G
121
jdelta = stencil (point,2) ;
123
kj = find (j2 >= 1 & j2 <= n) ;
125
% find the overlapping slices of G
126
kdelta = stencil (point,3) ;
128
kk = find (k2 >= 1 & k2 <= k) ;
130
% find the nodes in G the shifted G that touch
131
g2 = G (i2 (ki), j2 (kj), k2 (kk)) ; % shifted mesh
132
g1 = G (i1 (ki), j1 (kj), k1 (kk)) ; % unshifted mesh
134
% place the edges in the triplet list
136
Ti ((nz+1):(nz+e)) = g1 (:) ;
137
Tj ((nz+1):(nz+e)) = g2 (:) ;
141
% convert the triplets into a sparse matrix
144
A = npoints * speye (m*n*k) - sparse (Ti, Tj, 1, m*n*k, m*n*k) ;