5164
|
1 @c Copyright (C) 2004, 2005 David Bateman |
|
2 @c This is part of the Octave manual. |
|
3 @c For copying conditions, see the file gpl.texi. |
|
4 |
5648
|
5 @ifhtml |
|
6 @set htmltex |
|
7 @end ifhtml |
|
8 @iftex |
|
9 @set htmltex |
|
10 @end iftex |
|
11 |
5164
|
12 @node Sparse Matrices |
|
13 @chapter Sparse Matrices |
|
14 |
|
15 @menu |
|
16 * Basics:: The Creation and Manipulation of Sparse Matrices |
|
17 * Sparse Linear Algebra:: Linear Algebra on Sparse Matrices |
|
18 * Iterative Techniques:: Iterative Techniques applied to Sparse Matrices |
5648
|
19 * Real Life Example:: Real Life Example of the use of Sparse Matrices |
5164
|
20 @end menu |
|
21 |
5648
|
22 @node Basics, Sparse Linear Algebra, Sparse Matrices, Sparse Matrices |
5164
|
23 @section The Creation and Manipulation of Sparse Matrices |
|
24 |
|
25 The size of mathematical problems that can be treated at any particular |
|
26 time is generally limited by the available computing resources. Both, |
|
27 the speed of the computer and its available memory place limitation on |
|
28 the problem size. |
|
29 |
5506
|
30 There are many classes of mathematical problems which give rise to |
5164
|
31 matrices, where a large number of the elements are zero. In this case |
|
32 it makes sense to have a special matrix type to handle this class of |
|
33 problems where only the non-zero elements of the matrix are |
5506
|
34 stored. Not only does this reduce the amount of memory to store the |
5164
|
35 matrix, but it also means that operations on this type of matrix can |
|
36 take advantage of the a-priori knowledge of the positions of the |
|
37 non-zero elements to accelerate their calculations. |
|
38 |
|
39 A matrix type that stores only the non-zero elements is generally called |
|
40 sparse. It is the purpose of this document to discuss the basics of the |
|
41 storage and creation of sparse matrices and the fundamental operations |
|
42 on them. |
|
43 |
|
44 @menu |
|
45 * Storage:: Storage of Sparse Matrices |
|
46 * Creation:: Creating Sparse Matrices |
5648
|
47 * Information:: Finding out Information about Sparse Matrices |
5164
|
48 * Operators and Functions:: Basic Operators and Functions on Sparse Matrices |
|
49 @end menu |
|
50 |
|
51 @node Storage, Creation, Basics, Basics |
|
52 @subsection Storage of Sparse Matrices |
|
53 |
|
54 It is not strictly speaking necessary for the user to understand how |
|
55 sparse matrices are stored. However, such an understanding will help |
|
56 to get an understanding of the size of sparse matrices. Understanding |
|
57 the storage technique is also necessary for those users wishing to |
|
58 create their own oct-files. |
|
59 |
|
60 There are many different means of storing sparse matrix data. What all |
5648
|
61 of the methods have in common is that they attempt to reduce the complexity |
5164
|
62 and storage given a-priori knowledge of the particular class of problems |
|
63 that will be solved. A good summary of the available techniques for storing |
|
64 sparse matrix is given by Saad @footnote{Youcef Saad "SPARSKIT: A basic toolkit |
|
65 for sparse matrix computation", 1994, |
6620
|
66 @url{http://www-users.cs.umn.edu/~saad/software/SPARSKIT/paper.ps}}. |
5164
|
67 With full matrices, knowledge of the point of an element of the matrix |
|
68 within the matrix is implied by its position in the computers memory. |
|
69 However, this is not the case for sparse matrices, and so the positions |
|
70 of the non-zero elements of the matrix must equally be stored. |
|
71 |
|
72 An obvious way to do this is by storing the elements of the matrix as |
5506
|
73 triplets, with two elements being their position in the array |
5164
|
74 (rows and column) and the third being the data itself. This is conceptually |
|
75 easy to grasp, but requires more storage than is strictly needed. |
|
76 |
5648
|
77 The storage technique used within Octave is the compressed column |
5164
|
78 format. In this format the position of each element in a row and the |
|
79 data are stored as previously. However, if we assume that all elements |
|
80 in the same column are stored adjacent in the computers memory, then |
|
81 we only need to store information on the number of non-zero elements |
|
82 in each column, rather than their positions. Thus assuming that the |
|
83 matrix has more non-zero elements than there are columns in the |
|
84 matrix, we win in terms of the amount of memory used. |
|
85 |
|
86 In fact, the column index contains one more element than the number of |
|
87 columns, with the first element always being zero. The advantage of |
5648
|
88 this is a simplification in the code, in that their is no special case |
5164
|
89 for the first or last columns. A short example, demonstrating this in |
|
90 C is. |
|
91 |
|
92 @example |
|
93 for (j = 0; j < nc; j++) |
|
94 for (i = cidx (j); i < cidx(j+1); i++) |
5648
|
95 printf ("non-zero element (%i,%i) is %d\n", |
|
96 ridx(i), j, data(i)); |
5164
|
97 @end example |
|
98 |
|
99 A clear understanding might be had by considering an example of how the |
|
100 above applies to an example matrix. Consider the matrix |
|
101 |
|
102 @example |
|
103 @group |
|
104 1 2 0 0 |
|
105 0 0 0 3 |
|
106 0 0 0 4 |
|
107 @end group |
|
108 @end example |
|
109 |
|
110 The non-zero elements of this matrix are |
|
111 |
|
112 @example |
|
113 @group |
|
114 (1, 1) @result{} 1 |
|
115 (1, 2) @result{} 2 |
|
116 (2, 4) @result{} 3 |
|
117 (3, 4) @result{} 4 |
|
118 @end group |
|
119 @end example |
|
120 |
|
121 This will be stored as three vectors @var{cidx}, @var{ridx} and @var{data}, |
|
122 representing the column indexing, row indexing and data respectively. The |
|
123 contents of these three vectors for the above matrix will be |
|
124 |
|
125 @example |
|
126 @group |
5506
|
127 @var{cidx} = [0, 1, 2, 2, 4] |
5164
|
128 @var{ridx} = [0, 0, 1, 2] |
|
129 @var{data} = [1, 2, 3, 4] |
|
130 @end group |
|
131 @end example |
|
132 |
|
133 Note that this is the representation of these elements with the first row |
5648
|
134 and column assumed to start at zero, while in Octave itself the row and |
|
135 column indexing starts at one. Thus the number of elements in the |
5164
|
136 @var{i}-th column is given by @code{@var{cidx} (@var{i} + 1) - |
|
137 @var{cidx} (@var{i})}. |
|
138 |
5648
|
139 Although Octave uses a compressed column format, it should be noted |
|
140 that compressed row formats are equally possible. However, in the |
|
141 context of mixed operations between mixed sparse and dense matrices, |
|
142 it makes sense that the elements of the sparse matrices are in the |
|
143 same order as the dense matrices. Octave stores dense matrices in |
|
144 column major ordering, and so sparse matrices are equally stored in |
|
145 this manner. |
5164
|
146 |
5324
|
147 A further constraint on the sparse matrix storage used by Octave is that |
5164
|
148 all elements in the rows are stored in increasing order of their row |
5506
|
149 index, which makes certain operations faster. However, it imposes |
5164
|
150 the need to sort the elements on the creation of sparse matrices. Having |
|
151 dis-ordered elements is potentially an advantage in that it makes operations |
|
152 such as concatenating two sparse matrices together easier and faster, however |
|
153 it adds complexity and speed problems elsewhere. |
|
154 |
5648
|
155 @node Creation, Information, Storage, Basics |
5164
|
156 @subsection Creating Sparse Matrices |
|
157 |
|
158 There are several means to create sparse matrix. |
|
159 |
|
160 @table @asis |
|
161 @item Returned from a function |
|
162 There are many functions that directly return sparse matrices. These include |
|
163 @dfn{speye}, @dfn{sprand}, @dfn{spdiag}, etc. |
|
164 @item Constructed from matrices or vectors |
|
165 The function @dfn{sparse} allows a sparse matrix to be constructed from |
5506
|
166 three vectors representing the row, column and data. Alternatively, the |
5164
|
167 function @dfn{spconvert} uses a three column matrix format to allow easy |
|
168 importation of data from elsewhere. |
|
169 @item Created and then filled |
|
170 The function @dfn{sparse} or @dfn{spalloc} can be used to create an empty |
|
171 matrix that is then filled by the user |
|
172 @item From a user binary program |
|
173 The user can directly create the sparse matrix within an oct-file. |
|
174 @end table |
|
175 |
|
176 There are several basic functions to return specific sparse |
|
177 matrices. For example the sparse identity matrix, is a matrix that is |
|
178 often needed. It therefore has its own function to create it as |
|
179 @code{speye (@var{n})} or @code{speye (@var{r}, @var{c})}, which |
|
180 creates an @var{n}-by-@var{n} or @var{r}-by-@var{c} sparse identity |
|
181 matrix. |
|
182 |
|
183 Another typical sparse matrix that is often needed is a random distribution |
|
184 of random elements. The functions @dfn{sprand} and @dfn{sprandn} perform |
5506
|
185 this for uniform and normal random distributions of elements. They have exactly |
|
186 the same calling convention, where @code{sprand (@var{r}, @var{c}, @var{d})}, |
|
187 creates an @var{r}-by-@var{c} sparse matrix with a density of filled |
5164
|
188 elements of @var{d}. |
|
189 |
5506
|
190 Other functions of interest that directly creates a sparse matrices, are |
5164
|
191 @dfn{spdiag} or its generalization @dfn{spdiags}, that can take the |
|
192 definition of the diagonals of the matrix and create the sparse matrix |
|
193 that corresponds to this. For example |
|
194 |
|
195 @example |
6411
|
196 s = spdiag (sparse(randn(1,n)), -1); |
5164
|
197 @end example |
|
198 |
|
199 creates a sparse (@var{n}+1)-by-(@var{n}+1) sparse matrix with a single |
|
200 diagonal defined. |
|
201 |
6620
|
202 @DOCSTRING(spatan2) |
|
203 |
|
204 @DOCSTRING(spcumprod) |
|
205 |
|
206 @DOCSTRING(spcumsum) |
|
207 |
|
208 @DOCSTRING(spdiag) |
|
209 |
|
210 @DOCSTRING(spdiags) |
|
211 |
|
212 @DOCSTRING(speye) |
|
213 |
|
214 @DOCSTRING(spfun) |
|
215 |
|
216 @DOCSTRING(spmax) |
|
217 |
|
218 @DOCSTRING(spmin) |
|
219 |
|
220 @DOCSTRING(spones) |
|
221 |
|
222 @DOCSTRING(spprod) |
|
223 |
|
224 @DOCSTRING(sprand) |
|
225 |
|
226 @DOCSTRING(sprandn) |
|
227 |
|
228 @DOCSTRING(sprandsym) |
|
229 |
|
230 @DOCSTRING(spsum) |
|
231 |
|
232 @DOCSTRING(spsumsq) |
|
233 |
5164
|
234 The recommended way for the user to create a sparse matrix, is to create |
5648
|
235 two vectors containing the row and column index of the data and a third |
5164
|
236 vector of the same size containing the data to be stored. For example |
|
237 |
|
238 @example |
6421
|
239 ri = ci = d = []; |
|
240 for j = 1:c |
|
241 ri = [ri; randperm(r)(1:n)']; |
|
242 ci = [ci; j*ones(n,1)]; |
|
243 d = [d; rand(n,1)]; |
|
244 endfor |
|
245 s = sparse (ri, ci, d, r, c); |
5164
|
246 @end example |
|
247 |
6421
|
248 creates an @var{r}-by-@var{c} sparse matrix with a random distribution |
|
249 of @var{n} (<@var{r}) elements per column. The elements of the vectors |
|
250 do not need to be sorted in any particular order as Octave will sort |
|
251 them prior to storing the data. However, pre-sorting the data will |
|
252 make the creation of the sparse matrix faster. |
5164
|
253 |
|
254 The function @dfn{spconvert} takes a three or four column real matrix. |
|
255 The first two columns represent the row and column index respectively and |
|
256 the third and four columns, the real and imaginary parts of the sparse |
|
257 matrix. The matrix can contain zero elements and the elements can be |
|
258 sorted in any order. Adding zero elements is a convenient way to define |
|
259 the size of the sparse matrix. For example |
|
260 |
|
261 @example |
|
262 s = spconvert ([1 2 3 4; 1 3 4 4; 1 2 3 0]') |
|
263 @result{} Compressed Column Sparse (rows=4, cols=4, nnz=3) |
|
264 (1 , 1) -> 1 |
|
265 (2 , 3) -> 2 |
|
266 (3 , 4) -> 3 |
|
267 @end example |
|
268 |
|
269 An example of creating and filling a matrix might be |
|
270 |
|
271 @example |
|
272 k = 5; |
|
273 nz = r * k; |
|
274 s = spalloc (r, c, nz) |
|
275 for j = 1:c |
|
276 idx = randperm (r); |
5648
|
277 s (:, j) = [zeros(r - k, 1); ... |
|
278 rand(k, 1)] (idx); |
5164
|
279 endfor |
|
280 @end example |
|
281 |
5324
|
282 It should be noted, that due to the way that the Octave |
5164
|
283 assignment functions are written that the assignment will reallocate |
5506
|
284 the memory used by the sparse matrix at each iteration of the above loop. |
|
285 Therefore the @dfn{spalloc} function ignores the @var{nz} argument and |
|
286 does not preassign the memory for the matrix. Therefore, it is vitally |
5648
|
287 important that code using to above structure should be vectorized |
|
288 as much as possible to minimize the number of assignments and reduce the |
5164
|
289 number of memory allocations. |
|
290 |
6620
|
291 @DOCSTRING(full) |
|
292 |
|
293 @DOCSTRING(spalloc) |
|
294 |
|
295 @DOCSTRING(sparse) |
|
296 |
|
297 @DOCSTRING(spconvert) |
|
298 |
|
299 @DOCSTRING(spfind) |
|
300 |
6570
|
301 The above problem can be avoided in oct-files. However, the construction |
|
302 of a sparse matrix from an oct-file is more complex than can be |
|
303 discussed in this brief introduction, and you are referred to chapter |
|
304 @ref{Dynamically Linked Functions}, to have a full description of the |
|
305 techniques involved. |
5164
|
306 |
5648
|
307 @node Information, Operators and Functions, Creation, Basics |
|
308 @subsection Finding out Information about Sparse Matrices |
|
309 |
|
310 There are a number of functions that allow information concerning |
|
311 sparse matrices to be obtained. The most basic of these is |
|
312 @dfn{issparse} that identifies whether a particular Octave object is |
|
313 in fact a sparse matrix. |
|
314 |
|
315 Another very basic function is @dfn{nnz} that returns the number of |
|
316 non-zero entries there are in a sparse matrix, while the function |
|
317 @dfn{nzmax} returns the amount of storage allocated to the sparse |
|
318 matrix. Note that Octave tends to crop unused memory at the first |
|
319 opportunity for sparse objects. There are some cases of user created |
|
320 sparse objects where the value returned by @dfn{nzmaz} will not be |
|
321 the same as @dfn{nnz}, but in general they will give the same |
|
322 result. The function @dfn{spstats} returns some basic statistics on |
|
323 the columns of a sparse matrix including the number of elements, the |
|
324 mean and the variance of each column. |
|
325 |
6620
|
326 @DOCSTRING(issparse) |
|
327 |
|
328 @DOCSTRING(nnz) |
|
329 |
|
330 @DOCSTRING(nonzeros) |
|
331 |
|
332 @DOCSTRING(nzmax) |
|
333 |
|
334 @DOCSTRING(spstats) |
|
335 |
5648
|
336 When solving linear equations involving sparse matrices Octave |
|
337 determines the means to solve the equation based on the type of the |
|
338 matrix as discussed in @ref{Sparse Linear Algebra}. Octave probes the |
|
339 matrix type when the div (/) or ldiv (\) operator is first used with |
|
340 the matrix and then caches the type. However the @dfn{matrix_type} |
|
341 function can be used to determine the type of the sparse matrix prior |
|
342 to use of the div or ldiv operators. For example |
|
343 |
|
344 @example |
|
345 a = tril (sprandn(1024, 1024, 0.02), -1) ... |
|
346 + speye(1024); |
|
347 matrix_type (a); |
|
348 ans = Lower |
|
349 @end example |
|
350 |
|
351 show that Octave correctly determines the matrix type for lower |
|
352 triangular matrices. @dfn{matrix_type} can also be used to force |
|
353 the type of a matrix to be a particular type. For example |
|
354 |
|
355 @example |
|
356 a = matrix_type (tril (sprandn (1024, ... |
|
357 1024, 0.02), -1) + speye(1024), 'Lower'); |
|
358 @end example |
|
359 |
|
360 This allows the cost of determining the matrix type to be |
|
361 avoided. However, incorrectly defining the matrix type will result in |
|
362 incorrect results from solutions of linear equations, and so it is |
|
363 entirely the responsibility of the user to correctly identify the |
|
364 matrix type |
|
365 |
|
366 There are several graphical means of finding out information about |
|
367 sparse matrices. The first is the @dfn{spy} command, which displays |
|
368 the structure of the non-zero elements of the |
|
369 matrix. @xref{fig:spmatrix}, for an exaple of the use of |
5704
|
370 @dfn{spy}. More advanced graphical information can be obtained with the |
5648
|
371 @dfn{treeplot}, @dfn{etreeplot} and @dfn{gplot} commands. |
|
372 |
|
373 @float Figure,fig:spmatrix |
|
374 @image{spmatrix,8cm} |
|
375 @caption{Structure of simple sparse matrix.} |
|
376 @end float |
|
377 |
|
378 One use of sparse matrices is in graph theory, where the |
|
379 interconnections between nodes is represented as an adjacency |
|
380 matrix. That is, if the i-th node in a graph is connected to the j-th |
|
381 node. Then the ij-th node (and in the case of undirected graphs the |
|
382 ji-th node) of the sparse adjacency matrix is non-zero. If each node |
|
383 is then associated with a set of co-ordinates, then the @dfn{gplot} |
|
384 command can be used to graphically display the interconnections |
|
385 between nodes. |
|
386 |
|
387 As a trivial example of the use of @dfn{gplot}, consider the example |
|
388 |
|
389 @example |
|
390 A = sparse([2,6,1,3,2,4,3,5,4,6,1,5], |
|
391 [1,1,2,2,3,3,4,4,5,5,6,6],1,6,6); |
|
392 xy = [0,4,8,6,4,2;5,0,5,7,5,7]'; |
|
393 gplot(A,xy) |
|
394 @end example |
|
395 |
|
396 which creates an adjacency matrix @code{A} where node 1 is connected |
|
397 to nodes 2 and 6, node 2 with nodes 1 and 3, etc. The co-ordinates of |
|
398 the nodes are given in the n-by-2 matrix @code{xy}. |
|
399 @ifset htmltex |
|
400 @xref{fig:gplot}. |
|
401 |
|
402 @float Figure,fig:gplot |
|
403 @image{gplot,8cm} |
|
404 @caption{Simple use of the @dfn{gplot} command.} |
|
405 @end float |
|
406 @end ifset |
|
407 |
|
408 The dependencies between the nodes of a Cholesky factorization can be |
|
409 calculated in linear time without explicitly needing to calculate the |
|
410 Cholesky factorization by the @code{etree} command. This command |
|
411 returns the elimination tree of the matrix and can be displayed |
|
412 graphically by the command @code{treeplot(etree(A))} if @code{A} is |
|
413 symmetric or @code{treeplot(etree(A+A'))} otherwise. |
|
414 |
6620
|
415 @DOCSTRING(spy) |
|
416 |
|
417 @DOCSTRING(etree) |
|
418 |
|
419 @DOCSTRING(etreeplot) |
|
420 |
|
421 @DOCSTRING(gplot) |
|
422 |
|
423 @DOCSTRING(treeplot) |
|
424 |
5648
|
425 @node Operators and Functions, , Information, Basics |
5164
|
426 @subsection Basic Operators and Functions on Sparse Matrices |
|
427 |
|
428 @menu |
5648
|
429 * Functions:: Sparse Functions |
5164
|
430 * ReturnType:: The Return Types of Operators and Functions |
|
431 * MathConsiderations:: Mathematical Considerations |
|
432 @end menu |
|
433 |
|
434 @node Functions, ReturnType, Operators and Functions, Operators and Functions |
5648
|
435 @subsubsection Sparse Functions |
|
436 |
|
437 An important consideration in the use of the sparse functions of |
|
438 Octave is that many of the internal functions of Octave, such as |
|
439 @dfn{diag}, can not accept sparse matrices as an input. The sparse |
|
440 implementation in Octave therefore uses the @dfn{dispatch} |
|
441 function to overload the normal Octave functions with equivalent |
|
442 functions that work with sparse matrices. However, at any time the |
|
443 sparse matrix specific version of the function can be used by |
|
444 explicitly calling its function name. |
|
445 |
6620
|
446 The table below lists all of the sparse functions of Octave. Note that |
|
447 in this specific sparse forms of the functions are typically the same as |
|
448 the general versions with a @dfn{sp} prefix. In the table below, and the |
|
449 rest of this article the specific sparse versions of the functions are |
|
450 used. |
|
451 |
|
452 @c Table includes in comments the missing sparse functions |
5648
|
453 |
|
454 @table @asis |
|
455 @item Generate sparse matrices: |
|
456 @dfn{spalloc}, @dfn{spdiags}, @dfn{speye}, @dfn{sprand}, |
|
457 @dfn{sprandn}, @dfn{sprandsym} |
|
458 |
|
459 @item Sparse matrix conversion: |
|
460 @dfn{full}, @dfn{sparse}, @dfn{spconvert}, @dfn{spfind} |
|
461 |
|
462 @item Manipulate sparse matrices |
|
463 @dfn{issparse}, @dfn{nnz}, @dfn{nonzeros}, @dfn{nzmax}, |
6620
|
464 @dfn{spfun}, @dfn{spones}, @dfn{spy} |
5164
|
465 |
5648
|
466 @item Graph Theory: |
|
467 @dfn{etree}, @dfn{etreeplot}, @dfn{gplot}, |
6620
|
468 @dfn{treeplot} |
|
469 @c @dfn{treelayout} |
5648
|
470 |
|
471 @item Sparse matrix reordering: |
6620
|
472 @dfn{ccolamd}, @dfn{colamd}, @dfn{colperm}, @dfn{csymamd}, |
|
473 @dfn{dmperm}, @dfn{symamd}, @dfn{randperm}, @dfn{symrcm} |
5648
|
474 |
|
475 @item Linear algebra: |
|
476 @dfn{matrix\_type}, @dfn{spchol}, @dfn{cpcholinv}, |
|
477 @dfn{spchol2inv}, @dfn{spdet}, @dfn{spinv}, @dfn{spkron}, |
6620
|
478 @dfn{splchol}, @dfn{splu}, @dfn{spqr}, @dfn{normest}, |
|
479 @dfn{sprank} |
|
480 @c @dfn{condest}, @dfn{spaugment} |
|
481 @c @dfn{eigs}, @dfn{svds} but these are in octave-forge for now |
5648
|
482 |
|
483 @item Iterative techniques: |
6620
|
484 @dfn{luinc}, @dfn{pcg}, @dfn{pcr} |
|
485 @c @dfn{bicg}, @dfn{bicgstab}, @dfn{cholinc}, @dfn{cgs}, @dfn{gmres}, |
|
486 @c @dfn{lsqr}, @dfn{minres}, @dfn{qmr}, @dfn{symmlq} |
5648
|
487 |
|
488 @item Miscellaneous: |
|
489 @dfn{spparms}, @dfn{symbfact}, @dfn{spstats}, |
|
490 @dfn{spprod}, @dfn{spcumsum}, @dfn{spsum}, |
|
491 @dfn{spsumsq}, @dfn{spmin}, @dfn{spmax}, @dfn{spatan2}, |
|
492 @dfn{spdiag} |
|
493 @end table |
|
494 |
|
495 In addition all of the standard Octave mapper functions (ie. basic |
|
496 math functions that take a single argument) such as @dfn{abs}, etc |
|
497 can accept sparse matrices. The reader is referred to the documentation |
|
498 supplied with these functions within Octave itself for further |
|
499 details. |
5164
|
500 |
|
501 @node ReturnType, MathConsiderations, Functions, Operators and Functions |
|
502 @subsubsection The Return Types of Operators and Functions |
|
503 |
5506
|
504 The two basic reasons to use sparse matrices are to reduce the memory |
5164
|
505 usage and to not have to do calculations on zero elements. The two are |
|
506 closely related in that the computation time on a sparse matrix operator |
5506
|
507 or function is roughly linear with the number of non-zero elements. |
5164
|
508 |
|
509 Therefore, there is a certain density of non-zero elements of a matrix |
|
510 where it no longer makes sense to store it as a sparse matrix, but rather |
|
511 as a full matrix. For this reason operators and functions that have a |
|
512 high probability of returning a full matrix will always return one. For |
|
513 example adding a scalar constant to a sparse matrix will almost always |
|
514 make it a full matrix, and so the example |
|
515 |
|
516 @example |
|
517 speye(3) + 0 |
|
518 @result{} 1 0 0 |
|
519 0 1 0 |
|
520 0 0 1 |
|
521 @end example |
|
522 |
|
523 returns a full matrix as can be seen. Additionally all sparse functions |
|
524 test the amount of memory occupied by the sparse matrix to see if the |
|
525 amount of storage used is larger than the amount used by the full |
|
526 equivalent. Therefore @code{speye (2) * 1} will return a full matrix as |
|
527 the memory used is smaller for the full version than the sparse version. |
|
528 |
|
529 As all of the mixed operators and functions between full and sparse |
|
530 matrices exist, in general this does not cause any problems. However, |
|
531 one area where it does cause a problem is where a sparse matrix is |
|
532 promoted to a full matrix, where subsequent operations would resparsify |
5648
|
533 the matrix. Such cases are rare, but can be artificially created, for |
5164
|
534 example @code{(fliplr(speye(3)) + speye(3)) - speye(3)} gives a full |
|
535 matrix when it should give a sparse one. In general, where such cases |
|
536 occur, they impose only a small memory penalty. |
|
537 |
5648
|
538 There is however one known case where this behavior of Octave's |
5164
|
539 sparse matrices will cause a problem. That is in the handling of the |
|
540 @dfn{diag} function. Whether @dfn{diag} returns a sparse or full matrix |
|
541 depending on the type of its input arguments. So |
|
542 |
|
543 @example |
|
544 a = diag (sparse([1,2,3]), -1); |
|
545 @end example |
|
546 |
|
547 should return a sparse matrix. To ensure this actually happens, the |
|
548 @dfn{sparse} function, and other functions based on it like @dfn{speye}, |
|
549 always returns a sparse matrix, even if the memory used will be larger |
|
550 than its full representation. |
|
551 |
|
552 @node MathConsiderations, , ReturnType, Operators and Functions |
|
553 @subsubsection Mathematical Considerations |
|
554 |
|
555 The attempt has been made to make sparse matrices behave in exactly the |
|
556 same manner as there full counterparts. However, there are certain differences |
|
557 and especially differences with other products sparse implementations. |
|
558 |
|
559 Firstly, the "./" and ".^" operators must be used with care. Consider what |
|
560 the examples |
|
561 |
|
562 @example |
|
563 s = speye (4); |
|
564 a1 = s .^ 2; |
|
565 a2 = s .^ s; |
|
566 a3 = s .^ -2; |
|
567 a4 = s ./ 2; |
|
568 a5 = 2 ./ s; |
|
569 a6 = s ./ s; |
|
570 @end example |
|
571 |
|
572 will give. The first example of @var{s} raised to the power of 2 causes |
|
573 no problems. However @var{s} raised element-wise to itself involves a |
6431
|
574 large number of terms @code{0 .^ 0} which is 1. There @code{@var{s} .^ |
5164
|
575 @var{s}} is a full matrix. |
|
576 |
|
577 Likewise @code{@var{s} .^ -2} involves terms terms like @code{0 .^ -2} which |
|
578 is infinity, and so @code{@var{s} .^ -2} is equally a full matrix. |
|
579 |
|
580 For the "./" operator @code{@var{s} ./ 2} has no problems, but |
|
581 @code{2 ./ @var{s}} involves a large number of infinity terms as well |
|
582 and is equally a full matrix. The case of @code{@var{s} ./ @var{s}} |
|
583 involves terms like @code{0 ./ 0} which is a @code{NaN} and so this |
|
584 is equally a full matrix with the zero elements of @var{s} filled with |
|
585 @code{NaN} values. |
|
586 |
5648
|
587 The above behavior is consistent with full matrices, but is not |
5164
|
588 consistent with sparse implementations in other products. |
|
589 |
|
590 A particular problem of sparse matrices comes about due to the fact that |
|
591 as the zeros are not stored, the sign-bit of these zeros is equally not |
5506
|
592 stored. In certain cases the sign-bit of zero is important. For example |
5164
|
593 |
|
594 @example |
|
595 a = 0 ./ [-1, 1; 1, -1]; |
|
596 b = 1 ./ a |
|
597 @result{} -Inf Inf |
|
598 Inf -Inf |
|
599 c = 1 ./ sparse (a) |
|
600 @result{} Inf Inf |
|
601 Inf Inf |
|
602 @end example |
|
603 |
5648
|
604 To correct this behavior would mean that zero elements with a negative |
5164
|
605 sign-bit would need to be stored in the matrix to ensure that their |
|
606 sign-bit was respected. This is not done at this time, for reasons of |
6750
|
607 efficiency, and so the user is warned that calculations where the sign-bit |
5164
|
608 of zero is important must not be done using sparse matrices. |
|
609 |
5648
|
610 In general any function or operator used on a sparse matrix will |
|
611 result in a sparse matrix with the same or a larger number of non-zero |
|
612 elements than the original matrix. This is particularly true for the |
|
613 important case of sparse matrix factorizations. The usual way to |
|
614 address this is to reorder the matrix, such that its factorization is |
|
615 sparser than the factorization of the original matrix. That is the |
|
616 factorization of @code{L * U = P * S * Q} has sparser terms @code{L} |
|
617 and @code{U} than the equivalent factorization @code{L * U = S}. |
|
618 |
|
619 Several functions are available to reorder depending on the type of the |
|
620 matrix to be factorized. If the matrix is symmetric positive-definite, |
|
621 then @dfn{symamd} or @dfn{csymamd} should be used. Otherwise |
|
622 @dfn{colamd} or @dfn{ccolamd} should be used. For completeness |
|
623 the reordering functions @dfn{colperm} and @dfn{randperm} are |
|
624 also available. |
|
625 |
|
626 @xref{fig:simplematrix}, for an example of the structure of a simple |
|
627 positive definite matrix. |
5506
|
628 |
5648
|
629 @float Figure,fig:simplematrix |
|
630 @image{spmatrix,8cm} |
|
631 @caption{Structure of simple sparse matrix.} |
|
632 @end float |
5506
|
633 |
5648
|
634 The standard Cholesky factorization of this matrix, can be |
|
635 obtained by the same command that would be used for a full |
5652
|
636 matrix. This can be visualized with the command |
|
637 @code{r = chol(A); spy(r);}. |
|
638 @ifset HAVE_CHOLMOD |
|
639 @ifset HAVE_COLAMD |
|
640 @xref{fig:simplechol}. |
|
641 @end ifset |
|
642 @end ifset |
|
643 The original matrix had |
5648
|
644 @ifinfo |
|
645 @ifnothtml |
|
646 43 |
|
647 @end ifnothtml |
|
648 @end ifinfo |
|
649 @ifset htmltex |
|
650 598 |
|
651 @end ifset |
|
652 non-zero terms, while this Cholesky factorization has |
|
653 @ifinfo |
|
654 @ifnothtml |
|
655 71, |
|
656 @end ifnothtml |
|
657 @end ifinfo |
|
658 @ifset htmltex |
|
659 10200, |
|
660 @end ifset |
|
661 with only half of the symmetric matrix being stored. This |
|
662 is a significant level of fill in, and although not an issue |
|
663 for such a small test case, can represents a large overhead |
|
664 in working with other sparse matrices. |
5164
|
665 |
5648
|
666 The appropriate sparsity preserving permutation of the original |
|
667 matrix is given by @dfn{symamd} and the factorization using this |
|
668 reordering can be visualized using the command @code{q = symamd(A); |
|
669 r = chol(A(q,q)); spy(r)}. This gives |
|
670 @ifinfo |
|
671 @ifnothtml |
|
672 29 |
|
673 @end ifnothtml |
|
674 @end ifinfo |
|
675 @ifset htmltex |
|
676 399 |
|
677 @end ifset |
|
678 non-zero terms which is a significant improvement. |
5164
|
679 |
5648
|
680 The Cholesky factorization itself can be used to determine the |
|
681 appropriate sparsity preserving reordering of the matrix during the |
|
682 factorization, In that case this might be obtained with three return |
|
683 arguments as r@code{[r, p, q] = chol(A); spy(r)}. |
5164
|
684 |
5648
|
685 @ifset HAVE_CHOLMOD |
|
686 @ifset HAVE_COLAMD |
|
687 @float Figure,fig:simplechol |
|
688 @image{spchol,8cm} |
|
689 @caption{Structure of the un-permuted Cholesky factorization of the above matrix.} |
|
690 @end float |
5164
|
691 |
5648
|
692 @float Figure,fig:simplecholperm |
|
693 @image{spcholperm,8cm} |
|
694 @caption{Structure of the permuted Cholesky factorization of the above matrix.} |
|
695 @end float |
|
696 @end ifset |
|
697 @end ifset |
5164
|
698 |
5648
|
699 In the case of an asymmetric matrix, the appropriate sparsity |
|
700 preserving permutation is @dfn{colamd} and the factorization using |
|
701 this reordering can be visualized using the command @code{q = |
|
702 colamd(A); [l, u, p] = lu(A(:,q)); spy(l+u)}. |
5164
|
703 |
5648
|
704 Finally, Octave implicitly reorders the matrix when using the div (/) |
|
705 and ldiv (\) operators, and so no the user does not need to explicitly |
|
706 reorder the matrix to maximize performance. |
|
707 |
6620
|
708 @DOCSTRING(ccolamd) |
|
709 |
|
710 @DOCSTRING(colamd) |
|
711 |
|
712 @DOCSTRING(colperm) |
|
713 |
|
714 @DOCSTRING(csymamd) |
|
715 |
|
716 @DOCSTRING(dmperm) |
|
717 |
|
718 @DOCSTRING(symamd) |
|
719 |
|
720 @DOCSTRING(symrcm) |
|
721 |
5648
|
722 @node Sparse Linear Algebra, Iterative Techniques, Basics, Sparse Matrices |
5164
|
723 @section Linear Algebra on Sparse Matrices |
|
724 |
5324
|
725 Octave includes a poly-morphic solver for sparse matrices, where |
5164
|
726 the exact solver used to factorize the matrix, depends on the properties |
5648
|
727 of the sparse matrix itself. Generally, the cost of determining the matrix type |
5322
|
728 is small relative to the cost of factorizing the matrix itself, but in any |
|
729 case the matrix type is cached once it is calculated, so that it is not |
|
730 re-determined each time it is used in a linear equation. |
5164
|
731 |
|
732 The selection tree for how the linear equation is solve is |
|
733 |
|
734 @enumerate 1 |
5648
|
735 @item If the matrix is diagonal, solve directly and goto 8 |
5164
|
736 |
|
737 @item If the matrix is a permuted diagonal, solve directly taking into |
5648
|
738 account the permutations. Goto 8 |
5164
|
739 |
5648
|
740 @item If the matrix is square, banded and if the band density is less |
|
741 than that given by @code{spparms ("bandden")} continue, else goto 4. |
5164
|
742 |
|
743 @enumerate a |
|
744 @item If the matrix is tridiagonal and the right-hand side is not sparse |
5648
|
745 continue, else goto 3b. |
5164
|
746 |
|
747 @enumerate |
|
748 @item If the matrix is hermitian, with a positive real diagonal, attempt |
|
749 Cholesky factorization using @sc{Lapack} xPTSV. |
|
750 |
|
751 @item If the above failed or the matrix is not hermitian with a positive |
|
752 real diagonal use Gaussian elimination with pivoting using |
5648
|
753 @sc{Lapack} xGTSV, and goto 8. |
5164
|
754 @end enumerate |
|
755 |
|
756 @item If the matrix is hermitian with a positive real diagonal, attempt |
|
757 Cholesky factorization using @sc{Lapack} xPBTRF. |
|
758 |
|
759 @item if the above failed or the matrix is not hermitian with a positive |
|
760 real diagonal use Gaussian elimination with pivoting using |
5648
|
761 @sc{Lapack} xGBTRF, and goto 8. |
5164
|
762 @end enumerate |
|
763 |
|
764 @item If the matrix is upper or lower triangular perform a sparse forward |
5648
|
765 or backward substitution, and goto 8 |
5164
|
766 |
5322
|
767 @item If the matrix is a upper triangular matrix with column permutations |
|
768 or lower triangular matrix with row permutations, perform a sparse forward |
5648
|
769 or backward substitution, and goto 8 |
5164
|
770 |
5648
|
771 @item If the matrix is square, hermitian with a real positive diagonal, attempt |
5506
|
772 sparse Cholesky factorization using CHOLMOD. |
5164
|
773 |
|
774 @item If the sparse Cholesky factorization failed or the matrix is not |
5648
|
775 hermitian with a real positive diagonal, and the matrix is square, factorize |
|
776 using UMFPACK. |
5164
|
777 |
|
778 @item If the matrix is not square, or any of the previous solvers flags |
5648
|
779 a singular or near singular matrix, find a minimum norm solution using |
|
780 CXSPARSE@footnote{CHOLMOD, UMFPACK and CXSPARSE are written by Tim Davis |
|
781 and are available at http://www.cise.ufl.edu/research/sparse/}. |
5164
|
782 @end enumerate |
|
783 |
|
784 The band density is defined as the number of non-zero values in the matrix |
|
785 divided by the number of non-zero values in the matrix. The banded matrix |
|
786 solvers can be entirely disabled by using @dfn{spparms} to set @code{bandden} |
|
787 to 1 (i.e. @code{spparms ("bandden", 1)}). |
|
788 |
5681
|
789 The QR solver factorizes the problem with a Dulmage-Mendhelsohn, to |
|
790 seperate the problem into blocks that can be treated as over-determined, |
|
791 multiple well determined blocks, and a final over-determined block. For |
|
792 matrices with blocks of strongly connectted nodes this is a big win as |
|
793 LU decomposition can be used for many blocks. It also significantly |
|
794 improves the chance of finding a solution to over-determined problems |
|
795 rather than just returning a vector of @dfn{NaN}'s. |
|
796 |
|
797 All of the solvers above, can calculate an estimate of the condition |
|
798 number. This can be used to detect numerical stability problems in the |
|
799 solution and force a minimum norm solution to be used. However, for |
|
800 narrow banded, triangular or diagonal matrices, the cost of |
|
801 calculating the condition number is significant, and can in fact |
|
802 exceed the cost of factoring the matrix. Therefore the condition |
6620
|
803 number is not calculated in these case, and Octave relies on simplier |
5681
|
804 techniques to detect sinular matrices or the underlying LAPACK code in |
|
805 the case of banded matrices. |
5164
|
806 |
5322
|
807 The user can force the type of the matrix with the @code{matrix_type} |
|
808 function. This overcomes the cost of discovering the type of the matrix. |
|
809 However, it should be noted incorrectly identifying the type of the matrix |
|
810 will lead to unpredictable results, and so @code{matrix_type} should be |
5506
|
811 used with care. |
5322
|
812 |
6620
|
813 @DOCSTRING(normest) |
|
814 |
|
815 @DOCSTRING(spchol) |
|
816 |
|
817 @DOCSTRING(spcholinv) |
|
818 |
|
819 @DOCSTRING(spchol2inv) |
|
820 |
|
821 @DOCSTRING(spdet) |
|
822 |
|
823 @DOCSTRING(spinv) |
|
824 |
|
825 @DOCSTRING(spkron) |
|
826 |
|
827 @DOCSTRING(splchol) |
|
828 |
|
829 @DOCSTRING(splu) |
|
830 |
|
831 @DOCSTRING(spparms) |
|
832 |
|
833 @DOCSTRING(spqr) |
|
834 |
|
835 @DOCSTRING(sprank) |
|
836 |
|
837 @DOCSTRING(symbfact) |
|
838 |
5648
|
839 @node Iterative Techniques, Real Life Example, Sparse Linear Algebra, Sparse Matrices |
5164
|
840 @section Iterative Techniques applied to sparse matrices |
|
841 |
6620
|
842 The left division @code{\} and right division @code{/} operators, |
|
843 discussed in the previous section, use direct solvers to resolve a |
|
844 linear equation of the form @code{@var{x} = @var{A} \ @var{b}} or |
|
845 @code{@var{x} = @var{b} / @var{A}}. Octave equally includes a number of |
|
846 functions to solve sparse linear equations using iterative techniques. |
|
847 |
|
848 @DOCSTRING(pcg) |
|
849 |
|
850 @DOCSTRING(pcr) |
5837
|
851 |
6620
|
852 The speed with which an iterative solver converges to a solution can be |
|
853 accelerated with the use of a pre-conditioning matrix @var{M}. In this |
|
854 case the linear equation @code{@var{M}^-1 * @var{x} = @var{M}^-1 * |
|
855 @var{A} \ @var{b}} is solved instead. Typical pre-conditioning matrices |
|
856 are partial factorizations of the original matrix. |
5648
|
857 |
6620
|
858 @DOCSTRING(luinc) |
|
859 |
|
860 @node Real Life Example, , Iterative Techniques, Sparse Matrices |
5648
|
861 @section Real Life Example of the use of Sparse Matrices |
|
862 |
|
863 A common application for sparse matrices is in the solution of Finite |
|
864 Element Models. Finite element models allow numerical solution of |
|
865 partial differential equations that do not have closed form solutions, |
|
866 typically because of the complex shape of the domain. |
|
867 |
|
868 In order to motivate this application, we consider the boundary value |
|
869 Laplace equation. This system can model scalar potential fields, such |
|
870 as heat or electrical potential. Given a medium |
|
871 @iftex |
|
872 @tex |
|
873 $\Omega$ |
|
874 @end tex |
|
875 @end iftex |
|
876 @ifinfo |
|
877 Omega |
|
878 @end ifinfo |
|
879 with boundary |
|
880 @iftex |
|
881 @tex |
|
882 $\partial\Omega$ |
|
883 @end tex |
|
884 @end iftex |
|
885 @ifinfo |
|
886 dOmega |
|
887 @end ifinfo |
|
888 . At all points on the |
|
889 @iftex |
|
890 @tex |
|
891 $\partial\Omega$ |
|
892 @end tex |
|
893 @end iftex |
|
894 @ifinfo |
|
895 dOmega |
|
896 @end ifinfo |
|
897 the boundary conditions are known, and we wish to calculate the potential in |
|
898 @iftex |
|
899 @tex |
|
900 $\Omega$ |
|
901 @end tex |
|
902 @end iftex |
|
903 @ifinfo |
|
904 Omega |
|
905 @end ifinfo |
|
906 . Boundary conditions may specify the potential (Dirichlet |
|
907 boundary condition), its normal derivative across the boundary |
|
908 (Neumann boundary condition), or a weighted sum of the potential and |
|
909 its derivative (Cauchy boundary condition). |
|
910 |
|
911 In a thermal model, we want to calculate the temperature in |
|
912 @iftex |
|
913 @tex |
|
914 $\Omega$ |
|
915 @end tex |
|
916 @end iftex |
|
917 @ifinfo |
|
918 Omega |
|
919 @end ifinfo |
|
920 and know the boundary temperature (Dirichlet condition) |
|
921 or heat flux (from which we can calculate the Neumann condition |
|
922 by dividing by the thermal conductivity at the boundary). Similarly, |
|
923 in an electrical model, we want to calculate the voltage in |
|
924 @iftex |
|
925 @tex |
|
926 $\Omega$ |
|
927 @end tex |
|
928 @end iftex |
|
929 @ifinfo |
|
930 Omega |
|
931 @end ifinfo |
|
932 and know the boundary voltage (Dirichlet) or current |
|
933 (Neumann condition after diving by the electrical conductivity). |
|
934 In an electrical model, it is common for much of the boundary |
|
935 to be electrically isolated; this is a Neumann boundary condition |
|
936 with the current equal to zero. |
|
937 |
|
938 The simplest finite element models will divide |
|
939 @iftex |
|
940 @tex |
|
941 $\Omega$ |
|
942 @end tex |
|
943 @end iftex |
|
944 @ifinfo |
|
945 Omega |
|
946 @end ifinfo |
|
947 into simplexes (triangles in 2D, pyramids in 3D). |
|
948 @ifset htmltex |
|
949 We take as an 3D example a cylindrical liquid filled tank with a small |
|
950 non-conductive ball from the EIDORS project@footnote{EIDORS - Electrical |
|
951 Impedance Tomography and Diffuse optical Tomography Reconstruction Software |
|
952 @url{http://eidors3d.sourceforge.net}}. This is model is designed to reflect |
|
953 an application of electrical impedance tomography, where current patterns |
|
954 are applied to such a tank in order to image the internal conductivity |
|
955 distribution. In order to describe the FEM geometry, we have a matrix of |
|
956 vertices @code{nodes} and simplices @code{elems}. |
|
957 @end ifset |
|
958 |
|
959 The following example creates a simple rectangular 2D electrically |
|
960 conductive medium with 10 V and 20 V imposed on opposite sides |
|
961 (Dirichlet boundary conditions). All other edges are electrically |
|
962 isolated. |
|
963 |
|
964 @example |
|
965 node_y= [1;1.2;1.5;1.8;2]*ones(1,11); |
|
966 node_x= ones(5,1)*[1,1.05,1.1,1.2, ... |
|
967 1.3,1.5,1.7,1.8,1.9,1.95,2]; |
|
968 nodes= [node_x(:), node_y(:)]; |
|
969 |
|
970 [h,w]= size(node_x); |
|
971 elems= []; |
|
972 for idx= 1:w-1 |
|
973 widx= (idx-1)*h; |
|
974 elems= [elems; ... |
|
975 widx+[(1:h-1);(2:h);h+(1:h-1)]'; ... |
|
976 widx+[(2:h);h+(2:h);h+(1:h-1)]' ]; |
|
977 endfor |
|
978 |
|
979 E= size(elems,1); # No. of simplices |
|
980 N= size(nodes,1); # No. of vertices |
|
981 D= size(elems,2); # dimensions+1 |
|
982 @end example |
|
983 |
|
984 This creates a N-by-2 matrix @code{nodes} and a E-by-3 matrix |
|
985 @code{elems} with values, which define finite element triangles: |
5164
|
986 |
5648
|
987 @example |
|
988 nodes(1:7,:)' |
|
989 1.00 1.00 1.00 1.00 1.00 1.05 1.05 ... |
|
990 1.00 1.20 1.50 1.80 2.00 1.00 1.20 ... |
|
991 |
|
992 elems(1:7,:)' |
|
993 1 2 3 4 2 3 4 ... |
|
994 2 3 4 5 7 8 9 ... |
|
995 6 7 8 9 6 7 8 ... |
|
996 @end example |
|
997 |
|
998 Using a first order FEM, we approximate the electrical conductivity |
|
999 distribution in |
|
1000 @iftex |
|
1001 @tex |
|
1002 $\Omega$ |
|
1003 @end tex |
|
1004 @end iftex |
|
1005 @ifinfo |
|
1006 Omega |
|
1007 @end ifinfo |
|
1008 as constant on each simplex (represented by the vector @code{conductivity}). |
|
1009 Based on the finite element geometry, we first calculate a system (or |
|
1010 stiffness) matrix for each simplex (represented as 3-by-3 elements on the |
|
1011 diagonal of the element-wise system matrix @code{SE}. Based on @code{SE} |
|
1012 and a N-by-DE connectivity matrix @code{C}, representing the connections |
|
1013 between simplices and vectices, the global connectivity matrix @code{S} is |
|
1014 calculated. |
|
1015 |
|
1016 @example |
|
1017 # Element conductivity |
|
1018 conductivity= [1*ones(1,16), ... |
|
1019 2*ones(1,48), 1*ones(1,16)]; |
|
1020 |
|
1021 # Connectivity matrix |
|
1022 C = sparse ((1:D*E), reshape (elems', ... |
|
1023 D*E, 1), 1, D*E, N); |
|
1024 |
|
1025 # Calculate system matrix |
|
1026 Siidx = floor ([0:D*E-1]'/D) * D * ... |
|
1027 ones(1,D) + ones(D*E,1)*(1:D) ; |
|
1028 Sjidx = [1:D*E]'*ones(1,D); |
|
1029 Sdata = zeros(D*E,D); |
|
1030 dfact = factorial(D-1); |
|
1031 for j=1:E |
|
1032 a = inv([ones(D,1), ... |
|
1033 nodes(elems(j,:), :)]); |
|
1034 const = conductivity(j) * 2 / ... |
|
1035 dfact / abs(det(a)); |
|
1036 Sdata(D*(j-1)+(1:D),:) = const * ... |
|
1037 a(2:D,:)' * a(2:D,:); |
|
1038 endfor |
|
1039 # Element-wise system matrix |
|
1040 SE= sparse(Siidx,Sjidx,Sdata); |
|
1041 # Global system matrix |
|
1042 S= C'* SE *C; |
|
1043 @end example |
|
1044 |
|
1045 The system matrix acts like the conductivity |
|
1046 @iftex |
|
1047 @tex |
|
1048 $S$ |
|
1049 @end tex |
|
1050 @end iftex |
|
1051 @ifinfo |
|
1052 @code{S} |
|
1053 @end ifinfo |
|
1054 in Ohm's law |
|
1055 @iftex |
|
1056 @tex |
|
1057 $SV = I$. |
|
1058 @end tex |
|
1059 @end iftex |
|
1060 @ifinfo |
|
1061 @code{S * V = I}. |
|
1062 @end ifinfo |
|
1063 Based on the Dirichlet and Neumann boundary conditions, we are able to |
|
1064 solve for the voltages at each vertex @code{V}. |
|
1065 |
|
1066 @example |
|
1067 # Dirichlet boundary conditions |
|
1068 D_nodes=[1:5, 51:55]; |
|
1069 D_value=[10*ones(1,5), 20*ones(1,5)]; |
|
1070 |
|
1071 V= zeros(N,1); |
|
1072 V(D_nodes) = D_value; |
|
1073 idx = 1:N; # vertices without Dirichlet |
|
1074 # boundary condns |
|
1075 idx(D_nodes) = []; |
|
1076 |
|
1077 # Neumann boundary conditions. Note that |
|
1078 # N_value must be normalized by the |
|
1079 # boundary length and element conductivity |
|
1080 N_nodes=[]; |
|
1081 N_value=[]; |
|
1082 |
|
1083 Q = zeros(N,1); |
|
1084 Q(N_nodes) = N_value; |
|
1085 |
|
1086 V(idx) = S(idx,idx) \ ( Q(idx) - ... |
|
1087 S(idx,D_nodes) * V(D_nodes)); |
|
1088 @end example |
|
1089 |
|
1090 Finally, in order to display the solution, we show each solved voltage |
|
1091 value in the z-axis for each simplex vertex. |
|
1092 @ifset htmltex |
5652
|
1093 @ifset HAVE_CHOLMOD |
|
1094 @ifset HAVE_UMFPACK |
|
1095 @ifset HAVE_COLAMD |
5648
|
1096 @xref{fig:femmodel}. |
|
1097 @end ifset |
5652
|
1098 @end ifset |
|
1099 @end ifset |
|
1100 @end ifset |
5648
|
1101 |
|
1102 @example |
|
1103 elemx = elems(:,[1,2,3,1])'; |
|
1104 xelems = reshape (nodes(elemx, 1), 4, E); |
|
1105 yelems = reshape (nodes(elemx, 2), 4, E); |
|
1106 velems = reshape (V(elemx), 4, E); |
|
1107 plot3 (xelems,yelems,velems,'k'); |
|
1108 print ('grid.eps'); |
|
1109 @end example |
|
1110 |
|
1111 |
|
1112 @ifset htmltex |
|
1113 @ifset HAVE_CHOLMOD |
|
1114 @ifset HAVE_UMFPACK |
|
1115 @ifset HAVE_COLAMD |
|
1116 @float Figure,fig:femmodel |
|
1117 @image{grid,8cm} |
|
1118 @caption{Example finite element model the showing triangular elements. |
|
1119 The height of each vertex corresponds to the solution value.} |
|
1120 @end float |
|
1121 @end ifset |
|
1122 @end ifset |
|
1123 @end ifset |
|
1124 @end ifset |
|
1125 |
5164
|
1126 @c Local Variables: *** |
|
1127 @c Mode: texinfo *** |
|
1128 @c End: *** |