CO M PUTAT I ONAL SCI ENCE AND ENGI NEE R I NG
GILBERT STRANG
Massachusetts Institute of Technology
WELLESLEY-CAMBRIDGE PRESS Box 812060 Wellesley MA 02482
Computational Science and Engineering Copyright @2007 by Gilbert Strang ISBN- 10 0-9614088- 1-2 ISBN- 1 3 978-0-9614088- 1-7 All rights reserved. No part of this work may be reproduced or stored or transmitted by any means, including photocopying, without written permission from Wellesley-Cambridge Press. Translation in any language is strictly prohibited - authorized translations are arranged. 9 8 7 6 5 4 32
Other texts from Wellesley-Cambridge Press Introduction to Linear Algebra, Gilbert Strang ISBN- 1 0 0-96 14088-9-8 ISBN-13 978-0-96 14088-9-3. Wavelets and Filter Banks, Gilbert Strang and Truong Nguyen ISBN-10 0-96 14088-7-1 ISBN- 13 978-0-96 14088-7-9. Linear Algebra, Geodesy, and GPS, Gilbert Strang and Kai Borre ISBN- 10 0-9614088-6-3 ISBN-13 978-0-9614088-6-2. Introduction to Applied Mathematics, Gilbert Strang ISBN-10 0-9614088-0-4 ISBN- 13 978-0-9614088-0-0. An Analysis of the Finite Element Method, Gilbert Strang and George ISBN-10 0-9802327-0-8 ISBN-13 978-0-9802327-0-7. Calculus, Gilbert Strang ISBN-10 0-9614088-2-0 Wellesley-Cambridge Press Box 812060 Wellesley MA 02482 USA www. wellesleycambridge.com
Fix
ISBN -13 978-0-96 14088-2-4.
[email protected] .edu math.mit .edu /"'gs phone (78 1 ) 431-8488 fax ( 61 7) 253-4358
J5IEX text preparation by Valutone Solutions, www.valutone.com. Ib'IEX assembly and book design by Brett Coonley, Massachusetts Institute of Technology. MATLAB@ is a registered trademark of The Mathworks, Inc. Course materials including syllabus and MATLAB codes and exams are available on the computational science and engineering web site: math.mit.edu j cse. Problem solutions will also be on this cse site, with further examples. Videotaped lectures of the CSE courses 18.085 and 18.086 (which now use this book) are available on the course web sites: math.mit.edu / 18085 and math.mit.edu / 18086. Computational Science and Engineering is also included in OpenCourseWare ocw.mit .edu.
TABLE OF CONTENTS
1
1 Applied Linear Algebra 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1 .8
Four Special Matrices Differences, Derivatives, Boundary Conditions Elimination Leads to K = LDLT Inverses and Delta Functions Eigenvalues and Eigenvectors Positive Definite Matrices Numerical Linear Algebra: LU, QR, SVD Best Basis from the SVD
2 A Framework for Applied Mathematics
*
2. 1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9
Equilibrium and the Stiffness Matrix Oscillation by Newton's Law Least Squares for Rectangular Matrices Graph Models and Kirchhoff's Laws Networks and Transfer Functions Nonlinear Problems Structures in Equilibrium Covariances and Recursive Least Squares Graph Cuts and Gene Clustering
3 Boundary Value Problems 3. 1 3.2 3.3 3.4 3.5 3.6 3.7
Differential Equations and Finite Elements Cubic Splines and Fourth-Order Equations Gradient and Divergence Laplace's Equation Finite Differences and Fast Poisson Solvers The Finite Element Method Elasticity and Solid Mechanics
4 Fourier Series and I ntegrals 4.1 4.2 4.3 4.4 4.5 4.6 4.7
Fourier Series for Periodic Functions Chebyshev, Legendre, and Bessel Discrete Fourier Transform and the FFT Convolution and Signal Processing Fourier Integrals Deconvolution and Integral Equations Wavelets and Signal Processing
iii
1 13 26 36 46 66 78 92
98 98 111 128 142 1 56 1 71 185 200 217
229 229 245 255 269 283 293 310
317 317 334 346 356 367 38 1 388
Ta ble of Contents
5 Ana lytic Functions 5.1 5.2 5.3 5.4
Taylor Series and Complex Integration Famous Functions and Great Theorems The Laplace Transform and z- Transform Spectral Methods o f Exponential Accuracy
6 I nitial Value Problems 6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8
Introduction Finite Difference Methods Accuracy and Stability for Ut = c Ux Wave Equations and Staggered Leapfrog Diffusion, Convection, and Finance Nonlinear Flow and Conservation Laws Fluid Flow and Navier-Stokes Level Sets and Fast Marching
7 Solving Large Systems 7. 1 7.2 7.3 7.4
403 403 419 426 440
456 456 461 472 485 500 517 533 547
551
Elimination with Reordering Iterative Methods Multigrid Methods Krylov Subspaces and Conjugate Gradients
551 563 571 586
8 Optimization and Minimum Principles
598
8.1 8.2 8.3 8.4 8.5 8.6 8.7
Two Fundamental Examples Regularized Least Squares Calculus of Variations Errors i n Projections and Eigenvalues The Saddle Point Stokes Problem Linear Programming and Duality Adjoint Methods i n Design
598 613 627 646 652 661 678
Linear Algebra in a Nutshell Sampling and Aliasing Computational Science and Engineering
685 691 694
Bibliography
698
Index
704
Teaching and Learning from the Book
v
T EACH I N G A N D L E A R N I N G F R O M TH E BOOK
I hope that mathematics and also engineering departments will approve of this textbook. It developed from teaching the MIT course 18.085 for thirty years. I thank thousands of engineering and science students for learning this subject with me. I certainly do not teach every single topic ! Here is my outline:
1.
Applied linear algebra (its importance i s now recognized)
2.
Applied differential equations (with boundary values and initial values)
3.
Fourier series including the Discrete Fourier Transform and convolution.
You will have support from the book and the cse website (and the author) . Please select the sections appropriate for the course and the class. What I hope is that this book will serve as a basic text for all mathematicians and engineers and scientists, to explain the core ideas of applied mathematics and scientific computing. The subject is beautiful, it is coherent , and it has moved a long way. The course text in earlier years was my book Introduction to Applied Mathematics (Wellesley-Cambridge Press) . That text contains very substantial material that is not in this book, and vice versa. What naturally happened, from lectures and exams and homeworks and projects over all those years, was a clearer focus on how applied and engineering mathematics could be presented. This new book is the result. This whole book aims to bring ideas and algorithms together . I am convinced that they must be taught and learned in the same course. The algorithm clarifies the idea. The old method, separation of responsibilities, no longer works:
Not perfect
Mathematics courses teach analytical techniques Engineering courses work on real problems
Even within computational science there is a separation we don't need:
Not efficient
Mathematics courses analyze numerical algorithms Engineering and computer science implement the software
I believe it is time to teach and learn the reality of computational science and engineering. I hope this book helps to move that beautiful subject forward. Thank you for reading it .
vi Gilbert Strang is in the Department of Mathematics at MIT. His textbooks have transformed the teaching of linear algebra into a more useful course for many students. His lectures are on the OpenCourseWare website at ocw. mit.edu, where 18.06 is the most frequently visited of 1 700 courses. The next course 18.085 evolved in a natural way to become Computational Science and Engineering, and led to this textbook. A wards have come for research and teaching and mathematical exposition:
Von Neumann Medal in Computational Mechanics Teaching Prizes from the MIT School of Science Henrici Prize for Applied Analysis Haimo Prize for Distinguished Teaching, Mathematical Association of America Su Buchin Prize, International Congress of Industrial and Applied Mathematics Gilbert Strang served as President of SIAM ( 1 999-2000) and as chair of the U.S. National Committee on Mathematics. Earlier books presented the finite element method and the theory of wavelets and the mathematics of GPS. On those topics George Fix and Truong Nguyen and Kai Borre were valuable coauthors. The textbooks Introduction to Linear Algebra and Linear Algebra and Its Applications are widely adopted by mathematics and engineering departments. With one exception ( LAA ) , all books are published by Wellesley-Cambridge Press. They are available also through SIAM. The present book developed step by step-text first , then problems, MATLAB codes, and video lectures. The response from students has been wonderful. This development will continue on the website math .mit.edu/cse ( also /18085 and /18086) . Problem solutions will be on that cse site, with further examples. The crucial need for today's students and readers is to move forward from the older "formula-based" emphasis toward a solution-based course. Solving problems is the heart of modern engineering mathematics and scientific computing.
T H E COVER O F T H E BOOK Lois Sellers and Gail Corbett created the cover from the "circles" o f Section 2.2. The solution to aim for is a true circle, but Euler's method takes discrete steps. When those steps spiral out, they produce the beautiful background on the cover ( not the best circle ) . The spirals and circles and meshes, plus microarrays and the Gibbs phenomenon, are serious parts of Computational Science and Engineering. It was the inspiration of the cover artists to highlight the three letters C S E. Those letters have come to identify an exciting direction for applied mathematics. I hope the book and the cover from birchdesignassociates.com and the evolving website math . m it.edu/cse will give you ideas to work with, and pleasure too.
Acknowledgements
vii
ACK N OWL E D G E M E N T S
I have had wonderful help with this book. For a long time we were a team of two : Brett Coonley prepared hundreds of lb-'JEX pages. The book would not exist without his steady support . Then new help came from four directions :
1.
Per-Olof Persson and Nick Trefethen and Benj amin Seibold and Aslan Kasimov brought the computational part of the book to life. The text explains scientific computing, and their codes do it.
2.
The typesetting was completed by www.val utone.com (highly recommended ! ) .
3.
Jim Collins and Tim Gardner and Mike Driscoll gave advice on mathematical biology (including the gene microarray on the back cover) . From biomechanics to heart rhythms to gene expression, we want and need computational biology. It became clear that clustering is a crucial algorithm in bioinformatics, and far beyond. Des Higham and Inderjit Dhillon and Jon Kleinberg generously helped me to develop the newest section *2.9 on Graph Cuts and Gene Clustering.
4.
A host of applied mathematicians and engineers told me what to write.
The words came from teaching thousands of students over 40 happy years. The structure of a textbook emerges safely but slowly, it can't be rushed. For ideas of all kinds, I owe thanks to so many (plus Oxford and the Singapore-MIT Alliance) : Stephen Boyd, Bill Briggs, Yeunwoo Cho, Daniel Cremers, Tim Davis, Sohan Dhar maraja, Alan Edelman, Lotti Ekert , Bob Fourer, Michael Friedlander, Mike Giles (es pecially) , Gene Golub, Nick Gould, Mike Heath, David Hibbitt , Nick Higham, Steven Johnson, David Keyes, Brian Kulis, Ruitian Lang, Jorg Liesen, Ross Lippert , Kon stantin Lurie, Bill Morton, Jean-Christophe Nave, Jaime Peraire, Raj Rao, John Reid, Naoki Saito, Mike Saunders, Jos Starn, Vasily Strela, Jared Tanner, Kim Chuan Toh, Alar Toomre, Andy Wathen (especially) , Andre Weideman, Chris Wiggins, Karen Willcox, and (on a memorable day at Hong Kong airport) Ding-Xuan Zhou.
May I dedicate this book to my family and friends. They make life beautiful. Gilbert Strang
viii
I ntroduction
I N T RO D U CT I O N
When you study a subject as large as applied mathematics, or teach it, or write about it , you first need to organize it . There has to be a pattern and a structure. Then the reader (and the author! ) can fit the pieces together. Let me try to separate this subject into manageable pieces, and propose a structure for this book and this course. A first step is to see two parts-modeling and solving. Those are reflected in the contents of this book. Applied mathematics identifies the key quantities in the problem, and connects them by differential equations or matrix equations. Those equations are the starting point for scientific computing. In an extreme form, modeling begins with a problem and computing begins with a matrix. A few more words about those two parts. "Applied mathematics" traditionally includes a study of special functions. These have enormous power and importance (sometimes a complete analysis has to wait for a more advanced course) . Also tra ditionally, "scientific computing" includes a numerical analysis of the algorithm-to test its accuracy and stability. Our focus stays on the basic problems that everybody meets:
(balance equations)
A.
Constructing the equations of equilibrium and of motion
B.
Solving steady state and time-dependent matrix and differential equations.
Most scientists and engineers, by the nature of our minds and our jobs, will concentrate more heavily on one side or the other. We model the problem, or we use algorithms like the FFT and software like MATLAB to solve it . It is terrific to do both. Doing the whole job from start to finish has become possible, because of fast hardware and professionally written software. So we teach both parts. The complete effort now defines Computational Science and Engineering. New departments are springing up with that name. This is really a text for the basic course in that great (and quickly growing) subject of CSE.
Fou r Simplifications We all learn by example. One goal in writing this book and teaching this course is to provide specific examples from many areas of engineering and science. The first section of the first chapter starts with four very particular matrices. Those matrices appear over and over in computational science. The underlying model has been made linear, and discrete, and one-dimensional, with constant coefficients. I see those as the great simplifications which make it possible to understand ap plied mathematics. Let me focus on these four steps:
I ntroduction
1.
Nonlinear becomes linear
2.
Continuous becomes discrete
3.
Multidimensional becomes one-dimensional
4.
Variable coefficients become constants.
ix
I don't know if "becomes" is the right word. We can't change the reality of nature. But we do begin to understand the real problem by solving a simpler problem. This is illustrated by Einstein and Newton, the two greatest physicists of all time. Einstein's equations of relativity are not linear ( and we are still trying to solve them ) . Newton linearized the geometry of space ( and this book works with F = ma ) . His linear equation came 250 years before Einstein connected a nonlinearly to m .
[-i -� ]
]
Those four great simplifications are fundamental to the organization of this book. Chapter 1 includes all four, by working with the special matrices K, T, B, and C. Here are K and C:
Stiffness K= Matrix
-1 2 -1 -1 2 -1
Circulant C Matrix
=
[
2 -1 -1 -1 2 -1 2 -1 -1 -1 -1 2
This - 1 , 2 , - 1 pattern shows constant coefficients in a one-dimensional problem. Being matrices, K and C are already linear and discrete. The difference is in the boundary conditions, which are always crucial. K is "chopped off" at both ends, while C is cyclic or circular or "periodic. " ( An interval wraps around into a circle, because of - 1 in the corners. ) The Fourier transform is perfect for C. Chapter 1 will find K- 1 , and the triangular factors in K = LU, and the eigenvalues of K and C. Then Chapter 2 can solve equilibrium problems Ku = f ( steady state equations ) and initial-value problems Mu" + Ku = f ( time-dependent equations ) .
If you get to know this remarkable matrix K, and apply good software when it becomes large ( and later multidimensional ) , you have made a terrific start . K is a positive definite second difference matrix, with beautiful properties.
1. Nonlinear becomes linear
Chapter 2 models a series of important scientific and engineering and economic problems. In each model, the "physical law" is taken to be linear: ( a)
(b ) (c)
(d)
Hooke 's Law in mechanics: Displacement is proportional to force Ohm 's Law in networks: Current is proportional to voltage difference Scaling law in economics: Output is proportional to input Linear regression in statistics: A straight line or a hyperplane can fit the data.
X
I ntroduction
None of those laws is actually true. They are all approximations ( no apology for that , false laws can be extremely useful ) . The truth is that a spring behaves almost linearly until the applied force is very large. Then the spring stretches easily. A resistor is also close to linear-but the highly nonlinear transistor has revolutionized electronics. Economies of scale destroy the linearity of input-output laws ( and a price-sales law ) . We work with linear models as long as we can-but eventually we can't. That was not a complete list of applications-this book gives more. Biology and medicine are rich in the nonlinearities that make our bodies work. So are engineering and chemistry and materials science, and also financial mathematics. Linearization is the fundamental idea of calculus-a curve is known by its tangent lines. Newton's method solves a nonlinear equation by a series of linear equations. No wonder that I find linear algebra everywhere. Let me note that "physical nonlinearity" is easier than "geometric nonlinearity." In the bending of a beam, we replace the true but awful curvature formula u 11 / ( 1 + ( u 1 ) 2 ) 312 by a simple u 11 • That succeeds when u 1 is small-typical for many problems. In other cases we can't linearize. If Boeing had assumed ideal flow and ignored the Navier-Stokes equations, the 777 would never fly. Chapter 3 introduces differential equations. 2 . Continuous becomes discrete The leading example is Laplace 's equation fJ 2 ujfJx 2 +fJ 2 ujfJy 2 = 0, when the magic of complex variables produces a complete family of particular solutions. The solutions come in pairs from (x + iy) n and r n em0• We call the pairs u and s:
u(x, y)
s (x, y)
u(r, O)
s (r, O)
y 2xy
r cos e r 2 cos 2B
r 2 sin 2B
r sin B
Laplace's equation shows ( in action ) the gradient and divergence and curl. But real applications solve a discrete form of the differential equation. That innocent sentence contains two essential tasks: to discretize the continuous equation into K u = f, and to solve for u. Those steps are at the center of scientific computing, and this book concentrates on two methods for each of them:
Continuous to discrete ( Chapter 3) Solving discrete K u ( Chapter 7)
=
1 . The finite element method 2. Finite difference methods
f
1. Direct elimination 2. Iterations with preconditioning
The matrix K can be very large ( and very sparse ) . A good solution algorithm is usually a better investment than a supercomputer. Multigrid is quite remarkable. Chapter 6 turns to initial-value problems, first for wave and heat equations ( convection + diffusion ) . Waves allow shocks, diffusion makes the solution smooth. These are at the center of scientific computing. The diffusion equation has become
C H APT E R 1 A P P L I ED L I N EA R A LG E B R A
1.1
FO U R S P EC I A L M AT R I C ES
An m by n matrix has m rows and n columns and mn entries. We operate on those rows and columns to solve linear systems Ax = b and eigenvalue problems Ax = >.x. From inputs A and b (and from software like MATLAB) we get outputs x and >.. A fast stable algorithm is extremely important , and this book includes fast algorithms. One purpose of matrices is to store information, but another viewpoint is more important for applied mathematics. Often we see the matrix as an "operator. " A acts on vectors x to produce Ax. The components of x have a meaning displacements or pressures or voltages or prices or concentrations. The operator A also has a meaning-in this chapter A takes differences. Then Ax represents pressure differences or voltage drops or price differentials. Before we turn the problem over to the machine-and also after, when we interpret A \b or e ig( A )-it is the meaning we want , as well as the numbers.
This book begins with four special families of matrices-simple and useful, absolutely basic. We look first at the properties of these particular matrices Kn , Cn , Tn , and Bn . (Some properties are obvious, others are hidden. ) It is terrific to practice linear algebra by working with genuinely important matrices. Here are K2 , K3 , K4 in the first family, with - 1 and 2 and - 1 down the diagonals:
K2
=[
2 -1 -1 2
]
1 0 2 -1 -1 2 0 -1
-
What is significant about K2 and K3 and K4 , and eventually the n by n matrix Kn? I will give six answers in the same order that my class gave them-starting with four properties of the K's that you can see immediately.
1
2
Chapter 1 Applied Linear Algebra 1 . These matrices are symmetric. The entry in row i, column j also appears in row j , column i. Thus Kij = Kj. , on opposite sides of the main diagonal. Symmetry can be expressed by transposing the whole matrix at once: K = K T .
2. The matrices Kn are sparse. Most of their entries are zero when n gets large. K1 000 has a million entries, but only 1000 + 999 + 999 are nonzero. 3. The nonzeros lie in a "band" around the main diagonal, so each Kn is The band has only three diagonals, so these matrices are tridiagonal.
banded.
Because K is a tridiagonal matrix, Ku = f can be quickly solved. If the unknown vector u has a thousand components, we can find them in a few thousand steps (which take a small fraction of a second). For a full matrix of order n = 1000, solving K u = f would take hundreds of millions of steps. Of course we have to ask if the linear equations have a solution in the first place. That question is coming soon.
4. The matrices have constant diagonals. Right away that property wakes up Fourier. It signifies that something is not changing when we move in space or time. The problem is shift-invariant or time-invariant. Coefficients are constant. The tridiagonal matrix is entirely determined by the three numbers - 1 , 2, - 1 . These are actually "second difference matrices" but my class never says that. The whole world of Fourier transforms is linked to constant-diagonal matrices. In signal processing, the matrix D = K/4 is a "highpass filter." Du picks out the rapidly varying (high frequency) part of a vector u. It gives a convolutio n with � ( - 1 , 2, - 1 ) . We use these words t o call attention t o the Fourier part (Chapter 4 ) of this book. Mathematicians call K a Toeplitz matrix , and MATLAB uses that name:
The command K
=
toeplitz([ 2 - 1 zeros ( 1 , 2) ] ) constructs K4 from row 1 .
Actually, Fourier will be happier i f we make two small changes i n Kn. Insert - 1 in the southwest and northeast corners. This completes two diagonals (which circle around). All four diagonals of C4 wrap around in this "periodic matrix" or "cyclic convolution" or circulant matrix: Circulant matrix
c4
=
[
2 -1 0 -1 0 -1 2 -1 0 -1 2 -1 0 -1 2 -1
l
=
toeplitz([ 2 - 1 0
-
1 ])
.
This matrix is singular. It is not invertible. Its determinant is zero. Rather than computing that determinant , it is much better to identify a nonzero vector u that solves C4 u = 0. (If C4 had an inverse, the only solution to C4 u = 0 would be the zero vector. We could multiply by C4 1 to find u = 0.) For this matrix, the column vector u of all ones (printed as u = ( 1 , 1 , 1 , 1) with commas) solves C4 u = 0.
1 . 1 Four Special Matrices
3
The columns of C add to the zero column. This vector u = ones( 4, 1 ) is in the The nullspace contains all solutions to Cu = 0.
nullspace of C4•
Whenever the entries along every row of a matrix add to zero, the matrix is certainly singular. The same all-ones vector u is responsible. Matrix multiplication Cu adds the column vectors and produces zero. The constant vector u = ( 1 , 1 , 1 , 1 ) o r u = (c, c, c, c) i n the nullspace i s like the constant C when we integrate a function. In calculus, this "arbitrary constant" is not knowable from the derivative. In linear algebra, the constant in u = (c, c, c, c) is not knowable from Cu = 0.
5. All the matrices K = Kn are invertible. They are not singular, like Cn. There is a square matrix K - 1 such that K - 1 K = I = identity matrix. And if a square matrix has an inverse on the left , then also K K - 1 = I. This "inverse matrix" is also symmetric when K is symmetric. But K - 1 is not sparse. Invertibility is not easy to decide from a quick look at a matrix. Theoretically, one test is to compute the determinant. There is an inverse except when det K = 0, because the formula for K - 1 includes a division by det K. But computing the deter minant is almost never done in practice! It is a poor way to find u = K- 1 f. What we actually do is to go ahead with the elimination steps that solve Ku = Those steps simplify the matrix, to make it triangular. The nonzero pivots on the main diagonal of the triangular matrix show that the original K is invertible. (Important: We don't want or need K - 1 to find u = K - 1 f. The inverse would be a full matrix, with all positive entries. All we compute is the solution vector u . )
f.
6. The symmetric matrices Kn are positive definite. Those words might be new. One goal of Chapter 1 is to explain what this crucial property means (K4 has it , C4 doesn't) . Allow me to start by contrasting positive definiteness with invertibility, using the words "pivots" and "eigenvalues" that will soon be familiar. Please notice the Appendix that summarizes linear algebra.
(Pivots ) An invertible matrix has
n nonzero pivots. positive definite symmetric matrix has n positive pivots. (Eigenvalues ) An invertible matrix has n nonzero eigenvalues. A positive definite symmetric matrix has n positive eigenvalues.
A
Positive pivots and eigenvalues are tests for positive definiteness, and C4 fails those tests because it is singular. Actually C4 has three positive pivots and eigenvalues, so it almost passes. But its fourth eigenvalue is zero (the matrix is singular) . Since no eigenvalue is negative (>. ;:::: 0) , C4 is positive semidefinite. The pivots appear on the main diagonal in Section 1 .3, when solving Ku = f by elimination. The eigenvalues arise in K x = >.x. There is also a determinant test for positive definiteness (not just det K > 0) . The proper definition of a symmetric positive definite matrix (it is connected to positive energy) will come in Section 1 .6.
4
Chapter 1 Applied Linear Algebra
1:
(1, 1) l (1) [ -! �� -� Changing
Kn
to
Tn
After Kn and Cn , there are two more families of matrices that you need to know. They are symmetric and tridiagonal like the family Kn . But the entry in Tn is changed from 2 to T,
Tn ( 1 , 1) = 1
�
[ -� -� l
and T,
�
That top row ( T stands for top ) represents a new boundary condition, whose meaning we will soon understand. Right now we use T3 as a perfect example of elimination. Row operations produce zeros below the diagonal, and the pivots are circled as they are found. Two elimination steps reduce T to the upper triangular U.
Step 1 . Add row
1
to row 2, which leaves zeros below the first pivot.
[= -10-1 -1 l 8�1 �-10-1 l s�
Step 2. Add the new row 2 to row 3, which produces U.
-1 1. -1 1 [ 1 -11 -1 l 1 1 0
0
T
o
2
0
2
2
2
0
t0-10-1� = 1 1. 0 0
U
.
0
All three pivots of T equal We can apply the test for invertibility ( three nonzero pivots ) . T3 also passes the test for positive definiteness ( three positive pivots ) . In fact every Tn in this family is positive definite, with all its pivots equal to
1
That matrix U has an inverse ( which is automatically upper triangular ) . The exceptional fact for this particular u - 1 is that all upper triangular entries are 's: u- 1
=
o
0
0 -1
0
0
:]
�
triu (ones(3) ) .
(2)
This says that the inverse of a 3 by 3 "difference matrix" is a 3 by 3 "sum matrix." This neat inverse of U will lead us to the inverse of T in Problem 2. The product u - 1 u is the identity matrix I. U takes differences, and u- 1 takes sums. Taking differences and then sums will recover the original vector ( u 1 , u 2 , u3 ) :
Differences from U Sums from
u-l
[ -�]1 [ �� ] = �� �: ] [ 1 11 11 l [ ] [ l
[ 0� -0�
0 0 0 1
=
U3
U3 - 0
u 1 - u2 u 2 - UJ U3 - 0
-
u1 U2 U3
5
1 . 1 Four Special Matrices
Changing
Tn
to
Bn
The fourth family Bn has the last entry also changed from 2 to 1 . The new boundary condition is being applied at both ends (B stands for both ) . These matrices Bn are symmetric and tridiagonal, but you will quickly see that they are not invertible. The Bn are positive semidefinite but not positive definite: Bn ( n, n ) = 1
B2 =
[
1 -1 -1 1
]
(3)
Again, elimination brings out the properties of the matrix. The first n - 1 pivots will all equal 1 , because those rows are not changed from Tn . But the change from 2 to 1 in the last entry of B produces a change from 1 to 0 in the last entry of U:
[ �-� -� ]- [0 0 l [0 0 l -1
B=
0 -1
1
0
0 -1 0 -1 1
-1
0 0
0
-1 0 0
=
U.
(4)
There are only two pivots. ( A pivot must be nonzero. ) The last matrix U is certainly not invertible. Its determinant is zero, because its third row is all zeros. The constant vector ( 1 , 1 , 1 ) is in the nullspace of U, and therefore it is in the nullspace of B:
The whole point o f elimination was t o simplify a linear system like Bu = 0, without changing the solutions. In this case we could have recognized non-invertibility in the matrix B, because each row adds to zero. Then the sum of its three columns is the zero column. This is what we see when B multiplies the vector ( 1 , 1 , 1 ) . Let me summarize this section in four lines ( all these matrices are symmetric ) :
Kn and Tn are invertible and ( more than that ) positive definite. Cn and Bn are singular and ( more than that ) positive semidefinite. The nullspaces of Cn and Bn contain all the constant vectors u = (c, c, . . . , c) . Their columns are dependent. The nullspaces of Kn and Tn contain only the zero vector u = (0, 0, . . . , 0) . Their columns are independent.
6
Chapter 1 Applied Linear Algebra
Matrices in M AT LAB I t i s natural t o choose MATLAB for linear algebra, but the reader may select another system. ( Octave is very close, and free. Mathematica and Maple are good for symbolic calculation, LAPACK provides excellent codes at no cost in netlib, and there are many other linear algebra packages. ) We will construct matrices and operate on them in the convenient language that MATLAB provides.
Our first step is to construct the matrices Kn . For n = 3, we can enter the 3 by 3 matrix a row at a time, inside brackets. Rows are separated by a semicolon K=[
2 -1 0 ; -1 2 -1 ; 0 -1 2 ]
For large matrices this is too slow. We can build
eye(8) = 8 by 8 identity matrix
K8 from "eye"
and "ones" :
ones(7, 1 ) = column vector of seven 1 's
The diagonal part is 2*eye(8) . The symbol * means multiplication ! The - 1 's above the diagonal of K8 have the vector -ones(7, 1 ) along diagonal 1 of the matrix E: Superdiagonal of - l 's
E = -diag(ones(7, 1 ) , 1 )
The - 1 's below the diagonal of K8 lie on the diagonal numbered - 1 . For those we could change the last argument in E from 1 to - 1 . Or we can simply transpose E, using the all-important symbol E ' for ET. Then K comes from its three diagonals: Tridiagonal matrix K8
K = 2 * eye(8) + E + E '
Note: The zeroth diagonal ( main diagonal ) is the default with no second argument, so eye(8)= diag(ones(8, 1 ) ) . And then diag(eye(8) ) = ones(8, 1 ) .
The constant diagonals make K a Toeplitz matrix. The toeplitz command produces K, when each diagonal is determined by a single number 2 or - 1 or 0. Use the zeros vector for the 6 zeros in the first row of K8: Symmetric Toeplitz row1 = [ 2 - 1 zeros( 1 , 6) ] ; K = toeplitz( row1 )
For an unsymmetric constant-diagonal matrix, use to eplitz( col l , row1 ) . Taking coll [ 1 - 1 0 0 ] and row 1 = [ 1 0 0 ] gives a 4 by 3 backward difference matrix. It has two nonzero diagonals, 1 's and - 1 's. =
To construct the matrices T and B and C from K, just change entries as in the last three lines of this M-file that we have named KTBC. m. Its input is the size n, its output is four matrices of that size. The semicolons suppress display of K, T, B, C:
function [K,T,B,C) = KTBC(n) % Create the four specia l matrices assuming n>1 K = toeplitz ( [2 - 1 zeros(1 , n-2)] ) ; T = K; T ( 1 , 1 ) = 1 ; B = K; 8 ( 1 , 1 ) = 1; B(n , n ) = 1; C = K; C(1,n) = -1; C(n , 1 ) = - 1 ;
1 . 1 Four Specia l Matrices If we happened to want their determinants (we shouldn't! ) , then with
[ det (K) det (T) det (B) det ( C) J
produces the output
n
1
=8
[9 1 0 0]
One more point. MATLAB could not store Kn as a dense matrix for n = 10,000. The 108 entries need about 800 megabytes unless we recognize K as sparse. The code sparseKTBC . m on the course website avoids storing (and operating on) all the zeros. It has K, T, B, or C and n as its first two arguments. The third argument is 1 for sparse, 0 for dense (default 0 for narg = 2, no third argument) . The input to Sparse MATLAB includes the locations of all nonzero entries. The command A = sparse ( i , j, 8 , m , n ) creates an m by n sparse matrix from the vectors i, j, 8 that list all positions i, j of nonzero entries 8. Elimination by l u ( A ) may produce additional nonzeros (called fill-in) which the software will correctly identify. In the normal "full" option, zeros are processed like all other numbers. 8
It is best to create the list of triplets i, j, 8 and then call sparse. Insertions A(i, j) = or A( i, j) = A( i, j) + 8 are more expensive. We return to this point in Section 3.6.
The sparse KTBC code on the website uses spdiags to enter the three diagonals. Here is the toeplitz way to form K8 , all made sparse by its sparse vector start :
vsp = Ksp = bsp = usp = uuu =
sparse( [2 - 1 zeros( 1 , 6)] ) % please look at each output toeplitz(vsp) % sparse format gives the nonzero positions a nd entries % colon keeps all rows of col umn 2, so bsp = col u m n 2 of Ksp Ksp( : , 2) Ksp\bsp % zeros in Ksp and bsp are not processed , sol ution: usp(2) = 1 full(usp) % return from sparse format to the fu ll u u u = [0 1 0 0 0 0 0 OJ
Note The open source language Python is also very attractive and convenient . The next sections will use all four matrices in these basic tasks of linear algebra:
( 1 .2) The finite difference matrices K, T, B , C include boundary conditions ( 1 .3) Elimination produces pivots in
D
and triangular factors in LDLT
(1 .4) Point loads produce inverse matrices K - 1 and r - 1 ( 1 .5) The eigenvalues and eigenvectors of K, T, B , C involve sines and cosines. You will see K\f in 1 . 2 , lu(K) in 1 . 3 , inv( K) in 1 . 4 , eig( K) in 1 . 5 , and choi (K) in 1 .6. I very much hope that you will come to know and like these special matrices.
8
Chapter 1 Applied Linear Algebra a
1.1 A
WO R K E D EXA M P L ES
a
f and Cu = f might be solvable even though B and C are singular ! Show that every vector f = Bu has h + 12 + + fn = 0. Physical meaning: the external forces balance. Linear algebra meaning: Bu = f is solvable when f is perpendicular to the all-ones column vector e = ( 1 , 1 , 1 , 1 , . . . ) = ones(n, 1 ) . Bu =
·
·
·
Solution Bu is a vector of "differences" of u's. Those differences always add to zero:
All terms cancel in ( u 1 - u 2 ) + ( -u 1 + 2 u 2 - u3) + ( -u 2 + 2 u3 - u4 ) + ( -u3 + u4 ) = 0. The dot product with e = ( 1 , 1, 1, 1 ) is that sum J T e = h + 12 + /3 + f4 = 0.
(f 1 * e in MATLAB) .
Dot product
A second explanation for J T e = 0 starts from the fact that Be = 0 . The all-ones vector e is in the nullspace of B. Transposing f = Bu gives J T = uT B T , since the transpose of a product has the individual transposes in reverse order. This matrix B is symmetric so B T = B. Then
Conclusion Bu = f is only solvable when f is perpendicular to the all-ones vector e. ( The same is true for Cu = f. Again the differences cancel out.) The external forces balance when the f's add to zero. The command B\f will produce l nf because B is square and singular, but the "pseudoinverse" u = pinv( B) * f will succeed. (Or add a zero row to B and f before the command B\f, to make the system rectangular. )
1.1 B The "fixed-free" matrix H changes the last entry of K from 2 t o 1 . Connect H to the "free-fixed" T (first entry = 1 ) by using the reverse identity matrix J: comes from JT J via the
reverse identity J
J=
[ ]
0 0 1 0 1 0 . 1 0 0
Chapter 2 shows how T comes from a tower structure (free at the top) . H comes from a hanging structure (free at the bottom) . Two MATLAB constructions are H = toeplitz( [ 2 - 1 0 ] ) ; H(3, 3) = 1
or
J = fliplr(eye(3) ) ; H = J * T * J
9
1 . 1 Four Specia l Matrices Solution
JT reverses the rows of T. Then JT J reverses the columns to give H: ( JT ) J = H .
JT = ( rows )
(columns too)
We could reverse columns first by T J. Then J ( T J ) would be the same matrix H as ( JT ) J. The parentheses never matter in (AB)C = A(BC) ! Any permutation matrix like J has the rows of the identity matrix I in some order. There are six 3 by 3 permutation matrices because there are six orders for the numbers 1 , 2, 3. The inverse of every permutation matrix is its transpose. This particular J is symmetric, so it has J = JT = J - 1 as you can easily check: H = JT J so
H - 1 = J- 1 T- 1 J- 1
which is
H - 1 = JT - 1 J.
(5)
With back = 3:- 1 : 1 , reordering to JT J isH = T(back, back) in MATLAB.
P roblem Set 1 . 1
Problems 1-4 are about T-1 and Problems 5-8 are about K-1•
1
The inverses of T3 and T4 ( with
T11 = 1 in the top corner )
are
Guess T5- 1 and multiply by T5. Find a simple formula for the entries of T;; 1 on and below the diagonal (i;::: j ) , and then on and above the diagonal (i :::; j ) .
2
3
4
T3- 1 in three steps, using U and u - 1 in equation (2) : 1 . Check that T3 = UTU, where U has 1 's on the main diagonal and - 1 's along the diagonal above. Its transpose uT is lower triangular. 2. Check that uu - 1 = I when u - 1 has 1 's on and above the main diagonal. 3. Invert UTU to find T3- 1 = ( U - 1 ) ( U - 1 ) T. Inverses come in reverse order! The difference matrix U = U5 in MATLAB is eye(5) -diag(ones(4,1) , 1 ) . Con struct the sum matrix S from triu (ones(5) ) . ( This keeps the upper triangular part of the 5 by 5 all-ones matrix. ) Multiply U * S to verify that S = u - 1 . For every n, Sn = Un - 1 is upper triangular with ones on and above the diagonal. For n = 4 check that SST produces the matrix T4 - 1 predicted in Problem 1 . Why is ssT certain to b e a symmetric matrix? Compute
10
Chapter 1 Applied Linear Algebra
5
The inverses of K3 and
First
K4
(please also invert
=
guess the determinant of K K5 .
K2 ) have fractions
Then compute det(K) and
det ( K) * in v ( K) any software is allowed. -
6
7
inv(K) and
(Challenge problem) Find a formula for the i, j entry of K4 1 below the diagonal (i 2: j ) . Those entries grow linearly along every row and up every column. (Section 1 .4 will come back to these important inverses. ) Problem 7 below is developed in the Worked Example of Section 1 .4.
[
] []
A column u times a row vT is a rank-one matrix uvT. All columns are multiples of u, and all rows are multiples of vT. T4 - 1 - K4 - 1 has rank 1 :
r4- 1 _ K4- 1 - �5 _
Write 8
� = l' �:
d t
16 12 8 12 9 6 8 6 4 4 3 2
K3 - T3 in this special form uvT.
4 3 2 1
� 5
4
[4 3 2 1 ]
3 2 1
Predict a similar formula for T3- 1 - K3 1 .
(a) Based on Problem 7, predict the i , j entry of T5- 1 - K5 1 below the diagonal.
(b) Subtract this from your answer to Problem 1 (the formula for i 2: j ) . This gives the not-so-simple formula for K5 1 .
9
10
11
T5- 1
when
==
Following Example 1 . 1 A with C instead of B, show that e = ( 1 , 1 , 1 , 1) is perpendicular to each column of C4 . Solve Cu f = ( 1 , - 1 , 1 , - 1 ) with the singular matrix C by u pinv(C) * f. Try u C\e and C\f, before and after adding a fifth equation 0 = 0.
=
=
The "hanging matrix" H in Worked Example 1.1 B changes the last entry of K3 to H33 = 1 . Find the inverse matrix from s - 1 JT - 1 J. Find the inverse also from H = UUT (check upper times lower triangular!) and s - 1 (U - 1 )Tu - 1 .
=
Suppose U i s any upper triangular matrix and J is the reverse identity matrix in 1 . 1 B. Then JU is a "southeast matrix" . What geographies are U J and JU J? By experiment , a southeast matrix times a northwest matrix is . __
12
Carry out elimination on the 4 by 4 circulant matrix C4 to reach an upper triangular U (or try [L, U] = l u (C ) in MATLAB) . Two points to notice: The last entry of U is because C is singular. The last column of U has new nonzeros. Explain why this "fill-in" happens. __
1 . 1 Fou r Specia l Matrices 13
14
11
By hand, can you factor the circulant C4 ( with three nonzero diagonals, allowing wraparound ) into circulants L times U ( with two nonzero diagonals, allowing wraparound so not truly triangular ) ?
Gradually reduce the diagonal 2, 2, 2 in the matrix K3 until you reach a singular matrix M. This happens when the diagonal entries reach . Check the determinant as you go, and find a nonzero vector that solves Mu = 0. __
Questions 15-2 1 bring out important facts about matrix multiplication. 15
How many individual multiplications to create Ax and A 2 and AB? An x
16
n Xn
x
1
x
n Bn
x
p
= ( AB ) mxp
You can multiply Ax by rows ( the usual way ) or by columns ( more important ) . Do this multiplication both ways:
By rows By columns 17
A m
[ ][] [ [ ][] [] [] [
]
2 3 5
1 inner product using row 1 = inner product using row 2 2
2 3 4 5
1 2 combination 3 =1 + 2 = 2 4 5 of columns
4
]
The product Ax is a linear combination of the columns of A. The equations Ax = b have a solution vector x exactly when b is a of the columns. __
Give an example in which b is not in the column space of A. There is no solution to Ax = b, because b is not a combination of the columns of A. 18
Compute C = AB by multiplying the matrix A times each column of B :
Thus, A * B ( : ,j ) = C( : ,j ) . 19
You can also compute AB by multiplying each row o f A times B :
[ ][ ] [ 2 3 4 5
] [ ]
8 16 1 2 2 * row 1 + 3 * row 2 = = 2 4 4 * row 1 + 5 * row 2 * *
·
A solution to Bx = 0 is also a solution to ( AB ) x = 0. Why? From
12
Chapter 1 Applied Linear Algebra
20
The four ways to find AB give numbers, 1 (rows of A) times ( columns of B) 2 A times ( columns of B) 3 (rows of A) times B 4 ( columns of A) times ( rows of B)
columns, rows, and matrices:
C(i,j) = A(i , : ) * B ( : ,j) C( : ,j) = A * B ( : ,j) C(i , : ) = A( i , : ) * B for k = 1 : n , C = C + A( : , k) * B(k, : ) ; end
Finish these 8 multiplications for columns times rows. How many for n by n?
[� �] [� �]= [�]
21
Which
one
24
25
[2 4]
=
by n matrices
A and B?
(AB)B = B(BA)
(AB)A = A(BA)
=
n
= [� :] +[: :] = [ � :].
=
1000; e ones(n, 1 ) ; K spdiags( [-e, 2 * e , -e ] , - 1 : 1 , n , n ) ; to enter as a sparse matrix. Solve the sparse equation Ku e by u = K\e. Plot the solution by plot(u) .
Use
n
K1 000
23
+[�]
of these equations is true for all
AB = BA 22
[1 2]
=
Create 4-component vectors u, v , w and enter A = spdiags([u, v, w] , - 1 : 1 , 4, 4) . Which components of u and w are left out from the - 1 and 1 diagonals of A?
Build the sparse identity matrix I = sparse(i, j, s , 100, 100) by creating vectors i, j, s of positions i, j with nonzero entries s. (You could use a for loop.) In this case speye(100) is quicker. Notice that sparse(eye(10000)) would be a disaster, since there isn't room to store eye(lOOOO) before making it sparse.
=
The only solution to Ku = 0 or Tu = 0 is u 0, so K and T are invertible. For proof, suppose u i is the largest component of u. If -u i - l + 2ui - ui +1 is zero, this forces Ui - 1 ui ui + l · Then the next equations force every Uj = ui . At the end, when the boundary is reached, -u n _ 1 + 2un only gives zero if u = 0.
==
Why does this "diagonally dominant" argument fail for v
B and C?
is toeplitz( v ) a circulant matrix (cyclic diagonals) ?
26
For which vectors
27
(Important) Show that the 3 by 3 matrix K comes from
Ao
=[
-1 1 0 0 -1 1 0 0 -1
�
0
]
A;j' A0 :
is a "difference matrix"
=
Which column of A0 would you remove to produce A 1 with T AT A 1 ? Which column would you remove next to produce A 2 with B = Ai A 2 ? The differ ence matrices A 0 , A 1 , A 2 have 0, 1 , 2 boundary conditions. So do the "second differences" K, T, and B.
1 . 2 Differences, Derivatives, Boundary Conditions 1.2
13
D I F FE R E N C ES , D E R I VAT IVES , B O U N DA RY C O N D I T I O N S
This important section connects difference equations to differential equations. A typ ical row in our matrices has the entries - 1 , 2, - 1 . We want to see how those numbers are producing a second difference ( or more exactly, minus a second difference ) . The second difference gives a natural approximation to the second derivative. The matrices Kn and Cn and Tn and Bn are all involved in approximating the equation
2 - ddxu2 = f(x)
with boundary conditions at
x = 0 and x = 1 .
(1)
Notice that the variable i s x and not t. This i s a boundary-value problem and not an initial-value problem. There are boundary conditions at x = 0 and x = 1 , not initial conditions at t = 0. Those conditions are reflected in the first and last rows of the matrix. They decide whether we have Kn or Cn or Tn or Bn ·
We will go from first differences to second differences. All four matrices have the special form AT A ( matrix times transpose ) . Those matrices AT and A produce first differences, and AT A produces second differences. So this section has two parts: I. II.
Differences replace derivatives ( and we estimate the error ) .
We solve
d2 u = 1 and then - b. 2 u - dx 2 (b.x) 2
= 1 using the matrices K and T.
Part I : Finite Differences How can we approximate dujdx, the slope of a function u(x)? The function might be known, like u( x) = x 2 . The function might be unknown, inside a differential equation. We are allowed to use values u( x) and u( x + h) and u( x - h) , but the stepsize h = b.x is fixed. We have to work with b.uj box without taking the limit as b.x ---t 0. So we have "finite differences" where calculus has derivatives. Three different possibilities for b.u are basic and useful. We can choose a forward difference or a backward difference or a centered difference. Calculus textbooks typi cally take b.u = u( x + box) - u( x) , going forward to x + b.x. I will use u( x) = x 2 to test the accuracy of all three differences. The derivative of x 2 is 2x, and that forward difference b. + is usually not the best ! Here are b. + , b. _ , and b-0 : u(x+h)-u(x) h
(x + h) 2 - x 2 = 2x + h h 2 x - (x - h) 2 = 2x - h Backward difference u(x)-u(x-h) The test gives h h (x + h) 2 - (x - h) 2 = 2x Centered difference u(x+h)-u(x-h) The test gives 2h 2h For u = x 2 , the centered difference is the winner. It gives the exact derivative 2x, while forward and backward miss by h. Notice the division by 2h ( not h) . Forward difference
The test gives
14
Chapter 1 Applied Linear Algebra
Centered is generally more accurate than one-sided, when h = b.x is small. The reason is in the Taylor series approximation of u(x + h) and u(x - h) . These first few terms are always the key to understanding the accuracy of finite differences:
u(x + h) = u(x) + hu' (x) + 4h2 u" (x) + ih3 u111(x) + u(x - h) = u(x) - hu'(x) + 4h2 u"(x) - ih3 u111(x) +
Forward Backward
·
·
·
·
·
·
(2) (3)
u(x) from each side and divide by h. The forward difference is first order accurate because the leading error 4hu"(x) involves the first power of h:
Subtract
One-sided is first order
--'-----:'-:.......0..
u(x + h) - u(x) = U' ( X ) + 1 h " ( ) + h 2 -
U
X
·
·
(4)
·
The backward difference is also first order accurate, and its leading error is - 4 hu" ( x) . For u(x) = x 2 , when u"(x) = 2 and u111 = 0, the error 4hu" is exactly h. For the centered difference, subtract (3) from (2) . Then u(x) cancels and also cancels (this gives extra accuracy) . Dividing by 2h leaves an h 2 error:
� h2 u"(x)
Centered is second order
1 2 " u(x + h) - u(x - h) = u'(x) + -h u '(x) + 2h 6
·
·
·
(5)
The centered error is O(h 2 ) where the one-sided errors were O(h) , a significant change. 1 If h = 1 0 we are comparing a 1% error to a 10% error. The matrix for centered differences is
antisymmetric ( like the first derivative ) : u,- 1
Centered difference matrix
-1 0 1 -1 0 1
ao T = -ao
u, u ,+ 1
u• + 1 - ui - 1 Ui+2 - U ,
u ,+2
Transposing b. 0 reverses - 1 and 1 . The transpose of the forward difference matrix b. + would be - ( backward difference ) = -b._ . Centered difference quotients b. 0 u/2h are the average of forward and backward ( Figure 1 . 1 shows u(x) = x 3 ). Forward - - - -
u=8 u=1
Backward · · · · · · · · ·
0
�; .....
Centered - · - · -
1
2
b. + u = 8 - 1 = 7 h b,._u = 1 - 0 1 h b. 0 u = 8 - 0 = 4(2h) Notice 4 = Hl + 7) =
Figure 1 . 1 : b. + /h and b._jh and b. 0 /2h approximate u' = 3x 2 = 3 by 7, 1, 4 at x = 1 . The second difference b. 2 u = 8 - 2 ( 1 ) + 0 i s exactly u" = 6x = 6 with step h = 1 .
1.2 Differences, Derivatives, Boundary Conditions
15
Second Differences from First Differences We can propose a basic problem in scientific computing. Find a finite difference approximation to this linear second order differential equation:
-::�
=
f(x)
with the boundary conditions
u(O) = 0 and u(1) = 0 .
(6)
The derivative of the derivative is the second derivative. In symbols djdx(dujdx) is It is natural that the first difference of the first difference should be the second difference. Watch how a second difference � - � + u is centered around point i:
d2 ujdx 2 .
Difference of difference Those numbers 1 , -2, 1 appear on the middle rows of our matrices K and T and B and C (with signs reversed ) . The denominator is h 2 = (�x) 2 under this second difference. Notice the right positions for the superscripts 2, before u and after x:
� 2 u _ u(a:: + .6-a:: ) - 2u(a:: ) + u(a:: - .6-a:: ) (8) �x 2 ( .6-a:: ) 2 What is the accuracy of this approximation ? For u(x + h) we use equa tion (2) , and for u(x - h) we use (3) . The terms with h and h 3 cancel out: �2 u(x) = u(x + h) - 2u(x) + u(x - h) = h 2 u"(x) + ch4 u""(x) + (9) Dividing by h2 , � 2 uj(�x) 2 has second order accuracy ( error ch 2 u 1111 ) . We get that extra order because � 2 is centered. The important tests are on u(x) = x 2 and u(x) = x3 . The second difference divided by (�x) 2 gives the correct second derivative: (x + h) 2 - 2x 2 + (x - h) 2 = 2 . Perfection for u = a:: 2 ( 10) h2 An equation d2 ujdx 2 = constant and its difference approximation � 2 uj(�x) 2 = con stant will have the same solutions. Unless the boundary conditions get in the way . . . Second difference
d2 u dx 2
� �
·
·
·
The I mportant M u ltiplications You will like what comes now. The second difference matrix ( with those diagonals 1 , -2, 1) will multiply the most important vectors I can think of. To avoid any problems at boundaries, I am only looking now at the internal row s which are the same for K, T, B, C. These multiplications are a beautiful key to the whole chapter. -
.6.2 (Squares) = 2·(0nes) .6. 2 (Ramp) = Delta .6. 2 (Sines) = ..X · (Sines) (11)
16
Chapter 1 Applied Linear Algebra Here are column vectors whose second differences are special: Constant ones( n , 1) (1, 1 , . . . , 1) Linear (1, 2, . . . , n ) ( 1 : n)' ( in MATLAB notation ) Squares (1 2 , 2 2 , , n2 ) ( 1 : n )'."2 •
Delta at k Step at k Ramp at k Sines Cosines Exponentials
.
•
[zeros(k- 1 , 1 ) ; 1 ; zeros(n-k, 1)] [zeros(k- 1 , 1 ) ; ones(n-k+1, 1)] [zeros(k-1, 1 ) ; O:(n-k)'] sin ( ( 1 : n)'*t) cos( ( 1 : n )'*t) exp(( 1 : n)'*i*t)
(0, 0, 1 , 0, . . . , 0) (0, 0, 1 , 1, . . . , 1) (0, 0, 0 , 1 , . . . , n - k)
( sin t, . . . , sin n t) ( cos t, . . . , cos n t) ( e it ' 0 . 0 ' e int )
Now come the multiplications in each group. The second difference of each vector is analogous ( and sometimes equal ! ) to a second derivative. I.
For constant and linear vectors, the second differences are zero:
[ ["
.6. 2 (constant)
.6. 2 (linear)
i -2
1 1 -2
i -2
1 1 -2
J m [�] J m [�]
(12)
For squares, the second differences are constant ( the second derivative of x 2 is 2) . This is truly important: Matrix multiplication confirms equation (8) .
.6. 2 (squares)
Then II.
Ku = ones for u =
(13) - (squares ) / 2 . Below come boundary conditions.
[.
- � -�
..J m m
Second differences of the ramp vector produce the delta vector:
i
=
delta
(14)
Section 1.4 will solve Ku = 8 with boundary conditions included. You will see how each position of the "1" in delta produces a column u in K - 1 or r - 1 . For functions: The second derivative of a ramp max ( x , 0) is a delta function.
1.2 Differences, Derivatives, Boundary Conditions III.
17
Second differences of the sine and cosine and exponential produce 2 cos t - 2 times those vectors. (Second derivatives of sin xt and cos xt and eixt produce -t 2 times the functions. ) In Section 1 .5, sines or cosines or exponentials will be eigenvectors of K, T, B, C with the right boundary conditions.
;[ [ ] J "[ ; [ ] [ ; J] [ ] ·
a 2 ( sines )
-2
1
a 2 ( cosines )
-2
1
1
s in ! s � n 2t sm 3t sin 4t
1
=! cos 2t cos 3t cos 4t
-2
-2
..
Ll.'
( exponentials )
-2
1
1
-2
1 ...
e" e2it e3 � t e 4�t
= (2 cos t _
] [ [ �� ] [l
sin ! s � n 2t 2) sm 3t sin 4t
(15)
=!
= (2 cos t - 2)
��:
(16)
e" e2it e 3i t e4it
(17)
cos 4t
= (2 cos t - 2)
The eigenvalue 2 cos t - 2 is easiest to see for the exponential in (17) . It is exactly eit - 2 + e-it, which factors out in the matrix multiplication. Then (16) and (15) , cosine and sine, are the real and imaginary parts of (17) . Soon t will be e.
Part I I : Finite Difference Equations We have an approximation !::l. 2 uj(!::l. x ) 2 to the second derivative d 2 ujdx 2 . So we can quickly create a discrete form of -d2 ujdx 2 = f(x) . Divide the interval [0, 1] into equal pieces of length h = !::l. x . If that meshlength is h = n� l , then n + 1 short subintervals will meet at x = h, x = 2 h, . . . , x = nh. The extreme endpoints are x = 0 and x = (n + 1)h = 1 . The goal is to compute approximations u 1 , . . . , Un to the true values u( h) , . . . , u( nh) at those n mesh points inside the [0, 1] interval.
U�ow� u �
Figure 1 .2:
[f]
u2 0
and Un+ l known from boundary conditions Uo
u(x)
h 2h nh (n+ 1)h = 1 The discrete unknowns u 1 , . . . , Un approximate the true u(h) , . . . , u(nh) . 0
Certainly -d2 / dx 2 is replaced by our -1, 2, - 1 matrix, divided by h 2 and with the minus sign built in. What to do on the right side? The source term f(x) might be a smooth distributed load or a concentrated point load. If f ( x) is smooth as in sin 21rx, the first possibility is to use its values /i at the meshpoints x = i!::l. x .
18
Chapter 1 Applied Linear Algebra (18)
Finite difference equation
The first equation (i = 1) involves u 0 . The last equation (i = n ) involves Un + l · The boundary conditions given at x = 0 and x = 1 will determine what to do. We now solve the key examples with fixed ends u(O) = u 0 = 0 and u(1) = Un + l = 0. Example 1 Solve the differentia l a nd difference eq uations with constant force
2 - ddxu2
=
I
=
=
1:
u(1) = 0
(19)
1 with u0 = 0 and Un + I = 0
(20)
1 with u(O) = 0
-Ut· + l + 2u·t - U·t h2
f(x)
(fixed end) and
Solution For every linear equation, the complete solution has two parts. One "particular solution" is added to any solution with zero on the right side (no force) : Complete solution
Ucomplete
=
Uparticular
(21)
+ Unullspace ·
This is where linearity is so valuable. Every solution to L u = 0 can be added to one particular solution of L u = f . Then by linearity L( Upart + Unun) = f + 0.
2 - ddxu2 = 1 is solved by Upart (x) = - �x 2 d2 u Nullspace solution - 2 = 0 is solved by Unun(x) = Cx + D . dx The complete solution is u(x) = - �x 2 + Cx + D . The boundary conditions will tell us the constants C and D in the nullspace part. Substitute x = 0 and x = 1: Particular solution
Boundary condition at Boundary condition at
x = 0 u(O) = 0 x = 1 u(1) = 0
=0 C= �
Solution
gives D gives
In Figure 1 .3, the finite difference solution agrees with this u(x) at the meshpoints. This is special: (19) and (20) have the same solution (a parabola) . A second difference of u i = i 2 h 2 gives exactly the correct second derivative of u = x 2 . The second difference of a linear u i = ih matches the second derivative (zero) of u x: =
(i + 1)h - 2ih + (i - 1)h _- 0 matehes !£__ ( x ) o . (22) dx 2 h2 The combination of quadratic i 2 h 2 and linear ih (particular and nullspace solutions) -
is exactly right . It solves the equation and satisfies the boundary conditions. We can
19
1.2 Differences, Derivatives, Boundary Conditions 32 3 32
4
0
2h
h
4h
3h
=
1
Solution to
d2 u = 1 - dx 2
Solution to
2 - ��xu2 = ones
X
Figure 1.3: Finite differences give an exact match of u(x) and u i for the special case -u" = 1 with u0 = Un+ l = 0. The discrete values lie right on the parabola.
x = ih in the true solution u(x)
� (x - x 2 ) to find the correct ui . u ; = 21 (zh. - z· 2 h2 ) has Un + l = 2.1 (1 - 1 2 ) = 0. Finite difference solution It is unusual to have this perfect agreement between u i and the exact u( ih ) . It is also unusual that no matrices were displayed. When 4 h = 1 and f = 1, the matrix is K3 / h2 = 16K3 . Then ih = � ' � ' � leads to ui = f2 , fi , f2: 1 3/32 2 -1 0 (23) 16 - 1 2 - 1 4/32 = 1 . Ku = f 0 -1 2 3/32 1 The -1 's in columns 0 and 4 were safely chopped off because u 0 = u4 = 0. set
=
l[ ] [ l
[
A Different Boundary Condition Chapter 2 will give a host of physical examples leading to these differential and difference equations. Right now we stay focused on the boundary condition at x = 0, changing from zero height to zero slope :
d2 u = f(x) - dx 2
with
du (0) = 0 ( free end ) dx
and
u(1) = 0.
(24)
With this new boundary condition, the difference equation no longer wants u 0 = 0. Instead we could set the first difference to zero: u 1 - u0 = 0 means zero slope in the first small interval. With u 0 = u 1 , the second difference -u 0 + 2 u 1 - u 2 in row 1 reduces to u 1 - u 2 . The new boundary condition changes Kn to Tn . Example 2 Solve the differential and difference eq uations starting from zero slope: Free-fixed
O
d2 u = 1 with du ( ) = 0 and u(1) = 0 dx dx 2 -u'· +1 + 2u' - u,_ 1 = 1 with u l - uo = 0 a nd U = 0 n+ l h h2
·
- -
(25)
(26)
20
Chapter 1 Applied Linear Algebra Continuous solution u(O) = f6 Discrete solution u0 = u 1 = 166
5 16
�--
f---+--1--+--"�t-7
Free end
16 x Fixed end 2h 3h 4h = 1
h
0
Figure 1 .4: u i is below the true u(x) = � ( 1 - x 2 ) by an error � h(1 - x) . Solution u ( x ) = - �x 2 + Cx + D is still the complete solution to -u" = 1. But the new boundary condition changes the constants to C = 0 and D = � :
�� = 0
at
x=0
gives
C = 0.
Then u = 0 at x = 1 gives D =
The free-fixed solution is u ( x ) = � ( 1 - x 2 ) .
�·
Figure 1 . 4 shows this parabola. Example 1 was a symmetric parabola, but now the discrete boundary condition u 1 = u0 is not exactly satisfied by u(x) . So the finite difference u/s show small errors. We expect an O (h) correction because of the forward difference (u 1 - u0) jh. For n = 3 and h = � ' gives Figure 1 .4 shows that solution (not very accurate, with three meshpoints) . The discrete points will lie much nearer the parabola for large n. The error is h(1 - x ) /2 . For completeness we can go ahead to solve Tn u = h 2 ones(n, 1 ) for every n:
Tn = ( backward ) ( -forward ) =
[
1 -1
0 1
0 -1
�
[]
� -i
-
: -i
]
(28)
The inverses of those first difference matrices are sum matrices (triangles of 1 's) . The inverse of Tn is an upper triangle times a lower triangle:
[ : .: ; ] [ : : : ] [ 1] . [ ;:::::� l 1
T�1ones
�
(29)
1
1+
u = h2 T-t ones = h2 n
o o •
+n n
(30)
1 . 2 Differences, Derivatives, Boundary Conditions
21
For n = 3 we recover 1 + 2 + 3 = 6 and 2 + 3 = 5 , which appeared i n (27) . There is a formula for those sums in (30) and it gives the approximation U( Discrete solution
(31)
This answer has Un+1 = 0 when i = n + 1. And u0 = u 1 so the boundary conditions are satisfied. That starting value u0 = � nh is below the correct value u(O) = � = H n + 1 ) h only by � h. This � h is the first-order error caused by replacing the zero slope at x = 0 by the one-sided condition u 1 = u0 . The worked example removes that O (h) error by centering the boundary condition.
MATLAB Experiment
The function u(x) = cos('rr x /2) satisfies free-fixed boundary conditions u'(O) = 0 and u(1) = 0. It solves the equation -u" = f = (7r/2) 2 cos(7rx/2) . How close to u are the solutions U and V of the finite difference equations Tn U = f and Tn+1 V = g?
h = 1 /( n+1 ) ; u = cos ( pi* ( 1 : n ) '*h / 2 ) ; c = ( pi / 2 )1' 2; f = C* U ; % Usual matrix T U = h*h* T \ f; % Sol ution u 1 , . . . , Un with one-sided condition u0 = u 1 e = 1 - U(1) % First-order error at x = 0 g = [c / 2;f] ; T = ; % Create Tn+ 1 as in eq uation (34) below. Note g ( 1 ) = f (0) /2 V = h*h* T \ g; % Sol ution u0 , . . . , Un with centered condition u_ 1 = u 1 % Second-order error from centering at x = 0 E = 1 - V( 1 ) .
.
.
Take n = 3, 7, 15 and test T \ f with appropriate T and f. Somehow the right mesh has (n + � ) h = 1 , so the boundary point with u' = 0 is halfway between meshpoints. You should find e proportional to h and E proportional to h 2 • A big difference.
a
WO R K E D EXA M P LES
a
1 . 2 A Is there a way to avoid this O (h) error from the one-sided boundary condition u 1 = u0? Constructing a more accurate difference equation is a perfect example of numerical analysis. This crucial decision comes between the modeling step (by a differential equation) and the computing step (solving the discrete equation) . Solution The natural idea is a centered difference (u 1 - u_ 1 ) /2h = 0. This copies the true u' (O) = 0 with second order accuracy. It introduces a new unknown u_ 1 , so extend the difference equation to x = 0. Eliminating u_ 1 leaves size ( T ) = n + 1 : -u - 1 + 2uo - u 1
=
h2 f (O)
and
u- 1
=
u1
give
uo - u 1 = �h2 f (O) . (32)
22
[ [ l l
Chapter 1 Applied Linear Algebra
Centering the boundary condition multiplies
f(O) by � -
Try
n =
3 and h = :f :
uo u1 u2 U3
gives
__!__ 16
8.0
7.5
6.0 3.5
.
(33)
Those numbers ui are exactly equal to the true u(x) = � ( 1 - x 2 ) at the nodes. We are back to perfect agreement with the parabola in Figure 1 .4. For a varying load f(x) and a non-parabolic solution to -u" = f(x) , the centered discrete equation will have second-order errors O(h 2 ) . Problem 2 1 shows a very direct approach to
u 0 - u 1 = 4h2 f(O) .
1 .2 B When we multiply matrices, the backward 1 and -2 and 1 on the interior rows:
.6. _ .6. + =
[ -�
0
l �- 1 �1 l [ - 0� - 0� - �1
.6. _
times the forward
[ -� -� � l 0
1 -2
.6. +
gives
(34)
We didn't get K3 , for two reasons. First , the signs are still reversed. And the first corner entry is - 1 instead of -2. The boundary rows give us T3 , because .6._ (.6- + u) sets to zero the first value b. + u = (u 1 - u 0 )/h ( not the value of u itself! ) .
[
l
.6. 2 u boundary row with u0 = u 1 -T3 = .6. 2 u typical row u2 - 2u 1 + u0 (35) .6. 2 u boundary row with u4 = 0 The boundary condition at the top is zero slope. The second difference u 2 - 2 u 1 + u0 becomes u 2 - u 1 when u0 = u 1 . We will come back to this, because in my experience 99% of the difficulties with differential equations occur at the boundary. K has Uo = Un + l = 0 u { O ) = 0, u { l ) = 0 ' ' { ) u O = 0, u ( l ) = 0 B has Uo = u 1 , Un = Un + l T has Uo = u 1 , Un + l = 0 u' { O ) = 0 , u { l) = 0 ' ' u {l) { { ) , ) C has Uo = Un , u 1 = Un+ l u O = {l) u O = u -1 1 0 1 -2 1 0 1 -2
+-
+-
+-
An infinite tridiagonal matrix, with no boundary, maintains 1 , - 2 , 1 down its infinitely long diagonals. Chopping off the infinite matrix would be the same as pretending that uo and Un + l are both zero. That leaves Kn , which has 2's in the corners.
1 . 2 Differences, Derivatives, Boundary Conditions
23
P roblem Set 1 . 2 1
2
What are the second derivative u"(x) and the second difference !::l. 2 Un ? Use 6 (x) .
{
u(x)
=
u(x)
and
Ax Bx
if x :S O if X � 0
Un
= { AnBn ifif nn :S� O0
-2A -A 0 B 2B
U are piecewise linear with a corner at 0. Solve the differential equation -u"(x) = 8(x) with u( -2) = 0 and u(3) = 0. The pieces u A(x + 2) and u B(x - 3) meet at x 0. Show that the vector U = (u(-1), u(O) , u(1), u(2)) solves the corresponding matrix problem KU = F (0, 1, 0, 0) .
=
=
=
=
Problems 3-12 are about the "local accuracy" of finite differences. 3 4
h2 term in the error for a centered difference (u(x + h) - u(x - h))/2h is 2 ! h u"'(x) . Test by computing that difference for u(x) x 3 and x4 . Verify that the inverse of the backward difference matrix f::l. _ in (28) is the sum matrix in (29) . But the centered difference matrix !::l. 0 (!::l. + + f::l. _ )/2 might 3 and 5. not be invertible! Solve !::l. 0 u = 0 for In the Taylor series (2) , find the number a in the next term ah 4 u""(x) by testing u(x) x4 at x = 0. For u(x) x 4 , compute the second derivative and second difference !::l.? u j(!::l.. x ) 2 . From the answers, predict c in the leading error in equation (9) . Four samples of u can give fourth-order accuracy for dujdx at the center: -u2 + 8u 1 - 8u _ l + u - 2 du + bh4 d5 u + - dx 12h dx 5 · · · 1. Check that this is correct for u = 1 and u x 2 and u = x4 . 2. Expand u 2 , u 1 , u _ l , u - 2 as in equation (2) . Combine the four Taylor series to discover the coefficient b in the h4 leading error term. Question Why didn't I square the centered difference for a good !::l.. 2 ? Answer A centered difference of a centered difference stretches too far: !::l.. o !::l.o U = Un + 2 - 2un + Un - 2 2h 2h n (2h) 2 The
= n= =
n=
5 6 7
=
=
_
=
8
The second difference matrix now has 1 , 0, - 2 , 0, 1 on a typical row. The accuracy is no better and we have trouble with U n + 2 at the boundaries. Can you construct a fourth-order accurate centered difference for d 2 ujdx 2 , choos ing the right coefficients to multiply u 2 , u 1 , uo, u _ l , u - 2 ?
24
Chapter 1 Applied Linear Algebra
9
Show that the fourth difference !::l. 4 uj(!::l. x ) 4 with coefficients proximates d4 u / dx 4 by testing on u = x, x 2 , x 3 , and x 4 :
1, -4, 6, -4, 1 ap
u2 - 4u l +---.,.6u:o --: 4u--- _ l + u - 2 = d4 u + ( which leading error ? ) . .- -,dx4 (.6.x) 4
----
----
-
10
Multiply the first difference matrices in the order !::l. + f::l. _ , instead of !). _ !). + in equation (27) . Which boundary row, first or last , corresponds to the boundary condition u = 0? Where is the approximation to u' = 0?
11
Suppose we want a one-sided approximation t o
�� with second order accuracy:
ru(x) + su(x - !::l. x ) + tu(x - 2.6-x) du for u = 1, x, x 2 . dx !::l.x Substitute u = 1 , x, x 2 to find and solve three equations for r, s, t. The corre
[
J
sponding difference matrix will be lower triangular. The formula is "causal." 12
Equation ( 7 ) shows the "first difference o f the first difference." Why i s the left side within O(h 2 ) of k u: +� - u: _ � ? Why is this within O(h 2 ) of u� ?
Problems 13-19 solve differential equations to test global accuracy. 13
14
Graph the free-fixed solution u o, . . . , u8 with n = 7 in Figure 1.4, in place of the existing graph with n = 3. You can use formula (30) or solve the 7 by 7 system. The O(h) error should be cut in half, from h = � to � ( a ) Solve -u" = 12x 2 with free-fixed conditions u'(O) = 0 and u(1) = 0 . The complete solution involves integrating f(x) = 12x 2 twice, plus Cx + D.
h = n� l and n = 3, 7, 15, compute the discrete u 1 , . . . , Un using Tn : ui +l - 2u, + u,_ l = 3 ( . h ) 2 w1th . u0 = 0 and Un +l = 0 . z h2 Compare u i with the exact answer at the center point x = ih = �. Is the error proportional to h or h 2 ? Plot the u = cos 47fx for 0 ::; x ::; 1 and the discrete values u, = cos 47fih at the meshpoints x = ih = n� 1 . For small n those values will not catch the oscillations of cos 7fX. How large is a good n? How many mesh points per ( b ) With
15
oscillation?
16
Solve -u" = cos 47fx with fixed-fixed conditions u(O) = u(1) = 0. Use K4 and Ks to compute u 1 , . . . , Un and plot on the same graph with u(x) : with
Uo = Un +l = 0 .
1.2 Differences, Derivatives, Boundary Conditions
25
17
Test the differences 0 u = (u i + l - Ui - 1 ) and b. 2 u = ui + 1 - 2ui + u i - 1 on u(x) = eax. Factor out eax (this is why exponentials are so useful) . Expand eat:,x = 1 + ab.x + (ab.x) 2 /2 + · · · to find the leading error terms.
18
Write a finite difference approximation (using
b.
20
with boundary conditions u(O)
100
100 df
-
Verify the summation by parts Hint: Change i + 21
= 0 and u(1) = 0 .
u 1 , u2 , u3 , u4 . Compare them to the true solution. Construct a centered difference approximation using Kjh 2 and b. 0 /2h to 2 du - ddxu2 + dx = 1 with u(O) = 0 and u(1) = 0 . Separately use a forward difference b.. + U jh for dujdx. Notice b. o =(b. + +b.. - )/2. Solve for the centered u and uncentered U with h = 1/5. The true u(x) is the particular solution u = x plus any A+Bex. Which A and B satisfy the boundary conditions ? How close are u and U to u( x) ? The transpose of the centered difference b. 0 is - b.. 0 ( antisymmetric) . That is like the minus sign in integration by parts, when f(x)g(x) drops to zero at ±oo: dg dx = - g(x) dx . f(x) I ntegration by parts dX oo oo dX Solve for
19
�:� = x
K) with n = 4 unknowns to
-
00 L fi (Yi+ 1 - Yi - 1 ) = - L Ui+ 1 - fi - 1 ) Yi · oo -00 00
-
1 to i in 2: fi 9i + 1 , and change i - 1 to i in 2: fi 9i - 1 · Use the expansion u(h) = u(O) +hu'(O) + � h 2 u"(O) + · · with zero slope u'(O) = 0 and -u" = f ( x) to derive the top boundary equation u 0 - u 1 = � h2 f ( 0 ) . This factor � removes the O(h) error from Figure 1.4: good.
26
Chapter 1 Applied Linear Algebra
1.3
E L I M I N AT I O N LEADS TO
K
LDLT
=
This book has two themes-how to understand equations, and how to solve them. This section is about solving a system of n linear equations Ku = f. Our method will be Gaussian elimination (not determinants and not Cramer's Rule ! ) . All software packages use elimination on positive definite systems of all sizes. MATLAB uses u = K\f (known as backslash ) , and [L, U] = lu(K) for triangular factors of K.
The symmetric factorization K = LDL T takes two extra steps beyond the solution itself. First , elimination factors K into LU: lower triangular L times upper triangular U. Second, the symmetry of K leads to U = DLT. The steps from K to U and back to K are by lower triangular matrices-rows operating on lower rows.
K = LU and K = LDLT are the right "matrix ways" to understand elimination. The pivots go into D. This is the most frequently used algorithm in scientific com puting (billions of dollars per year) so it belongs in this book. If you met LU and LDLT earlier in a linear algebra course, I hope you find this a good review.
Our first example is the 3 by 3 matrix K = K3 . It contains the nine coefficients (two of them are zero) in the linear equations Ku = f. The vector on the right side is not so important now, and we choose f = (4, 0, 0) . =
4 0 = 0
2u 1 - u 2 -u 1 + 2u 2 - u3 - u 2 + 2u3
Ku = f
=
The first step is to eliminate u 1 from the second equation. Multiply equation 1 by � and add to equation 2. The new matrix has a zero in the 2, 1 position-where u 1 is eliminated. I have circled the first two pivots:
[0(D-1 -1 l [ l [ l 0 0
-1
0
U1
u2
2
�
h h+!h
2u 1 - u 2 3 2 u 2 - u3
is
- u2
h
=
=
4 2
+ 2u3 = 0
The next step looks at the 2 by 2 system in the last two equations. The pivot d 2 = � is circled. To eliminate u 2 from the third equation, add � of the second equation. Then the matrix has a zero in the 3, 2 position. It is now the upper triangular U. The three pivots 2 , �, �, are on its diagonal: is
2u 1 - u 2 3 2 U 2 - U3 4 3
u3
=
4
=
2
=
4 3
(1)
Forward elimination i s complete. Note that all pivots and multipliers were decided by K, not f. The right side changed from f = (4, 0, 0) into the new c = (4, 2, � ) , and back substitution can begin. Triangular systems are quick to solve ( n 2 operations) .
1 . 3 Elimination Leads to K =
LDLT 27
Solution by back substitution. The last equation gives u3 = 1. Substituting into the second equation gives � u 2 - 1 = 2. Therefore u 2 = 2. Substituting into the first equation gives 2u 1 - 2 = 4. Therefore u 1 = 3 and the system is solved. The solution vector is u = (3, 2, 1). When we multiply the columns of K by those three numbers, they add up to the vector f. I always think of a matrix-vector multiplication Ku as a combination of the columns of K. Please look:
Combine columns for Ku That sum is f = (4, 0, 0) . Solving a system Ku = f is exactly the same as finding a combination of the columns of K that produces the vector f. This is important. The solution u expresses f as the "right combination" of the columns (with coefficients 3, 2, 1). For a singular matrix there might be no combination that produces f, or there might be infinitely many combinations. Our matrix K is invertible. When we divide K u = ( 4, 0, 0) by 4, the right side becomes (1, 0, 0) which is the first column of I. So we are looking at the first column of K K- 1 = I. We must be seeing the first column of K - 1 . After dividing the previous u = (3, 2, 1) by 4, the first column of K - 1 must be �, �, �: Column 1 of inverse
= l r -� �� -n r L : l r � : : I
(3)
If we really want K - 1 , its columns come from Ku = columns of I. So K - 1 = K \ I .
Note about the multipliers: When we know the pivot i n row j , and we know the entry i, the multiplier iii is their ratio: entry to eliminate (in row i) M uItip . 1.1er >:- ij = ----.---(4) ptvot (in row j) The convention is to subtract (not add) iii times one equation from another equation. The multiplier €21 at our first step was - � ( the ratio of -1 to 2). That step added � of row 1 to row 2, which is the same as subtracting - � ( row 1) from row 2. to be eliminated in row
0
Subtract .eij times the pivot row j from row i. Then the i, j entry is 0. The 3, 1 entry in the lower left corner of K was already zero. So there was nothing to eliminate and that multiplier was €3 1 = 0. The last multiplier was €32 = -l
Elimination Produces
K
=
LU
Now put those multipliers € 21 , €3 1 , €3 2 into a lower triangular matrix L, with ones on the diagonal. L records the steps of elimination by storing the multipliers. The
28
Chapter 1 Applied Linear Algebra
[
0l
[ -� 0 00 l [ 0 0 l
upper triangular U records the final result , and here is the connection K = LU:
K = LU
0 2
-1 -1 2 -1
-1
2
=
0 1
0 �0 -l2 -1
i
-3 1 -
.
(5)
3
The short and important and beautiful statement of Gaussian elimination is that K = LU. Please multiply those two matrices L and U.
The lower triangular matrix L times the upper triangular matrix U recovers the original matrix K. I think of it this way: L reverses the elimination steps. This takes U back to K. LU is the "matrix form" of elimination and we have to emphasize it.
Su ppose forward elimination uses the m u ltipliers in L to change the rows of K into the rows of U (u pper triangular) . Then K is factored into L times U. Elimination is a two-step process, going forward (down) and then backward (up) . Forward uses L, backward uses U. Forward elimination reached a new right side 1 c . (The elimination steps are really multiplying by L - to solve L c = f.) Back substitution on Uu = c leads to the solution u . Then c = L - l f and u = u- 1 c combine into u = u - 1 L f which is the correct u = K-1 f.
-l
G o back to the example and check that L c
Lc = f
n [ �: l
=
f produces the right vector
[�l
gives
c1 = 4 C2
C3
= 2 = 34
c:
as in ( 1 ) .
By keeping the right side up t o date i n elimination, we were solving L c = f. Forward elimination changed f into c. Then back substitution quickly finds u = (3, 2 , 1 ) .
You might notice that we are not using "inverse matrices" anywhere in this com putation. The inverse of K is not needed. Good software for linear algebra (the LAPACK library is in the public domain) separates Gaussian elimination into a fac toring step that works on K, and a solving step that works on f: [L, U] = l u (K) in MATLAB L c = f forward for c , then Uu = c backward
Step 1 . Factor K into L U Step 2. Solve K u = f for u
The first step factors K into triangular matrices L times U. The solution step computes c (forward elimination) and then u (back substitution) . MATLAB should almost never be asked for an inverse matrix. Use the backslash command K\f to compute u , and not the inverse command inv(K) * f: Step 1
+2
Solve Ku = f by
u =
K\f (Backslash notices symmetry) .
1 . 3 Elimi nation Leads to
K
= LDLT )
29
The reason for two subroutines in LAPACK is to avoid repeating the same steps on K when there is a new vector f * . It is quite common ( and desirable to have several right sides with the same K. Then we Factor only once; it is the expensive part. The quick subroutine Solve finds the solutions u , u * , . . without computing K - 1 . For multiple f 's, put them in the columns of a matrix F . Then use K\f. .
U
Singular Systems
Back substitution is fast because is triangular. It generally fails if a zero appears in the pivot . Forward elimination also fails, because a zero entry can't remove a nonzero entry below it . The official definition requires that pivots are never zero. If we meet a zero in the pivot position, we can exchange rows-hoping to move a nonzero entry up into the pivot. An invertible matrix has a full set of pivots. When the column has all zeros in the pivot position and below, this is our signal that the matrix is singular. It has no inverse. An example is C.
= = -�.
=
=
Example 1 Add - 1 's in the corners to get the circulant C. The first pivot is d 1 2 with mu ltipliers €2 1 €3 1 The second pivot is d2 �- But there is no third pivot:
C = [ � � -� ] --+ lcp �rD �� ] --+ [cp m �� l = U . U. -1 -1
2
0
2
� 2
0
0
0
I n the language of linear algebra , the rows of C are linearly dependent. Elimination fou nd a combination of those rows ( it was their su m ) that produced the last row of all zeros in With only two pivots, C is singular. Example 2 Suppose a zero appears in the second pivot position but there is a nonzero below it. Then a row excha nge produces the second pivot and elimination can continue. This example is not singular, even with the zero appearing in the 2, 2 position:
[� � �] 1 1 0
leads to
. Excha nge rows to
U=
Exchange rows on the right side of the eq uations too ! The pivots become all ones, and elimination succeeds. The original matrix is invertible but not positive definite. ( Its determinant is minus the product of pivots, so - 1 , beca use of the row exchange. )
LU U
P PA
PA = LU) .
The exercises show how a permutation matrix carries out this row exchange. The triangular L and are now the factors of ( so that The original had no factorization, even though it was invertible. After the row exchange, has its rows in the right order for We summarize the three possibilities:
APA
LU.
30
Chapter 1 Applied Linear Algebra
Elimination on an
n
by n matrix A may or may not req uire row exchanges:
No row exchanges to get n pivots: A is invertible and A = LU. Row exchanges by P to get n pivots: A is invertible and PA = LU. No way to find n pivots: A is singular. There is no inverse matrix A -l .
Positive definite matrices are recognized by the fact that they are symmetric and they need no row exchanges and all pivots are positive. We are still waiting for the meaning of this property-elimination gives a way to test for it .
Symmetry Converts
K
=
LU to
K
=
LDLT
The factorization K = LU comes directly from elimination-which produces U by the multipliers in L. This is extremely valuable, but something good was lost. The original K was symmetric, but L and U are not symmetric: Symmetry is lost
K=
[� -
0
��1 2� -
l
=
[ � - 1l [ -
0
-
�
2
-
i -� -
3
3
l
=
LU .
The lower factor L has ones on the diagonal. The upper factor U has the pivots. This is unsymmetric, but the symmetry is easy to recover. Just separate the pivots into a diagonal matrix D, by dividing the rows of U by the pivots 2, � and � : ' Symmetry is recovered
K=
1
[ Eto E])1 1 l [ .] [ � e] 2
�
(6)
1
3
Now we have it . The pivot matrix D is in the middle. The matrix on the left is still L. The matrix on the right is the transpose of L:
The symmetric factorization of a symmetric matrix is
K = LD L T .
This triple factorization preserves the symmetry. That is important and needs to be highlighted. It applies to LDLT and to every other "symmetric product" ATCA.
The product LDLT is a utomatical ly a symmetric matrix, if D is diagona l . More than that, ATCA i s a utomatical ly symmetric i f C i s symmetric. The factor A is not necessarily sq uare and C is not necessarily diagonal. The reason for symmetry comes directly from matrix multiplication. The transpose of any product AB is equal to BT AT. The individual transposes come in the opposite order, and that is just what we want:
This is
LDLT again.
1 . 3 Elimi nation Leads to K =
LDLT 31
(LT)T i s the same as L. Also DT = D ( diagonal matrices are symmetric ) . The displayed line says that the transpose of LDLT is LDLT. This is symmetry. The same reasoning applies to ATCA. Its transpose is ATCT(AT)T. If C is symmetric (C = CT) , then this is ATCA again. Notice the special case when the matrix in the middle is the identity matrix C = I:
For any rectangular matrix
A,
the product
AT A is square and symmetric.
We will meet these products AT A and ATCA many times. By assuming a little more about A and C, the product will be not only symmetric but positive definite.
n�1 .
The Determinant of
Kn
Elimination on K begins with the three pivots f and � and �. This pattern continues. 1 The product of the pivots is the The ith pivot is i � . The last pivot is determinant, and cancelling fractions produces the answer +
Determinant of Kn
n 1: ( � ) ( � ) (�) · · · ( n: 1 )
( 7)
=n+l.
The reason is that determinants always multiply: ( det K ) = ( det L )( det U) . The triangular matrix L has 's on its diagonal, so det L = The triangular matrix U has the pivots on its diagonal, so det U = product of pivots = + The LU factorization not only solves Ku = f, it is the quick way to compute the determinant.
1
1. n 1.
There is a similar pattern for the multipliers that appear in elimination: Multipliers
e2 1 =
-1
-
2
,
3
2
en n - 1 = -
e32 = - 3 e43 = - 4 -
-
n n- 1
--
.
(8)
All other multipliers are zero. This is the crucial fact about elimination on a tridi agonal matrix, that L and U are bidiagonal. If a row of K starts with p zeros (no elimination needed there), then that row of L also starts with p zeros. If a column of K starts with q zeros, then that column of U starts with q zeros. Zeros inside the band can unfortunately be "filled in" by elimination. This leads to the fundamental problem of reordering the rows and columns to make the p's and q's as large as possible. For our tridiagonal matrices the ordering is already perfect .
1
1 1, 1
You may not need a proof that the pivots i � and the multipliers i i are correct. For completeness, here is row i of L multiplying columns i - i , and i + of U:
[ - �i1 1 ] .
[ ..)_�__ �
-
i� 1
- 1 01 l
The Thomas algorithm in Example
_
=
[ -1
2 -l
]
= row i of K .
4 will solve tridiagonal systems in 8n steps.
32
Chapter 1 Applied Linear Algebra
Positive Pivots and Positive Determinants I will repeat one note about positive definiteness (the matrix must be symmetric to start with) . It is positive definite if all pivots are positive. We need nonzero pivots for invertibility, and we need positive pivots (without row exchanges) for positive definiteness.
n n
n
For 2 by 2 matrices [ b � J , the first pivot is a. The only multiplier is f2 1 = b/ a. Subtracting bja times row 1 from row 2 puts the number c - (b 2 fa) into the second pivot. This is the same as (ac - b2 )ja. Please notice L and LT in K = LDLT : (9)
2 by 2 factors
[� �]
These pivots are positive when
a > 0 and ac - b2 > 0.
This is the 2 by 2 test :
is positive definite if and only if a > 0 and ac - b2 > 0 .
[� �] pos def
[ � : ] [ � � ] [ -2-3 -3-8 ] indef neg def pos semidef
Out of four examples, the last three fail the test :
The matrix with b = 4 is singular (pivot missing) and positive semidefinite. The matrix with b = 6 has ac - b2 = -20. That matrix is indefinite (pivots +2 and - 10) . The last matrix has a < 0. It is negative definite even though its determinant is positive.
3
K shows the key link between pivots and upper left determinants:
Example 3
[� -� l = [=iJ 0
1
2
0 - -3 1
l [:IJJ . ] [� -� ] · 3
-
1
The upper left determinants of K are 2, 3, 4. The pivots are their ratios 2, �' 1- All upper left determinants are positive exactly when all pivots are positive.
Operation Counts The factors L and U are bidiagonal when K = LU is tridiagonal. Then the work of elimination is proportional to (a few operations per row) . This is very different from the number of additions plus multiplications to factor a full matrix. The leading terms are with symmetry and in general. For = 1000, we are comparing thousands of operations (quick) against hundreds of millions.
�n3
n
�n3
n
1 . 3 Elimination Leads to
K = LDLT 33
Between those extremes (tridiagonal versus full) are band matrices. There might be w nonzero diagonals above and also below the main diagonal. Each row operation needs a division for the multiplier, and w multiplications and additions. With w entries below each pivot, that makes 2 w 2 + w to clear out each column. With n columns the overall count grows like 2w 2 n, still only linear in n. On the right side vector f, forward elimination and back substitution use w multiply-adds per row, plus one division. A full matrix needs n 2 multiply-adds on the right side, [(n - 1 ) + (n - 2) + . . · + 1] forward and [1 + 2 + . . · + (n - 1)] backward. This is still much less than � n 3 total operations on the left side. Here is a table:
Operation Count ( Multiplies + adds) Factor: Find L and U Solve : Forward and back on f
Banded
2w 2 n + wn 4wn + n
Tridiagonal
3n 5n
Au = f in 8n floating-point operations. A has b 1 , . . . , bn on the diagonal with a 2 , . . . , an below and c 1 , . . . , Cn- 1 above. Exchange equations i and i + 1 if l b; l < lai+ l l at step i. With no exchanges: Example 4 The Thomas algorithm solves tridiagonal
n-1 cdb; fdb; b;+l - ai+l c; /i+l - a;+ di
for i from 1 to
c; /; b;+l /i+ l
ffff-
end forward loop
Un
f-
end backward loop
H �� i ]
Example 5 Test the commands [L, U , P]
AI �
fn /bn n - 1 to 1 U; j; - C;U;+l
f-
for i from
-
= l u ( A ) a nd P * A - L * U on A 1 , A 2 , A3 .
A, �
[� ! �]
A, �
[� ! :]
For A 1 , the permutation matrix P exchanges which rows? Always P A = LU . For A2 , MATLAB exchanges rows to achieve the largest pivots colu m n by col u m n . For A3 , which i s not positive definite, rows are still exchanged : P -=/= I a n d U -=/= DLT. P roblem Set 1 . 3 1 2
Extend equation ( 5 ) into a determinant of K4 ?
4 by 4 factorization K4 = L4 D4 LJ.
What is the
1 . Find the inverses of the 3 by 3 matrices L and D and £T in equation ( 5 ) . 2. Write a formula for the ith pivot of K. 3. Check that the i, j entry of L4 1 is j/i (on and below the diagonal) by multiplying L4 L4 1 or L4 1 L4 .
34
Chapter
1
Applied Linear Algebra
1 . Enter the matrix K5 by the MATLAB command toeplitz ( [ 2 - 1 0 0 0] ) .
3
2 . Compute the determinant and the inverse by det ( K ) and inv ( K ) . For a neater answer compute the determinant times the inverse.
L, D, U factors of K5 and verify that the i, j entry of L- 1 is jfi. The vector of pivots for K4 is d = [t � � �] . This is d = (2 : 5) . / ( 1 : 4) , using MATLAB's counting vector i : j = (i, i + 1 , . . . , j) . The extra . makes the division act a component at a time. Find f in the MATLAB expression for L = eye ( 4) - diag ( f, - 1 ) and multiply L * diag ( d ) * L ' to recover K4 . If A has pivots 2, 7, 6 with no row exchanges, what are the pivots for the upper 3. Find the
4
5
left 2 by 2 submatrix B (without row 3 and column 3)? Explain why. 6
How many entries can you choose freely in a 5 by 5 symmetric matrix K? How many can you choose in a 5 by 5 diagonal matrix D and lower triangular L (with ones on its diagonal) ?
7
Suppose
8
A is rectangular ( m by n ) and C is symmetric ( m by m ) . 1 . Transpose ATCA to show its symmetry. What shape is this matrix? 2. Show why AT A has no negative numbers on its diagonal. Factor these symmetric matrices into A = LDLT with the pivots in D: A=
9
[! ;]
and
A=
[ ! �]
and
A=
[ ;] 2 1 0 1 2 0 1
The Cholesky command A = choi ( K ) produces an upper triangular A with = AT A. The square roots of the pivots from D are now included on the diagonal of A (so Cholesky fails unless K = K T and the pivots are positive) . Try the chol command on K3 , T3 , B3 , and B3 + eps * e ye (3) .
K
10
The all-ones matrix ones ( 4) is positive semidefinite. Find all its pivots (zero not allowed) . Find its determinant and try eig ( ones ( 4 ) ) . Factor it into a 4 by 1 matrix L times a 1 by 4 matrix LT.
11
The matrix K = ones ( 4 ) + eye(4) / 100 has all 1 's off the diagonal, and 1 .01 down the main diagonal. Is it positive definite ? Find the pivots by lu ( K ) and eigenvalues by eig ( K ) . Also find its LDLT factorization and inv ( K ) .
12
The matrix K =pasca1 ( 4 ) contains the numbers from the Pascal triangle (tilted to fit symmetrically into K ) . Multiply its pivots to find its determinant. Factor K into LLT where the lower triangular L also contains the Pascal triangle!
13
The Fibonacci matrix n �] is indefinite. Find its pivots. Factor it into LDLT. Multiply ( 1 , 0) by this matrix 5 times, to see the first 6 Fibonacci numbers.
1 . 3 Elimination Leads to 14
K = L D L T 35
If A = LU, solve by hand the equation Ax = f without ever finding A itself. Solve Lc = f and then Ux = c (then LUx = Lc is the desired equation Ax = f) . Lc = f is forward elimination and U x = c is back substitution:
[ �] 2 8 0
U= 15
From the multiplication LS show that
3
is the inverse of
S
[-t'-t'32�1 ] ·
=
1 0 1
S subtracts multiples of row 1 from lower rows. L adds them back. 16
Unlike the previous exercise, which eliminated only one column, show that is
not the inverse of
Write L as £ 1 £ 2 to find the correct inverse L - 1
17
S=
[-t'-t'32�1 -t'32 ] · 1
1
= L2 1 L1 1
(notice the order) :
By trial and error, find examples of 2 by 2 matrices such that
22 B
1 . LU f= UL 2. A = -1, with real entries in A 3. = 0, with no zeros in 4. CD = -DC, not allowing CD = 0
18 19
20
B
Write down a 3 by 3 matrix with row 1 - 2 * row 2 + row 3 = 0 and find a similar dependence of the columns-a combination of columns that gives zero. Draw these equations in their row form (two intersecting lines) and find the solution ( x , y) . Then draw their column form by adding two vectors:
[� � ] [ � ] = [ � ]
has column form
[ � :] = LU ?
x
[�] + y [ � ] = [�] .
True or false: Every matrix A can be factored into a lower triangular L times an upper triangular U, with nonzero diagonals. Find L and U when possible: When is
A=
[ �] =
A= �
LU ?
36
Chapter 1 Applied Linear Algebra
I NV E R S ES A N D D E LTA F U N CT I O N S
1.4
We are comparing matrix equations with differential equations. One is Ku = f, the other is -u" = f(x) . The solutions are vectors u and functions u(x) . This comparison is quite remarkable when special vectors f and functions f(x) are the forcing terms on the right side. With a uniform load f(x) = constant , both solutions are parabolas ( Section 1 .2) . Now comes the opposite choice with f = point load: In the matrix equation, take f = Dj = j th column of the identity matrix. In the differential equation, take f(x) = 8(x - a ) = delta function at x
= a.
The delta function may be partly or completely new to you. It is zero except at one point . The function 8(x - a ) represents a "spike" or a "point load" or an "impulse" concentrated at the single point x = a. The solution u(x) or u(x, a ) , where a gives the placement of the load, is the Green's function. When we know the Green's function for all point loads 8(x - a ) , we can solve -u" = f(x) for any load f(x) . In the matrix equation
Ku = 8j , the right side is column j of I.
The solution is
u = column j of K - 1 . We are solving KK - 1 = I, column by column. So we are finding the inverse matrix, which is the "discrete Green's function." Like a, the discrete (K - 1 ) ij locates the solution at point i from a load at point j.
x and
The amazing fact i s that the entries o f K - 1 and r - 1 fall exactly o n the solutions u( x) to the continuous problems. The figures show this, and so will the text.
u(x) slope drops from 4
1
� to - � fixed
fixed
u(O) = 0
2
1
u(l) = 0
u 1(0) = 0
Figure 1 .5 : Middle columns of h K5 1 and
h T5- 1
2
u(l) = 0
1
lie on solutions to
-u" = 8(x - �).
Concentrated Load Figure 1 . 5 shows the form of u(x) , when the load is at the halfway point x = � Away from this load, our equation is u" = 0 and its solution is u = straight line. The problem is to match the two lines ( before and after �) with the point load. Example 1
d2 u dx
- -2 =
Solve -u" = point load with fixed-fixed and free-fixed endpoints: 1 j ( X ) = 8 ( X - ) with -
2
{
fixed: u ( O ) = 0 and fixed: free: u' ( O ) = 0 and fixed:
u( l ) = 0 u(l ) = 0
1 .4 I nverses and Delta Functions
37
Solution In the fixed-fixed problem, the up and down lines m ust start and end at u = 0. At the load point x = �. the function u ( x ) is contin uous and the lines meet. The slope drops by 1 because the delta function has "area = 1" . To see the drop in slope, integrate both sides of -u" = 8 across x = �:
l.right - dxd2u2 dx = l.right 8 x - 1 ) dx (
( dxdu )
( )
du = 1 . (1) + 2 left left right dx left The fixed-fixed case has u ;eft = � and u � ight = - � - The fixed-free case has u ;eft = 0 and u�ight = -1. I n every case the slope drops by 1 at the unit load . These solutions u ( x ) are ramp functions, with a corner. In the rest of the section we move the load to x = a and compute the new ramps. ( The fixed-fixed ramp will have slopes 1 - a and -a, always dropping by 1.) And we will find discrete ramps for the columns of the inverse matrices K - 1 and r - 1 . The entries will increase -
-
gives
_
linearly, up to the diagonal of K- 1 , then go linearly down to the end of the column.
It is remarkable to be finding exact solutions and exact inverses. We take this chance to do it. These problems are exceptionally simple and important , so why not? Example 2 Move the point load to x = a. Everywhere else u" = 0, so the sol ution is u = Ax + B up to the load . It changes to u = Cx + D beyond that point. Four equations (two at boundaries, two at x = a ) determine those constants A, B, C, D: Boundary Conditions
fixed u ( O ) = 0 fixed u(1) = 0
x=a No jump in u : Aa + B Ca + D A = 0+ 1 Drop by 1 in u' : Jump/No Jump Conditions at
B 0 : : C+D = 0 Substitute B = 0 and D = - C into the first eq uation on the right: Aa + 0 = Ca - C and A = C + 1 give slopes A = 1 - a and C = -a.
(2)
Then D = -C = a produces the sol ution in Figure 1 .6. The ramp is u = (1 - a)x going up and u = a(1 - x ) going down . On the right we show a col umn of K - 1 , computed in eq uation (10): linear up and down .
u (x )
0
Column 5 of K(; 1 7
2 ·5
a -- §.7 1 Response at x to a load at a = ¥
1
2 3 4 5 6
Row i
Figure 1 . 6 : ( fixed-fixed boundary ) . For the matrix K(; \ the entries in each column go linearly up and down like the true u ( x ) .
38
Chapter 1 Applied Linear Algebra
Delta Function and G reen's Function
-u" = 8(x - a) again, by a slightly different method ( same answer ) . A particular solution is a ramp. Then we add all solutions Cx + D to u" = 0. Example 2 used the boundary conditions first, and now we use them last. You must recognize that 8(x) and 8(x - a) are not true functions! They are zero except at one point x = 0 or x = a where the function is "infinite" -too vague. The We solve
spike is "infinitely tall and infinitesimally thin." One definition is to say that the integral of 8 ( x) is the unit step function S ( x) in Figure 1. 7. " The area is 1 under the spike at x = 0." No true function could achieve that , but 8(x) is extremely useful.
The standard ramp function is R = 0 up to the corner at x = 0 and then R = Its slope dRjdx is a step function. Its second derivative is d 2 Rjdx 2 = 8(x) .
_c
8(x) = dS dx 0 Delta function
0 Step function
8(x)
S(x) = dR dx X
S(x)
_L_
x.
X
0 Ramp function
Figure 1.7: The integral of the delta function is the step function, The integral of the step S(x) is the ramp R(x) , so 8(x) = d 2 Rjdx 2 .
R( x) so 8(x) = dSjdx.
Now shift the three graphs by a. The shifted ramp R(x - a) is 0 then x - a. This has first derivative S(x - a) and second derivative 8(x - a) . In words, the first derivative jumps by 1 at x = a so the second derivative is a delta function. Since our equation -d2 ujdx 2 = 8(x - a) has a minus sign, we want the slope to drop by 1 . The descending ramp -R( x - a) is a particular solution to -u " = 8 ( x - a) .
Main point We have u" = 0 except at x = a. So u is a straight line on the left and right of a. The slope of this ramp drops by 1 at a, as required by -u" = 8(x - a) . The downward ramp -R(x - a) is one particular solution, and we can add Cx + D. The two constants C and D came from two integrations. The complete solution Complete solution
(particular + nullspace) is a family of ramps:
2 - ddxu2 = 8(x - a)
is solved by
u(x) = -R(x - a) + Cx + D . (3)
The co nstants C and D are determined by the boundary conditions. u(O) = -R(O - a) + C 0 + D = 0. Therefore D must be zero . From u(1) = 0 we learn that the other constant ( in Cx) is C = 1 - a: u(1) = -R(1 - a) + C 1 + D = a - 1 + C = 0. Therefore C = 1 - a . So the ramp increases with slope 1 - a until x = a. Then it decreases to u(1) = 0. When we substitute R = 0 followed by R = x - a, we find the two parts: ·
·
39
1 .4 I nverses and Delta Functions FIXED E N DS
u(x) = -R(x - a) + (1 - a)x =
{
( 1 - a ) x for ( 1 - x ) a for
x�a x 2': a
(4)
The slope of u(x) starts at 1 - a and drops by 1 to -a. This unit drop in the slope means a delta function for -d 2 ujdx 2 , as required. The first part (1 - a)x gives u(O) = 0, the second part (1 - x)a gives u(1) = 0. Please notice the symmetry between x and a in the two parts ! Those are like i and j in the symmetric matrix (K- 1 ) ij = (K - 1 ) j i · The response at x to a load at a equals the response at a to a load at x. It is the "Green's function."
Free- Fixed Boundary Conditions When the end x = 0 becomes free, that boundary condition changes to u'(O) This leads to C = 0 in the complete solution u(x) = -R(x - a) + Cx + D: Set Then
x = 0 : u'(O) = 0 + C + 0.
Therefore
= 0.
C must be zero .
u(1) = 0 yields the other constant D = 1 - a:
Set x
= 1 : u(1) = -R(1 - a) + D = a - 1 + D = 0.
Therefore
D = 1 -a.
The solution is a constant D ( zero slope ) up to the load at x = a. Then the slope drops to - 1 ( descending ramp ) . The two-part formula for u(x) is
FREE FIXED
u(x) =
{
1 - a for 1 - x for
u=1-a
x�a x 2': a
(5)
0
a -- �3
1
Free-Free: There is no solution for f = c5(x - a) when both ends are free. If we require u'(O) = 0 and also u'(1) = 0, those give conditions on C and D that cannot be met. A ramp can't have zero slope on both sides ( and support the load ) . In the same way, the matrix B is singular and BB - 1 = I has no solution.
The free-free problem does have a solution when J f(x) dx = 0. The example in problem 7 is f(x) = c5 (x - �) - c5 (x - � ) . The problem is still singular and it has infinitely many solutions ( any constant can be added to u(x) , without changing u 1 (0) = 0 and u 1 (1) = 0) .
Integrating -u " = f(x) from 0 to 1 gives this requirement J f(x) dx = 0. The integral of -u 11 is u 1 (0) - u 1 (1), and free-free boundary conditions make that zero. In the matrix case, add the n equations Bu = f to get 0 = !I + · · · + fn as the test .
40
Chapter 1 Applied Linear Algebra
Discrete Vectors: Load and Step a nd Ramp Those solutions u(x) in (4) and (5) are the Green's functions G(x, a) for fixed ends and free-fixed ends. They will correspond to K - 1 and r- 1 in the matrix equations. The matrices have second differences in place of second derivatives. It is a pleasure to see how difference equations imitate differential equations. The crucial equation becomes /). 2 R = 8. This copies R"(x) = 8(x) :
8 has one nonzero component 80 = 1: The step vector S has components Si = 0 or 1 : The ramp vector R has components Ri = 0 or i: The delta vector
8 = ( . . . , 0, 0, 1 , 0, 0, . . . s = ( . . . , 0, 0 , 1 , 1, 1, . . . R = ( . . . , 0, 0, 0, 1, 2, . . .
These vectors are all centered at i = 0. Notice that f::l. _ S = 8 but !::l. + R = S. We need a backward /)._ and a forward /). + to get a centered second difference !::l. 2 = /). _ !). + · Then !::l. 2 R = f::l. _ S = 8. Matrix multiplication shows this clearly:
.6. 2 ( ramp )
(6)
The ramp vector R is piecewise linear. At the center point , the second difference jumps to R 1 - 2Ro + R _ 1 = 1 . At all other points (where the delta vector is zero) the ramp solves !::l. 2 R = 0. Thus !::l. 2 R = 8 copies R"(x) = 8(x) . 0
-o----o-+-o--o-
-2 - 1 0 1 2
s
0
0
0
--o-o--t---t---
-2 - 1 0 1 2
R
0
0
-o------o-2
-2 -1 0 1
Figure 1 .8: The delta vector 8 and step vector S and ramp vector R. The key relations are t5 = .6- _ S (backward) and S = .6- + R (forward) and t5 = .6. 2 R (centered) . The solutions t o d 2 ujdx 2 = 0 are linear functions Cx + D. The solutions to 2 !::l. u = 0 are "linear vectors" with u, = Ci + D. The equation ui + 1 - 2u, + u, _ 1 = 0 is satisfied by constant vectors and linear vectors, since ( i + 1 ) - 2i + ( i - 1 ) = 0. The complete solution to !::l. 2 u = 8 is U particular + U nullspace · Thus Ui = � + Ci + D. I want to emphasize that this is unusually perfect. The discrete Ri + Ci + D is an exact copy of the continuous solution u(x) = R(x) + Cx + D. We can solve !::l. 2 u = 8 by sampling the ramp u(x) at equally spaced points, without any error.
41
1.4 I nverses and Delta Functions
The Discrete Equations
Ku
=
t5i and Tu
=
t5i
In the differential equation, the point load and step and ramp moved to x = a. In the difference equation, the load moves to component j . The right side Dj has components Di -j , zero except when i = j. Then the shifted step and shifted ramp have components Si -j and � -j, also centered at j .
-u ( x) = 8(x - a ) is now -b. 2 u = Dj : . A 2 ui = -ui+ l + 2ui - ui 1 = 1 if i =i= j w1th Uo = 0 and Un + l = 0 . (7) 0 if i j The left side is exactly the matrix-vector multiplication Kn u. The minus sign in -b. 2 changes the rows 1 , -2, 1 to their positive definite form - 1, 2, -1. On the right side, the shifted delta vector is the jth column of the identity matrix. When the load is at meshpoint j = 2, the equation is column 2 of K K - 1 = I: n=4 j=2 (8) j=2 0 -1 2 - 1 U3 0 0i 0� - 1 �2 0 U��4 When the right sides are the four columns of I (with j = 1, 2, 3, 4) the solutions are the four columns of K4 1 . This inverse matrix is the discrete Green's function. What is the solution vector u? A particular solution is the descending ramp -� -j , shifted by j and sign-reversed. The complete solution includes Ci + D , which solves b. 2 u = 0. Thus ui = -� -j + Ci + D . The constants C and D are determined by the two boundary conditions u 0 = 0 and Un + l = 0: u0 = -Ra -j + C 0 + D = 0. Therefore D must be zero (9) . n + 1 J. Un+ l = -Rn + l -j + C (n + 1 ) + 0 = 0. Therefore C = n +� = 1 - niT ( 10 ) Those results are parallel to D = 0 and C = 1 - a in the differential equation. The tilted ramp u = - R + Ci in Figure 1 . 9 increases linearly from u 0 = 0. Its peak is at the position j of the point load, and the ramp descends linearly to U n + l = 0: ( n���j ) i for i :::; j FIXED u = -� = (1 1) j + C z i ENDS ( n+ l -i ) J. for z. ?::. J.
{
The fixed-ends difference equation from -u
"
� � [ l[ l [ l
+-
·
. {
n+ l
Those are the entries of K;;I (asked for in earlier problem sets) . Above the diagonal, for i :::; j , the ramp is zero and u i = Ci. Below the diagonal, we can j ust exchange i and j, since we know that K;; 1 is symmetric. These formulas for the vector u are exactly parallel to ( 1 - a )x and ( 1 - x) a in equation (4) for the fixed-ends continuous problem.
(�,
�) .
Figure 1 . 9 shows a typical case with n = 4 and the load at j = 2. The formulas in ( 1 1 ) give u = �' g, The numbers go linearly up to � (on the main diagonal 1 of K4 ). Then 4/5 and 2/5 go linearly back down. The matrix equation (8) shows that this vector u should be the second column of K4 1 , and it is.
42
Chapter 1 Applied Linear Algebra
� 4 .; 0
1
2 3
f = = u = =
5
load at j = 2 column 2 of I response to load column 2 of K- 1
K4_ 1 = _!: 5
[4 6 4 4] 2 1 3 3 2 2 4 6 3 1 2 3
Figure 1 .9: K4 u = 82 has the point load in position j = 2 . The equation is column 2 of K4 Ki 1 = I. The solution u is column 2 of K4 1 . The free-fixed discrete equation Tu = f can also have f = OJ = point load at j : Discrete
- t!::l? u, = 8, _ J
with u 1 - u0 = 0 (zero slope) and Un + l = 0 .
( 12)
The solution is still a ramp u i = - R. - i + Ci + D with corner at j. But the constants C and D have new values because of the new boundary condition u 1 = u0 : u 1 - Uo = 0 + C + 0 = 0 Un + l = - Rn + l- J + D = 0
so the first constant is C = 0 so the second constant is D = n + 1 - j .
( 1 3) ( 14)
Those are completely analogous to C = 0 and D = 1 - a in the continuous problem above. The solution equals D up to the point load at position j . Then the ramp descends to reach Un + 1 = 0 at the other boundary. The two-part formula -R. -J + D, before and after the point load at i = j , is
FREE FIXED
. {
u, = -R. -J + (n + 1 - J ) =
n+l -j n+1-i
for i :::; j for i � j
(15)
The two parts are above and below the diagonal in the matrix r- 1 . The point loads at j = 1 , 2, 3, . . . lead to columns 1 , 2, 3, . . . and you see n + 1 - 1 in the corner:
� 4 0
1
2 3
5
'i
! = load at j = 2 column 2 of I U = response to load column 2 of r- 1
r- 1 _ 4
-
Figure 1 . 10: T4 u = 82 is column 2 of TT- 1 = I, so u = column 2 of r- 1 .
This r- 1 is the matrix that came in Section 1 . 2 by inverting T = UTU. Each column of r- 1 is constant down to the main diagonal and then linear, just like u(x) = 1 - a followed by u(x) = 1 - x in the free-fixed Green's function u( x , a) .
43
1 .4 I nverses and Delta Functions
G reen 's Function and the I nverse M atrix If we can solve for point loads, we can solve for any loads. In the matrix case this is immediate ( and worth seeing ) . Any vector f is a combination of n point loads: (16) The inverse matrix multiplies each column to combine three point load solutions:
u = K - 1 f is perfectly chosen to combine those columns. In the continuous case, the combination gives an integral not a sum. The load f(x) is an integral of point loads f(a)8(x - a ) . The solution u(x) is an integral over all a of responses u(x, a) to those loads at each point a:
Matrix multiplication
-u" = J(x) =
1 f(a)8(x 1
a)da
is solved by
u(x) =
1 f(a)u(x, a)da .
( 18)
x
( 1 9)
1
The Green's function u(x, a) corresponds to "row x and column a" of a continuous K - 1 . We will see it again. To summarize, we repeat formulas (4) and (5) for u(x, a) :
FIXED ENDS
u
_ -
{
( 1 - a)x for ( 1 - x)a for
x :::; a x 2: a
FREE FIXED
u=
{
1 1
-
a x
for for
If we sample the fixed-ends solution at x = n: l , when the load is at a = n� l , then we ( almost! ) have the i, j entry of K;; 1 . The only difference between equations ( 1 1 ) and (19) i s an extra factor of n + 1 = 11 f::J. x . The exact analogy would b e this:
�u = 8(x) - dx 2
corresponds to
( )
K 8 . U = 2 f::J. f::J. x ( x)
(20)
We divide K by h 2 = (b.x) 2 to approximate the second derivative. We divide 8 by h = f::J. x because the area should be 1 . Each component of 8 corresponds to a little x- interval of length f::J.x , so area = 1 requires height = 1 I l::J. x . Then our u is UI l::J. x . c
WO R K E D EXA M P L ES
c
1.4 The "Woodbury-Sherman-Morrison formula" will find K - 1 from r- 1 . This for mula gives the rank-one change in the inverse, when the matrix has a rank-one change in K = T - uvT. In this example the change is only +1 in the 1 , 1 entry, coming from T1 1 = 1 + K11 . The column vectors are v = ( 1 , 0, . . . 0) = -u.
44
Chapter 1 Applied Linear Algebra Here is one of the most useful formulas in linear algebra (it extends to T - U VT) :
1 Tr - 1 (21) K - 1 = r - 1 + T1 -- uv vT T- 1 u The proof multiplies the right side by T - uvT, and simplifies to I. Problem 1.1.7 displays r - 1 - K - 1 when the vectors have length n = 4: v T T- 1 = row 1 of T - 1 = [4 3 2 1] 1 - vT T - 1 u = 1 + 4 = 5. For any n, K - 1 comes from the simpler r - 1 by subtracting wTwj(n+1) with w =n:-1:1 Woodbury-Sherman- Morrison Inverse of K = T - uvT
P roblem Set 1 . 4 1
For -u" = 8 (x - a) , the solution must be linear on each side of the load. What four conditions determine A, B , C, D if u(O) = 2 and u(1) = 0?
u(x) = Ax + B 2
3
5
6
7
0 ::::; x ::::; a
and
Change Problem 1 to the free-fixed case the four equations for A, B, C, D.
u(x) = Cx + D
for a ::::;
u'(O) = 0 and u(1) = 4.
x ::::; 1 .
Find and solve
Suppose there are two unit loads, at the points a = � and b = � - Solve the fixed-fixed problem in two ways: First combine the two single-load solutions. The other way is to find six conditions for A, B , C, D, E, F:
u(x) = Ax + B 4
for
for
x ::::; 31 , Cx + D
for
-31 -< x -< -32 , Ex + F
for
x ?: 32 .
Solve the equation -d2 ujdx 2 = 8 (x - a) with fixed-free boundary conditions u(O) = 0 and u'(1) = 0. Draw the graphs of u(x) and u'(x) . Show that the same equation with free-free conditions u'(O) = 0 and u'(1) = 0 has no solution. The equations for C and D cannot be solved. This corresponds to the singular matrix Bn (with 1, 1 and n, n entries both changed to 1). Show that -u" = 8(x - a) with periodic conditions u(O) = u(1) and u'(O) = cannot be solved. Again the requirements on C and D cannot be met. This corresponds to the singular circulant matrix Cn (with 1, n and n, 1 entries changed to -1).
u'(1)
A difference of point loads, f(x) = 8(x - �) - 8(x - � ) , does allow a free free solution to -u" = f. Find infinitely many solutions with u'(O) = 0 and
u'(1) = 0. 8
The difference f(x) = 8 (x - �) - 8 (x - �) has zero total load, and -u" = f(x) can also be solved with periodic boundary conditions. Find a particular solution U part ( x ) and then the complete solution U part + U null ·
45
1 .4 I nverses and Delta Functions 9
The distributed load f(x) = 1 is the integral of loads o(x - a) at all points The free-fixed solution u(x) = 4 ( 1 - x 2 ) from Section 1.3 should then be the integral of the point-load solutions (1 - x for a ::; x, and 1 - a for a � x) :
x = a.
u(x) =
1 0
x
(1 -x) da+
1 X
1
1 2 ) - (x- x 2 ) = -1 - -x 1 (1-a) da = (1-x)x+(1- -2 2 2 2 . YES ! 2
u(x) = J0x (1 - x)a da + J: (l - a)x da = . 10 If you add together the columns of K - 1 ( or r - 1 ) , you get a "discrete parabola" that solves the equation Ku = f ( or Tu = f) with what vector f? Do this addition for K4 1 in Figure 1 . 9 and T4- 1 in Figure 1. 10. Check the fixed-fixed case
__
Problems 1 1-1 5 are about delta functions and their integrals and derivatives
11
The integral o f o(x) i s the step function S(x) . The integral o f S(x) i s the ramp R(x) . Find and graph the next two integrals: the quadratic spline Q(x) and the cubic spline C(x) . Which derivatives of C(x) are continuous at x = 0?
12
The cubic spline C(x) solves the fourth-order equation u'111 = o(x) . What is the complete solution u(x) with four arbitrary constants? Choose those constants so that u(1) = u"(1) = u(-1) = u"(-1) = 0. This gives the bending of a uniform simply supported beam under a point load.
13
The defining property of the delta function
1: o(x) g(x) dx
=
How does this give "area =
14
The function
SW(x) =
o(x) is a
�
2
for
1"
g(O) under
o(x) is that
for every smooth function
o(x)?
What is f o(x
g(x) .
- 3) g(x) dx?
"weak limit" of very high, very thin square waves
l x l ::; h
has
1: SW(x) g(x) dx -+ g(O)
as
SW:
h -+ 0.
For a constant g(x) = 1 and every g(x) = x n , show that J SW(x)g(x) dx -+ g(O) . We use the word "weak" because the rule depends on test functions g(x) .
15
The derivative of o(x) is the
doublet o'(x) .
Integrate by parts to compute
1: g(x) o'(x) dx - 1: (?) o(x) dx =
=
(??)
for smooth
g(x) .
46
Chapter 1 Applied Linear Algebra
1.5
E I G E NVA L U ES A N D E I G E NVECTORS
This section begins with Ax = >.x. That is the equation for an eigenvector x and its eigenvalue >.. We can solve Ax = >.x for small matrices, starting from det(A- >.I) = 0. Possibly you know this already (it would be a horrible method for large matrices) . There is no "elimination" that leads in a finite time to the exact >. and x. Since >. multiplies x, the equation Ax = >.x is not linear. One great success of numerical linear algebra is the development of fast and stable algorithms to compute eigenvalues (especially when A is symmetric) . The command eig(A) in MATLAB produces n numbers >. 1 , . . . , An and not a formula. But this chapter is dealing with special matrices ! For those we will find >. and x exactly.
A = SAS - 1 Part 1: Applying eigenvalues to diagonalize A and solve u 1 = Au. K = QAQT Part II: The eigenvalues of Kn , Tn , Bn , Cn are all >. = 2 - 2 cos t9 . The two parts may need two lectures. The table at the end reports all we know about >. and x for important classes of matrices. The first big application of eigenvalues is to Newton's Law Mu " + Ku = 0 in Section 2.2.
Part
1:
Ax
=
..Xx and Akx
=
_.Xkx and Diagonalizing A
Almost every vector changes direction when it is multiplied by A. Certain excep tional vectors a:: lie along the same line as Ax. Those are the eigenvectors. For an eigenvector, Ax is a number A times the original a:: . The eigenvalue >. tells whether the special vector x is stretched or shrunk or reversed or left unchanged, when it is multiplied by A. We may find >. = 2 (stretching) or >. = � (shrinking) or >. = - 1 (reversing) or >. = 1 (steady state, because Ax = x is unchanged) . We may also find >. = 0. If the nullspace contains nonzero vectors, they have Ax = Ox. So the nullspace contains eigenvectors corresponding to >. = 0. For our special matrices, we will guess x and then discover >.. For matrices in general, we find >. first . To separate >. from x, start by rewriting the basic equation:
Ax = AX means that (A - Al) x = 0 .
(1)
The matrix A - >.I must b e singular. Its determinant must be zero. The eigenvector x will be in the nullspace of A - >.!. The first step is to recognize that >. is an eigenvalue exactly when the shifted matrix A - >.I is not invertible:
The number A is an eigenvalue of A if and only if
det (A - >.I) =
0.
This "characteristic equation" det (A - >.I) = 0 involves only >., not x . The determinant of A - >.I is a polynomial in >. of degree n. By the Fundamental Theorem of Algebra, this polynomial must have n roots >. 1 , . . . , An · Some of those eigenvalues may be repeated and some may be complex-those cases can give us a little trouble.
1 .5 Eigenva l ues and Eigenvectors Example 1 Start with the special
Step 1 Subtract Step
2
2 by 2 matrix K = [ 2 - 1 ; - 1 2 ] . Esti mate K 100 .
[
>. from the diagonal to get K _ ' I = 2 --1 >. 2 --1 >. . 1\
Take the determinant of this matrix. That is
det ( K - >.1 ) = Step
47
1 2 _-1>.
]
(2 - >.) 2 - 1 and we simplify:
-1
I
2 2 _ >. = >. - 4>. + 3 .
3 Factoring into >. - 1 times >. - 3, the roots are 1 and 3:
>. 2 - 4>. + 3 = 0 yields the eigenval ues >. 1 = 1 and >. 2 = 3 . Now find the eigenvectors by solvi ng ( K - >.I ) x = 0 separately for each
1 -1 K - I = -1 1 -1 -1 K - 3I = - 1 - 1
[
[
]
]
>.:
leads to leads to
As expected , K - I and K -3I are singular. Each nullspace produces a line of eigenvectors. We chose x 1 and x 2 to have nice components 1 and - 1 , but any mu ltiples c 1 x 1 and c2 x 2 ( other tha n zero ) wou ld have been eq ually good as eigenvectors. The MATLAB choice is c 1 = c2 = 1 /..;2 , because then the eigenvectors have length 1 ( unit vectors ) . These eigenvectors of K are special ( since K is ) . If I gra ph the functions sin 1rx and sin 2 1rx , their sam ples at the two mesh points x = � and � are the eigenvectors in Figu re 1 . 1 1 . ( The fu nctions sin k1rx will soon lead us to the eigenvectors of Kn . )
=
K 1 00
will grow like because A ma"' 3.
3 100
[� �] from >. = 1
An exact formula for 2K 1 00 is
1 1 00
1 -1 + 3 100 - 1 1 from >. = 3
[
]
Figure 1 . 1 1 : The eigenvectors of
3
1
sin 21rx has samples ( sin 2; , sin �) = c(1, -1)
[ _ i - � ] lie on the graphs of sin 1rx and sin 21rx.
48
Chapter 1 Applied Linear Algebra
[2-
l
3 by 3 singu lar example, the circulant matrix C = 03 : >. -1 -1 and C - >.I = -1 2 - >. -1 . c= ; -1 -1 2 -1 -1 2 - >. A little patience (3 by 3 is already req uiring work ) produces the determinant and its factors: det ( C - >.I) = ->. 3 + 6>. 2 - 9>. = ->.(>. - 3) 2 . This third degree polynomial has th ree roots. The eigenval ues are >. 1 = 0 ( singular matrix ) and >. 2 = 3 and >. 3 = 3 ( repeated root ! ) . The all-ones vector x 1 = (1, 1, 1) is in the nullspace of C, so it is an eigenvector for >. 1 = 0. We hope for two independent eigenvectors corresponding to the repeated eigenvalue >. 2 = >. 3 = 3: Example 2
Here is a
[-i =�]
C - 3/ =
[ =� =� =�] -1 -1 -1
has ran k 1 ( doubly singular ) .
Elimination will zero out its last two rows. The three eq uations in ( C - 3/)x = 0 are all the sa me eq uation -x 1 - x 2 - x3 = 0, with a whole plane of sol utions. They are all eigenvectors for >. = 3. Allow me to make this choice of eigenvectors x 2 and x 3 from that plane of sol utions to Cx = 3x:
With this choice, the
x's are orthonormal ( orthogonal unit vectors ) .
Every symmetric
matrix has a full set of n perpendicular unit eigenvectors .
For an n by n matrix, the determinant of A - >.I will start with ( ->.) n . The rest of this polynomial takes more work to compute. Galois proved that an algebraic formula for the roots >. 1 , . . . , An is impossible for n > 4. ( He got killed in a duel, but not about this. ) That is why the eigenvalue problem needs its own special algorithms, which do not begin with the determinant of A - >.I. The eigenvalue problem is harder than A x = b, but there is partial good news. Two coefficients in the polynomial are easy to compute, and they give direct information about the product and sum of the roots >. 1 , . . . , An . The product of the n eigenvalues equals the determinant of A.
This is the constant term in det ( A - >.!) : Determinant
=
(2)
Product of A's
The sum of the n eigenvalues equals the sum of the n diagonal entries. The trace is the coefficient of ( ->.) n - 1 in det ( A - >.!) . Trace
=
Sum of A.'s
>. 1 + >. 2 +
·
·
·
+ >.n = an + a 22 + + ann = sum down diagonal of A. ·
·
·
(3)
1 . 5 Eigenval ues and Eigenvectors
49
Those checks are very useful, especially the trace. They appear in Problems 20 and 2 1 . They don't remove all the pain of computing det (A - >.I) and its factors. But when the computation is wrong, they generally tell us so. In our examples, .X = 1 , 3
has trace 2 + 2 = 1 + 3 =
K=
.X = 0, 3, 3 C =
4. det (K) = 1 3 . ·
has trace 2 + 2 + 2 = 0 + 3 + 3 =
Let me note three important facts about the eigenvalue problem 1.
2.
If A
6. det (C) = 0
Ax = >.x.
is triangular then its eigenvalues lie along its main diagonal. 4 >. � is (4 - >.) (2 - >.) , so >. = 4 and >. = 2. The determinant of �
[
2
>.
]
The eigenvalues o f A 2 are .X� , . . . , .X!. The eigenvalues o f A - l are 1/.Xl , , 1 /An · •
•
•
Multiply Ax = >.x by A. Multiply Ax = >.x by A - 1 .
Then Then
A 2 x = >.Ax = >. 2 x. x = >.A - 1 x and A - 1 x = t x.
Eigenvectors of A are also eigenvectors of A 2 and A- 1 (and any function of A) . 3.
Eigenvalues of A + B and AB are not known from eigenvalues of A and B. A=
[� � ] and B = [ � � ]
yield A + B =
[ � �] and AB = [ � � ] .
A and B have zero eigenvalues (triangular matrices with zeros on the diagonal) . But the eigenvalues of A + B are 1 and -1. And AB has eigenvalues 1 and 0. In the special case when AB = BA, these commuting matrices A and B will share eigenvectors: Ax = >.x and Bx = >.*x for the same eigenvector x. Then we do have (A + B)x = (>. + >.* ) x and ABx = >.>.*x. Eigenvalues of A and B can now be added and multiplied. (With B = A, the eigenvalues of A + A and A 2 are >. + >. and >. 2 .) Example 3 A Markov matrix has no negative entries and each col u m n adds to 1 ( some authors work with row vectors and then each row adds to one ) : Markov matrix
[ .7.3 ]
8 A = .· 2
has >. = 1 and
.5
.
Every Markov matrix has >. = 1 as an eigenvalue (A - I has dependent rows ) . When the trace is .8 + .7 = 1.5, the other eigenvalue must be >. = .5. The determinant of A must be (>. 1 ) (>. 2 ) = .5 and it is. The eigenvectors are (.6, .4) and ( - 1, 1).
50
Chapter 1 Applied Linear Algebra
Eigshow A MATLAB demo (just type eigshow) displays the eigenvalue problem for a 2 by 2 matrix. Figure 1 . 12 starts with the vector x = ( 1 , 0) . The mouse makes this vector move around the unit circle. At the same time the screen shows Ax, in color and also moving. Possibly Ax is ahead of x. Possibly Ax is behind x. Sometimes Ax is parallel to x. At that parallel moment, Ax equals >.x.
A= y
[ :�
: �]
is behind y =
has eigenvalues
�� .!
......, x 1 = Ax 1 \
[�]
=
[ :: ]
Not eigenvectors
[ : � ] is ahead of x = [ � ] X
Figure 1 . 1 2 : Eigshow for the Markov matrix: The eigenvalue
x 1 and x 2 line up with Ax 1 and Ax2 •
>. is the length of Ax, when it is parallel to the unit eigenvector x.
On web.mit.edu/18.06 we added a voice explanation of what can happen. The choices for A illustrate three possibilities, 0 or 1 or 2 real eigenvectors:
1.
There may be no real eigenvectors. Ax stays behind or ahead of x. This means the eigenvalues and eigenvectors are complex (as for a rotation matrix) .
2.
There may be only one line of eigenvectors (unusual) . The moving directions Ax and x meet but don't cross. This can happen only when >. 1 = >. 2 .
3.
There are two independent eigenvectors. This is typical! Ax crosses x at the first eigenvector x 1 , and it crosses back at the second eigenvector x 2 (also at -x 1 and -x 2 ) . The figure on the right shows those crossing directions: x is parallel to Ax. These eigenvectors are not perpendicular because A is not symmetric. The Powers of a Matrix
Linear equations Ax = b come from steady state problems. Eigenvalues have their greatest importance in dynamic problems. The solution is changing with time growing or decaying or oscillating or approaching a steady state. We cannot use elimination (which changes the eigenvalues) . But the eigenvalues and eigenvectors tell us everything.
51
1 . 5 Eigenvalues and Eigenvectors
Example 4 The two components of u(t) are the US populations east a n d west of the M ississippi at time t. Every year, 180 of the eastern population stays east and 120 moves west. At the same time 170 of the western population stays west and 130 moves east:
u(t+l)
=
east at ti me t + 1 ] = [· 8 .3 ] [ east at ti me t ] [west _ t+1 _ t . at t1me . west at t1me
Au(t)
.2
7
Start with a million people in the east at t = 0. After one year ( m u ltiply by A), the numbers are 800,000 and 200,000. Nobody is created or destroyed beca use the col u m ns add to 1. Populations stay positive beca use a Markov matrix has no negative entries. The initial u = [ 1, 000, 000 0 ] combines the eigenvectors [ 600, 000 400, 000 ] and [ 400, 000 -400, 000 ] 00 After 100 steps the populations are almost at steady state beca use (�) 1 is so sma l l : .
00,000 ] + ( 1 ) 100 [ -400,000 400,000 ] [6400,000 . You can see the steady state directly from the powers A, A 2 , A3 , and A 1 00 : ] · 8 .3 ] A 2 = [ .70 .45 A3 = [ .650 .525 ] A 1 00 = [ .6000 A = [ .2 .7 .350 .475 .30 .55 .4000 Steady state plus transient
Three steps find u k
u(1 00) =
=
2
.6000 .4000
]
A k u0 from the eigenvalues and eigenvectors of A.
uo as a combination of the eigenvectors uo = a 1 x 1 + · · · + an Xn . Step 2. Multiply each number ai by (>.j ) k . Step 3. Recombine the eigenvectors into u k = a 1 (>. I ) k x l + · · · + an (>. n ) k x n . In matrix language this is exactly u k = SA k S - 1 u0 . S has the eigenvectors Step 1. Write
A in its columns. The diagonal matrix A contains the eigenvalues: Step 1 .
Step
2.
SA k a which is
Uk
=
SA k S - 1 u0.
of
52
Chapter 1 Applied Linear Algebra
Step 2 is the fastest-just n multiplications by Af . Step 1 solves a linear system to analyze u 0 into eigenvectors. Step 3 multiplies by to reconstruct the answer u k . This process occurs over and over in applied mathematics. We see the same steps next for dujdt u , and again in Section 3.5 for All of Fourier series and signal processing depends on using the eigenvectors in exactly this way (the Fast Fourier Transform makes it quick) . Example 4 carried out the steps in a specific case.
S A-1.
=A
Diagonalizing a Matrix For an eigenvector x, multiplication by just multiplies by a number: Ax AX. All the n by n difficulties are swept away. Instead of an interconnected system, we can follow the eigenvectors separately. It is like having a diagonal matrix, with no off-diagonal interconnections. The lOOth power of a diagonal matrix is easy.
A
=
.
The matrix turns into a diagonal matrix when we use the eigenvectors prop erly. This is the matrix form of our key idea. Here is the one essential computation.
A
A
Suppose the n by n matrix has n linearly independent eigenvectors , Xn · Those are the columns of an eigenvector matrix Then is diagonal:
A
Diagonalization
[ . l=
A1 = s- 1 AS = A
S.
s-1 AS = A x 1 .
eige nv�lue matrix
.
.
(4)
An We use capital lambda for the eigenvalue matrix, with the small A's on its diagonal.
A times its eigenvectors x 1 , . . . , Xn , which are the columns of S. The first column of AS is Ax 1 . That is A 1 x 1 : Proof Multiply
A times S
The trick is to split this matrix
AS into S times A:
Keep those matrices in the right order! Then A 1 multiples the first column shown. We can write the diagonalization in two good ways:
AS = SA
is
AS = SA s- 1 AS = A or A = SAS- 1 .
x 1 , as (5)
The matrix has an inverse, because its columns (the eigenvectors of were assumed to be independent. Without n independent eigenvectors, we cannot diagonalize With no repeated eigenvalues, it is automatic that has n independent eigenvectors.
S
A
A)
A.
1.5 Eigenval ues and Eigenvectors
53
Application to Vector Differential Equations
�� = ay has the general solution y(t) = Ce at . The initial value y(O) determines C. The solution y(O) e at decays if a < 0 and it grows if a > 0. Decay is stability, growth is instability. When a is a complex number, its real part determines the growth or decay. The imaginary part gives an oscillating factor eiwt = cos wt + i sin wt. Now consider two coupled equations, which give one vector equation: du dyjdt = 2y - z or - = Au dzjdt = -y + 2z dt A single differential equation
The solution will still involve exponentials e >-.t . But we no longer have a single growth rate as in e at . There are two eigenvalues >. = 1 and >. = 3 of this matrix A = K2 . The solution has two exponentials e t and e 3 t . They multiply x = ( 1 , 1 ) and ( 1 , - 1 ) . The neat way to find solutions is by the eigenvectors. Pure solutions e-Xt:z: are eigenvectors that grow according to their own eigenvalue 1 or 3. We combine them: y(t) = ce t + De 3t · is (6) 3t t z(t)
[ ] [ Ge - De ]
This is the complete solution. Its two constants ( C and D) are determined by two initial values y(O) and z(O) . Check first that each part e >-.t x solves �� = Au: Each eigenvector
u(t) = e.\tx
yields
�� = >.e >-.t x = Ae >-.t x = Au .
(7)
The number e >-.t just multiplies all components of the eigenvector x. This is the point of eigenvectors, they grow by themselves at their own rate >.. Then the complete solution u(t) in (6) combines the pure modes Ce t x 1 and De 3t x 2 . The three steps for powers apply here too: Expand u { O) = Sa, multiply each a3 by e-X;t, recombine into u(t) = Se.xts - 1 u(O) .
y(O) = 7 and z(O) = 3. This determines the C and D. At the starting time t = 0, the growth factors e >-.t are both one:
Example 5 Suppose the initial val ues are
constants
We solved two equations to find C = 5 and D = 2. Then u(t) = 5e t x 1 + 2e 3 t x 2 solves the whole problem . The sol ution is a combination of slow growth and fast growth . Over a long time the faster e 3t will dominate, and the sol ution will line up with x 2 •
Section 2.2 will explain the key equation M u " + Ku = 0 in much more detail. Newton's law involves acceleration ( second derivative instead of first derivative ) . We might have two masses connected by springs. They can oscillate together, as in the first eigenvector ( 1 , 1 ) . Or they can be completely out of phase and move in opposite directions, as in the second eigenvector ( 1 , - 1 ) . The eigenvectors give the pure motions e iwt x, or "normal modes." The initial conditions produce a mixture.
54
Chapter 1 Applied Linear Algebra
Symmetric Matrices and Orthonormal Eigenvectors Our special matrices Kn and Tn and Bn and Cn are all symmetric. When symmetric matrix, its eigenvectors are perpendicular ( and the >.'s are real ) :
A is a
Symmetric matrices have real eigenvalues and orthonormal eigenvectors.
The columns of S are these orthonormal eigenvectors q 1 , . . . , qn . We use q instead of x for orthonormal vectors, and we use Q instead of S for the eigenvector matrix with those columns. Orthonormal vectors are perpendicular unit vectors: when i i- j (orthogonal vectors ) (8) when i = j (orthonormal vectors ) The matrix Q is easy to work with because Q T Q = I The transpose is the inverse! This repeats in matrix language that the columns of Q are orthonormal. QTQ = I contains all those inner products q{qi that equal 0 or 1 : .
Orthogonal Matrix
(9)
For two orthonormal columns in three-dimensional space, Q is 3 by 2. In this rect angular case, we still have QTQ = I but we don't have QQT = I . For our full set of eigenvectors, Q is square and QT is Q - 1 . The diagonalization
of a real symmetric matrix has S = Q and s - 1 = QT: Symmetric diagonalization A = SAS - 1 = QAQ T with QT Q -1 . ( 10) Notice how QAQT is automatically symmetric ( like LDLT). These factorizations perfectly reflect the symmetry of A. The eigenvalues >. 1 , . . . , An are the "spectrum" of the matrix, and A = QAQT is the spectral theorem or principal axis theorem. =
Part I I : Eigenvectors for Derivatives a nd Differences A main theme of this textbook is the analogy between discrete and continuous prob lems (matrix equations and differential equations) . Our special matrices all give sec ond differences, and we go first to the differential equation -y 11 = >.y. The eigen functions y (x ) are cosines and sines:
d2 y d:z:2
- -
=
..Xy(x) is solved by y = cos wx and y = sin wx with ..X = w 2 . (1 1 )
Allowing all frequencies we have too many eigenfunctions. The boundary condi tions will pick out the frequencies and choose cosines or sines. w,
w
55
1 . 5 Eigenva l ues and Eigenvectors
For y(O) = 0 and y(1) = 0, the fixed-fixed eigenfunctions are y (a:: ) = sin k1rx. The boundary condition y (O) = 0 reduces to sin O = 0, good. The condition y(1) = 0 reduces to sin br = 0. The sine comes back to zero at 1r and 21r and every integer multiple of 1r. So k = 1, 2, 3, . . . (since k = 0 only produces sin Ox = 0 which is useless) . Substitute y(x) = sin k1rx into (11) to find the eigenvalues >. = k 2 1r 2 : -
d2
. . ( sm k1rx ) = k 2 1r 2 sm k1rx so 2 dx
We will make a similar guess
\ A
= k 2 1r 2 = { 1r 2 , 47r 2 , 97r 2 , . . . } .
(12)
(discrete sines) for the discrete eigenvectors of Kn .
Changing the boundary conditions gives new eigenfunctions and eigenvalues. The equation -y 11 = >.y is still solved by sines and cosines. Instead of y = sin k1rx which is zero at both endpoints, here are the eigenfunctions Yk (x) and their eigenvalues >. k for free-free (zero slope) and periodic and free-fixed conditions:
y 1 (0) = 0 and y 1 (1) = 0 y(x) = cos k1rx y(O) = y(1), y 1 (0) = y 1 (1) y(x) = sin 27rka:: , cos 2Trka:: >. = 4k 2 7r 2 y 1 (0) = 0 and y(1) = 0 y(x) = cos (k+ � )1rx >. = {k+ � ) 2 7r 2 Remember that Bn and Cn are singular matrices (>. = 0 is an eigenvalue) . Their continuous analogs also have >. = 0, with cos Ox = 1 as the eigenfunction (set k = 0) . This constant eigenfunction y(x) = 1 is like the constant vector y = (1, 1 , . . . , 1). The free-fixed eigenfunctions cos(k + ! ) 1rx start with zero slope because sin 0 = 0. They end with zero height because cos( k + ! )1r = 0. So y 1 (0) = 0 and y(1) = 0. The Analog of Bn Analog of Cn Analog of Tn
matrix eigenvectors will now use these same sines and cosines (but >. is different) .
Eigenvectors of Kn : Discrete Sines Now come eigenvectors for the - 1 , 2, - 1 matrices. They are discrete sines and cosines-try them and they work. For all the middle rows, sin j(} and cos j(} are still successful for - Yi - l + 2yi - Yi + l = >.yi , with eigenvalues .X = 2 - 2 cos () � 0 : _
1
{
sin (j 1 ) (} cos(J - 1)(} .
-
} { } { +
2
sin j (} COS J· (}
_
1
sin(j. + 1 )(} COS (J + 1)(}
}
=
(2
_
2 cos e)
{ �}
sin (} · COS J (}
(13)
These are the imaginary and real parts o f a simpler identity:
The boundary rows decide (} and everything! For Kn the angles are (} = k1r / ( n + 1). The first eigenvector y 1 will sample the first eigenfunction y(x) = sin 1rx at the n meshpoints with h = nl l : First eigenvector = Discrete sine
y 1 = (sin 7rh, sin 27rh, . . . , sin n1rh)
( 1 4)
56
Chapter 1 Applied Linear Algebra
The jth component is sin .J:;1 . It is zero for j = 0 and j = n + angle is () = 1rh = n: l . The lowest eigenvalue is 2 - 2 cos () � () 2 : First eigenvalue of Kn AI = 2 - 2 cos 7rh = 2 - 2
(1 - �
1r h2
1,
as desired. The
+...
)
�
1r 2 h2 .
(15)
Compare with the first eigenvalue A = 1r 2 of the differential equation (when y(x) = sin 1rx and -y 11 = 1r 2 y ) . Divide K by h 2 = (box ) 2 to match differences with deriva tives. The eigenvalues of K are also divided by h 2 :
The other continuous eigenfunctions are sin 27rx, sin 37rx, and generally sin k1rx. It is neat for the k th discrete eigenvector to sample sin k1rx again at x = h, . . . , nh: Eigenvectors
=
Discrete sines
All eigen values of Kn
Yk
=
Ak
=
(sin k1rh, . . . , sin nk1rh) 2 - 2 cos k1rh, k
=
1, . . . , n .
( 16) ( 17 )
The sum AI + · · · + A n must be 2n, because that is the sum of the 2's on the diagonal (the trace ) . The product of the A's must be n + l . This probably needs an expert (not the author) . For K2 and K3 , Figure 1.13 shows the eigenvalues (symmetric around 2) .
( 1) ( -1)
Eigenvalues 2 - 2 cos () of K3 = 2 - V2 .At = 2 - 2 =2 .A 2 = 2 - 2 (0) = 2 + V2 .Aa = 2 - 2
4
Trace AI + A 2 + A 3 = 6 Determinant A I A 2 A 3 = For B4 include also Ao = 0 Figure
1 . 13:
0
1r 1 4 21r 1 4
Eigenvalues * of Kn - 1 interlace eigenvalues
o
3 7r 1 4
1r
= 2 - 2 cos nk_;1 of Kn .
Orthogonality The eigenvectors of a symmetric matrix are perpendicular. That is confirmed for the eigenvectors (1, 1 ) and ( 1 , - 1 ) in the 2 by 2 case. The three eigenvectors (when n = 3 and n + 1 = 4) are the columns of this sine matrix : Discrete Sine Transform
. 27r sm . . 37r sm 4 4 .sm 27r sm 47r sm. 6 7r 4 4 4 9 7r 7r 7r sin 34 sin 64 sm 4 sm 47r
DST =
•
•
1 J2 J2 1 0 -1 1 -1 1 J2 J2 1
1
( 18)
57
1 . 5 Eigenva l ues and Eigenvectors
The columns of S are orthogonal vectors, of length ..;2. If we divide all components by ..;2, the three eigenvectors become orthonormal. Their components lie on sine curves. The DST matrix becomes an orthogonal Q = DST/..;2, with Q - 1 = QT.
Section 3 . 5 uses the D S T matrix i n a Fast Poisson Solver for a two-dimensional difference equation (K2D)U = F. The columns of the matrix are displayed there for n = 5. The code will give a fast sine transform based on the FFT. ,-,-0-._ 11 \
II II
0
-
1
4
\
sin 3 7r x ,, \ *- Eigenvectors of K3 ' lie along sine curves
' sin 1rx
\
\
\
\
\
"'
\ I I
(
\
3
-
4
\
/ -o
I
I
I
Eigenvectors of B3 lie along cosines --+
1
sin 2 7r x
' 0....
.. ..._0
I
0
\ 1
1 6
\
'
0
,
\ 1 \
0
cos Ox = 1
\
' \
1 1
'o,
6 ' I
3
'r
1
,.
t1
,'
,
,.
cos 27rx
51 1I 6
' 'o COS 7rX ..... -
Figure 1 . 14: Three discrete eigenvectors fall on three continuous eigenfunctions.
Eigenvectors of Bn : Discrete Cosines The matrices Bn correspond to zero slope at both ends. Remarkably, Bn has the same n - 1 eigenvalues as Kn _ 1 plus the additional eigenvalue >. = 0. (B is singular with (1, . . . , 1) in its nullspace, because its first and last rows contain +1 and - 1 . ) Thus B3 has eigenvalues 0, 1 , 3 and trace 4, agreeing with 1 + 2 + 1 on its diagonal: Eigenvalues of Bn
k 7r >. = 2 - 2 cos , n
k = 0, . . . , n - 1 .
(19)
(cos -1 -k7r cos -3 -k7r , . . . , cos (n - -1 ) -k7r )
Eigenvectors of B sample cos k1rx at the n midpoints x = (j - � ) / n in Figure 1 . 14, where eigenvectors of K sample the sines at the meshpoints x = j / ( n + 1 ) : Eigenvectors of Bn
Yk =
2 n '
2 n
2
n
·
(20)
Since the cosine is even, those vectors have zero slope at the ends: and Notice that k = 0 gives the all-ones eigenvector y0 = ( 1 , 1, . . . , 1) which has eigenvalue >. = 0. This is the DC vector with zero frequency. Starting the count at zero is the useful convention in electrical engineering and signal processing.
58
Chapter 1 Applied Linear Algebra
These eigenvectors of Bn give the Discrete Cosine Transform. Here is the cosine matrix for n = 3, with the unnormalized eigenvectors of B3 in its columns:
Discrete Cosine Transform
DCT =
[
l [
cos O cos l2 1!:3 cos l2 237r cos 0 cos �2 1!:3 cos �2 2371" cos 0 cos §.2 1!:3 cos §.2 2371"
=
1 1 1
(21)
Eigenvectors of Cn : Powers of
w
= e 2 1r ijn
After sines from Kn and cosines from Bn , we come to the eigenvectors of Cn . These are both sines and cosines. Equivalently, they are complex exponentials. They are even more important than the sine and cosine transforms, because now the eigenvectors give the Discrete Fourier Transform. You can't have better eigenvectors than that . Every circulant matrix shares these eigenvectors, as we see in Chapter 4 on Fourier transforms. A circulant matrix is a "periodic matrix." It has constant diagonals with wrap-around (the - 1 's below the main diagonal of Cn wrap around to the - 1 in the upper right corner) . Our goal is to find the eigenvalues and eigenvectors of the matrices Cn , like C4 :
04 =
Circulant matrix (periodic)
[
2 -1 0 2 -1
-1
-1
0 o -1 2 - 1 - 1 0 -1 2
l
·
This symmetric matrix has real orthogonal eigenvectors (discrete sines and cosines) . They have full cycles like sin 2k1Tx, not half cycles like sin k1rx. But the numbering gets awkward when cosines start at k = 0 and sines start at k = 1 . It is better to work with complex exponentials e i8. The kth eigenvector of Cn comes from sampling Yk ( x ) = ei21rkx at the n meshpoints which are now x = jjn: jth component of Y k
ei21rk (j jn) wjk =
where
w e21rijn =
= nth root of 1 . ( 2 2)
That special number w = e 27ri / n is the key to the Discrete Fourier Transform. Its angle is 21rjn, which is an nth part of the whole way around the unit circle. The powers of cycle around the circle and come back to n = 1 :
w
Eigenvectors of Cn Eigenvalues of Cn
w
Yk - ( 1 ' w k ' w 2 k , , w < n - l ) k ) A. k 2 - w k - w- k 2 - 2 cos 27rnk .
=
•
•
=
(23) (24)
The numbering is k = 0, 1 , . . . , n - 1. The eigenvector with k = 0 is the constant y0 = ( 1 , 1 , . . . , 1 ) . The choice k = n would give the same ( 1 , 1 , . . . , 1 ) -nothing new, just aliasing ! The lowest eigenvalue 2 - 2 cos 0 is >. 0 = 0. The Cn are singular.
1 . 5 Eigenva lues and Eigenvectors
59
The eigenvector with k = 1 is y 1 = ( 1, w, . . . , w n - 1 ) . Those components are the n roots of 1. Figure 1.15 shows the unit circle r = 1 in the complex plane, with the n = 4 numbers 1 , i, i 2 , i 3 equally spaced around the circle on the left . Those numbers are e 0 , e 27ri / 4 , e 47ri/ 4 , e 67ri /4 and their fourth powers are 1. Oy 1 =
[
2
-1
-1
2
0
-1
-1
0
[l l 1 i
(2 - z. - z· 3 )
[
l
1 i i 2 . (25)
= _1 i2 � -1 0 -1 2 � For any n, the top row gives 2 - w - w n - 1 = 2 - w - w. Notice that w n - 1 is also the complex conjugate w = e - 21ri/n = 1/w, because one more factor w will reach 1. 2 7r Eigenvalue of C >. 1 = 2 - w - w = 2 - e 21ri j n - e - 21ri j n = 2 - 2 cos . (26)
0
_1
2
n
n=4 n=B w = e - 2 rr i/ 8
Figure
1 . 15:
The solutions to
z 4 = 1 are 1 , i, i 2 , i 3 .
The 8th roots are powers of e 27ri / 8 .
Now we know the first eigenvectors y0 = (1, 1, 1 , 1) and y 1 = (1, i, i 2 , i 3 ) of 04 . The eigenvalues are 0 and 2. To finish, we need the eigenvectors y 2 = ( 1, i 2 , i 4 , i 6 ) and y3 = (1, i 3 , i 6 , i 9 ) . Their eigenvalues are 4 and 2, which are 2 - 2 cos 7r and 2 - 2 cos 3; . Then the sum of the eigenvalues is 0 + 2 + 4 + 2 = 8, agreeing with the sum of the diagonal entries (the trace 2 + 2 + 2 + 2) of this matrix 04 .
The Fourier Matrix As always, the eigenvectors go into the columns of a matrix. Instead of the sine or cosine matrix, these eigenvectors of On give the Fourier matrix Fn . We have the DFT instead of the DST or DCT. For n = 4 the columns of F4 are y0 , y 1 , Y2 , y3 : Fourier matrix F4 Eigenvectors of C4
F4 =
,; l [; 1 i i2 i3
1 i2 i4 i6 i 6 ig
(Fn ) j k
= wi k = e2rrij kjn .
60
Chapter 1 Applied Linear Algebra
The columns of the Fourier matrix are orthogonal ! The inner product of two complex vectors requires that we take the complex conjugate of one of them (by convention the first one) . Otherwise we would have y'[y3 = 1 + 1 + 1 + 1 = 4. But y 1 is truly orthogonal to y3 because the correct product uses the conjugate fh : Complex inner product
[1
-i
( -i)2 ( -i)3 ] [l z· 6
Similarly Yf Y1 = 4 gives the correct length FT F of all the column inner products is 4/. Orthogonal
-
1-1+1-1
�
ig
FT4 F4 = 4 /
so that
-
-
0.
(27)
II Y 1 IIi = 2 (not Y f Y 1 = 0) . The matrix Orthogonality of columns reveals F - 1 : T . (28) of F . F4- 1 = 4l p4 = Inverse
Always F� Fn = nl. The inverse of Fn is F�/n. We could divide Fn by ..fii , which normalizes it to Un = Fn / ..fii . This normalized Fourier matrix is unitary:
(29)
Orthonormal
T
A unitary matrix has U U = I and orthonormal columns. It is the complex analog of a real orthogonal Q (which has QTQ = I) . The Fourier matrix is the most important complex matrix ever seen. Fn and F;; 1 produce the Discrete Fourier Transform.
P roblem Set 1 . 5
The first nine problems are about the matrices Kn , Tn , Bn , Cn .
1 2
The 2 by 2 matrix K2 in Example 1 has eigenvalues 1 and 3 in A. Its unit eigenvectors q 1 and q2 are the columns of Q. Multiply QAQT to recover K2 .
When you multiply the eigenvector y = (sin 1r h, sin 27r h, . . ) by K, the first row will produce a multiple of sin 1rh. Find that multiplier A by a double-angle formula for sin 27rh: .
( Ky h = 2 sin 7r h - 1 sin 27r h = A sin 1r h
Then A =
3
In MATLAB, construct K = K5 and then its eigenvalues by e = eig(K) . That column should be (2 - J3, 2 - 1 , 2 - 0, 2 + 1 , 2 + J3) . Verify that e agrees with 2 * ones(5, 1 ) - 2 * cos([1 : 5 ] * pi/6)' .
4
Continue 3 to find an eigenvector matrix Q by [Q, E] = eig(K) . The Discrete Sine Transform DST = Q * diag( [ - 1 - 1 1 - 1 1 ] ) starts each column with a positive entry. The matrix J K = [1 : 5 ]' * [1 : 5 ] has entries j times k. Verify that DST agrees with sin ( J K * pi/6) jsqrt(3) , and test DST T = DST - 1 .
61
1.5 Eigenva l ues and Eigenvectors 5
Construct B = B6 and [Q, E] = eig(B) with B ( 1 , 1) = 1 and B(6, 6) = 1. Verify that E = diag(e) with eigenvalues 2 * ones(1, 6) - 2 * cos( [O : 5 ] * pi/6) in e . How do you adjust Q to produce the ( highly important ) Discrete Cosine Transform with entries DCT = cos([.5 : 5.5 ]' * [0 : 5 ] * pi/6) /sq rt(3) ?
6
The free-fixed matrix T = T6 has T(1, 1) = 1. Check that its eigenvalues are 2 - 2 cos [(k - �)1r /6.5] . The matrix cos([.5 : 5.5 ]' * [.5 : 5.5 ] * pi/6.5) /sqrt(3.25) should contain its unit eigenvectors. Compute Q 1 * Q and Q 1 * T * Q.
7
The columns of the Fourier matrix F4 are eigenvectors of the circulant matrix C = C4 . But [Q, E] = eig(C) does not produce Q = F4 . What combinations of the columns of Q give the columns of F4 ? Notice the double eigenvalue in E.
8 9
Show that the n eigenvalues 2 - 2 cos :.:1 of
Kn add to the trace 2 +
·
·
·
+ 2.
K3 and B4 have the same nonzero eigenvalues because they come from the same 4 x 3 backward difference L L . Show that K3 = LL T .6._ and B4 = .6._.6._ T . The eigenvalues of K3 are the squared singular values a 2 of .6._ in 1. 7.
Problems 1 0-23 are about diagonalizing A by its eigenvectors in S.
10
Factor these two matrices into A = SAS - 1 . Check that A 2 = SA 2 S - 1 : and
11 12 13 14
I f A = SAS - 1 then A - 1 = ( ) ( columns of S ) ( different vectors ) .
)(
) . The eigenvectors o f A 3 are ( the same
If A has >. 1 = 2 with eigenvector x 1 = [ � J and >. 2 = 5 with x 2 = [ l J , use SAS - 1 to find A. No other matrix has the same >.'s and x's. Suppose A = SAS- 1 • What is the eigenvalue matrix for A + 21? What is the eigenvector matrix? Check that A + 2I = ( ) ( ) ( ) - 1 .
If the columns of S ( n eigenvectors of A ) are linearly independent , then ( a) A is invertible
( b ) A is diagonalizable
( c ) S is invertible
15
The matrix A = [ 3 A J is not diagonalizable because the rank of A - 3/ is . A only has one line of eigenvector. Which entries could you change to make A diagonalizable, with two eigenvectors?
16
A k = SA k s - 1 approaches the zero matrix as k ---+ oo if and only if every >. has absolute value less than . Which of these matrices has A k ---+ 0?
__
[ ] .4 .4 .6
6 A1 = ·
and
[.1 ]
6 A2 = ·
.9
.6
and
62
Chapter
17
Find
18
Diagonalize
1
Applied Linear Algebra
A and S to diagonalize A 1 in Problem 16.
[i �]
Diagonalize B and compute B
20
A 1 1 0u0 for these u0 ?
A and compute SA k S - 1 to prove this formula for A k : A=
19
What is
=
[�
has
SA k S - 1 to show how B k involves 3 k and 2 k :
�]
has
Suppose that A = SAS - 1 . Take determinants to prove that det A = A 1 A 2 · · · An = product of A's. This quick proof only works when A is -� .
21
Show that trace G H
= trace H G, by adding the diagonal entries of G H and HG: G=
[ � �]
and
G = S and H = AS - 1 . Then SAS- 1 = A has the same trace as 1 AS S = A, so the trace is the sum of the eigenvalues. 22 Substitute A = SAS - 1 into the product ( A - A 1 I ) ( A - A 2 I ) · · · ( A - An i ) and explain why ( A - A 1 I ) · · · ( A - A n i ) produces the zero matrix. We are substi tuting A for A in the polynomial p ( A ) = det ( A - A/ ) . The Cayley-Hamilton Theorem says that p( A ) = zero matrix ( true even if A is not diagonalizable ) . Choose
Problems 23-26 solve first-order systems
23
24
Find A's and x's so that
u 1 = Au by using Ax = Ax .
u = e >-.t x solves du = 4 u. dt 0 1
[
3]
Find A to change the scalar equation y" = 5y' + 4y into a vector equation for u = (y, y') . What are the eigenvalues of A? Find A 1 and A 2 also by substituting y = e >-.t into y" = 5y' + 4y.
1.5 Eigenval ues and Eigenvectors 25
63
The rabbit and wolf populations show fast growth of rabbits (from 6r) but loss to wolves (from -2w) . Find A and its eigenvalues and eigenvectors:
dr = 6r - 2w dt
dt
dw = 2r + w.
and
If r(O) = w(O) = 30 what are the populations at time t? After a long time, is the ratio of rabbits to wolves 1 to 2 or is it 2 to 1 ?
26
Substitute y = e >-.t into y" = 6y' - 9y to show that >. = 3 is a repeated root . 3 This is trouble; we need a second solution after e t. The matrix equation is
Show that this matrix has >. = 3, 3 and only one line of eigenvectors. here too. Show that the second solution is y = te 3t .
27
Explain why A and AT have the same eigenvalues. Show that >. an eigenvalue when A is a Markov matrix, because each row of and the vector is an eigenvector of AT. __
28
= 1 is always AT adds to 1
Find the eigenvalues and unit eigenvectors of A and T, and check the trace:
A= 29
[ ]
Trouble
1 1 1 1 0 0 1 0 0
T=
[
1 -1 -1 2
].
Here is a quick "proof" that the eigenvalues of all real matrices are real:
Ax = >.x
gives
xT Ax = >.x T x
so
>. = xTAx xT x
-
is real.
Find the flaw in this reasoning-a hidden assumption that is not justified.
30
Find all 2 by 2 matrices that are orthogonal and also symmetric. Which two numbers can be eigenvalues of these matrices?
31
To find the eigenfunction y(x) = sin k7r x, we could put y = e= in the differential equation - u" = >. u . Then - a 2 e x = >.e= gives a = i .fX or a = - i .fX . The VX YX complete solution y(x) = Ce i x + De - i x has C + D = 0 because y(O) = 0. That simplifies y(x) t o a sine function:
a
y(x) = C(e i VXx - e - iVXx ) = 2iC sin ..f>..x . y(1) = 0 yields sin .fX = 0. Then .fX must be a multiple of k1r, and >. = k 2 1r 2 as before. Repeat these steps for y'(O) = y'(1) = 0 and also y'(O) = y(1) = 0.
64
Chapter 1 Applied Linear Algebra
32
Suppose eigshow follows x and Ax for these six matrices. How many real eigen vectors? When does Ax go around in the opposite direction from x?
33
Scarymatlab shows what can happen when roundoff destroys symmetry:
A = [ 1 1 1 1 1; 1 : 5 ] ' ; B = A' * A; P = A * inv(B) * A'; [ Q, E ] = eig(P) ; B is exactly symmetric. The projection P should b e symmetric, but isn't. From Q' * Q show that two eigenvectors of P fail badly to have inner product 0. a
WO R K E D EXA M P L E
a
The eigenvalue problem -u 11 + x 2 u = >.u for the Schrodinger equation is im portant in physics ( the harmonic oscillator ) . The exact eigenvalues are the odd numbers ).. = 1 , 3, 5, . . . . This is a beautiful example for numerical experiment . One new point is that for computations, the infinite interval ( - oo , oo ) is reduced to -L ::;: x ::;: L. The eigenfunctions decay so quickly, like e- x2 /2 , that the matrix K could be replaced by B (maybe even by the circulant C) . Try harmonic(10, 10, 8) and (10, 20, 8) and (5, 10, 8) to see how the error in ).. = 1 depends on h and L. % positive integers L, n, k function harmonic( L , n , k) h=1/n; N=2 n L + 1 ; % N points in interval [ - L, L] K= toeplitz( [2 - 1 zeros( 1 , N - 2)] ) ; % second difference matrix H = K/h 1\ 2 + diag( ( - L: h : L) . 1\ 2) ; % diagonal matrix from x 1\ 2 % trideig is faster for large N [V, F] = eig( H ) ; E=diag( F) ; E=E( 1 : k) % first k eigenvalues (near 2n + 1) % choose sparse K and diag if needed j = 1 : k; plotU . E) ; A tridiagonal eigenvalue code trideig is on math . mit.edu/rvpersson. *
*
The exact eigenfunctions U n = Hn (x)e -x 2 1 2 come from a classical method: Put u(x) = (L ajxJ)e -x 2 12 into the equation -u " + x 2 u = (2n + 1)u and match up each power of x. Then aH 2 comes from a1 (even powers stay separate from odd powers) :
(j + 1)(j + 2)aH 2 = -2(n - j)a1 . At n = j the right side is zero, so a1 + 2 = 0 and the power series stops (good thing) . Otherwise the series would produce a solution u(x) that blows up at infinity. (The cutoff explains why ).. = 2n + 1 is an eigenvalue. ) I am happy with this chance to The coefficients are connected by
show a success for the power series method, which is not truly a popular part of computational science and engineering. The functions Hn (x) turn out to be Hermite polynomials. The eigenvalues in physical units are E = (n + �)liw. That is the quantization condition that picks out discrete energy states for this quantum oscillator.
1 . 5 Eigenval ues and Eigenvectors
65
The hydrogen atom is a stiffer numerical test because e -x 2 1 2 disappears. You can see the difference in experiments with -u 11 + (l(l + 1)/2x 2 - 1/x )u = >.u on the radial line 0 ::; x < oo. Niels Bohr discovered that A n = c j n 2 , which Griffiths [ 69 ] highlights as "the most important formula in all of quantum mechanics. Bohr obtained it in 1913 by a serendipitous mixture of inapplicable classical physics and premature quantum theory . . . " Now we know that Schrodinger's equation and its eigenvalues hold the key.
Properties of eigenvalues and eigenvectors
Matrix
Eigenvalues
Symmetric: AT = A Orthogonal: QT = Q - 1 Skew-symmetric: AT =
all ).. are real
-A Complex Hermitian: AT = A Positive Definite: x TAx > 0 Markov: mij > 0, 2:: �= 1 mij = 1 Similar: B = M - 1 AM Projection: P = P 2 = pT Reflection: I 2uu T Rank One: u v T Inverse: A - 1 Shift: A + ci Stable Powers: An __...., 0 Stable Exponential: eA t __...., 0 Cyclic: P ( 1 , . . , n ) = (2, . . , n , 1 ) -
Toeplitz: - 1 , 2 , - 1 on diagonals
SAS- 1 Symmetric: QAQT Jordan: J = M - 1 AM SVD: A = UEVT Diagonalizable:
all l >-. 1 = 1 all ).. are imaginary all ).. are real
0 Am ax = 1 >.(B) = >.(A) ).. = 1; 0 ).. = - 1 ; 1 , . . , 1 >. = v T u ; 0, . . , 0 1 / >.(A) >.(A) + c all 1 >. 1 < 1 all Re ).. < 0 A k = e 21rik j n >. k = 2 - 2 cos .E!... n+ 1. diagonal of A diagonal of A ( real ) diagonal of J singular values in E all ).. >
Eigenvectors
X r Xj = 0 orthogonal xr X j = 0 orthogonal xr X j = 0 orthogonal xr X j = 0 orthogonal
orthogonal
x>0 x(B) = M - 1 x (A)
steady state
column space; nullspace
u ; u.l u ; v.l eigenvectors of A eigenvectors of A
X k = ( 1 , A k , . . . ' ).. � - 1 ) k7r , S1n n2k7r X k = ( S1n n+1 +1 , . · ·) columns of S are independent columns of Q are orthonormal each block gives x = (0, . . , 1 , . . , 0) eigenvectors of AT A, AAT in V, U •
•
66
Chapter 1 Applied Linear Algebra
1.6
POSITIVE D E F I N I TE MAT R I C ES
This section focuses on the meaning of "positive definite." Those words apply to square symmetric matrices with especially nice properties. They are summarized at the end of the section, and I believe we need three basic facts in order to go forward:
1. 2. 3.
K = ATA i s symmetric and positive definite (or at least semidefinite) . If K1 and K2 are positive definite matrices then so is K1 + K2 . Every
All pivots and all eigenvalues of a positive definite matrix are positive.
The pivots and eigenvalues have been emphasized. But those don't give the best approach to facts 1 and 2. When we add K1 + K2 , it is not easy to follow the pivots or eigenvalues in the sum. When we multiply AT A (and later ATCA) , why can't the pivots be negative ? The key is in the energy �uTKu. We really need an energy-based definition of positive definiteness, from which facts 1 , 2 , 3 will be clear. Out of that definition will come the test for a function P(u) to have a minimum. Start with a point where all partial derivatives 8Pj8u 1 , 8Pj8u 2 , . . . , 8P/8un are zero. This point is a minimum (not a maximum or saddle point) if the matrix of second derivatives is positive definite. The discussion yields an algorithm that actually finds this minimum point. When P(u) is a quadratic function (involving only � Kii u� and KijUi Uj and fi ui ) that minimum has a neat and important form: The minimum of
P(u) = �uT Ku - uT f
is
Pmin = - 4 / T K - 1 f
when
Ku = f.
Examples and Energy-based Definition Three example matrices �K, B, M are displayed below, to show the difference between definite and semidefinite and indefinite. The off-diagonal entries in these examples get larger at each step. You will see how the "energy" goes from positive (for K) to possibly zero (for B) to possibly negative (for M) . Definite
-� � 1 -2 u� - u 1 u 2 + u�
[
]
Always positive
Semidefinite
B
=
[ -� -� ]
u� - 2u 1 u 2 + u�
Positive or zero
[ -31 31 ] I ndefinite
M=
-
u� - 6u 1 u2 + u�
Positive or negative
Below the three matrices you will see something extra. The matrices are multiplied on the left by the row vector u T = [ u 1 u 2 ] and on the right by the column vector u. The results u T ( � K) u and u T Bu and u T Mu are printed under the matrices.
With zeros off the diagonal, I is positive definite (pivots and eigenvalues all When the off-diagonals reach -!, the matrix ! K is still positive definite. At
1). -1
67
1 . 6 Positive Definite Matrices
we hit the semidefinite matrix B ( singular matrix ) . The matrix M with -3 off the diagonal is very indefinite ( pivots and eigenvalues of both signs ) . It is the size of those off-diagonal numbers - � , - 1 , - 3 that is important , not the minus signs. Quadratics These pure quadratics like ur - u 1 u 2 + u� contain only second degree terms. The simplest positive definite example would be ur + u�, coming from the identity matrix I. This is positive except at u 1 = u 2 = 0. Every pure quadratic function comes from a symmetric matrix. When the matrix is S, the function is u T Su. When S has an entry b on both sides of its main diagonal, those entries combine into 2b in the function. Here is the multiplication u T Su, when a typical 2 by 2 symmetric matrix S produces aui and 2b u 1 u 2 and cu�: Quadratic Function
(1)
a and c on the diagonal multiply ur and u�. The two b's multiply u 1 u 2 . The numbers a, b, c will decide whether uTSu is always positive ( except at u = 0) . This positivity of uT Su is the requirement for S to be a "positive definite matrix."
Notice how
Definition
The symmetric matrix S is positive definite when u T Su > 0 for every vector u except u = 0.
The graph of uT Su goes upward from zero. There is a minimum point at Figure 1 . 16a shows ui - u 1 u 2 + u�, from S = � K. Its graph is like a bowl.
u
=
0.
This definition makes it easy to see why the sum K1 + K2 stays positive definite We are adding positive energies so the sum is positive. We don't need to know the pivots or eigenvalues. The sum of uT K1 u and uT K2 u is uT(K1 + K2 )u. If the two pieces are positive whenever u i= 0, the sum is positive too. Short proof !
( Fact 2 above ) .
In the indefinite case, the graph of u T Mu goes up and down from the origin in Figure 1 . 16c. There is no minimum or maximum, and the surface has a "saddle point." If we take u 1 = 1 and u 2 = 1 then u T Mu = -4. If u 1 = 1 and u 2 = 10 then uTMu = +4 1 . The semidefinite matrix B has uTBu = (u 1 - u2 ) 2 . This is positive for most u, but it is zero along the line u 1 = u 2 .
Figure 1 . 16: Positive definite, semidefinite, and indefinite: Bowl, trough, and saddle.
68
Chapter 1 Applied Linear Algebra
Sums of Squares To confirm that M is indefinite, we found a vector with u T Mu > 0 and another vector with uT Mu < 0. The matrix K needs more thought . How do we show that uT Ku stays positive? We cannot substitute every ul > u2 and it would not be enough to test only a few vectors. We need an expression that is automatically positive, like uTu = u� + u�. The key is to write uT Ku as a sum of squares: ( three squares )
uT Ku = 2u� - 2u 1 u2 + 2u � = ui + (u 1 - u2 ) 2 + u �
The right side cannot be negative. It cannot be zero, except if u 1 = 0 and u 2 this sum of squares proves that K is a positive definite matrix.
(2) = 0.
So
two squares instead of three: uT Ku = 2u 21 - 2u 1 u2 + 2u22 = 2 ( u 1 - 21 u2 ) 2 + 23 u22 ( two squares ) (3) What I notice about this sum of squares is that the coefficients 2 and � are the pivots of K. And the number -� inside the first square is the multiplier € 2 1 , in K = LDLT: 2 � 1 -1 = LDLT . (4) Two squares K = - � ; = -i 1 The sum of three squares in (2) is connected to a factorization K = AT A, in which A has three rows instead of two. The three rows give the squares in u� + (u 2 - u 1 ) 2 + u�: 2 -1 = 1 -1 0 = AT A . (5) Three squares K = -1 2 0 1 -1 0 -1 Probably there could be a factorization K = AT A with four squares in the sum and four rows in the matrix A. What happens if there is only one square in the sum ? Semidefinite uT Bu = u� - 2u 1 u 2 + u� = (u 1 - u 2 ) 2 ( only one square ) . (6) We could achieve the same result with
[
[
][
[
]
][
]
] [ -� � l
] [
The right side can never be negative. But that single term ( u 1 - u 2 ) 2 could be zero ! A sum of less than n squares will mean that an n by n matrix is only semidefinite.
uT Mu is a difference of squares ( mixed signs ) : uT Mu = ui - 6u 1 u2 + u� = (u 1 - 3u2 ) 2 - 8u� ( square minus square ) . (7) Again the pivots 1 and -8 multiply the squares. Inside is the number € 2 1 = -3 from elimination. The difference of squares is coming from M = LDLT, but the diagonal pivot matrix D is no longer all positive and M is indefinite: 1 -3 = 1 1 -3 = LDLT . (8) 1 I ndefinite M = -3 1 -3 1 -8 1 The indefinite example
[
] [
The next page moves to the matrix form
][
][
]
uT AT Au for a sum of squares.
69
1.6 Positive Definite Matrices
Positive Definiteness from AT A, AT CA, LDLT , and QAQT Now comes the key point. Those 2 by 2 examples suggest what happens for n by positive definite matrices. K might come as AT times A, for some rectangular matrix A. Or elimination factors K into LDLT and D > 0 gives positive definiteness. Eigenvalues and eigenvectors factor K into Q A Q T , and the eigenvalue test is A > 0. n
The matrix theory only needs a few sentences. In linear algebra, "simple is good."
=ATA
K
is symmetric positive definite if and only if
A
has independent columns .
This means that the only sol ution to Au = 0 is the zero vector u = 0. If there are nonzero sol utions to Au = 0, then AT A is positive semidefinite. We now show that
uT Ku 2:: 0, when K is AT A.
Basic trick for
AT
Just move the parentheses!
(9)
A
This is the length squared of Au. So
AT A is at least semidefinite. When A has independent columns, Au = 0 only happens when u = 0. The only vector in the nullspace is the zero vector. For all other vectors u T (AT A )u = I Au 11 2 is positive. So ATA is positive definite, using the energy-based definition uTKu > 0. Example 1 If A has more col umns than rows, then those col u m ns are not independent. With dependent col umns AT A is only semidefinite. This exa mple ( the free-free matrix B3 ) has three col umns and two rows in A, so dependent col umns: -1 0 1 -1 0 -1 1 0 3 columns of add to zero _1 _ 1 0 -1 1 - 01 _ 21 _ 11 3 columns of add to zero 0 1
ATA A
[
l[
]
_
[
l
·
This is the semidefinite case. If Au = 0 then certainly AT Au = 0. The rank of AT A always equals the rank of A ( its rank here is only r = 2) . The energy uT Bu is (u2 - u 1 ) 2 + (u3 - u2 ) 2 , with only two squares but n = 3. It is a short step from AT A to positive definiteness of the triple products ATCA and LDLT and Q A Q T . The middle matrices C and D and A are easily included. The matrix K = ATCA is symmetric positive definite, provided A has independent
col umns and the middle matrix C is symmetric positive definite. To check positive energy in Same trick
ATCA, use the same idea of moving the parentheses: (10 )
u is not zero then Au is not zero ( because A has independent columns ) . Then (Au)TC(Au) is positive because C is positive definite. So uT Ku > 0: positive definite. C = aT in the middle could be the pivot matrix D or the eigenvalue matrix A.
If
70
Chapter 1 Applied Linear Algebra
If a symmetric K has a full set of positive pivots, it is positive definite.
Reason: The diagonal pivot matrix D in LDLT is positive definite. £T has indepen dent columns ( 1 's on the diagonal and invertible ) . This is the special case of ATCA with C = D and A = LT. Pivots in D multiply squares in LTu to give uT Ku: (1 1) The pivots are those factors
a
and
c -
�.
This is called "completing the square."
If a symmetric K has all positive eigenvalues in A, it is positive definite.
Reason: Use K = QAQT. The diagonal eigenvalue matrix A is positive definite. The orthogonal matrix is invertible (Q - 1 is QT) . Then the triple product QAQT is positive definite. The eigenvalues in A multiply the squares in QT u: ( 12 ) The eigenvalues are
3 and 1 .
The unit eigenvectors are ( 1 , - 1 ) / v'2 and ( 1 , 1 ) / v'2 .
If there were negative pivots or negative eigenvalues, we would have a difference of squares. The matrix would be indefinite. Since Ku = >. u leads to u T Ku = >. uT u, positive energy u T Ku requires positive eigenvalues >.. Review and Summary A symmetric matrix K is positive definite if it passes any of these five tests ( then it passes them all ) . I will apply each test to the 3 by 3 second difference matrix K = toeplitz( [2 - 1 0] ) . 1.
All pivots are positive
2.
Upper left determinants > 0
3.
All eigenvalues are positive
4. 5.
uT Ku > 0 if u -=/= 0 K = AT A, indep. columns
2, 4
K = LDLT with pivots 2, � ' � K has determinants 3, K = QAQT with >. = 2, 2 + v'2, 2 - v'2 uT Ku = 2(u l - �u 2 ) 2 + � (u2 - �u3 ) 2 + �u3 2 A can be the Cholesky factor choi (K)
That Cholesky factorization chooses the square upper triangular A = v75£T. The command chol will fail unless K is positive definite, with positive pivots: Square
AT A = K A = choi (K)
K=
[ 1.4142 1.2247 l [1.4142 - 0 . 7071
-0.8165 1 . 1547
-0.7071 1 . 2247 -0.8 165 1 . 1547
l
1 . 6 Positive Definite Matrices
M inimum P roblems in
n
71
Dimensions
Minimum problems appear everywhere in applied mathematics. Very often, � u T Ku is the "internal energy" in the system. This energy should be positive, so K is naturally positive definite. The subject of optimization deals with minimization, to produce the best design or the most efficient schedule at the lowest cost. But the cost function P( u) is not a pure quadratic uT Ku with minimum at 0. A key step moves the minimum away from the origin by including a linear term When K = K2 , the optimization problem is to minimize P(u) :
-uTJ.
�
Total energy P(u) = uT Ku - uT f = (u� - u 1 u 2 + u � ) - u d1 - u 2 f2 .
(13)
The partial derivatives (gradient of P) with respect to
u 1 and u2 must both be zero: 8Pj8u 1 = 2u 1 - u2 - !I = 0 (14) Calculus gives K u f 8Pj8u2 = -u 1 + 2u 2 - h = 0 In all cases the partial derivatives of P(u) are zero when Ku = f. This is truly a minimum point (the graph goes up) when K is positive definite. We substitute u = K- 1 f into P(u) to find the minimum value of P: =
P(u) is never below that value Pmin · For every P(u) the difference is � 0: P(u) - P(K - 1 f) = 4uT Ku - uT f - (-4fT K - 1 f) = 4 (u - K - 1 J)TK(u - K - 1 f) � 0 .
(16)
The last result is never negative, because it has the form � vT Kv . That result is zero only when the vector v = u - K - 1 f is zero (which means u = K - 1 f). So at every point except u = K - 1 f, the value P(u) is above the minimum value Pmin ·
Shifted bowl �;;::::;;7"'-:.___-
u2 Pmin = -4fTK - 1 f
72
Chapter 1 Applied Linear Algebra
Test for a Minimum: Positive Definite Second Derivatives Suppose P(u 1 , . . . , un ) is not a quadratic function. Then its derivatives won't be linear functions. But to minimize P( u) we still look for points where all the first derivatives (the partial derivatives) are zero:
1st derivative vector is gradient 8Pj8u
(17)
If those n first derivatives are all zero at the point u * = (ui , . . . , u�), how do we know whether P(u) has a minimum (not a maximum or saddle point) at u * ? To confirm a minimum we look at the second derivatives. Remember the rule for an ordinary function y(x) at a point where dyldx = 0. This point is a minimum if d2 yldx 2 > 0. The graph curves upward. The n-dimensional version of d2 yldx2 is the symmetric "Hessian" matrix H of second derivatives:
(18)
2"d derivative matrix
The Taylor series for P(u), when u is near u * , starts with these three terms (constant , linear from gradient , and quadratic from Hessian) : Ta� I or senes
8P (u * ) + 1 (u * - u) T H(u * ) (u * - u) + P(u) = P(u * ) + (u * - u) T -2 8u
·
·
·
(1 9 )
Suppose the gradient vector {)PI au of the first derivatives is zero at u * , as in (17) . So the linear term is gone and the second derivatives are in control. If H is positive definite at u * , then (u * - u)T H(u * - u) carries the function upward as we leave u * . A positive definite H(u*) produces a minimum at u = u * .
Our quadratic functions were P ( u) = � uT Ku-u T f . The second derivative matrix was H = K, the same at every point . For non-quadratic functions, H changes from point to point , and we might have several local minima or local maxima. The decision depends on H at every point u * where the first derivatives are zero. Here is an example with one local minimum at (0, 0) , even though the overall minimum is - oo . The function includes a fourth power ut.
P(u) = 2ui + 3u� - ut has zero derivatives at (ui , u�) = (0, 0) . a2 P1 aui a2 P1 au 1 au 2 = 4 - 12ui o Second derivatives H = [)2 pI 8u2 8u 1 [)2 pI au� 0 6 At the point ( 0, 0 ) , H is certainly positive definite. So this is a local minimum. There are two other points where both first derivatives 4u 1 - 4u� and 6u2 are zero. Those points are u * = ( 1 , 0 ) and u * = ( - 1 , 0 ) . The second derivatives are -8 and 6 at both of those points, so H is indefinite. The graph of P(u) wil l look like a bowl around (0, 0) , but ( 1 , 0 ) and ( - 1 , 0 ) are saddle points. MATLAB could draw y = P(u 1 , u2 ) . Example 2
. .
[
] [
]
1 . 6 Positive Definite Matrices
73
N ewton's Method for Minimization This section may have seemed less "applied" than the rest of the book. Maybe so, but minimization is a problem with a million applications. And we need an algorithm to minimize P(u), especially when this function is not a quadratic. We have to expect an iterative method, starting from an initial guess u 0 and improving it to u 1 and u 2 ( approaching the true minimizer u * if the algorithm is successful ) .
The natural idea is to use the first and second derivatives of P( u) at the current point . Suppose we have reached u i with coordinates ui , . . . , u�. We need a rule to choose the next point ui + l . Close to ui , the function P(u) is approximated by cutting off the Taylor series, as in (19) . Newton will minimize PcutotT(u) .
Pcutoff (u) = P(u'). + (u - u'). T aaup + 21 (u - u'). T H(u - u') . ·
(20)
Pcutoff is a quadratic function. Instead of K it has the second derivative H. Both aPjau and H are evaluated at the current point u = ui ( this is the expensive part of the algorithm ) . The minimum of Pcutoff is the next guess u i +1 . . . Newton's method to solve 8 Pj8u = 0 H(u'. +1 - u'). = - aP (21) (u') au For quadratics, one step gives the minimizer u 1 = K - 1 f. Now aP;au and H are changing as we move to u 1 and ui and ui + 1. If u i exactly hits u * ( not too likely ) then aPjau will be zero. So ui + 1 - ui = 0 and we don't move away from perfection. Section 2.6 will return to this algorithm. We propose examples in the Problem Set below, and add one comment here. The full Newton step to u i + 1 may be too bold, when the true minimizer u * is far away. The terms we cut off could be too large. In that case we shorten the Newton step u i + 1 - ui , for safety, by a factor c < 1. P roblem Set 1 . 6
1
Express
uTTu as a combination of u�, u 1 u 2 , and u� for the free-fixed matrix
[
]
T = - 11 - 21 . Write the answer as a sum of two squares to prove positive definiteness.
2
uT Ku = 4u 1 2 + 16u 1 u 2 + 26u2 2 c h o i(K) = ..fi5LT. Express
as a sum of two squares. Then find
74
Chapter 1 Applied Linear Algebra
3
A produces the circulant second-difference matrix C = AT A: -1 -1 -1 A= 1 gives AT A = 2 -1 0 - 1 -1 2 How can you tell from A that C = AT A is only semidefinite ? Which vectors solve Au = 0 and therefore Cu = 0 ? Note that chol ( C ) will fail. Confirm that the circulant C = AT A above is semidefinite by the pivot test. Write uT Cu as a sum of two squares with the pivots as coefficients. ( The eigenvalues 0, 3, 3 give another proof that C is semidefinite. ) uTcu 2: 0 means that ui + u� + u� 2: u 1 u2 + u2 u3 + u3 u 1 for any u 1 , u2 , u3 . A
4
5
A different
u -n
l ::; Jui
Which u's give
+ u 2 u3 + u 3 u 1
equality ?
Check that
For what range of numbers
+ u� + u�
l
Ju� + u� + ui .
more unusual way to check this is by the Schwarz inequality
l u 1 u2
6
[ -�
l vTw l ::; l v l l w l :
u Tcu = 0 for those u .
K= [ � 1] ·
b is this matrix positive definite ?
There are two borderline values of b when K is only semidefinite. In those cases write u T Ku with only one square. Find the pivots if b = 5 .
7
Is
K = AT A or M = BT B positive definite ( independent columns in A or B) ?
We know that uT Mu = (Bu)T(Bu) = (u 1 + 4u 2 ) 2 + (2u 1 + 5 u 2 ) 2 + (3u 1 + 6u 2 ) 2 . Show how the three squares for uT Ku = (Au)T(Au) collapse into one square.
Problems 8-16 are about tests for positive definiteness.
8
9
Which of A 1 , A 2 , A 3 , A 4 has two positive eigenvalues ? Use the tests ac > b2 , don't compute the .A's. Find a vector u so that u T A 1 u < 0.
[
]
[
]
-2 1 10 A 2 -- -1 -2 - 5 A3 = 10 100 For which numbers b and c are these matrices positive definite ? A=
With the pivots in
[ � �]
and
D and multiplier in L,
factor each
A into LDLT.
a > 0 and
75
1 . 6 Positive Definite Matrices
y) = + + 3y2 f difference y) f f(x, y) = 2xy (0, 0) . S A ATA A= [� �] A = [ � � �] . 3 3 S [ x, x , x, ] S ] [ �;] = 4(x, - x , + x 3 2 S f = xTSx ? 3 3 X�-X1X2-X2X3) 3) . ff == 22 xx� ++ X�X� ++ X�-X1X2-X1X3-X2X (1c 1,d2 A 3 B3) A= [ c11 1c1 c11 ] AA-is1 positive definite then A- 1 is posiSecondtive proof definite. A-1 = ac 1 b2 [ -cb -b] uTAu 0. ] [4 � � 1 � 1 [u1 U2 U3] [u�:1] (u1, u2 , u3) = ( A-A -
10
Show that f(x, x 2 4xy does not have a minimum at (0, 0) even though it has positive coefficients. Write as a of squares and find a point (x, where is negative.
11
The function certainly has a saddle point and not a minimum at What symmetric matrix produces this f ? What are its eigenvalues ?
12
Test the columns of
to see if
will be positive definite in each case:
and
13
Find the
by
matrix
and
and its pivots, rank, eigenvalues, and determinant :
2 ) .
[
14
Which by symmetric matrices produce these functions is the first matrix positive definite but not the second one ? (a)
(b)
15
(
(
Why
�
For what numbers left determinants
and by
are and positive definite ? Test the three upper by 2, by of each matrix: and
16
If of
are positive because
The entries of
17
_
__
Best proof: The eigenvalues (only quick for 2 by 2) :
.
a
pass the determinant tests
.
A positive definite matrix cannot have a zero (or even worse, a negative number) on its diagonal. Show that this matrix fails to have > is not positive when
18
__
, , ).
A diagonal entry a11 of a symmetric matrix cannot be smaller than all the >.'s. If it were, then a11 I would have eigenvalues and would be positive definite. But a11 I has a zero on the main diagonal. __
76
Chapter 1 Applied Linear Algebra
19
If all >. > 0, show that uTKu > 0 for u #- 0, not just the eigenvectors x i . Write u as a combination of eigenvectors. Why are all "cross terms" xr Xj = 0 ?
20
Without multiplying A =
every
(a) the determinant of A (c) the eigenvectors of A
21
[ ���: - �;� :] [ � � ] [ ��� : �;� : ] _
. find
(b) the eigenvalues of A (d) a reason why A is symmetric positive definite.
For JI (x, y) = ix4 +x 2 y+y 2 and h(x, y) = (Hessian) matrices H1 and H2 :
x3 +xy - x find the second derivative
H1 is positive definite so h is concave up (= convex) . Find the minimum point of h and the saddle point of h (look where first derivatives are zero) . 22 The graph of z = x 2 + y 2 is a bowl opening upward. z = x2 - y2 The graph of z = -x 2 - y 2 is a bowl opening downward. What is a test on a, b, c for z = ax 2 + 2bxy + cy 2 to have a saddle at (0, 0) ?
The graph of
is a saddle.
23
Which values of c give a bowl and which give a saddle point for the graph of z = 4x 2 + 12xy + cy 2 ? Describe this graph at the borderline value of c.
24
Here is another way to work with the quadratic function
25
.
Check that
fK- 1Pminf, · f 8Pj8u u� + u� - c(u� + u�) 4 •
The last term - UT K - 1 always When u = __
P(u).
is
The other (long) term on the right side is this long term is zero so P = Pmin .
Find the first derivatives in = and the second derivatives in the matrix Start Newton's iteration (21) at u 0 = (1, 0) . H for P(u) = Which values of c give a next vector u 1 that is closer to the local minimum at u * (0, 0) ? Why is (0, 0) not a global minimum ?
=
26
Guess the smallest
27
If H and but N =
[� 1]
2, 2 block that makes [ c- l A ; A T -- ]
K are positive definite, explain why M =
[� �]
semidefinite.
is positive definite
is not. Connect the pivots and eigenvalues of
to the pivots and eigenvalues of choi(H) and choi(K) ?
H and K.
How is
choi(M)
M
and N
constructed from
1.6 Positive Definite Matrices
28
>.I = 1, >.2 = 2, >.3 = -1: Saddle point . [WI w2 u J [ - �1 0 - 011 ] [ w:2Il = w� w� - 2uwi 2uw2 . Put its unit eigenvectors inside the squares and >. = 1, 2, -1 outside: Verify w� w� - 2uwi 2uw2 = 1 ( )2 ) 2 -1( ) 2 . The first parentheses contain (WI -w 2 ) I from the eigenvector ( 1, -1, 0) I We are using QAQT instead of LDLT. Still two squares minus one square. This "KKT matrix" has eigenvalues
�
+
+
+
__
V2
29
77
+ 2(
+
__
__
..;2.
(Important) Find the three pivots of that indefinite KKT matrix. Verify that the product of pivots equals the product of eigenvalues (this also equals the determinant) . Now put the pivots outside the squares:
N U M E R I CA L L I N EA R A LG E B RA: LU, QR, SVD
1.7
Applied mathematics starts from a problem and builds an equation to describe it. Scientific computing aims to solve that equation. Numerical linear algebra displays this process in its clearest form, with matrix models:
"build up, break down" Ku = f
or
Kx =
>.x
or
Mu" + Ku = O .
Often the computations break K into simpler pieces. The properties of K are crucial: or not , or not, or not , or not. Numerical linear algebra can deal with a large class of matrices in a uniform way, without adj usting to every detail of the model. The algorithm becomes clearest when we see it as a factorization into triangular matrices or orthogonal matrices or very sparse matrices. We will summarize those factorizations quickly, for future use.
banded
symmetric
sparse
well conditioned
This chapter began with the special matrices K, T, B, C and their properties. We needed something to work with! Now we pull together the factorizations you need for more general matrices. They lead to and of any A. In my experience, applications of rectangular matrices constantly lead to A T and AT A.
"norms" "condition numbers"
Three Essential Factorizations I will use the neutral letter A for the matrix we start with. It may be rectangular. If A has independent columns, then K = A T A is symmetric positive definite. Sometimes we operate directly with A ( better conditioned and more sparse ) and sometimes with K ( symmetric and more beautiful ) . Here are the three essential factorizations, A = LU and A = QR and A = UEV T : ( 1 ) Elimination reduces A to U by row operations using multipliers in L:
A
lower triangular upper triangular Q: orthonormal columns upper triangular orthonormal columns singular values orthonormal rows left and right singular vectors SA
=
LU
times
=
( 2 ) Orthogonalization changes the columns of A to orthonormal columns in
A
=
QR =
times
(3) Singular Value Decomposition sees every A as ( rotation ) ( stretch ) ( rotation ) :
A
=
U:EV T
=
X
X
As soon as I see that last line, I think of more to say. In the SVD , the orthonormal columns in U and V are the ( eigenvectors of AA T and T A A ) . Then AV = UE is like the usual diagonalization AS = by eigenvectors, but with two matrices U and V. We only have U = V when AA T = AT A.
LU, QR, SVD 79
1.7 N u merical Linear Algebra :
For a positive definite matrix K, everything comes together: U is Q and VT is QT. The diagonal matrix E is A (singular values are eigenvalues) . Then K = QAQT. The columns of Q are the principal axes = eigenvectors = singular vectors. Matrices with orthonormal columns play a central role in computations. Start there.
Orthogona l M atrices The vectors
J
q qj
q1 , q2 , . . . , qn are
=
orthonormal
if all their inner products are
q,Tq,. 1
(normalization to unit vectors)
=
0 if i -.:J j (orthogonality)
[- � -] [�
0 or 1 :
]
(1)
Those dot products are beautifully summarized by the matrix multiplication QTQ Orthonormal q's
If Q is
square,
QT Q =
1 �n I I
q - qn -
[� � �] o
=
1
I
.
= I: (2)
o
QT Q = I tells us immediately that The inverse of an orthogonal matrix is its transpose: Q - 1 = QT.
o
Multiplying a vector by Q doesn't change its length:
we call it an orthogonal matrix.
IIQx ll = llxll · 11 Qx ll 2 = xTQTQx = xTx ll x ll 2 . =
Length (soon called norm) is preserved because This doesn't require a square matrix: QTQ = I for rectangular matrices too. But a two-sided inverse Q - 1 = QT (so that QQT is also I) does require that Q is square. Here are three quick examples of Q: permutations, rotations, reflections.
P has the same rows as I, but probably in a different order. P has a single 1 in every row and in every col u m n . M u ltiplying Px puts the components of x in that row order. Reordering doesn't change the length . All n by n permutation matrices (there are n! of them) have p- 1 = p T _ The 1's in p T hit the 1's in P to give p T P = I Here is a 3 by 3 example of Px: Example 1 Every permutation matrix
.
0�
0
Example 2 Rotation changes the direction of vectors. It doesn't change lengths. Every vector just turns: Rotation matrix in the 1-3 plane
Q=
[
co�
sin O
0
�
-sn
cos O
l
Every orthogonal matrix Q with determinant 1 is a product of plane rotations.
80
Chapter 1 Applied Linear Algebra
Example 3 The reflection
H takes every v to its image Hv on the other side of a plane mirror. The unit vector u ( perpendicular to the mirror ) is reversed into Hu = -u:
[
H = I 2uu T =
Reflection matrix u = ( cos (), 0, sin 0)
-
0 - sin 2() 1 0 - sin 2() 0 cos 2()
-
cos 2()
0
l
(4)
This "Householder reflection" has determinant 1 Both rotations and reflections have orthonormal col u m ns, and (I - 2uuT)u = u - 2u guarantees that Hu = -u. Modern orthogonalization uses reflections to create the Q in A = QR. -
.
Orthogona lization A = QR We are given an m by n matrix A with linearly independent columns a 1 , . . . , an . Its rank is n . Those n columns are a basis for the column space of A, but not necessarily a good basis. All computations are improved by switching from the a, to orthonormal vectors q1 , . . . , qn . There are two important ways to go from A to Q.
1.
The Gram-Schmidt algorithm gives a simple construction of the q's from the a's. First, ql is the unit vector ad l l ai i i - In reverse, a 1 = ruq1 with rn = l l a& Second, a2 q1 (the Gram-Schmidt idea) . That vector B = a 2 - (q!a 2 )q1 is orthogonal to q1 . Normalize B to q2 = B/ IIB II · At every step, subtract from a k its components in the settled directions q1 , . . . , qk _1 , and normalize to find the next unit vector qk .
subtract from its component in the direction
Gram-Schmidt ( m by n ) ( n by 2.
n
)
(5)
The Householder algorithm uses reflection matrices I - 2uuT. Column by column, it produces zeros in R. In this method, Q is square and R is rectangular: Householder qr ( A ) ( m by m ) ( m by n )
(6)
The vector q3 comes for free! It is orthogonal to a 1 , a 2 and also to q1 , q2. This method is MATLAB's choice for qr because it is more stable than Gram-Schmidt and gives extra information. Since q3 multiplies the zero row, it has no effect on A = QR. Use q r (A , 0) to return to the "economy size" in (5) . Section 2.3 will give full explanations and example codes for both methods. Most linear algebra courses emphasize Gram-Schmidt , which gives an orthonormal basis ql , . . . , qr for the column space of A. Householder is now the method of choice, completing to an orthonormal basis q 1 , . . . , qm for the whole space Rm .
1.7 N u merical Linear Algebra :
LU, QR,
SVD
81
Numerically, the great virtue o f Q i s its stability. When you multiply by Q, overflow and underflow will not happen. All formulas involving ATA become simpler, since QT Q = I. A square system Q = will be because = and an error produces an error o f the
Llb l xl l bl Q( x Llx) b Llb +
=
+
gives
x b Llx persame fectlysicondi ze: tioned, Q( Llx ) Llb l llx l l llb l · =
=
and
(7)
Singular Value Decomposition This section now concentrates on the SVD, which reaches a diagonal matrix I:. Since diagonalization involves eigenvalues, the matrices from A = QR will not do the job. Most square matrices A are diagonalized by their eigenvectors . . . , Xn . If x is a combination + + Cn X n , then A multiplies each Xi by >. i .
x1, c1x1 Ax SAS 1x. Usually, the eigenvector matrix S is not orthogonal. A A two different Q 's. U V, I:? singular values ATA. ·
·
·
In matrix language this is = Eigenvectors only meet at right angles when is special (for example symmetric) . If we want to diagonalize an ordinary by orthogonal matrices, we need They are generally called and so A = U:EV T .
What is this diagonal matrix It now contains ai instead of eigenvalues >. i . To understand those ai , the key is always the same: Look at Find V and :E leaves This is exactly like K = QAQT, The diagonal matrix contains the numbers al , and those are the positive eigenvalues of The orthonormal eigenvectors of AT A are in V. =
applies to K =UTUATA. I ATV(L:TL:)VT. I;TI; A. AV UL:. AAT. v1, . . . , Vr Ur svd(A, 0) Removing
but it
= In the end we want S o we must choose U i = Avdui. These ui are orthonormal eigenvectors of At this point we have the "reduced" SVD , with and u 1 , , as perfect bases for the column space and row space of A. The rank r is the dimension of these spaces, and gives this form: .
.
•
A Reduced SVD from ui = A vi/ Ui
=
u,[ [ J
Um x r L:r x r V:.� n U l . . . Ur
1
vT T
Vr
l
(9)
To complete the v 's, add any orthonormal basis Vr + l , . . . , Vn for the nullspace of A . To complete the u's, add any orthonormal basis Ur + l , . . . , Um for the nullspace of AT. To complete I: to an m by n matrix, add zeros for svd(A) and the unreduced form:
Normally we number the u i , (Ji , Vi so that (J l 2: (}2 2: · · · 2: (Jr > 0. Then the SVD has the wonderful property of splitting any matrix A into rank-one pieces ordered by their size:
A = u 1 (}1 v{
Columns times rows
(largest
(J l ) + · · · + Ur (Jr V; (smallest (Jr ) (11)
The first piece u 1 (} 1 v[ i s described by only m + n + 1 numbers, not mn. Often a few pieces contain almost all the information in A (in a stable form) . This isn't a fast method for image compression because computing the SVD involves eigenvalues. (Filters are faster. ) The SVD is the centerpiece of matrix approximation. The right and left singular vectors v, and u, are the Karhunen-Loeve bases in engineering. A symmetric positive definite K has v, = u i : one basis. I think of the SVD as the final step in the Fundamental Theorem of Linear Algebra. First come the of the four subspaces. Then their Then the
di m ensi o ns ort h ogonal i t y . bases orthonormal u1 , , Um and v1 , . . . , Vn which diagonalize A. = (J3V3 AvJ = (JJUJ r rr ATu3 ATu3 0 AvJ = 0 .
•
.
for j ::=::; for j >
SVD
-
-
-
for j ::=::; for j >
=
-
-
-
-
r
(12)
-
u
..-------....
�
v
Figure
/
/
1 . 18: U and V are rotations and reflections. E stretches by (} 1 , . . . , (Jr .
1.7 N u merical Linear Algebra : LU, QR,
SVD 83
ui = Avd(ji are orthonormal eigenvectors of AAT. Start from ATAvi = (ji 2 W Multiply by v{: v'[ AT Avi = (ji 2 v'[ vi says that IIAvi ll = (ji so ll ui ll = 1 Multiply by vJ: vJ AT Avi = (ji 2 vJvi says that (Avj) · (Avi ) = 0 so uJui = 0 says that AA T u i ui 2 u i Multiply by A: AAT Avi = (ji 2 Avi
These
=
Here is a homemade code to create the SVD . It follows the steps above, based primarily on eig(A ' * A) . The faster and more stable codes in LAPACK work directly with A. Ultimately, stability may require that very small singular values are replaced by (j = 0. The SVD identifies the dangers in A x = b ( near 0 in A, very large in x ) .
A, output orthogonal U, V and diagonal sigma with A=U *sigma*V' [m , n ] =size ( A ) ; r=rank ( A ) ; [V,sq uares] =eig ( A' *A ) ; % n by n matrices % r by r , singular values > 0 on diagonal sing=sqrt ( sq uares ( 1 : r, 1 : r )) ; sigma=zeros ( m , n ) ; sigma ( l : r, l : r ) =sing; % m by n singular value matrix u=A*V ( : , l : r ) * inv ( sing ) ; % first r columns of U ( singular vectors ) [ U , R] =qr ( u ) ; U ( : , l : r ) = u ; % qr command completes u t o an m by m U % test for zero m by n matrix ( could print its norm ) A-U*sigma*V' ; % input
Example 4 Find the SVD for the singu lar matrix Solution
AT A =
A=
[ � �] .
A has rank one, so there is one singular value. First comes AT A:
[�� ��] has >. = 100 a nd 0, with eigenvectors [v1
The singular value is u2 = (-7, 1)/ V50 :
v2 ] =
� [� - �]
.
(7 1 = v'I05 = 10. Then u 1 = Av l /10 = (1, 7)/V50. Add in
OJ [ 1]
1 1 1 -7 10 _ A = U L; VT = _ V50 7 1 0 0 -12 - 1 1
[1 ] [
.
Example 5 Find the SVD of the
n + 1 by n backward difference matrix b._. Solution With diagonal l 's a n d su bdiagonal - l 's in b. _ , the products S:b. _ a n d � - s: are Kn and Bn+l · When (n + 1)h = 1r, Kn has eigenvalues >. = (7 2 = 2 - 2 cos kh and eigenvectors vk = ( sin kh, . . . , sin nkh) . Bn+l has the same eigenvalues ( plus >. n+l = 0) and its eigenvectors are u k = ( cos �kh, . . . , cos(n + 4)kh) in U. Those eigenvectors vk and u k fill the DST and DCT matrices. Normalized to unit length, these are the colu m ns of V and U. The SVD is b. _ = (DCT) L; (DST) . The equation b. _ v k = (jk Uk says that the first differences of sine vectors are cosine vectors. Section 1 . 8 will apply the SVD to Principal Component Analysis and to Model Reduction. The goal is to find a small part of the data and the model ( starting with u 1 and vi) that carries the important information.
84
Chapter 1 Applied Linear Algebra
The Pseudoinverse By choosing good bases, A multiplies vi in the row space to give a,u, in the column space. A - 1 must do the opposite! If Av = au then A - 1 u = v j a . The singular values of A - 1 are 1/ a , just as the eigenvalues of A - 1 are 1/>.. The bases are reversed. The u's are in the row space of A - 1 , the v 's are in the column space. Until this moment we would have added "if A- 1 Now we don't. A matrix that multiplies u, to produce v, j ai exist . It is the pseudoinverse A+ = pinv(A) .
exists."
does
Pseudoinverse A +
=
V� + u T A + u, = _.: for i :::; r and A + u, = 0 for > v a,
i r.
(13)
The vectors u 1 , . . . , Ur in the column space of A go back to the row space. The other vectors Ur + l , . . . , Urn are sent to zero. When we know what happens to each basis vector u i , we know A+ . The pseudoinverse has the same rank r as A. In the pseudoinverse E+ of the diagonal matrix E, each a is replaced by a- 1 . The product E+E is as near to the identity as we can get. So are AA+ and A+ A:
AA+ = projection matrix onto the column space of A A+ A = projection matrix onto the row space of A Example 6
Find the pseudoinverse A+ of the same rank one matrix A =
[ ]
[� �] .
Solution Since A has a 1 = 10, the pseudoinverse A+ = pinv(A) has 1/10. 1 1 1 1 1/10 1 7 _ 1 7 . _ A+ = VE+ uT = _..!._ 1 = 1 1 0 0 V50 - 7 100 1 7 J2
[ ][
OJ
[ ]
The pseudoinverse of a rank-one matrix A = auv T is A+ = vuT j a, also rank-one.
Always A+b is in the row space of A (a combination of the basis u 1 , . . . , ur ) · With n > m, Ax = b is solvable when b is in the column space of A. Then A+b is the shortest solution because it has no nullspace component , while A\b is a different "sparse solution" with n - m zero components.
Condition N u mbers and Norms
condition number
The of a positive definite matrix is c(K) = >.max/ A m in · This ratio measures the "sensitivity" of the linear system Ku = f. Suppose f changes by b.. f because of roundoff or measurement error. Our goal is to estimate b.. u (the change in the solution) . If we are serious about scientific computing, we have to control errors. Subtract K u = f from K(u + b.. u ) = f + b.. f . The error equation is K( b.. u ) = b.. f . Since K is positive definite, A m in gives a reliable bound on b..u : Error bound
K(b.. u ) = b.. f means b.. u = K- 1 ( b.. f ) . Then l l �u l l :::;
ll b.. f ll ( 14 ) A m in (K)
1 . 7 N u merical Linear Algebra :
LU, QR, SVD 85
The top eigenvalue of K- 1 is 1/.X m in (K) . Then f::J. u is largest in the direction of that eigenvector. The eigenvalue A m in indicates how close K is to a singular matrix ( but eigenvalues are not reliable for an unsymmetric matrix A) . That single number A m i n has two serious drawbacks in measuring the of K u = f or Ax = b.
sensitivity
First, if we multiply K by 1000, then u and f::J.. u are divided by 1000. That rescaling ( to make K less singular and A m i n larger ) cannot change the reality of the problem. The relative error I I !::J.. u l l / llull stays the same, since 1000/ 1000 = 1 . I t i s the relative changes in u and f that we should compare. Here is the key for positive definite K: Dividing II !::J.. u ll ::::;
II !::J.. f ll by !lull A m i n (K)
> _
ll f::J.. u l l Amax (K) l l t::J.. / 1 1 11/11 . gives Amax (K) M ::::; A m in (K) m ·
In words: f::J.. u is largest when l::J.. f is an eigenvector for A m in · The true solution u is when f is an eigenvector for A max· The ratio A max/ A m in produces the condition number c(K) , the maximum "blowup factor" in the relative error.
smallest
Condition number for positive definite K
c(K) =
Amax(K) A m in (K)
When A is not symmetric, the inequality II Ax ll ::::; Amax (A) II x l l can be false ( see Figure 1 . 19 ) . Other vectors can blow up more than eigenvectors. A triangular matrix with 1 's on the diagonal might look perfectly conditioned, since Amax=A m in=l . We need a norm I I A I I to measure the size of every A, and Amax won't work.
DEFINITIONS The norm I I A I I is the maximum of the ratio I I Ax l l / l l x ll · The condition number of A is I I A II times I I A - 1 11 ·
II Ax ll Norm II A I I = max 0
#
A= ATA =
[� n [� �]
det ATA = 1
llxll
Condition number c(A) = II A I I II A - 1 1 1
II A II =
1
+2
( 15)
v'5
I I A II 2 = Amax (AT A) � 2.6 1/ II A- 1 11 2 = .X m in (AT A) � 1/2.6 c(A) = II A II II A - 1 11 � 2 . 6
ellipse of all Ax Figure 1 . 19: The norms of A and A- 1 come from the longest and shortest Ax.
86
Chapter 1 Applied Linear Algebra
I I Ax l l / l l x l l i s never larger than I I A I I (its maximum) , s o always II Ax ll all matrices and vectors, the number II A II meets these requirements: I I Ax ll
::=::;
II A II I I x l l
and
IIABII
::=::;
IIAII IIBII
and
IIA + Bll
::=::;
::=::;
II A II II x l l - For
II AII + I I B I I . (16)
The norm of 1000A will be lOOO II AI I · But lOOOA has the same condition number as A. For a positive definite matrix, the largest eigenvalue is the norm: II K I I = >- max(K) . Reason: The orthogonal matrices in K = QAQT leave lengths unchanged. So II KII = I I A II = >- m ax· Similarly I I K- 1 11 = 1/>. m in (K) . Then c(K) = Amax/A m in is correct. A very unsymmetric example has >- max = 0, but the norm is II A II = 2 : Ax =
[� �] [�]=[�]
2 1"
II Ax il llxll
and the ratio is
This unsymmetric A leads to the symmetric AT A = [ g � J . The largest eigenvalue is ar = 4. I I A I I = 2 = largest singular value. This singular value J>.m ax (AT A) is generally larger than Amax(A) . Here is the great formula for II A II 2 all on one line:
Its square root is the norm:
(17)
Norm
The norm of A- 1 is 1/am i n , generally larger than 1/>. m in · The product is c(A) : amax c(A) = II A I I II A- 1 11 = Condition number . (18) O"m in
nearest
Here is one comment: am in tells us the distance from an invertible A to the When O" m i n changes to zero inside E, it is multiplied by U and V T (orthogonal, preserving norms) . So the norm of that smallest change in A is O" m in ·
singular matrix.
Example 7 For this 2 by 2 matrix A, the inverse j ust changes 7 to -7. Notice that 72 + 1 2 = 50. The condition n u m ber c(A) = II A II II A- 1 11 is at least v'55 J55 = 50:
Ax = A- 1 x =
[� �] [�] [ � -� ] [ � ]
Ax il has II ll x ll A- 1 x l l has II ll x ll
v'55
1
So II A II
v'55
?: v5o
1
Suppose we intend to solve Ax = b = [ I ] . The �olution is x = [ � ] . Move th � right side by b.. b = [ .� ] . Then x moves by b.. x = [ -:-i7 ] , smce A(D.x) = .6-b. The relat1ve change in x is 50 times the relative change in b:
ll b.. x l l = ( l ) vSo llxll ·
is 50 times greater than
I I D- bll ll bll
.1
J55 "
1.7 Numerical Linear Algebra :
LU, QR, SVD
1 , 2, -1 matrix are >. = 2 - 2 cos � Then k = 1 = n give A m i n and >. max · The -condition number of Kn grows like n2:
Example 8 The eigenvalues of the
and
k
87
l .
n
is nearly 2 - 2 cos 1r 4, at the top of Figure 1 . 13. The smallest eigenvalue uses cos (} � 1 - � (} from calcu lus, which is the same as 2 - 2 cos (} � (} : .
>. max
=
2
2 = ( )2 n
1
A rough rule for Ax b is that the computer loses about log c decimals to roundoff error. MATLAB gives a warning when the condition number is large is
=
(c
not calculated exactly, the eigenvalues of would take too long ) . It is normal for to be of order 1/(.6.x) 2 in approximating a second-order differential equation, agreeing with in (19). Fourth order problems have � Cj(.6.x) 4 .
ATA
c(K)
n2
Amax / A m i n
Row Exchanges in P A
=
LU
Our problems might be ill conditioned or well conditioned. We can't necessarily control but we don't want to make the condition worse by a bad algorithm. Since elimination is the most frequently used algorithm in scientific computing, a lot of effort has been concentrated on doing it right. Often we reorder the rows of A. The main point is that To find the numbers that multiply rows, we divide by the pivots. Small pivots mean large multipliers in Then ( and probably are more ill-conditioned than The simplest cure is to exchange rows by P, bringing the largest possible entry up into the pivot. The command l u does this for [ 1 2; 3 3 ] . The first pivot changes from 1 to 3. Partial pivoting avoids multipliers in larger
c(A),
L
than
1:
small pivots are dangerous. U) A. (A) "partial pivoting" A =
L.
L
PA = [ i � ] = L = [� � ] [ � i] = LU The product of pivots is - det A = +3 since P exchanged the rows of A. positive definite matrix K has no need for row exchanges. Its factoriza tion into K = LDLT can be rewritten as K = L..fi5..fi5LT ( named after Cholesky ) . In this form we are seeing K = AT A with A = VJ5L T . Then we know from (17) that Amax (K) = I K I = a�ax (A) and Am i n (K) = a� i n (A). Elimination to A = choi ( K) does absolutely no harm to the condition number of a positive definite K = AT A: (K) = ( amax(A) ) 2 = (c(A))2 • (20) c(K) = Amax A = choi ( K ) A m i n (K) am i n (A) Usually elimination into PA = LU makes c(L )c(U) larger than the original c(A). That price is often remarkably low-a fact that we don't fully understand. [P, L, U] = l u { A ) A
88
Chapter
1
Applied Linear Algebra
The next chapters build models for important applications. Discrete problems lead to matrices A and AT and AT A in Chapter 2. A differential equation produces many discrete equations, as we choose finite differences or finite elements or spectral methods or a Fourier transform-or any other option in scientific computing. All these options replace calculus, one way or another, by linear algebra. P roblem Set 1 . 7
Problems 1-5 are about orthogonal matrices with Q T Q
1
= I.
Are these pairs of vectors orthonormal or only orthogonal or only independent? (b)
[: � ] and [- : � ]
(c)
[ csm?s ()() ] and [- cossin ()() ] .
Change the second vector when necessary to produce orthonormal vectors. 2
Give an example of each of the following: (a) A matrix Q that has orthonormal columns but QQT -=/= I. (b) Two orthogonal vectors that are not linearly independent. (c) An orthonormal basis for R4 , where every component is � or - � .
3
If Q 1 and Q 2 are orthogonal matrices, show that their product orthogonal matrix. (Use QTQ = I . )
Q 1 Q 2 is also an
4
Orthonormal vectors are automatically linearly independent. Two proofs:
5
(a) Vector proof: When c 1 q1 + c2 q2 + c3 q3 = 0, what dot product leads to c 1 = 0? Similarly c2 = 0 and c3 = 0. Thus the q's are independent. (b) Matrix proof: Show that Qx = 0 leads to x = 0. Since Q may be rectan gular, you can use QT but not Q - 1 . If a 1 , a2 , a3 is a basis for R3 , any vector b can be written as or (a) Suppose the a's are orthonormal. Show that x 1 = aJb. (b) Suppose the a's are orthogonal. Show that x 1 = aJb/aJa 1 • (c) If the a's are independent, x 1 is the first component of
__
times b.
1 . 7 N u merical Li near Algebra : LU,
QR, SVD 89
Problems 6-14 and 31 are about norms and condition numbers.
6
Figure 1 . 18 displays any matrix A as rotation times stretching times rotation: A = U� VT =
[ csm�s aa
- sin a cos a
] [ u1 u ] [ - csm�s ()() 2
sin () cos ()
]
(21)
The count of four parameters a, u 1 , u2 , () agrees with the count of four entries an , a 1 2 , a2 1 , a22 · When A is symmetric and a 1 2 = a2 1 , the count drops to three because a = () and we only need one Q. The determinant of A in (21) is u 1 u2 . For det A < 0, add a reflection. In Figure 1 . 19, verify >.m a x ( AT A) = 4 (3 + v's) and its square root I I A I I = 4 ( 1 + v's) .
7
Find by hand the norms >.max and condition numbers A max / A m i n of these posi tive definite matrices:
8
Compute the norms and condition numbers from the square roots of >. (AT A) :
[- � � ] . 9
Explain these two inequalities from the definitions of the norms I I A II and l i B I I : II ABx ll ::; II A I I II Bx ll ::; I I A I I II B I I II x l l · From the ratio that gives II AB II , deduce that I I AB II ::; II A II I I B II · This fact is the key to using matrix norms.
10
Use II AB I I ::; II A II II B I I to prove that the condition number of any matrix A is at least 1 . Show that an orthogonal Q has Q) = 1 .
11
If >. is any eigenvalue of A , explain why 1 >. 1 ::; II A I I · Start from Ax = >.x.
12
The p(A) = l >.m a x l is the largest absolute value of the eigen values. Show with 2 by 2 examples that p(A + B) ::; p(A) + p(B) and p(AB) ::; p(A)p(B) can both be The spectral radius is not acceptable as a norm.
c(
"spectral radius"
false.
13 14
Estimate the condition number of the ill-conditioned matrix A = [ � The "€ 1 norm" and the "€00 norm" of x = (x 1 , . . . , x n ) are
1
t . o 01
Compute the norms l l x l l and llx ll 1 and llx ll oo of these two vectors in R5: X = ( 1 , 1 , 1 , 1 , 1)
X = ( . 1 , .7, .3, .4, .5).
]
.
90
Chapter 1 Applied Linear Algebra
Problems 1 5-22 are about the Singular Value Decomposition.
15
Suppose A = UL;VT and a vector x is a combination c1v1 + + CnVn of the columns of V. Then Ax is what combination of the columns u 1 , . . . , Un of U?
16
Compute AT A and AAT and their eigenvalues O"r , 0. Then complete the SVD:
17
Find the eigenvalues and unit eigenvectors of AT A and AAT for the Fibonacci matrix, and construct its SVD :
18
Compute AT A and AAT and their eigenvalues and unit eigenvectors for
·
A= Multiply the three matrices
[ 01
1 0 1 1
·
·
].
UL;VT to recover A.
19
Explain how the SVD expresses the matrix A as the sum of r rank one matrices:
20
Suppose u 1 , . . . , Un and v1 , . . . , V n are orthonormal bases for Rn . Which matrix transforms each Vj into Uj to give Av1 = u 1 , . . . , A vn = un ? What are the O"'s?
21
22
Suppose A is invertible (with 0"1 > 0"2 > 0) . Change A by as small a matrix as possible to produce a singular matrix A0 . Hint: U and V do not change:
(a) If A changes to 4A, what is the change in the SVD? (b) What is the SVD for AT and for A- 1 ? (c) Why doesn't the SVD for A + I just use E + I?
1.7 Numerical Linear Algebra :
LU, QR, SVD 91
Problems 23-27 are about A = LU and K = LDLT and A = QR.
23
For K = [ � � ] , why does lu (K) not give factors with K = LU? Which pivots are chosen instead of 1 and 1? Try A = choi (K) to find the factor A = L.Ji5 with no row exchange.
24
What multiple of a = [ } ] should be subtracted from b = B orthogonal to a? Sketch a figure to show a, b, and B.
25
Complete the Gram-Schmidt process in Problem 24 by computing q 1 = a / l l a ll and q2 = B/ II B II and factoring into QR:
[ 11 04 ] = [ql q2] [ l l 0 ll a
[ g ] to make the result
]
? IIBII .
26
(MATLAB) Factor [ Q, R ] = q r(A) for A = eye (4 ) - diag ( [ l 1 1 ] , - 1 ) . Can you renormalize the orthogonal columns of Q to get nice integer components?
27
For n = 3 and n = 4, find the QR factors of the special tridiagonal matrices T and K and B from qr(T) and qr(K) and qr(B) . Can you see a pattern?
28
What condition number do you compute for K9 and T9 , using the eig command to find Am a x/ A m in ? Compare with the estimate in equation (19) .
29
For the matrix A in Example 4, how do you know that A=
[� �]
50 < Am a x (AT A) < 5 1 ?
30
Apply [U, sigma, V] = svd(DI FF) to the 3 by 2 backward difference matrix DIFF = [1 0; - 1 1 ; 0 - 1] . Reverse signs in u1 , u2 , v1 , v2 to recognize them as the nor malized cosine and sine vectors in Example 5 with h = 1r /3 . Which column vector is in the nullspace of (DI FF)T?
31
The Frobenius norm II A ll � = :L :L l aij l 2 treats A as a long vector. Verify that II A + B I I F � II AI I F + I I B I I F II I II F = Vii II AB II F � II A II F I I B I I F II A II � = trace(AT A) . (Recommended) Using pinv(A) to find the pseudoinverse A + of the 4 by 5 forward difference A. Multiply AA + = I and A + A =I I. Predict A + when A is n by n + l .
32
92
Chapter 1 Applied Linear Algebra
B EST BAS I S F R O M T H E SVD
1.8
for and and
This optional section could have been called "SVD PCA MOR POD." I don't know if you would approve of such a title. But after explaining eigenvalues and singular values, I want to show one of the ways they are used. The of AT A and AAT are the right and left singular vectors of A. The nonzero ( and equal ) of AT A and AAT are the squares of the singular values ai (A) . The eigenvectors give orthonormal bases V I , , Vn and ui , . . . , Um in V and U. The numbers .Xi (AT A) = .Xi (AAT) = al(A) put those basis vectors in order of importance. Those ordered bases are highly valuable in applications:
eigenvectors eigenvalues
.
.
•
(1) AT Avi = .Xi vi AATu, = .X i ui (2) ATA = VAVT AAT = UAUT AV = UL. All five matrices A, AT A, AAT, A, and L, have the same rank The last four share positive eigenvalues .X i = al. If A is m by n, AT A has size n and AAT has size m. Then AT A has n - r zero eigenvalues and AAT has m - r . Those zeros produce n - r eigenvectors v in the nullspace of A (.X = 0) , and m - u 's in the nullspace of AT. Example 1 Often A is a tal l thin matrix ( m > n ) with independent col umns, so r = n :
Orthonormal bases VT V = l UTU = l
r.
r
r
A=
[ -�
�l
(3)
0 -1
The matrix AAT has size m = 3 and ran k = 2. The unit vector u 3 = ( 1 , 1, 1 ) / v'3 is in its nullspace. The point of this section is that the v's and u's are good bases for the col u m n spaces. For a first difference matrix like A, those bases are sensational:
r
V I , . . . , Vn = discrete sines ui , . . . , Un = discrete cosines Un + l = (1, . . . , 1)/ vn
The extra cosine is cos O ( and sin O is useless ) . The key property Av i = O"iUi says that first differences of discrete sines are cosines. The reverse property ATui = ai v• says that first differences of discrete cosines are minus discrete sines. AT has - 1 's above the diagonal and first differences are antisymmetric. The orthogonality VTV = I of discrete sine vectors leads to the Discrete Sine Transform. UTU = I leads to the Discrete Cosine Transform. But this ( v ry section is about data matrices, not difference matrices. Start by measuring m properties ( m features ) of n samples. The measurements could be grades in m courses, for n students. The goal is to find meaning in those mn numbers. In the absurd case when AT A has only zeros off the diagonal after shifting to zero mean, the course grades are independent. The success of the SVD is to find combinations of courses and combinations of students that are independent. In matrix language, A = UL,VT shows the right combinations in U and V to produce the diagonal matrix L..
e optional)
1 . 8 Best Basis from the SVD
93
Correlation Matrices AT A and AA T In typical examples, A is a Each of the n samples gives a column aj of the data matrix A. Each of the m properties corresponds to a row. The n2 dot products aT aj indicate "correlations" or "covariances" between samples:
matrix of measurement data.
Sample correlation matrix
AT A has entries a{ ai = rows times columns. ( 4 )
In the opposite direction, AAT indicates correlations between properties ( features ) : Property correlation matrix
n AAT = L ajaJ = columns times rows. j= l
(5)
Some applications focus on AT A and others on AAT. Some applications have m > n and others have m < n. Common sense suggests that we should solve the smaller eigenvalue problem. But one more thought reveals that a good svd code will solve both eigenvalue problems at once. We get both sets of eigenvectors, v's and u's. And those right and left singular vectors have the remarkable property Avi = CJi ui . The Golub-Welsch algorithm begins by reducing A to B = U[ AV1 . The orthogonal U1 and V1 come directly from rotations to produce zeros in B ( no eigenvalue problems ) . Then U2 and V2 find the singular values of B and the eigen values of BT B ( the same O"i and .A.i ) · MATLAB has no special commands for that bidiagonal svd and tridiagonal eig, so Persson unwrapped the LAPACK subroutines. The codes bidsvd and trideig on math . m it.edujrvpersson allow you to skip U1 and vl when A is already bidiagonal and AT A is already tridiagonal ( as in 1D problems ) .
bidiagonal form
Principal Component Analysis The goal of principal component analysis (PCA) is to identify the most important properties revealed by the measurements in A. Those will be of the original properties. Often the weights in the combination are called loadings and all are nonzero. We will always assume, by shifting if necessary, that this data has The variance is the critical indicator of importance, large or small, and the n samples in the data give an m by m covariance matrix:
combinations
mean
value zero.
Covariance matrix
1 ( E n = -a aT + n-1 1 1
·
·
·
+ an aTn )
1 T. = --AA n-1
(6)
This approximates the true covariance matrix E for the whole population ( we are seeing only n samples ) . The off-diagonal entries show correlations between properties. Section 2.8 will give a short introduction to covariance matrices in statistics, which correspond perfectly to resistances in electric circuits and elasticities of springs. Here I just mention that "correlation matrices" are often normalized to have ones on the diagonal. When some course grades are 1 to 5 and others go to 100, that
·
94
Chapter 1 Applied Linear Algebra
rescaling is needed. But if the units are consistent, the covariance matrix (6) is the best. A statistician explains n 1 as the number of degrees of freedom, when one degree has already been used for zero mean. The eigenvectors u 1 , u 2 , of AA T tell us the independent combina tions of properties in order of their variance (highest to lowest) . The u's are the best basis in property space Rm . The v's are the best basis in sample space Rn . If A is already a covariance matrix, then PCA looks at >-m a x(A) and its eigenvector. Orthogonality of the u's makes the combinations independent. The mixture of properties given by u 1 has highest variance a?/(n - 1 ) . This is the largest eigenvalue >.j (n - 1) of the sample covariance matrix AAT / (n - 1 ) . PCA says that the optimal number to measure is uTa. The other combinations u{ a have lesser importance. -
•
•
•
Suppose each col u m n of A measu res the position x, y, z of a mass moving in a stra ight line. With exact measu rements ai = ( x i , y., z,) , A has rank r = 1. After shifting to zero mean ( line through origin ) , the constant ratios of x, y, z are given by the unit vector u 1 ( eigenvector of E, left singu lar vector of A. direction cosines of the line ) . The perpendicular u 2 and u 3 directions show no movement, and the measurements uia and uja are zero. Rea l measurements include noise. The sa mple covariances are not exact. The noisy A has ful l ra n k r = 3, but a 1 > > a2 . The data uia and uja will not be exactly zero, but the svd still tells us to measure uTa. By comparing al , . . . , a; we determine how many combinations of properties are revealed by the experiment. Example 2
Principal component analysis is a fundamental technique in statistics [99] , invented and used long before the SVD made it computationally feasible for large m and n. Gene Expression Data In bioinformatics, the SVD determines combinations of genes ( eigengenes) that are seen together. Applications to drug testing are of enormous importance. Determining their function is the outstanding problem of genetics. Observing frequency of appearance of mRNA is a first step, and huge quantities of data are now produced by single experiments. is the primary tool in proteomics, and DNA give the gene expression data. The back cover of this book shows a small fraction of the data that comes from a single sample (one column of A is packed into that 2D Affymetrix chip, measuring tens of thousands of genes) . This is data mining with a difference. Studies of large data sets lead to classifying, with Vector Support Machines, or clustering (Section 2.9) , or ranking as in Coogle. The SVD produces numerical weights based on the data, and it is unsupervised. The extra feature of genetic experiments is the biological science behind them-we not just counts. PCA gives a large dimension reduction for gene microarrays, but it is not the end of the analysis.
microarrays
Mass spectrometry
want explanations of the functions of the genes,
1 . 8 Best Basis from the SVD
95
In systems biology (and eventually in medical diagnosis) , the rows of A correspond to genes and the columns correspond to samples (assays) . The n right singular vectors Vj are eigengenes (usually n << m ) . Those capture the expression profiles, and the true dimension, that is seen in the n samples. n samples
9i genes t----t--t-i m
eigensample
u
eigengene
D EJ
Figure 1.20: The SVD of a gene expression matrix. Its largest rank-1 piece is a 1 u 1 v f . Important note In fundamental applications throughout science and engineering, the singular values have an extremely useful property. They drop almost to zero after the first r ( ar+l is small) . Then is the effective rank of the matrix A. The conventional rank of A may be larger, and noisy data leads to full rank. The SVD and the QR factors from orthogonalization are "rank-revealing." A central idea of high-dimensional statistics (and dynamical systems) is to locate the low-dimensional manifold on which the important action occurs. This is the century of data, but we try hard to reduce r.
r
Model Order Reduction
dynamic
The goal of model order reduction (MOR) is to identify the components in a problem that are most important to follow. The dynamics are given by differential equations. Some components of the solution may be nearly constant , perhaps nearly zero. Our effort should go into computing the other components, that are varying with the flow. Those will be (a few) combinations of the (many) original components. The differential equations may come from biology or control theory or physics. When they are nonlinear, we may linearize. When they are linear time-invariant, a Fourier transform moves to the frequency domain. In all cases the goal is A proper orthogonal decomposition (POD) is based on the SVD:
to reduce
the order.
... , an
Start with n snapshots a 1 , showing the m components of the solution Find the largest k eigenvalues of AAT = I: ai ai. The eigenvectors fill uk = [u l . . . u k ] The projection Pk that minimizes I:llai - Pk ai ll 2 is Pk = Uk U"[ . That projection is picking out the k most important combinations of components. Again I emphasize that two eigenvalue problems are being solved at once. The eigenvectors ui of AAT give the projection. The singular values match the variances
96
Chapter 1 Applied Linear Algebra
a} in decreasing order. The ordering and the orthogonality of the basis are the key contributions of the SVD. Ultimately the goal is to reduce m differential equations to k equations. The projection Pk acts in sample space. The samples ai are all over that high dimensional space. Their projections Pk ai lie in a much smaller k-dimensional sub space, spanned by u 1 , . . . , u k . The projection is optimal for the n samples a, :
L II a, - Pk a. ll 2 = A k + l + . . . + An = az + l + . . . + 0"� (7) Linear algebra shows that the trace L lla, ll 2 , from the sum of diagonal entries of R = AT A, equals the sum of all the eigenvalues a} of R. The projection captures Minimum variance
the top k eigenvalues, from the combinations that have the greatest variance (the most information) . No k-dimensional projection can do better than that. I need to say that Model Reduction is a much deeper subject when it works on the underlying differential equations. We applied the SVD to data matrices, with output samples. Better to reduce the problem size first. A key application is to the equations of control theory, with state vector x, control u, and observations y :
The real problem is to reduce the model, not
just the data. State eqn
dx jd = Ax ( ) + Bu ( t )
t t
Observations
y
t = C t + Du(t) . (8)
()
x
()
Our data-based approach applied to y . The state-based approach reduces the size of x. The model is smaller, faster, and much cheaper. Its key features are saved. Control engineering models factories and whole industries. At a different scale, integrated circuits have the same need for model reduction. Section 2.5 introduces the transfer function from input to output. The model-based problem is to reduce the degree of G (often by a Pade approximation, described on the cse website) . The data-based problem is to reduce the size of the measurement matrix.
G(s)
Limitations of the SVD
A = UL:VT produces remarkable basis vectors in the columns of U and V. But they cannot be perfect in every way. Here are two serious limitations on the SVD: 1.
and are not at all sparse. have small components from everywhere.
U V Computing and using them has a significant cost. Very large matrices are expected in computational science, when they reflect "local" behavior. The neighborhood remains small even if the world is large. But orthogonal eigenvectors and singular vectors are not local.
They
In processing an image, the SVD is not a top choice for compression. It gives optimal Karhunen-LoEwe bases, but their cost can be high. Good eigenvectors are computed at speeds once thought to be impossible--but local processing of pixel values is faster by the filters of Section 4.4.
1.8 Best Basis from the SVD
97
The search for good decompositions was advanced by Tucker and Kruskal in mathematical psychology (measuring many attributes) . Now statistics and finance regularly see dimensions like 2 50 or 2 1 00 , where the SVD is slow. Sparsity in finance means fewer transaction costs-very small loadings are useless in the applications of PCA. 2.
The y)SVD. is "two-dimensiA onal."
Matrix entries A ij are like function values The SVD splits into rank one matrices auv T, like separating a ( x, y) into a sum of b ( x ) c(y). Separation of variables is an enormous simplification when it works. But eigenvectors and the SVD have no perfect extension to tensors Aj kl with four indices, or by analogy to a ( x , y, z, w ) with four variables. a ( x,
This chapter is ending with two research problems. The SVD does not even exist for a fourth-order tensor A ij k£ · And so many computations would be faster if the SVD bases in U and V were sparse. You will see that least squares approximations are vitally important, minimizing IIAu - b ll 2 for Au in a low-dimensional subspace. (This may be the number one application of linear algebra. ) More and more often, u is made sparse by including a penalty term a( l u 1 1 + + lu n l ) in the minimization. The search is on for sparse-fast-accurate approximations to the SVD . ·
·
·
A request No textbook can be a newspaper of fast-breaking ideas. The cse website is far better able to fill that need. Readers are invited to help in identifying important links. As I write these words, a SIAM Review article on Sparse PCA has just arrived (49:434-448, 2007) . It adapts the f 1 methods of Sections 4.7 and 8.6 to variance maximization. New techniques are appearing throughout computational science and engineering-this subject is alive ! When chapters end with open problems, I hope the cse page can go farther and faster than the book.
C H A PT E R 2 A F RA M EWO R K FO R A P P L I E D
M AT H E M AT I C S
2.1
EQ U I L I B R I U M A N D T H E STI F F N ESS M AT R I X
This chapter highlights a basic structure o f this book. You will see it i n a wide range of applications. This framework appears over and over again in applied mathematics (differential equations as well as matrix equations) . I I There are generally three equations in the framework:
look for it every time meet a e = Au w = Ce f = ATw . u, f. f = ATw = ATCe = ATCAu. = ATCA u f. A C = ATCA equilibrium problems.u. The vector of f forces equals times the vector u of displacements. = ATCA. u = f. 2.1 new problem.
Three steps
and
and
(1)
The primary unknown is the force from outside is When we combine those three equations they give In matrix language, the triple product K connects the output directly to the input As soon as these matrices and are identified, a new application fits into the framework. This matrix K is associated with The system is in steady state-time is not a factor. Forces produce movements K K is the stiffness matrix in mechanics and it reappears all over applied mathematics. The modeling problem is to find K The computing problem is to solve K This framework will be illustrated first in three specific examples: 1 . A line of springs (the springs can be stretched or compressed) : Section 3 . Best solution of Au = b (least squares regression in statistics) : Section 2.3 4. A network with flows on the edges (driven by potential differences) : Section 2.4 If your own field of application is different from those three, no surprise. These are an excellent starting point; they are not the end. We will discuss other applications (chemical engineering, fluid flow, economics, control theory, and many more) as we go. We also move to -oscillation, diffusion, changing response to changing inputs. The goal is to understand A and C and the product K = ATCA.
dynamical problems
98
99
2 . 1 Eq uilibri u m and the Stiffness Matrix
Dyna mics and Nonlinearity
Ku = f
is the framework of linear equilibrium. It will be extended (in fact it must be extended) in two directions. One is to escape from linearity. The other is to escape from equilibrium. The material may have a nonlinear response-current is not exactly proportional to voltage, and displacement is not exactly proportional to force. Ohm's Law and Hooke's Law are close approximations to the truth, but not perfect. Nonlinearity starts to be important when voltages and forces are large. We will show by example how to account for nonlinearity. The other major extension is to time-dependent problems. The equations can stay linear but they become dynamic (not static) . In our three examples, the external forces and the incoming measurements and the applied voltages can change with time. Then we find that 2. The springs are oscillating. They obey Newton's law F m a : Section 2.2 5 . The circuit has inductors and capacitors and alternating current: Section 2.5 8 . New measurements require us to update the statistics: Section 2.8 The steady state matrix equation is For dynamic problems this becomes a differential equation in time, either first-order or second-order:
=
Ku = f.
-dudt = Ku-f
ddtu2 Ku = f t) partial differential equation Ku 2
or
M
+
( .
(2)
Nonlinearity and time-dependence push us to the frontiers of computational science. Chapter 3 goes forward to continuum models, where the unknown becomes a function x, y) or x, y, t) . Our system changes to a ( may involve Uxx or Uyy ) · The computer is really stretched by nonlinear time-dependent partial differential equations. But the framework doesn't change.
u( u(
A Line of Springs Figure 2. 1 shows three masses m 1 , m2 , m3 connected by a line of springs. In one case there are four springs, with top and bottom fixed. The second example has only three springs; it is fixed at the top, and the lowest mass hangs freely. The two problems are fixed-fixed and fixed-free. We want the equations for the important unknowns-the displacements of the masses and the tension in the springs: u w
(u 1 , 2 , 3 ) displacements of the masses ( w 1 , w 2 , w3 , w4 ) or ( w 1 , w 2 , w3 ) tension in the springs .
= uu =
=
For the masses, displacement is positive downwards. For the springs, tension is pos itive and compression is negative ( wi < 0) . In tension, the spring is stretched and pulls the masses inward. In compression, the masses are pushed outward. We need the elastic properties (the spring constants ci ) of each spring. This is a key change from Chapter There Kn and Tn had "spring constants
1!
= 1. "
100
Chapter 2 A Framework for Applied Mathematics
Here Ci connects the stretching ei to the force wi. Hooke's Law is Wi ci e i , four constants c1 , c2 , c3 , c4 for four springs. = Our job is to link these one-spring equations into a vector equation f = Ku for the whole system. The vector f is the force from outside. Gravity pulls down on each mass and produces f = m 1 , m2 , m3 . At the earth's surface is about 32 feet/ sec2 or 9.8 meters/ sec 2 , and multiplied by mass this gives force. =
Force (spring constant) (elongation). ( g g g) g
u0 =
fixed
u
u0 =
0
0
2
U2 U3 u U4 =
fixed
Figure
3
free
0
2.1: Fixed-fixed springs with u4 = 0. Fixed-free with w4 = 0.
Our real problem is the stiffness matrix K, connecting u to f. Two different structures, fixed-fixed and fixed-free, produce two different K's. The best way to create K is in three steps, not one. Here comes the dominating framework of this chapter, seen first for a line of springs. Instead of connecting the displacements u directly to the forces f, it is much better to connect each vector to the next vector in the following list: u
e
w f
( u 1 , · · · , Un ) ( e 1 , · · · , em ) ( w l , · · · , wm ) ( JI , · · · , Jn )
Displacements of n masses Elongations of m springs Internal forces in m springs External forces on n masses
The framework that connects u to e to w to f looks like this: Displacement Elongation I nternal force External force
@]
[!] jAT
Al �
c
-----+
�
e
Au
f
ATw
w
Ce
A is c is AT is
m m n
by by by
n m m
101
2. 1 Eq uilibri u m and the Stiffness Matrix
We will write down the matrices A and C and AT for the two examples, first with fixed ends and then with the lower end free. Forgive the simplicity of these matrices, it is their form that is so important. STEP 1: The is the stretching-how far the springs are extended. Originally there is no displacement and no stretching-the system is on a table. When it becomes vertical and upright, gravity acts. The masses fall by u 1 , u 2 , u3 . If mass 2 drops by u 2 and mass 1 drops by u 1 , the spring stretches by u 2 - u 1 :
elongation e
First spring e1 = u 1 Second spring e 2 = u 2 Third spring e3 = u3 Fourth spring e4 =
- u1 - u2 u3
-
((( (
t he top is fixed so u 0 = 0) old as in the figure ) length L as in the figure ) u•. t he bottom is fixed so U4 = 0)
i
�
The lower end of spring moves down by U i · The upper end moves down by u i_ 1 . If both ends move the same distance, that spring is not stretched: u i = ui _ 1 and ei = 0. Notice that the equation e i = ui - ui - 1 applies also at the ends, when we fix the top and bottom by u o = 0 and u 4 = 0. The matrix A in those four equations is a 4 by 3 We write those four differences ui - ui _ 1 as a matrix A times a vector u. Our equation is e = Au:
(the difference in displacements) difference matrix.
Stretching
(3)
e = Au
In a continuous problem, the differences e = Au will become e = du j The matrix becomes a derivative! We get a differential equation instead of a matrix equation. STEP 2: The physical equation w = Ce connects the spring elongations e with the spring tensions w. w i = ci e i It is the "constitutive law" that depends on the material in the spring and its shape. A soft thin spring has small so a moderate force w can produce a large elongation Note again that Hooke's law is This is nearly exact for real springs over a wide range, before the spring is overstretched and the material becomes plastic. Since each spring has its own law, the matrix in w = Ce is a diagonal matrix C:
This is Hooke's Law c, linear.
Hooke's Law
w = Ce
w1 w2 W3 W4
c1 e 1 c2 e 2
c3e3c4e4
is
[ �� ] [
dx. for each separate spring.
e.
c
'
c,
c
•
J [� ]
Combining e = Au with w = Ce, we now know the relation internal spring forces w and mass displacements u.
w
� ce . (4)
CAu between
102
Chapter 2 A Framework for Applied Mathematics
STEP 3: Finally comes the "balance equation." The internal forces w from the springs must balance the external forces on the masses. Each mass is in equilibrium, pulled up by a spring force w1 and down by w1 + 1 plus the gravitational force Thus = or f + : = j Wj Wj Wj Wj+ l +l
f
fj·
f1
Balance of forces
and
ATw = f
. (5)
The equation for balance of forces is f f-
That matrix is AT ! ! = AT w. Nature transposes the rows and columns of the e - u matrix to produce the w matrix. T This is the beauty of the framework, that A appears along with A. A proper author would never use two exclamation marks-1 apologize. One of those marks is to call attention to the wonderful appearance of A T (which makes K a symmetric matrix) . The other is to emphasize the presence of a balance equa tion. To understand equations you have to know what to look for, and "balance" or "conservation" or "continuity" appears somehow in every model. The three equations combine into Ku = where K = AT CA is n by n : m m n
by by by
n m m
{
f,
e w
f
= =
combine into AT CAu = f .
(6)
In the language of elasticity, = Au is the kinematic equation (for displacement) . The force balance = AT w is the static equation (for equilibrium) . They are connected by the constitutive law w = (from the material properties) .
f
e
Ce
Stiffness Matrix and Solution All large finite element programs spend major effort on assembling the stiffness matrix
K = AT CA from smaller pieces. We do it for four springs by matrix multiplication of AT times CA. Here is the fixed-fixed stiffness matrix K: 0 -1 0 K = 0 1 -1 0 0 1
[1 Important note:
( 7)
c3 =K = = 1.
Suppose all springs are identical with c 1 = c2 = = The stiffness matrix reduces to substituting all ci = 1 , it becomes the special matrix K3 of Chapter
C is the identity matrix: C
I.
c4
1.
Then
A T A. By
2 . 1 Eq uilibri u m and the Stiffness Matrix Stiffness matrix with C
=
I
K3 = AT A =
[ -� -� -�] 0 -1
103
2
Four identical springs, fixed at both ends, have produced our favorite matrix. A line of n + 1 identical springs would produce Kn . The matrix is tridiagonal because each spring connects only to its two neighbors. It has constant diagonals because all springs are identical. Kn is symmetric positive definite because Nature insists on that property ( by producing A and AT) . K3 = AT A is very different from K3 = LLT . The matrix A from four springs is 4 by 3. The matrix L from elimination is square. K is assembled from AT A, and then it is broken up into LLT . One step is applied mathematics, the other is computational mathematics. Each matrix Kn is built from rectangular matrices and factored into square matrices. May I list some properties of K = ATCA? You know almost all of them:
1.
K is tridiagonal, because mass 3 is not connected t o mass 1 .
2.
K is symmetric, because C is symmetric ( and A T appears with A) .
3.
K is positive definite, because A has independent columns.
4.
K- 1 is a full matrix with all positive entries.
That last property leads to an important fact about u = K- 1 (fi > 0) (ui > 0) . Notice well that "positiveness" of a matrix is different from "positive definiteness." Here K is not positive ( it has - 1 's) while both matrices K and K- 1 are positive definite.
then all displacements are downwards f: If all forces act
downwards
= c and mi = m. Find the displacements u and forces w . All springs are the same and all masses are the same. But all displacements and elongations and spring forces will not be the same. And the inverse matrix K- 1 incl udes the factor � beca use K = ATCA incl udes c: Example 1 Suppose all
ci
[ ]
1.5 mg 2.0 c
Displacements
1.5
The displacement u 2 , for the mass in the middle, i s greater than u 1 a n d u3 . The units are correct: the force mg divided by force per unit length gives a length u. The elongations of the springs are = Au to compute next.
e
,
c
104
[
Chapter 2 A Framework for Applied Mathematics
Elongations
e = Au =
-� � � 0 _1 1 0 0 -1
l
mg
c
1
[ ] 1.5 2.0 1.5
1
mg
c
[ ] 1 .5 0.5 -0.5 - 1 .5
.
Those elongations add to zero beca use the ends of the line are fixed . The sum u 1 + (u 2 - u 1 ) + (u3 - u2 ) + ( -u 3 ) is certainly zero. For each spring force w Hooke's Law . 1 ·1es e by c. S o w , w , w , w are 23 mg , mg , - mg , - 3 mg Th e upper two J. USt mu I t1p 2 2 2 1 2 3 4 . springs are stretched , the lower two springs are compressed .
Notice how u, e, w are computed in that order. We assembled K = ATCA from rectangular matrices. To find u = K - 1 f , we work with the whole matrix and not its three pieces. The rectangular matrices A and AT do not have (two-sided) inverses.
I Warning:
Normally you cannot write
K - 1 = A - 1 c - 1 (AT) - 1 . 1
The matrices are mixed together by the triple product ATCA, and they cannot easily be untangled. In general, ATw = f has many solutions. And four equations Au = e would usually have no solution with three unknowns u. But ATCA gives the correct solution to all three equations in the framework. Only when m = n and the matrices are square can we go from w = (AT) - 1 f to = c - 1 w to u = A - 1 e. We will see that now.
e
Fixed End and Free End Remove the fourth spring. All matrices become 3 by 3. The pattern does not change! The matrix A loses its fourth row (there is no e 4 ) . Then AT loses its fourth column (there is no w4 ) . The stiffness matrix becomes a product of square matrices:
The missing column and row both multiplied the missing c4 . So the quickest way to find the new AT CA is to set c4 = 0 in the old stiffness matrix: FIXED FREE
(8)
You recognize this matrix in the standard case when c 1 = c2 = c3 = 1. It is the familiar - 1 , 2, - 1 tridiagonal matrix, except the last entry is c3 = 1 instead of c3 + c4 = 2. Compared with T3 in Chapter 1 , the ends are reversed to give the hanging matrix H3 . This corresponds to a second difference matrix with uo = 0 at one end but u4 = u 3 at the other end. The spring at the bottom is free.
2 . 1 Eq uilibriu m and the Stiffness Matrix Example 2 All
Ci
[
1 05
l
= c and all mi = m in the fixed-free hanging line of springs. Then 2 -1
AT CA = c -1 The displacements u =
0
2 -1
0 -1
1
K - 1 f change from the fixed-fixed exa mple beca use K has changed
Displacements
In this fixed-free case, those displacements 3, 5, 6 are greater than 1 .5, 2.0, 1 .5. The number 3 appears in the first displacement u 1 because all three masses are pulling the first spring down . The next mass has an additional displacement ( 3 + 2 = 5 ) from the two masses below it. The third mass drops even more ( 3 + 2 + 1 = 6) . The elongations e = Au in the three springs display those n u mbers 3, 2, 1 : Elongations
Mu ltiplying by c, the forces in the three springs are w 1 = 3mg and w 2 = 2mg and w3 = mg. The first spring has three masses below it, the second spring has two, the third
spring has one. All springs are now stretched . The special point of a sq uare matrix A is that those internal forces w can be found directly from the externa l forces f. The balance eq uation ATw = f determines w im me diately and uniquely, because m = n a nd AT is sq uare and invertible:
r!�:: 5
.
w = (AT ) - 1 f is
[
1 1 1 0 1 1 0 0 1
l[ l [ l mg 3mg mg = 2mg mg lmg
3 masses below
2 masses below 1 mass: free end
Then e comes from c - 1 w a nd u comes from A - 1 e. In this "determinate" case m we are allowed to write (ATCA) - 1 = A - 1 c - 1 (AT) - 1 .
= n,
Remark 1 When the displacement at the top is fixed by u 0 = 0, it req uires a force to keep it that way. This is an external reaction force f0 , holding up the line of springs. This reaction force is not given in advance. It is part of the output, from force balance at the top. The first spring is pu lling down with internal force w 1 = 3mg. The reaction fo = -3mg pulls upward to balance it. A structural engineer needs to know the reaction forces, to be sure the support will hold and the structure won 't col lapse.
106
Chapter 2 A Framework for Applied Mathematics
Example 3 A F R E E- F R E E line of springs has no supports. This means trouble in
and
K (spring 1 is gone) . The matrix A is 2 by 3, short and wide. Here is e = Au:
A
(9)
Unstable
Now there is a nonzero sol ution to Au = 0. The masses can move with no stretching of the springs. The whole line can shift by u = ( 1 , 1, 1) and this stil l leaves e = (0, 0) . The col u mns of A are dependent and the vector ( 1 , 1 , 1) is in the nullspace: Rigid motion u
�
[ �]
(10)
In this case, ATCA cannot be invertible. K must be singular, beca use Au = 0 certainly leads to ATCAu 0. The stiffness matrix ATCA is stil l sq uare and sym metric, but it is only positive semidefinite (like B in Chapter 1 , with both ends free) : =
Singular
(11)
ATCA
T h e pivots will b e c2 a n d c3 a n d n o third pivot. Two eigenval ues wil l b e positive but the vector ( 1 , 1, 1) will be an eigenvector for >. = 0. The matrix is not invertible and we can solve ATCAu = f only for special vectors f. The external forces have to add to zero, !I + h + h = 0. Otherwise the whole line of springs (with both ends free) will take off like a rocket.
Rigid motions with no supports f--
Translation Rotation �
Figure 2.2: The free-free line of springs can move without stretching so Au = 0 has nonzero solutions u = ( c , c, c ) . Then ATCA is singular ( also for the "circle" of springs ) .
2. 1 Eq uilibri u m and the Stiffness Matrix
107
Problem 4 pulls the top up and the bottom down, with ba lancing forces 1 and 1. We can solve ATCAu = ( 1 0 1) even though the system is singular. A circle of springs ( when K is the circu lant matrix C with wrap-around in Chapter 1 ) is also singular. -
-
,
,
Minimum P rinciples There are two ways to describe the laws of mechanics, by equations and also by minimum principles. One of our goals is to explain the connections. For masses and springs, we started with equations for e, w , and u (to reach Ku = f) . That was more direct than a minimum principle. But Section 1 . 6 described the minimization that leads to Ku = f, and that was exactly the minimum principle we want: Minimize the total potential energy P
Nature minimizes energy. The springs stretch (or compress) as gravity pulls the masses down. Stretching increases the internal energy �eTCe = �uTKu. The masses lose potential energy by JT u (force times displacement is the work done by gravity) . Equilibrium comes when a little more displacement b.u gives b. P = 0, energy gain = energy loss. b.P = 0 is the "equation of virtual work," where P is smallest. Rewriting P(u) shows why u = K - 1 f is minimizing, and Pmin = - U T K - 1 f:
At the minimum u - K - 1 f = 0. At first I was surprised that Pmin = - UT K - 1 f = -�JTu is negative. Now I realize that the masses lost potential energy when they were displaced. (Interesting that exactly half of that loss is stored in the springs as �uT Ku = �uT f. The other half must have gone into the Earth, a large mass that moved a very short distance.) In the next section about oscillation, the moving masses exchange potential energy for kinetic energy and back again. Our point is that minimum principles are an alternative to equations. Sometimes they come first, as in least squares (Section 2.3 will minimize the squared error) . Sometimes the equations Ku = f come first. In continuous time, the energy P(u) will be an integral and minimizing leads to a differential equation for u. Always the model problem is the first and best application of ordinary calculus: Minimize When
P(u) by solving
�� = 0 or gradient (P) = 0 or first variation �� = 0.
P(u) is not quadratic, its derivative is not linear. A
equation ATC(Au) = f has a function w
=
nonlinear stiffness C(e) , not j ust a multiplication.
108
Chapter 2 A Framework for Applied Mathematics
An I nverted Pendulum For pleasure, we describe a problem that is much less stable- b The system stays upright when the mass m is small. As the mass increases, we "bifurcate" into a new stable equilibrium at a tipping angle ()* . Figure 2.3 shows the old and new positions, with a "rotational spring" adding strength to the thin support. It is like a tomato plant that is staked up but still tips over part way. The mass increases to m, () = 0 becomes unstable, and we find the new stable angle ()* . The equilibrium position comes from force balance; at the same time it minimizes the potential energy. In all the stable problems of this chapter, that energy includes a positive definite quadratic � uT Ku . In this very different problem, The indicator is d 2 PI The potential energy P(()) is partly in the mass at height L eos (), and partly in the spring (stretched or compressed) . Equilibrium is at the minimum of P(()) :
the top.
ecause the mass is at
comes with loss of positive definiteness. ! c() 2
d()2 • loss of stability
Energy
P=
m
�� =
+ mgL cos ()
P(lJ) with mgL <
c
�l/. 0 stable at lJ
=
0
c()-
mgL sin () = 0
P( lJ) with mgL >
c
stable at O * and -lJ *
Figure 2.3: The mass tips over to the stable angle ()* when mgL >
d()
( 1 3)
c.
That equation dPI = 0 always has the solution () = 0. The first question is whether this vertical solution is stable. Stability is decided by the
second derivative:
d2 P = c - mgL cos () > 0 for stability ( 14) d() 2 This is positive at () = 0 provided c > mgL. Then the spring is strong enough to keep the system upright. When m or L increases, we pass the critical bifurcation point c = mgL and the vertical position () = 0 becomes unstable. The graphs in Figure 2.3 show how () = 0 changes from a global minimum of P(()) to a local The system has to look for a new minimum, which equation (15) finds at () = ()* : Stability /instability
maximum.
New equilibrium
mgL sin () * = c () *
P 11 (()* ) > 0
(15 )
In Figure 2.4, the line c () lmgL meets the curve sin () at this new equilibrium ()* . The second figure shows how ()* moves away from zero (the pendulum begins to tip
2 . 1 Eq uilibriu m and the Stiffness Matrix
109
over ) when that ratio >. = mgLjc passes >. = 1. The "pitchfork" in that middle figure is very typical of bifurcations. The last figure shows a straight line pitchfork, when the equation is Ax = >.x. For most )..' s the only solution is x = 0. When >. is an eigenvalue of A, nonzero solutions ( the eigenvectors ) suddenly appear. They disappear when >. passes the eigenvalue, where the inverted pendulum tips further over. Maybe it would be possible to slide a mass up a thin rod, increasing the effective length L. Then watch the rod begin to tip.
slope 0
curve is sin O
=
0
c
mgL
>
1
is stable slope < 1 O* stable
This is a graph of solutions B * to B * = >. sin B * as >. increases 0
o*
0 Figure 2.4: Solutions of
dP = 0 as mL increases. Bifurcation at >., as in Ax = >. . x dB P roblem Set 2 . 1
1
2
The formula for K - 1 involves division by the determinant of K ( which must not be zero ) . In the fixed-fixed case, the 3 by 3 determinant in (7) is det K = (c 1 + c2 ) (c2 + c3 ) (c3 + c4 ) - c� (c3 + c4 ) - c� (c 1 + c2 ) = c 1 c 2 c 3 + c 1 c 3 c4 + c 1 c 2 c4 + c2 c3 c4 . Find the determinant of ATCA in the 3-spring case (8) with the third mass hanging free ( maybe set c4 = 0) . Also find the determinant in the free-free case (11). The numerators in K - 1 are the 2 by 2 subdeterminants of K. These are called the cofactors of K, after they are given + and - signs alternately. For the first row of K - 1 we remove the first column of K, and find the 2 by 2 determinants from columns 2 and 3. Delete row 1 then row 2 then row 3 of K:
Find row 2 and then 3 of K - 1 by removing columns 2 and then 3 of K. Compute the 2 by 2 determinants, with rows 1 or 2 or 3 removed. Then alternate signs by (-1) i+J . The inverse K - 1 should be symmetric and all positive.
110
Chapter 2 A Framework for Applied Mathematics
3
Find (ATCA) - 1 in the fixed-free example by multiplying A- 1 c- 1 (AT) - 1 . Check the special case with all Ci = 1 and C = I.
4
In the free-free case when ATCA in (11) is singular, add the three equations ATCAu = f to show that we need fi + /2 + /3 = 0. Find a solution to ATCAu = f when the forces f = ( - 1 , 0, 1) balance themselves. Find all solutions!
5
In the fixed-fixed case, what are the reaction forces on the top of spring 1 and on the bottom of spring 4? They should balance the total force 3mg from gravity, pulling down on the three masses.
6
With c 1 = c3 = 1 in the fixed-free case, suppose you strengthen spring 2. Find K = ATCA for c2 = 10 and c2 = 100 . Compute u = K - 1 f with equal masses f = (1, 1 , 1).
7
With c 1 = c3 = c4 = 1 in the fixed-fixed case, weaken spring 2 in the limit to c2 = 0. Does K = ATCA remain invertible? Solve Ku = f = ( 1, 1, 1 ) and explain the answer physically.
8
For one free-free spring only, show that K = c
[ � �] = "element matrix." -
-
(a) Assemble K's for springs 2 and 3 into equation ( 1 1 ) for Kfree-free · (b) Now include K for spring 1 (top fixed) to reach Kfi xed -free in (8) (c) Now place K for spring 4 (bottom fixed) to reach Kfixed - fixed in ( 7 ) .
9
10
When P 1 (B* ) = 0 for the inverted pendulum, show that P 11 (B* ) > 0 which makes (}* stable. In other words: >. sin B* = B* in ( 13) gives >. cos (}* < 1 in (14 ) . For proof, show that F( B) = (} cos (}/ sin (} decreases from F(O) = 1 because its derivative is negative. Then F(B* ) = >. cos O* < 1.
The stiffness matrix is K = ATCA = D - W = diagonal - off-diagonal. It has row sums 2:: 0 and W 2:: 0. Show that K - 1 has positive entries by checking this identity (the infinite series converges to K - 1 and all its terms are 2:: 0 ) :
KK - 1 = (D - W) (D - 1 + D - 1 w D - 1 + D - 1 w D - 1 WD - 1 + · · · ) = I.
2.2 Oscillation by Newton's Law
2.2
111
OSC I L LAT I O N BY N EWTO N ' S LAW
This section is about the most important equation in mechanics. It is Newton's Law = ma. We have n masses m 1 , . . . , mn that obey this law, force = mass times acceleration. Their displacements u 1 (t) , . . . , un(t) are changing with time, but not at anywhere near the speed of light ( we hope ) . The acceleration of each mass is a = d2 u/ dt 2 ( also written Utt or u 11 or u) . We need the forces F. Compare F = ma with the previous section about equilibrium. There, the masses didn't move ( a = 0 ) . Each mass was in balance between external forces f and spring forces Ku. That balance F = f - Ku = 0 is now gone and the masses are in motion. When f = 0, and all forces come from the springs, we have Mu 11 -Ku. Friction and damping would involve the velocities dujdt. So would flow problems ( and many applications involve flows ) . This section has only U tt and not Ut. Without damping or external forces, the springs will oscillate forever. The total of the kinetic energies �mu; of the masses and stored energies �ce 2 of the springs must be constant. When the differential equations are coupled, of course we use matrices. The vector of n displacements will be u(t) , and the masses go into a diagonal mass matrix M: F
=
Displacem � nts u(t) Mass matnx M
u(t) =
[ l u 1 (t) : Un(t) ·
and
M=
[
m1
·
.
mn
l
The vector of n external forces on the masses is f ( t) . When Ku = f, we are in equilibrium: no oscillation. The force in F = ma is the difference F = f - Ku. Newton 's Law F
=
ma
f - Ku = Mu tt or MUtt + K u
=
f.
( 1)
We do not have to repeat the same steps for every new application. This is the point of the framework! Once you have found A and C and K = ATCA and M, the system takes over. The basic equation Mu 11 + Ku = 0 is conservative, with f = 0. We will solve it exactly using eigenvalues and eigenvectors of M - 1 K. In reality, large problems are solved by finite differences with time steps il.t. A key issue in scientific computing is the choice between "explicit and
implicit." Explicit methods tell us directly the new Mu(t + tl.t) . Implicit methods also involve Ku(t + b.. t ). A coupled system has to be solved at each step for u(t + tl.t) , but the implicit methods have extra stability and they allow a larger b.. t . This section describes the two leading methods, with computed examples: Explicit Leapfrog Method ( short fast steps ) ( chosen for molecular dynamics ) Implicit Trapezoidal Rule ( larger slower steps ) ( chosen for finite elements )
112
Chapter 2 A Framework for Applied Mathematics
[ � � ] [ u " ] + [ �! - � ] [ u ] = [ � ] with u(O) = [ � ]
We plan to solve a mass-spring example Example
Mu " + Ku = 0 in three ways: and u ' (O) =
[�]
There will be codes for the eigenvector solution ( normal modes ) and the leapfrog and trapezoidal methods. Sections 2.5 and 2.6 introduce damping and nonlinearity, working also with the parallel problems of circuit analysis. One Mass and One Spring Start with one mass m hanging from one spring ( with spring constant c) . The top is fixed. When the mass moves down by a distance u(t) , the spring pulls it back up with force -cu(t). The minus sign is because the spring force has opposite direction from the displacement. Newton's law is force = ( mass ) ( acceleration ) = m u ": One unknown
2 m ddtu2 + cu = 0 with u(O) and u ' (0) given.
(2)
Note that we are speaking about movement away from equilibrium. Gravity is already accounted for. If you want the complete displacement ( from no stretching at all ) , you would add mg to the right side and mg j c to the solution-this is the constant value of u in equilibrium. We measure from equilibrium instead of from absolute zero. The solution u(t) combines a cosine and sine ( a second order equation has two solutions ) . By themselves, cos t and sin t satisfy u " + u = 0, when m = 1 and c = 1. equation (2) needs cjm from the second derivative, so multiply t by the square root:
u(t) = A cos
Oscillating solution
-{!;;, t + B sin -{!;;, t .
(3)
At t = 0 the displacement is u(O) = A. Taking derivatives in (3) , the velocity at t = 0 is ..Jfi B = u1(0) . The initial conditions determine A = u(O) and B = �u 1 (0) . The oscillation frequency is w = ..;;;;_ . A small mass on a hard spring vibrates quickly, like an electron. A large mass hanging from a soft spring oscillates slowly, like a heavy ball on a rubber band. The potential energy in the single spring is �cu 2 . The kinetic energy of the single mass is �m(u1) 2 . For more springs and masses, the potential energy becomes �eTCe and the kinetic energy is Hu1 )T Mu1 • The total energy ( kinetic plus potential ) is constant, equal to the total energy at the start: Conserved energy
1 2 1 2 2 1 2 1 2 m (u (t)) + 2 c (u(t)) = 2 m (u (0)) + 2 c (u(O)) . I
I
(4)
For one spring, the derivative of this total energy is mu 'u " + cuu '. This is u ' times mu " + cu = 0, so the derivative is zero and the energy doesn't change.
2.2 Oscillation by Newton's Law
113
Key Example: Motion Around a Circle
1.
The simplest and best example is u 11 + u = 0. One solution is u = cos t. The velocity is v = u 1 = - sin t and certainly u 2 + v 2 = cos 2 t + sin 2 t = The exact solution travels around that constant energy circle in the u, v plane ( the phase plane) . Let me try four finite difference methods. I will write u " + u = 0 as two equations u 1 = v and v 1 = -u . All four methods replace u 1 by (Un + l - Un)/h, and v ' similarly. The crucial choice is where to evaluate the right sides v and - u . Both Euler methods quickly leave the circle in Figure 2.5, because of low accuracy. The growth matrices G F and GB at each time step h = tl.t are officially stable, but the O(h) errors are unacceptable. The eigenvalues >. of G produce growth or decay: Forward Euler
Un + l = Un + h Vn Vn + l = Vn - h Un
-[1 1]
1 1
>. = + ih, - ih I .X I > 1 (growth)
-h - l >. = (1 ± ih)/(1 + h2 ) Un + l = Un + h Vn + l GB h Vn + 1 = Vn - h Un + 1 I .X I < 1 (decay) Each step multiplies (Un, Vn) by G to find the next (Un + 1 , Vn + 1 ) . Notice that 32 steps don't return exactly to the x axis at t = 211". That is phase error. Backward Euler
/
I
I
I
I
'
/
Figure 2.5: Euler spirals out, Backward Euler spirals in,
h = �;,
'
\
\
I
[�] n= an [ � ] .
Second-order accuracy will make a big difference. The trapezoidal method is centered at n + � - Every (Un, Vn ) stays exactly on the circle ( a small phase error in the double bullet at 0)) . Energy is conserved because Gr is an orthogonal matrix.
(1,
114
Chapter 2 A Framework for Applied Mathematics
The leapfrog method also has I .X I = 1 for h ::::; 2. But GL is not an orthogonal matrix and the orbit follows an ellipse in Figure 2.6. The ellipse comes closer to the circle as h ----+ 0, and leapfrog has a giant advantage: it is explicit . From Un + 1 = Un + h Vn we know Vn + 1 = Vn - h Un + 1 = Vn - h 2 Vn - h Un : Leapfrog Method
.X 1 + .X 2 = trace = 2 - h2 I .X 1 I = I .X 2 I = 1 if h ::::; 2
Un + 1 = Un + h Vn Vn + 1 = Vn - h Un + 1
t-------+---9
f--
Leap onto ellipse !
small phase error
Figure 2.6: Trapezoidal (implicit) conserves energy. Leapfrog (explicit) conserves area.
Important new word: The determinants of Gr and G L are 1. The trapezoidal and leapfrog methods are "symplectic." Multiplication by Gr and GL preserves areas in the phase plane. All the triangles from (0, 0) to (Un, Vn) to (Un + 1 , Vn + I ) have the same area. Equal areas in equal times, as in Kepler's Second Law for planets. This property is fundamental for success in long-time integration. Equal areas are especially clear in the six triangles in Figure 2. 7. This special case has h = 1 and () = 211" /6 and e 6i8 = 1. Then G6 = I and (U6, V6) = (U0 , Vo ) . For each N, Problem 2 shows that the time step h = 2 sin(1rjN) gives G N = I. The jagged figure has h= 1 .3. This large time step is still stable and the points (Un.Vn) lie on an ellipse. But stability isn't everything; the accuracy is terrible. I intended to show h = 2.01 beyond the stability limit, but the graph left the page. '
I
I
'
I
/
"'
'
'
'
'
'
Figure 2.7:
'
32 leapfrog steps with tlt = h = 1.3; six steps with h = 1
( equal areas ) .
2.2 Oscillation by Newton's Law
115
Line o f Masses a n d S prings The framework u ---+ e ---+ w ---+ f does not change much when the displacement u(t) is measured from equilibrium. But the force balance looks different. That includes Newton's inertia term (mass)(acceleration) along with any applied force f(t) : oscillations
u1 (t) , . . . , un (t) Al
force balance
M
u Ku = f(t) "
+
� AT
e 1 (t) , . . . , em (t) £ spring forces w 1 (t) , . . . , Wm(t) The all-important matrix K is still ATCA. We will first discuss M + K = 0, assuming no applied force. We · need 2n solutions ( one constant C for each ) to match elongations
u u "
the starting vector and the n initial velocities in Those 2n solutions will come from eigenvectors x ! Try the solutions u = (cos wt)x and (sin wt) x .
u(O)
) + K( cos w t) x
Mu 1 Ku = M( -w2 cos wt x +
u'(O).
= 0 gives
K x = w 2 Mx .
(5)
The eigenvalue is >. = w 2 . The matrix with eigenvector x is M - 1 K (not symmetric) : (6) Row 1 contains k 1 2 / m 1 Unsymmetric 1 K = m�- 1 M Row 2 contains k 1 2 / m2 if m1 =I m2 M - 1 K is a product of positive definite matrices, but I won't call it positive definite. It would fit a wider definition of positive definiteness, but safer to insist on symmetry. Still the good properties of a symmetric K continue to be good for M - 1 K: 1 . The eigenvalues >.i o f M- 1 K are still real and positive: A i > 0.
[
2.
T
The eigenvectors xi can be chosen orthogonal, even orthonormal, but the inner product now involves M. Orthogonality is now x My = 0.
This is easy to prove if you look at the matrix M - � K M - ! . That matrix is symmetric and positive definite ( like K) , when we split M - 1 symmetrically. So the triple product has real positive eigenvalues >.i and orthonormal eigenvectors yi:
(8 )
M-orthogonality
The eigenvalues did not change, whether M - 1 is on one side or M - � is on both sides. The eigenvectors do change. The Yi are orthogonal and the xi are "M-orthogonal." Now comes the general solution vector u(t) to the equation M + K = 0.
u u "
116
Chapter 2 A Fra mework for Applied Mathematics
The solution combines the eigenvectors x, of M- I K with cos wit and also sin wi t:
u(t) = :L �= I (A cos A t + B, sin A t) x, . (9) Each term is a pure oscillation at a fixed frequency = ..;>:: . All >., are positive. At t = 0 we have u(O) = L A;xi (expansion in eigenvectors) and u'(O) = L B,A x, . A straightforward MATLAB code finds this u(t) from eig ( K, M ) : General solution
w,
I
I
i I l l }Ill �
I I
0
,
,
0
°
0
I
[vectors, va lues] = eig ( K, M ) ; eigen = diag ( values ) ; % solve Kx = >.Mx A = vectors \ uzero ; B = ( vectors * sqrt ( values ) ) \ vzero ; coeffs = A. * cos ( t * sqrt ( eigen ) ) + B. * sin ( t * sqrt ( eigen ) ) ; u = vectors * coeffs ; % solution (9) at time t to Mu + Ku = 0
1
Two eq ual masses mi = m 2 and three identical springs: Both ends fixed. The 2 by 2 mass matrix is j ust M = mi. The 2 by 2 stiffness matrix is also fa miliar:
Example 1
[
]
c - 21 - 21 and M - I K = mc _ 21 - 21 . The eigenvalues are >. I = cjm a nd >. 2 = 3cjm. The eigenvectors are XI = (1, 1) and x 2 = (1, -1) . They are orthogonal for the M-inner product. But here M = ml and Fixed-fixed
K=
[
]
M-I K is symmetric, so they are orthogonal in the usual way and x T x 2 = 0. Substitute Xs and x's into (9) , and the sol ution is a combination of the normal modes XI and x 2 :
Figu re 2.8 shows these two pure oscillations on the left. The masses move together in
xi = (1, 1). If they start together at ui (O) = u2 (0) and u� (O) = u�(O) , then they oscillate together forever. The eigenvector x 2 = (1, - 1) moves the masses in opposite directions, faster beca use >. 2 has the factor 3. Example
1
2 mi = 9
Example
Slower mode
Faster mode
A1 = -
A2 = 3 -
Masses go in same direction
Equal masses m = opposite directions 2
c
m
Figure 2.8: Eigenvectors
c
m
A1 = 5
1
ci = 75
t A2 = 10
C2 = 6 t Faster mode
[ � ] and [ _ � ] for equal masses, [ � ] and [ -� ] for mi -=/= m2 .
117
2.2 Oscillation by Newton's Law
2 Masses m 1 = 9 and m 2 = 1 with c 1 = 75 a n d c2 = 6: Lower end free. Now c 1 = 75 and c2 = 6 go into K = ATCA. The last row adds to zero ( free end ) :
Example
Fixed-free
The eigenvalues >. 1 = 5 and >. 2 = 10 come from M- 1 K ( notice the non-symmetry ) : 81 leads to det (M - 1 K - >.! ) = >. 2 - 15>. + 50 = 0 . M - 1 K = -6 9 -9 6
[
6
]
The eigenvectors ( 1 , 6) and (2, -3) are not orthogonal beca use M - 1 K is not sym metric. The rule is that x T Mx 2 = 0. Here (1) (9) (2) + (6) ( 1 ) ( -3) = 0. Both normal modes x 1 and x 2 in Figure 2.8b now have larger displacements for the smaller mass. Starting from rest at ( 1 , 0) ( no sine terms ) , the sol ution is again a combination of two normal modes:
u(t) =
( � cos Vs t + O sin Vs t) [ ! ] + (� cos JlO t + O sin JlO t) [ - � ] .
Please notice: The mass matrix M is not diagonal in the finite element method (Section 3.6) , when "Galerkin's method" discretizes the differential equation. The matrices M- 1 and M- 1 K become full. But eig ( K, M) is still successful. Standing Waves and Traveling Waves The oscillations become interesting (even worth a movie) with more masses. The point is that a sum of standing waves (up and down, staying in place) produces a traveling wave. A surfer rides the wave in to shore, but the water stays in the ocean. A standing wave has one normal mode x i . The n masses share the same A( Standing wave
We see the wave better when the springs are horizontal and the masses go up and down (Figure 2.9a) . Notice the special points in between with no movement. We are just looking at an eigenvector of M- 1 K. 0.5
0.5
0
-0.5
0
2
4
6
-0.5
0
2
4
6
'-----�--'
Figure 2.9: Standing wave (one eigenvector) and traveling wave (all eigenvectors) .
118
Chapter 2 A Fra mework for Applied Mathematics
A traveling wave can start at the left end (zeros elsewhere) . Eigenvectors go up and down at different frequencies. All down the line, masses pick up energy and lose it and recover it. (Figure 2.9b becomes a movie on math . m it.edu / cse. ) Observers see a wave travel down the line of springs, and reflect back at the other end (free or fixed) . The energy is conserved (no damping) so the motion never dies out. For equal masses m and equal spring constants c, the central equation becomes mlu 11 + cKu = 0. The eigenvectors of our - 1 , 2, - 1 second difference matrix K are discrete sines. The displacements involve the products sin( JX;; t ) sin(knjh) . Important A violin string is the limiting case of more masses ( n ) The discrete jh becomes a continuous variable x. The normal modes become sin ( ...jCfm t) sin (knx) , an infinite sequence of harmonics. Notice the separation of variables t and x. The discrete mlu 11 + cKu = 0 becomes the wave equation muu - CUxx = 0 of Section 6.4. -----+
oo
.
Total Energy is Conserved The kinetic energy of a mass is �mv 2 , when its velocity is v = du/ dt. The kinetic energy of a system of n masses is just the sum of n separate energies: ( 10)
Kinetic energy
The potential energy in a spring is �ce 2 , when its elongation is e. The potential energy in m springs is � (c 1 e� + · · · + cme;,) = �eTCe. Then e = Au brings in K: (11)
Potential energy
A n oscillation with no applied force f ( t ) conserves the total energy = Conservation
Mu 11 + Ku = 0 leads to
:t
"Hamiltonian."
( Kinetic + Potential) =
0 . (12)
Proof The ordinary derivative of a product u,v, has two terms, u i vf + u:v,. The derivative of u Tv = u 1 v 1 + + UnVn is the sum of n ordinary derivatives: ·
·
Derivative of dot product
·
:t uTv t (u,v: + u:v,) = uTv ' + (u ' )Tv. •= 1 =
� (��)TM (��) and PE = �uTKu: 1 du T d2 u + 1 d2 u T M du M dt dt 2 2 dt 2 2 dt
(13)
Apply this to the energies KE =
_:£ KE dt
( ) ( ) ( ) ( )
(14) (15)
2.2 Oscil lation by Newton's Law
119
The first terms o n the right add t o zero since Mu + Ku = 0. S o do the second terms. Therefore the left sides add to zero: total energy KE + PE is conserved. This is an excellent check on our codes.
1
Example 2 continued Suppose the masses m 1 = 9 and m 2 = 1 start from rest, so v(O) = u ( 0 ) = (0, 0) . The sine coefficients are B 1 = B2 = 0. The first mass is displaced so u(O) = ( 1 , 0) . The energy is 4 uTKu = 4 (81), all potential energy at the start.
1
Applied Force and Resonance Forcing terms f(t) = (h (t) , . . . , fn(t)) come from outside, like pushing a child on a swing ( or pushing n children on connected swings ) . Very often, all components of f(t) are oscillating at the same frequency w0 • Then we can solve Ku + Mu = fo cos w0 t. The oscillation will involve w0 as well as the n natural frequencies wi = A from the eigenvalues of M - 1 K. There is a critical case of resonance, when formulas break down. The forcing frequency equals a natural frequency, which can be good or bad. If we push a swing, we want it to go higher-so we match w5 = >. 1 . If we walk on a narrow bridge, we do not want it to oscillate-a good designer chooses >.'s that stay far from w 0 . The Millennium Bridge in London looked safe, but a sideways mode was overlooked. Here are solutions to mu + cu = cos w0 t, when w0 is near the natural frequency >. = JC1ffi and when w0 = >. exactly:
11
1
si n w0 t . (16) u(t) = t 2mw o Near resonance, the movie on the website shows large displacements because w5 - >. 2 is close to zero. At resonance, the movie has to stop because u(t) is blowing up. Near resonance
u ( t ) - cosm>.t( w -2 -cos"\ 2w) 0 t 0 _
Resonance
Explicit Finite Differences Large codes can find eigenvalues and eigenvectors in Kx = >. Mx . But the workhorse of computational engineering has finite differences in time. We begin with equal time steps Llt, and a centered second difference to replace Utt · Notice KU at time t: Leapfrog method with A. 2 U/ (A.t) 2
M [U(t+Llt) - 2U(t) + U(t-Llt)] + (Llt) 2 KU(t) = (Llt) 2 f(t)
U(t) is the approximation to u(t) . The centered time difference "leaps over" the forces KU(t) and f(t) to give U(t + Llt). It is natural to write Un for U( n ll t) . Then the new MUn + 1 comes explicitly from the known Un and Un 1 · Rewrite leapfrog: Explicit (17) MUn + 1 = [2M - (Llt) 2 K] Un - MUn - 1 + (Llt) 2 fn . _
120
Chapter 2 A Framework for Applied Mathematics
The starting value U0 is specified by u ( O ) . One step later, U1 also comes from the initial conditions: we can take U1 = u ( O ) + �t u 1 (0) , or do better. Then U2 , U3 , . . . come quickly from the explicit leapfrog equation (also called Stormer's method) . function u = leapfrog ( n ) dt = 2*pi j n; uold = 0; u = 3*dt; for i = 2 : n unew = 2*u- uold -9*dt/\2*u; uold = u; u = unew; end u C = nl\2 * u
% n time steps to t = 21r for u " + 9u = 0 % Starting values u ( O ) = 0 and u ( dt ) = 3 * dt % Leapfrog formula with Un+ l - 2un + Un-1 % Update u's for the next time step % Un approximates u ( 27r ) = sin(61r) = 0 % Second-order methods have leading error
Cj n 2
In practice, most computations work with first differences. By introducing the velocity v ( t ) , the differential equation Mu " + Ku = f becomes a first-order system: Mv 1 ( t ) + Ku ( t ) = f ( t ) and u ' ( t ) = v ( t ) .
First-order
(18)
A "staggered" difference equation involves Vn + 1 ;2 at ( n + �) �t. Centering the two first-order equations at staggered points produces a system equivalent to leapfrog: First-order
leapfrog
M
(vn+ 2 - Vn- 2 ) + �t KUn = �t fn 1
1
To see the equivalence, subtract the equation Un - Un 1 = �t Vn 1 at the previous time to find Un + 1 - 2 Un + Un 1 = �t(Vn + 1 - Vn 1 ) . Substitute into the first equation and (19) becomes (17) . The first-order system is better numerically. In molecular dynamics, discussed below, leapfrog is the "Verlet method" . The first order system (19) is a version of "velocity Verlet" . _
_
2
_
_
2
2
Stability and I nstability Stability places an essential limitation on the size of the step �t. To confirm that the stability condition is serious, we take 100 steps in a simple code for Mu " + Ku = 0. With step size �t = .64 in Example 2, the output is an explosion. That time step is just above the stability limit �t ::::; 2/ JIO = .632. The slightly smaller step �t = .63 has no explosion, but the output is totally inaccurate. The code divides �t by 2 until the ( �t ) 2 accuracy is dominant. Then smaller steps reduce the error by 4. Why is the stability limit between .63 and .64? Starting from Kx = >.. Mx , look for leapfrog's growth factor in the discrete normal mode U ( n �t ) = Gn x:
2.2 Oscillation by Newton 's Law
121
We cancelled an - l , leaving a quadratic equation with two roots. Their sum is that coefficient 2 - >.(.6.t) 2 • If this number is below -2, one of the roots is below - 1 and the leapfrog solution Gn x will grow exponentially. Example 2 has >. = 5 and 10:
(21)
Stability condition
Then (.63) 2 = .3969 gives a stable but very inaccurate U, and (.64) 2 = .4096 is a total disaster. Every stable .6-t has I G I = 1 exactly, so leapfrog has no damping. For a single mass with mu 11 +cu = 0, Problem 17 finds the condition tl.t � 2 Vm7C. Stability is a serious problem for explicit methods, studied in detail in Chapter 6. I mplicit Tra pezoidal Rule Large finite element codes need more stability than leapfrog offers. The way to remove limitations on .6-t is to move stiffness terms to the new time level t + .6-t. Since K is not a diagonal matrix, this produces a system of N equations for the N components of U(t + .6-t) . The time step is larger and safer but also more expensive. The model for an implicit method is the trapezoidal rule � (new + old):
Yn
Trapezoid
.6-t area 2 (Yn + 1 + Yn)
Yn +
1
(22)
t
If y(t) is linear as in the picture, the rule gives the correct integral-the area of the trapezoid. The approximation is second-order (because centered at the halfstep) . For a system dujdt = Au of differential equations, put dujdt for y in (22) : I ntegral of -
du dt
it+�t -du dt t dt
- (Au(t + .6-t)
.6-t + Au(t)) . (23) 2 When Un approximates u(t) , this is Un + l - Un = tl.t (AUn + l + AUn)/2. That equation has many names: Trapezoidal = Crank-Nicolson = Newmark = BDF2: u(t+.6.t) - u(t) =
Trapezoidal rule for
u
1
=
�
( 24)
Au
�t
When A is fixed, we can factor I - A into LU once and for all. In other problems, especially for large displacements, A depends on U (nonlinear equation) . An iteration will be needed and the natural choice is some form of Newton's method. This comes in Section 2.6, and here we pursue the key question of stability.
122
Chapter 2 A Framework for Applied Mathematics
Equation is a system 1 two cases, when the eigenvalues of A are
(23) Un + = GUnnegative with growth matrix G. You need to see or imaginary: 1 t - t Negative 0 G = (I - � A ) (I + � A) has eigenvalues I � � ��I 1 (25) �(�)ina:� G is barely stable: I � � �!�I = 1 and II Un + I l = II Un II (26) <
..X( A) <
Negative eigenvalues of A come from diffusion ( stable ) . Imaginary eigenvalues come from oscillation. Damping and viscosity push the real part of >. in the negative ( stable ) direction. The stability region for the trapezoidal rule is the half-plane Re >.(A) ::::; 0: if and only if Re ..X(A) � 0. Eigenvalues I ..X ( G ) I � 1
(27)
Second Order Equations To develop a trapezoidal rule for u 11 u 0, introduce the velocity v u 1 • The equation becomes v 1 u. All approximations are centered u 0 or v 1 at the half-step, for stability and second-order accuracy:
= M + K = M += K-M-= 1 K Trapezoidal rule for Vn + - Vn = -tl.tM- 1 K(Un + + Un) /2 (28) Un + Un = �t(Vn+ + Vn)/2 (29 ) = -M- 1 Ku, u 1 = v A very direct proof of stability shows that energy is conserved. Multiply (28) by ( Vn + + Vn)TM and multiply (29) by (Un + + Un)T K. Use MT = M and KT = K: VJ'+ l MVn + l - VJ' MVn= -�t(Vn+ l + Vn) T K(Un+l + Un)/2 (30) UJ + KUn + - U'J, KUn= tl.t(Un + + Un) T K( Vn + + Vn)/2 (31) Add (30) and (31) to see that energy is unchanged at time + 1 : Energy identity VJ'+ M Vn + + UJ + KUn + = V;[ M Vn + U'J, KUn . (32) This identity gives an excellent check on the code. Compare Vn, Un with Vo, U0. The new Vn + Un + come from the old Vn, Un by block matrices in (28) and (2 9 ): [ -tl.tIl/2�tM-I 1 K/2 ] [ UnVn ++ l ] = [ �tiI /2 -tl.tM-I 1 K/2 ] [ UnVn ] (33) B loc . orm If you multiply both sides by the block matrix on the right, the result is surprising. The off-diagonal blocks on the left become zero. Both diagonal blocks contain B = I + (tl.t) 2 M- 1 K/4. This is the matrix that has to be inverted at each step: 1 Kj2 ] 2 [ Vn ] . (34) [ I -tl.tMTrapezoidal rule B OJ Vn + l [ [ ] 0 B Un + Alternate form tl.tl /2 I Un The eigenvalues of B are 1 + ( �t) 2 >.j4, safely larger than 1. Introducing s - 1 = H leads to an unconventional but short code for M 11 + K = 0 trapezoidal rule . v
1
'
1 -
1
1
1
1
1
1,
1
1
1
1
1
n
1
1
1
1
k r
1
_
-
u
u
(
)
2.2 Oscillation by Newton's Law %
123
inputs M , K, d t , n , V, U ( initial values )
energyO = V ' * M * V + U ' * K * U ; H = inv(M + K * dt * dt/4) * M ; for i = 1 n % m u ltiply (U, V) twice by block matrix, then by H = B - 1 W= V - dt * inv(M) * K * U/2 ; U = U + dt * V/2 ; V = W - dt * inv(M) * K * U/2 ; U = U + dt * W/2 ; V = H* V; U = H* U; end % compute the energy change at T = n * dt change = V ' * M * V + U ' * K * U - energyO % change = 0, same energy [U, V] % output U(T) and V(T) :
Molecular Dyna mics For molecular dynamics, Newton's Law becomes u 11 + F (u) = 0. The force F depends nonlinearly on the position u. In fact F is the derivative or the gradient of a potential energy V(u) . When V = �uT Ku for a constant matrix K, we are back to the normalized linear model F(u) = Ku. In these pages, K depends on u. This is computational chemistry, a subject that requires fast computers for long times. It studies very fast vibrations. The goal is not the same as astronomy, which follows a single trajectory with high accuracy. Astronomers care about one planet, but chemists don't care about one atom! They average over millions of orbits and they live with errors in timing (phase errors) along those orbits. What astronomers and chemists cannot accept is a steady loss of energy for the sake of stability. Numerical damping is the savior of many computations in fluid dynamics, but it would bring a planet close to the Sun. The right choice for long time integration is a symplectic method, and the favorite in molecular dynamics is leapfrog-Verlet . We write it as "Velocity Verlet" or "velocity centered leapfrog" with Vn + .! = normal leapfrog value and Vn + 1 = saved value after the complete step: 2
Velocity Verlet
t1t ::; 2/>-.max(F ') : (!1t) 2 accuracy
stable
Vn - �t1t F(Un) Un + t1t Vn + .! Vn + .! - �t1t F(Un + I) 2
( 3 5)
2
Long-time I ntegration If you try to follow the Earth's orbit over many years, using Euler's explicit method Un + 1 = Un + t1t f(Un), you will soon be out beyond Pluto. These pages are about symplectic methods that maintain periodic motion, close to the correct orbits but not necessarily with the correct period. The Lotka-Volterra model from mathematical biology and ecology is an excellent nonlinear example with periodic solutions.
1 24
Chapter 2 A Framework for Applied Mathematics
Example 3
u1 v1
The Lotka-Volterra model with populations u and v (predator and prey)
u( v - b ) v(a - u)
Predator increases with more prey v Prey decreases with more predators u
The system is in eq uilibri u m when u = a and v = b ( a critical point where u 1 = v 1 = 0). If u0 < a at the start, the prey v will begin to increase (v 1 > 0). Then the predators u increase by feeding on the prey. When u passes a, the prey popu lation v starts to decrease. Then the predators decrease below a and the cycle starts again.To find this closed periodic orbit, combine the two eq uations and integrate:
v 1 ( v - b ) gives a log u - u = v + b log v + C. u 1 - u) = -(a (36) u v The constant C is determined by u 0 and v0 . The sol ution u(t) , v(t) stays on its own curve in Figu re 2. 10, which is drawn in the u-v plane ( the phase plane) . This cu rve shows where the popu lations go but not when. For the timing we compute u(t) and v(t).
u
Figure 2. 10: The predator u is in periodic equilibrium with the prey
Un + 1 = Un + b.. t f Un + �n + 1
v.
Symplectic methods preserve phase plane areas, and this section ends with four options. We already know most of them. The system of equations is u 1 = f ( u) . 1
I mplicit midpoint rule
2
Trapezoidal rule
(
)
b..t (f(U ) + J(U 1 )) Un + 1 = Un + 2 n n+
(37) (38)
For a partitioned system u 1 = g( u, v) , v 1 = h( u, v) like Latka-Volterra, we can treat u by backward Euler ( implicit ) and then v by forward Euler: 3
Partitioned Euler
(39a)
( 39b ) Vn + 1 = Vn + b.. t h(Un + I , Vn) A specially important partitioned system is u 1 = v and v 1 = -F(u) . This reduces to u 11 + F(u) = 0, for which the Stormer-Verlet-leapfrog method (35) was created.
2.2 Oscil lation by Newton's Law
125
What we now add is that Verlet is a composition of even simpler Euler methods, because the implicit step is actually explicit when u 1 = g (v) = v depends only on v: 4
Verlet for
2 at (Partitioned Euler) (Partitioned Euler reversing U, V)
This "composition idea" imitates our symmetric matrix AT A (now A is nonlinear) . In fact AT A will be midpoint or trapezoidal, when A is forward or backward Euler. Finally, the test for a (nonlinear) 2 by 2 symplectic method is straightforward:
Un + 1 = G(Un , Vn ) Vn + 1 = H(Un , Vn )
is symplectic if
aG aH - aG aH = 1 au av av au ·
( 40 )
The cse website displays the oscillations (normal modes) of a line of equal masses or a circle of masses. Each pure oscillation comes from an eigenvector of K or T or B or C. With n = 4 masses in a circle, the eigenvectors of C4 are (1, 1, 1 , 1) and (1, 0, -1, 0) and (0, 1 , 0, -1) and (1, - 1 , - 1 , 1). That fourth one is the fastest, with two pairs of masses going in opposite directions. The pictures are worth seeing! P roblem Set 2 . 2
[-�
Problems 1-8 are about the four ways to draw circles
1
2
]
(GF, G B , Gr , G£) .
1 � h 2 with eigenvalues AI , A 2 . (a) From the trace AI + A 2 = eifJ + e - ifJ, find cos (} = 1 - � h2 for h ::; 2. (b) At h = 2 find the eigenvalues and all eigenvectors of G L · (c) At h = 3 find the eigenvalues and verify AIA 2 = 1 but IAmax l > 1 . In Problem 1 , cos (} = 1 - �h2 turns into h = 2 sin((} 12) by a half-angle formula. Then (} = 21r IN and h = 2 sin( 1r IN) lead to cos N (} = cos 27r = 1. In this special case (UN , VN ) returns to (U0 , V0 ) and G N = I. For N = 3 and 4, plot the N points ( Un , Vn ) = Gn ( 1, 0 ) . Check the equal areas of the 3 and 4 triangles from ( 0, 0) to ( Un, Vn ) to ( Un + 1 , Vn+ I ) · The leapfrog matrix for u 11 +u = 0 is G L =
3
(Big challenge) I have no idea of the axes of the inner ellipse in Figure 2.7.
4
The leapfrog ellipse in Figure 2.6 has half-axes lTI and £T2 , the square roots of the eigenvalues of GIG£. Show that this matrix has determinant 1 (so lTilT2 = 1 ) and trace 2 + h4 (which is I + O"�, the sum of the eigenvalues) : £T
Ellipse close to circle
126 5
Chapter 2 A Framework for Applied Mathematics
[
l
The matrix in this question is skew-symmetric
du = dt
0
-b 0 a u b -a 0
-c
c
(AT = -A) :
or
( a ) The derivative of
llu(t) ll 2 = ui + u� + u5 is 2u 1 ui + 2u2 u� + 2u3 u£. Substitute uf, u�, u£ to get derivative = zero. Then ll u(t) 11 2 = ll u( O ) 11 2 . A A ( b ) In matrix language, Q = e t is orthogonal. Prove that QT = e t from A the series Q = e t = I + At + (At) 2 12! + . . . Then QTQ = e-AteAt = I. The trapezoidal rule conserves the energy llull 2 when u 1 = Au and AT = -A. Multiply (24) by Un + 1 + Un. Show that II Un + 1 11 2 = II Un ll 2 . The growth matrix Gr = (I - Ab.ti2)- 1 (I + Ab.tl2) is orthogonal like eAt if AT = -A. u 1 = Au conserves ll u ll 2 : (u, u) = (u 1 , u) + (u, u 1 ) = ((A + A T )u, u) = 0. t The trapezoidal rule has no energy error but a small phase error. The 32 steps with h = 27f 132 don't give a perfect 1. Compute >.32 and its angle () when >. = (1 + i�)l(1 - i�). Which low power of h is wrong when you compare >. with e• h ? Forward Euler multiplies the energy by 1 + h 2 at every step: -
.
6
7
8
Energy
U� + 1 + V� + 1 = (Un + hVn) 2 + (
Compute (1 + h2 )32 for h = 27f 132. Is it true or not that (1 + h2 ) 21r /h approaches 1 as h --t 0? If true, Euler does converge slowly. Show that a backward Euler step divides the energy U� + Vi by 1 + h2 . 9
The "ma" in Newton's Law has three steps dldt (m(u, t) duldt) . When the mass is constant, this is mu 11 • But Einstein found that mass increases with velocity. A low-speed example: Suppose rain falls into an open train at rate r = dmldt. What force F will keep the train at constant velocity v? ( Here ma = 0 but F '1- 0.)
10
In equation (16) , show that the resonance is the limit of the near resonance formula as approaches >.. L'Hopital's Rule f 1 I g 1 , for the limit as fIg ap proaches 010, is needed after all these years! w0
11
The "Hamiltonian" i s the total energy H = �pTM - 1 p + �uTKu for oscillating linear springs and masses. The position u and momentum p ( instead of the velocity u 1 ) are Hamilton's preferred unknowns. From Hamilton's equations p 1 = -8HI8u and u 1 = 8HI8p, derive Newton's Law Mu 11 + Ku = 0.
2.2 Oscillation by Newton's Law 12
127
H(p, u) = constant is a first integral for Hamilton's equations: dH = aH dp + aH du = - + - = O . rule dt ap dt au dt
Show that Chain
Great scientists hoped for a second integral, to complete the solution. We now know this is impossible for three attracting bodies. Pluto's orbit is chaotic.
13
14
The sun and one planet have H = �p� + � P� - (u� +u�) - 1 1 2 by the law of gravity. From pf = -aHjaui and uf = aHjapi show that the area A(t) = U 1 P2 - U2P 1 in the u-p plane has dA/ dt = 0. This is Kepler's Second Law: the line from sun to planet sweeps out area at a constant rate. Newton discovered Verlet's method in 1687 when he gave a geometric proof of this law (Principia Book I ) . "Gravitation is symplectic."
In the Lotka-Volterra example, a log u + b log v - u - v stays constant. With = log u and q = log v, this constant is H = ap + bq - eP - e q . Show that Hamilton's p 1 = -aHjaq and q 1 = aHjap are exactly the Lotka-Volterra equations. In logarithmic scale, area is preserved in the predator-prey plane.
p 15
The linear step Un + 1 = a Un + b Vn, Vn + 1 = c Un + d Vn is symplectic by the test ( 40) when = 1. What matrix G has determinant 1? Then triangle areas stay the same: __
det 16
[VnUn ++ 11
Un + 2 Vn + 2
18
= ( det G) det
. Show that nonhnear leapfrog also passes the test G(Un, Vn) H(Un, Vn)
17
]
[VnUn
Un + 1 Vn + 1
].
ac aH ac aH au av - av au
=
1.
Un + hVn Vn + hF(Un + 1 ) = Vn + hF(Un + hVn) -
For one equation mu 11 + cu = 0, write down the leapfrog equations for U + 1 and Vn + 1 · Find the growth matrix G and the sum of its eigenvalues ( the trace G 1 1 + G22 ) . Show that (.6.t) 2 � 4m/ c is the stability test for trace � -2. n
Graph the difference cos 9t - cos l lt. You should see a fast oscillation inside a slow 2 sin t envelope, because this difference ( an undamped forced oscillation ) equals 2 sin lOt sin t.
128
Chapter 2 A Framework for Applied Mathematics
2.3
L EAST S Q U A R ES FO R R ECTA N G U LAR M AT R I C ES
This section starts again with a linear system Au = b, but there is a big difference from Ku = f. The matrix K is square and invertible. In contrast, the matrix A is rectangular: more equations than unknowns ( m > n ) . The equations Au = b have no solution and A - l does not exist. We have to find the best solution u when the system Au = b is overdetermined: too many equations. Unsolvable equations are absolutely normal, when we try to fit m measurements by a small number n of parameters (linear regression in statistics) . We might have m = 100 points that nearly fall on a straight line. But a line C + Dx has only n = 2 parameters C and D. An exact fit means solving 100 equations with 2 unknowns. The closest line should be more reliable as m increases beyond 100 (more measurements) . But Au = b is less likely to be exactly solvable, as we try to fit more points. Example 1 Suppose we measure b = 1, 9, 9, 21 at the four positions x = 0, 1, 3, 4. If a straight line C + Dx passed through all four points ( wh ich I doubt ) , then the two u nknowns u = (C, D) would solve fou r eq uations Au = b: Line through 4 points: unsolvable
C C C C
+ + + +
OD 1D 3D 4D
1 9 or 9 21
(1)
Those eq uations have no sol ution. The vector b on the right is not a combination of the two col umn vectors ( 1 , 1, 1, 1) and (0, 1, 3, 4) . The first eq uation gives C = 1, then the second eq uation gives D = 8, then the other eq uations fail by a lot. This line 1 + 8x through the first two points is almost certainly not the best line.
The four equations in Au = b will have errors e1 , e2 , e3 , e4 . Right now one equation is not more reliable than another. So we minimize the sum e i + e � + e § + e� which is e T e. Since the residual error is e = b - Au (right side minus left side) , we are minimizing the total squared error E = (b - Au) T (b - Au) = ( sum of squares ) : E = (1
Total squared error E = ll ell 2 = li b - Au ll 2
- C - OD) 2 + ( 9 - C - 1D) 2 + ( 9 - C - 3D ) 2 + (21 - C - 4D ) 2 .
Our rule will be the principle of least squares. The vector e = b - Au gives the errors in the m equations. We choose u (in this case C and D) so that this error is as small as possible, and here we measure the error by ll e ll 2 = e i + · · · + e;, = E. If A has independent columns, then AT A is invertible. The normal equations will produce u. If A has dependent columns (or almost dependent, so its condition number is large) , the QR factorization is much safer. Least squares is a projection of b onto the columns of A.
129
2.3 Least Sq uares for Rectangular Matrices Summary
The (unweighted) least squares method chooses
Least Squares
u
to minimize
ll e ll 2 .
ll b - Au ll 2 = (b - Au) T (b - Au) .
Minimize
u,
We can use pure linear algebra to find the best or pure calculus. No statistics are involved at this point. We are treating all m measurements as independent and equally reliable. I will give away the answer immediately (the equation for and then explain it in two ways. The least squares estimate for u is the solution u of the square symmetric system using A T A:
u) , ( 2 ) Au=ATAu=b AT.ATb ATAu= ATb. [10 11 31 41 ] [ �11 3�4 ] [ CJ] = [ 01 11 31 41 J [ 21� ] ATA (3) x = 0, 1, 3, 4 b- = 2( -1,43,x 3) . = 2, 14, 18. b Au= A u = = (2, 4) = 318 b= � � [ �il � = [ 1148] 0 4 3 1 2. 1 : = 1 = 44.
"Normal equation"
In short, multiply the unsolvable equations
Example 1 (completed) The normal eq uation
by
Solve
in eq uation (2) is
9
D
After multiplication this matrix
.
is sq uare and sym metric and positive definite:
At this best line + in Figu re 2 . 1 1 has heights p 6, The minimum error p is e 5 The picture on the right is the "linear algebra way" to see least sq uares. We project to p in the col u m n space of (you see how p is perpendicular to the error vector e ) . Then p has the best right side p. The sol ution ( C, D) is the best choice of C and D. -
,
b
b
e4 P4
'
2
6
p
Figure
The total error is eT e
+ 9 + 25 + 9
-
p
projection of b onto = columns of A
Other lines have more error.
130
Chapter 2 A Framework for Applied Mathematics
U nderdetermined Equations and Sparsity Before continuing with least squares, allow me to mention recent developments. I can introduce them by discussing the opposite situation when the matrix A has m < < n. Then we have far fewer measurements ( samples in b) than descriptive parameters ( unknowns in u) . Instead of expecting no solution to an overdetermined Au = b ( and choosing a best u for m > n equations ) , the underdetermined Au = b has infinitely many solutions. What rule should govern the new choice u*? You would think that this century of data never leaves us with too few samples. But the fantastically active areas of gene expression analysis and bioinformatics present this problem all the time. We have 30, 000 genes, and maybe samples from 20 patients. The great puzzle ( very unsolved as I write this in 2007 ) is to discover which genes are responsible for the good or bad outcomes observed in those patients. A very similar problem appears in sparse sensing. A signal or an image is sampled only a few times, far fewer than the number of bits in the signal. How can we possibly reconstruct an accurate signal? This is closely related to sparse compression. How can we represent images by storing only a few bits, and still reconstruct their essential features with high probability ( although never 100 %)? Part of the answer is that the sum of squares norm ( Euclidean norm ) is not appropriate. That £ 2 norm led to the pseudoinverse A + in Section 1.7, but A+ b is generally a poor u* . In the gene expression problem, we are looking for a few responsible genes. A vector A + b that involves all 30, 000 genes in very small amounts is perfectly useless. Small is good in € 2 , because of the squaring, but zero is much better in many applications. We want a lot of zeros in u * , with a few nonzeros in the right positions. The norm that is dominating the new developments is the £ 1 norm :
£ 1 and L 1 norm ll u ll 1 I emphasize also the
=
j
l u 1 l + · · · + l un l and llu(x) l h = l u(x) l dx.
€ 1 and £ 1 norms of the difference !J.u and derivative u 1 (
j
( 4) x
):
ll ull v = lu2 - u 1 l + · · · + lun - Un - 1 1 and llu(x ) ll v = lu ' (x) l dx. (5) Minimizing ll ull v removes oscillations that don't cost much in € 2 or £2 . Section 4.7 Total variation
shows how these norms are used to compress signals and produce good images. Historically, the € 1 norm appeared in statistics because of outliers b, with large errors. Minimizing I I Au - bl l 2 gave too much importance to those b,. To fit data that includes significant noise, robust regression prefers to avoid squaring large (Au - b) i . It is curious that now ( to achieve sparsity ) we avoid squaring small u's. There is a computational cost in any move from € 2 to € 1 . The normal equation AT Au = ATb for the best €2 solution is linear. An € 1 penalty makes it piecewise linear, with exponentially many pieces. The problem is to identify which com ponents of the best u * are nonzero. This is the task of linear programming, to
2.3 Least Squares for Recta ngular Matrices
131
find the right m nonzeros among the n components o f u. The binomial coefficient (�) = n!jm! (n - m) ! counts the possible combinations. For m = 20 samples and n = 30, 000 genes, this is a daunting number that I won't even estimate. Section 8.6 describes two ways to compute u * : the simplex method and the interior point methods. Interior-point is a "primal-dual algorithm" that uses Newton's method of Section 2.6 on the nonlinear optimality equations in Section 8.6. To summarize: Energy minimization is a fundamental principle and it leads to €2 . That principle dominates this book. Minimization with sparsity leads to € 1 . This idea is at the heart of the intense efforts, and the host of proposed algorithms, to improve data compression and sampling. Surprisingly, the best sampling is by inner products with random vectors. Coherence will defeat the plan of reconstructing full images from sparse data. I notice sparsity appearing also in biomechanics: If many muscles are available to support a load, do a few of them actually do the job? The same question could be asked for human society: If m jobs have n > > m available workers, do m or n of them actually do the work ? Least Squares by Calculus Suppose we have only one unknown u but two equations. Thus n = (probably no solution) . One unknown means only one column in A:
Au = b The matrix A is 2 by
1 but m = 2
or
1. The squared error e T e is the sum of two terms: (6)
Sum of squares
The graph of E(u) is a parabola. Its bottom point is at the least squares solution u. The minimum error occurs when dE j du = 0:
(7)
Equation for u
Canceling the 2's leaves (a� + a�) u = (a 1 b 1 + a2 b2 ) . The left side is a� + a� The right side is now a 1 b 1 + a2 b2 = ATb. Calculus has found AT Au = ATb: produces Example 2 The special case a 1 = a 2 = 1 has two measu rements u = b 1 and the same quantity (like pu lse rate or blood pressure) . The matrix has AT = [1
= AT A. (8)
u = b2 of 1] . To
132
Chapter 2 A Fra mework for Applied Mathematics
mini mize If
( u - b 1 ) 2 + ( u - b2 ) 2 , the best u is j ust the average measurement:
b 1 +b2 a 1 = a2 = 1 then AT A = 2 and AT b = b 1 + b2 and u = 2 �
The average u between
b 1 and b2 makes the sum of sq uared distances smallest.
For m equations Au = b in n unknowns, we need matrix notation. The squared errors add to E = lib - Aull 2 = II Au - bll 2 . In (6) this was (a 1 u - b 1 ) 2 + (a2 u - b2 ) 2 . Now we separate the quadratic term 11 Aull 2 = uT AT Au from the linear terms and the constant term bTb, to see the general case: (9)
Error squared
The term (Au)Tb is the same as bT(Au) ; either vector can come first, making 2uT ATb. Write K = AT A in the quadratic term, and f = ATb in the linear term: Minimize uTATAu - 2uTATb + bTb which is uTKu 2 uTf + bTb . The constant term bTb doesn't affect the minimization. The minimizing u solves Ku = j, which is AT Au = ATb. When K = AT A is positive definite we know that u yields a minimum in Figure 2.12 and not a maximum or a saddle point. For two variables u = (u 1 , u 2 ) , we can see Ku = f by calculus: -
Minimize (kuu � + k 1 2 U 1 U2 + k2 1 u 2 u 1 + k22 u � ) - 2 (u dl + u 2 /2 ) + bT b u 1 derivative is zero: 2(knul + k 1 2 fi2 - h ) = 0 which is Ku = f.
curved surface E(u)
E(u) = l l e l l 2 = minimum squared error
u2 u = u
U!
minimizer
Figure 2.12: The graph of E(u) = l i b - Au ll 2 is a bowl opening upward. The lowest point occurs at u = (AT A) - 1 ATb. There E(u) = ll e ll 2 = ll b ll 2 - IIAfill 2 .
2.3 Least Sq uares for Rectangu lar Matrices
133
Error vector e is orthogonal to plane
column
a1
Column 1 : Column 2 :
aTe = 0 aie = 0 ATe = AT (b - Au) = o Then AT Au = ATb
Figure 2. 13: The projection p is the nearest point to b in the column space of The perpendicular error e = b - Au has ATe = 0. Then AT Au = ATb.
A.
Least Squares by Linear Algebra In the linear algebra picture, b is in m-dimensional space. The impossible equation Au = b is trying to write b as a combination of the n columns of A. But those columns only give an n-dimensional plane inside the much larger m-dimensional space. The vector b is not likely to lie in that plane, so Au = b is not likely to be solvable. The least squares choice Au is the point in the plane that is nearest to b. Here is the one-line proof from Section 1.6 that the total error E in equation (9) has its minimum when u = K - 1 f = (AT A) - 1 ATb. Rewrite E(u) in a special way:
The right side is smallest when its first term is zero, because that term is never negative. So the minimizer is u = K - 1 f. Then E reduces to the last two terms: Em i n = - JT K - 1 f + bTb, which is also the bottom height in the calculus picture:
Figure 2.13 has the error e = b - Au in its correct place. This error is not zero (Au = b has no solution) unless perfect measurements put b in the column space. The best Au is the projection p. This is the part of b that we can account for, by the columns of A. The residual error e = b - Au is the part we can't account for. The picture shows the key to the projection Au. Now we need the equation.
134
Chapter 2 A Framework for Applied Mathematics
�
The error vector e = b - Au is perpendicular to the column space. The n
l [ l [�l
dot products of e with the columns of A are all zero, which gives n equations ATe = 0:
[
Perpendicularity
(colum
1)T
(column n?
e
or
ATe = 0 .
0
This geometry equation ATe = 0 finds u. The projection is p = Au (the combination of columns that is closest to b) . We reach again the normal equation for u: ( 1 2)
Linear algebra
Changing from the minimum in calculus to the projection in linear algebra gives the right triangle with sides b, p, e. The perpendicular vector e hits the column space at the nearest point p = Au. This is the projection of b onto the column space:
(13)
Projection
The system Au = b had no solution. The system Au = p has one solution u. We are making the smallest adjustment from b to p that puts us in the column space. The measurements are inconsistent in Au = b, but consistent in Au = p. The projection matrix P = A( AT A) - 1 AT is symmetric. It has the special property P 2 = P, because two projections give the same result as one projection. P is m by m but its rank is only n. All three factors in A( AT A) - 1 AT have rank n. Example 3 A plane is overdetermined by trying to pass through fou r points in space. Find the closest plane b = C + Dx + Ey ( choose the best three para meters C, D , iE).
Fou r u nsolvable eq uations Au = b aim to reach height b i above (xi , Yi ) · They have no sol ution u = (C, D, E) . The normal eq uation AT Au = ATb gives the best u = C, D , E) and the closest plane in Figure 2. 14. Solution
C + Dx 1 + Ey 1 = b1 C + Dx 2 + Ey2 = b2 C + Dx3 + Ey3 = b3 C + Dx4 + Ey4 = b4
b
r--r---4----,-�-•
X
Figure 2. 14: The equation
•
y
AT Au = ATb gives u = (C, D , E) and the closest plane.
2.3 Least Sq uares for Rectangu lar Matrices
135
Example 4 Suppose we are tracking a satellite or monitoring the net worth of a company.
( There is uncertainty in both. ) Let us accept u 0 = 0 as an accurate starting val ue, in kilometers and dollars. We measu re the changes u 1 - u 0 , u 2 - u 1 , u 3 - u 2 between times t0 and t 1 , then t 1 and t 2 , then t 2 and t 3 . The measu rements give u 1 - u0 = b 1 ( with variance a� = 1/c!) u 2 - u 1 = b2 ( with varia nce a� = 1/c2 ) u 3 - u2 = b3 ( with variance a� = 1/c3 ) It would not be surprising if ci is proportional to the time interva l t i +1 -ti ( greater accu racy over a short time interva l ) . For the 3 by 3 system we don 't need least sq uares:
u 1 = b1 gives u 2 = b 1 + b2 U 3 = b 1 + b 2 + b3
(14)
Now add a measu rement b4 of u 3 ( with variance al = 1/ c4 ). This adds a fourth row to A, and Au = b becomes recta ngular. We use weighted least sq uares:
Please notice AT A, which is our fixed-fixed matrix K3 . The matrix ATCA already appeared in Section 2 . 1 , for a line of fou r springs. This example connects least sq uares to physics, and it leads to recursive least squares and the Kalman filter: How can we update the old u to the new u which accounts for b4 ? Adding a new row to A only changes ATCA in its last row and col u m n . We want to compute the new u from ATCA ( now including c4 = 1/al) without repeating the work already finished using b 1 , b2 , h Section 2.8 will update u by recursive least squares.
Computational Least Squares We stay with the basic question in numerical linear algebra: How to compute u? So far you have only seen one way: Solve the normal equations by elimination. That requires forming AT A or ATCA, and most people do it. But the condition number of AT A is the square of the condition number of A in Section 1.7. Working with AT A can make an unstable problem very unstable. When stability is in doubt, experts recommend a different computation of u: orthogonalize the columns. The rectangular matrix A is split into Q R.
136
Chapter 2 A Framework for Applied Mathematics
A = QR has a matrix Q with orthonormal columns times an upper triangular matrix R. Then AT Au = ATb reduces to a much simpler equation, because QTQ = 1: We multiply QTb (this is very stable) . Then back-substitution with R is very simple. For full matrices, producing Q and R takes twice as long as the mn 2 steps to form AT A. That extra cost gives a more reliable solution. One way to compute Q and R is by Gram-Schmidt (modified) . The orthonormal columns q1 , . . . , qn come from the columns a1 , . . . , an of A. Here is how Gram and Schmidt might do it in MATLAB. Start with [m, n] = size(A) ; Q = zeros(m, n ) ; R = zeros(n, n ) ; to initialize the matrices, then go a column at a time: % Gram-Schmidt orthogonalization = 1:n % v begins as column j of A v = A( : , j); % columns up to j - 1, already settled in Q for i = 1 : j - 1 R(i, j) = Q(:, i) * A(: , j) ; % modify A(:, j ) to v for more accuracy % subtract the projection (q[ ai)qi = (q[ v)qi v = v - R(i, j) * Q(: , i) ;
for j
I
end
R(j, j) = norm (v) ; Q(: , j) = vjR(j, j) ;
%
v is now perpendicular to all of q1 , . . . , (jj - 1
% normalize
end
v to be the next unit vector qi
If you undo the last step and the middle steps, you find column j: j-1 R(j, j)% = ( v minus its projections) = (column j of A) - L R( i, j) q, . (16) i =1 Moving the sum to the far left, this is column j in the multiplication A = QR. That crucial change from ai to v in line gives "modified Gram-Schmidt." In exact arithmetic, the number R( i, j ) = q[ ai is the same as q[ v. (The current v has subtracted from ai its projections onto earlier q 1 , . . . , q,_ 1 . But the new qi is orthogonal to those directions. ) In real arithmetic this orthogonality is not perfect, and computations show a difference in Q. Everybody uses v at that step in the code.
4
A is 2 by 2. The col umns of Q, normalized by i · are q1 and q2 : A = 3 - 21 = �5 3 -3 05 - 21 = QR . (17) Starting with the col u m ns a 1 and a2 of A, Gram-Schmidt normalizes a1 to q1 . Then it
Example 5
[4 ]
[4 4] [
]
su btracts from a2 its projection in the direction of q 1 . Here are the steps to the q's:
·
2.3 Least Sq uares for Rectangu lar Matrices
137
Along the way, we divided by lla 1 ll = 5 and ll v ll = 2. Then 5 and 2 go on the diagonal of R, and q!a2 = -1 is R(1 , 2) . The left side of Figu re 2. 15 shows every vector. 5
1
a=
[ -68 ] = 2q2
[:]
w = a - r
r=
H reflects a to r along u Gram-Schmidt
Figure
[� ]
Householder
2.15: Gram-Schmidt finds q 1 then q2 . Householder finds r first then u. Householder Reflectors in Q
MATLAB finds [Q, R] = q r (A) in a new way that Gram and Schmidt never thought of. It is more like elimination, where row operations reach an upper triangular U. Now the goal is R. We produce zeros below the diagonal of R by "reflection matrices." At the end, the orthogonal matrix Q is the product of those reflectors. The reflection matrices H have Householder's special form H I 2uu T . Here u is a unit vector w/ ll w ll , chosen t o produce the zeros i n equation (19) below. Notice that H is automatically symmetric and also orthogonal (HT H is I) : HT H = (I - 2uuT ) (I - 2uuT ) = I - 4uuT + 4uuT = I because uT u = 1 . (18) H reflects u into -u, because (I - 2uuT)u = u - 2u. All vectors x perpendicular to u are unchanged by H, because (I - 2uuT)x = x - 0. So H reflects every vector like x + cu to its image x - cu on the other side of that mirror perpendicular to u. How does H produce zeros below the diagonal of R ? Look at the first column a 1 of A, reflected to column r 1 = H1 a 1 of R. We must keep ll r 1 ll = ll a 1 ll , since HT H = I and reflections preserve length: =
H creates 3 zeros in
-
(19)
r
Figure 2. 15 shows the unit vector u 1 in the direction of w 1 a 1 r1 . MATLAB chooses between + ll a 1 ll and - 11 a 1 ll in r. By storing u 1 = w d ll w 1 ll it knows H1 . =
-
For the same 2 by 2 matrix A in (17), the first col u m n ( 4, 3) can be reflected to the first col umn r 1 = (5, 0) . That zero in r 1 makes R upper triangu lar.
Example 6
1 u 1 = v'fO
[ -13 ]
H1
= I-2u 1 uT1 = 51 43 _ 43
[
]
1 38
Chapter 2 A Framework for Applied Mathematics
The next step finds the next column r2 of R. Where equation (19) needed 3 zeros in r 1 , we just need 2 zeros in r2 . We only work on and below the diagonal of HA. The Householder code starts step k with column k of the current A. It looks at the lower part a on and below the diagonal. It finds w and the unit vector u (upper part zero) for the next reflector Hk . Multiplying by Hk gives n - k zeros in column k of the next A, which is turning into R. The u's are saved in a matrix U, to remember all the reflectors H1 , . . . , Hn that go into Q. We never multiply matrices to form Q ! When we need Q Tb in the simplified normal equation Ru = Q Tb, the n reflectors are applied in reverse order to b. Here is the commented code to construct the orthogonal U and upper triangular R:
[U, R] = house ( A ) % Produce R from Householder reflectors saved in U [m, n] = size(A) ; U = zeros(m, n) ; for k = 1 : n % start with column k of current A, from diagonal down w = A(k : m, k) ; w(1) = w(1)- n orm ( w ) ; % subtract ( ll w l l , 0, . . . , 0) from a = w. New w = a-r u = w j n orm ( w ) ; % normalize to unit vector u in the kth reflector Hk % save u in U to know the H's that produce Q U(k : m, k) = u; A(k : m, k : n) = A(k : m, k : n) - 2 * u * (u ' * A(k : m, k : n) ) ; % multiply current A by Hk function
end
R = triu(A(:, 1 : n) ) ;
% square R from nonzeros on and above diagonal of final A
I thank Per-Olof Persson for the Gram-Schmidt and Householder codes (and others ! ) . The Singular Value Decomposition in Section 1.7 factors A into U�VT. Here U and v are orthogonal matrices (UT = u - l and VT = v - 1 ) . Then ATA = v�T�VT. This leads to a formula for u that is the most stable of all: That matrix � + has 1/a1 , . . . , 1/an on its main diagonal and zeros elsewhere. An important advantage is that we can monitor the singular values a 1 2': . . . 2': O"n > 0. ATA is ill-conditioned when an is small. If O"n is extremely small, remove it. The operation count for the SVD is often comparable to QR. Here � + is the "pseudoinverse" of � . and v� + uT in (20) is the pseudoinverse of A. That is the neatest formula for the least squares solution of Au b, overdetermined or underdetermined: u A+b v�+uTb. =
=
=
Weighted Least Squares Section 2.8 will use statistical information about the measurement errors e. This is the "noise" in the system, and the true equation is Au = b - e. Typically, the errors e, (plus and minus) average to zero. Each "expected error" is E [e,] = 0. Otherwise
2.3 Least Squares for Rectangu lar Matrices
139
the zero point on the ith meter should be reset . But the average of er, which can't be negative, is almost certainly not zero. This average E [er] is the variance ul . Now we can bring in C, the weighting matrix. A small variance (JT implies that the measurement bi is more reliable. We weight that equation more heavily by choosing ci = 1/(JT- When the errors ei are not independent (next section) , the "covariances" E [e i ej] also enter the inverse of C. We are now minimizing the weighted error eTCe, where unweighted least squares (C = I) just minimizes eTe. The best u, taking these weights into account, comes from ATCAu ATCb. Our three-matrix framework fits perfectly. We learn the best u, and we also learn the statistics of u - u. How reliable is u (ATCA) - 1 ATCb ? This step comes in Section 2.8, where the errors ei need not be independent. The matrix of variances and covariances, in the outputs u, turns out to be (ATCA) - 1 . =
=
P roblem Set 2 . 3
1
Suppose Au = b has m equations ai u = bi in one unknown u. For the sum of squares E(u) = (a 1 u - b 1 ) 2 + · · · + (am u - bm ) 2 , find the minimizing u by calculus. Then use linear algebra to form AT Au = ATb with one column in A, and reach the same u.
2
Suppose Au = b has a solution
3
u. Show that u = u. When is u unique? A QR experiment on the Vandermonde matrix V = fliplr ( va nder ( ( O : 49)/49)) is proposed by Trefethen-Bau [159] . A = V(:, 1 : 12) and b = cos(O : .08 : 3.92) 1 have m = 50 and n = 12. In format long compute u in multiple ways (MATLAB's svd ( A ) is another way) . How many correct digits does each method yield?
1. 2.
3. 4. 5.
Directly from the normal equations by AT A\(ATb) From the unmodified Gram-Schmidt codes by R\(QTb) From the modified Gram-Schmidt code with v in line 4 From the Householder code using 12 columns of Q and 12 rows of R From MATLAB's A\b and MATLAB's q r (which uses Householder)
4
From the columns a 1 and a2 of [2 2 1 ; - 1 2 2] 1 , follow the steps of Gram-Schmidt to create orthonormal columns q 1 and q2 . What is R ?
5
For the same first column a 1 , follow the Householder steps to construct r 1 , w 1 , u 1 , and H1 . The second column of H1 A still needs work, on and below the diagonal (call those two components a2 ) . Follow the same steps to construct r2 , w 2 , u 2 , and H2 (with first row 1 , 0, 0) . Then find H2 H1 A = Q - 1 A = upper triangular R.
6
For stability, MATLAB chooses the sign in (15) opposite to the sign of a(1) . Our example with a = ( 4, 3) changes to r = ( - 5 , 0) and w = a - r = (9, 3) . Find u = w/llw ll and H = I - 2uuT and check that HA is upper triangular.
140
Chapter 2 A Framework for Applied Mathematics
7
With b = ( 4, 1 , 0, 1) at the points x = (0, 1 , 2, 3) , set up and solve the normal equation for the coefficients u = (C, D) in the nearest line C + Dx . Start with the four equations Au = b that would be solvable if the points fell on a line.
8
In Problem 7, find the projection p = Au. Check that those four values do lie on the line C + D x. Compute the error e = b - p and verify that ATe = 0. (Problem 7 by calculus) Write down E = l i b - Au ll 2 as a sum of four squares the last one is (1 - C - 3D ) 2 . Find the derivative equations 8Ej8C = 0 and 8Ej8D = 0. Divide by 2 to obtain the normal equation AT Au = AT b.
9
10 11
12
13
Find the height of the best horizontal line to fit b = (4, 1, 0, 1). Use the 4 by 1 matrix in the unsolvable equations C = 4, C = 1, C = 0, C = 1.
In Problem 7, the average of the four x ' s is x = i (O + 1 + 2 + 3) = 1.5. The average of the four b's is b = � ( 4 + 1 + 0 + 1 ) = 1.5 (by chance) . Verify that the best line b = C + D x goes through this center point ( 1.5, 1.5 ) . How does the first equation in AT Au = ATb lead to that fact C + Dx = b ? For the closest parabola C + Dx + Ex 2 to the same four points, write down the unsolvable equations Au = b for u = (C, D, E) . Set up the normal equation for u. If you fit the best cubic C + D x + Ex 2 + Fx 3 to those four points (thought experiment) , what is the error vector e ? Factor the 4 by 3 matrix A created in Problem 12 by [Q, R] = qr(A) . Solve R u = Q T b in equation ( 15 ) , and verify that u solves the full normal equation AT Au = ATb. Compute the error vector e = b - Au and compare ll e ll 2 for this quadratic C + D x + Ex 2 to ll e ll 2 = 4 for the best line.
Problems 14-17 introduce key ideas of statistics-the basis for least squares
14
(Recommended) This problem projects b = (b 1 , , bm) onto the line through a = ( 1 , . . . , 1 ) . We solve m equations au = b in 1 unknown (by least squares) . .
.
•
(a) Solve aT au = aT b to show that u is the mean (the average) of the b's. (b) Find e = b - au and the variance ll e ll 2 and the standard deviation ll e ll · (c) The horizontal line b = 3 is closest to b = ( 1, 2, 6) . Check that p = (3, 3, 3) is perpendicular to e and find the projection matrix P = A( AT A) - 1 AT. 15
First assumption behind least squares: Each measurement error has mean zero. Multiply the 8 error vectors b - Au = (±1, ±1, ±1) by (AT A) - 1 AT to show that the 8 vectors u - u also average to zero. The estimate u is unbiased.
16
Second assumption behind least squares: The m errors ei are independent with variance a 2 , so E[(b - Au) (b - Au) T ] = a2 I. Multiply on the left by (AT A) - 1 AT and on the right by A(AT A)- 1 to show that E[(u - u) (u - u)T] is a2 (AT A) - 1 . This is the covariance matrix for the error in u.
141
2.3 Least Sq uares for Recta ngular Matrices
A doctor takes 4 readings of your heart rate. The best solution to u = b 1 , u = b2 , u = b3 , u = b4 is the average u of b 1 , . . . , b4 . The matrix A is a column of 1 's. Problem 16 gives the expected error (u - u) 2 as 0" 2 (AT A) - 1 = . By averaging, the variance drops from 0" 2 to 0"2 /4. 18 If you know the average u9 of 9 numbers b 1 , . . . , b9 , how can you quickly find the average u1 0 with one more number b 1 0 ? The idea of recursive least squares is to avoid adding 10 numbers. What coefficient correctly gives u 1 0 ? 17
__
19
Write down three equations for the line b = C + Dt to go through b = 7 at t = -1, b = 7 at t = 1 , and b = 21 at t = 2. Find the least squares solution u = ( C, D) and draw the closest line.
20
Find the projection p = Au in Problem 19. This gives the three heights of the closest line. Show that the error vector is e = (2, - 6, 4) .
21
Suppose the measurements at t = -1, 1, 2 are the errors 2, 6 4 in Problem 20. Compute u and the closest line to these new measurements. Explain the answer: b = (2, -6, 4) is perpendicular to __ so the projection is p = 0.
22
Suppose the measurements at t = - 1 , 1, 2 are b = (5, 13, 17) . Compute the closest line and e. The error is e = 0 because this b is
-
,
u and
t = -2, - 1, 0, 1, 2. 24 Find the plane that gives the best fit to the 4 values b = (0, 1, 3, 4) at the corners (1, 0) and (0, 1) and (-1, 0) and (0, -1) of a square. The equations C + Dx + Ey = b at those 4 points are Au = b with 3 unknowns u = ( C, D, E) . At the center (0, 0) of the square, show that C + Dx + Ey = average of the b's. 25 Multiplying AT A seems to need n 2 inner products, but symmetry cuts this in 23
Find the best line C + Dt to fit b = 4, 2, - 1 , 0, 0 at times
half to leave mn 2 operations (multiply and add) . Explain where the Gram Schmidt code uses 2mn 2 operations. (So does the Householder code.)
26
The Householder matrices in Q are square. So that factorization A = Q R is ( m by m ) ( m by n ) where Gram-Schmidt is reduced to ( m by n ) ( n by n ) .
The Gram-Schmidt columns in QGs are an orthonormal basis for m - n columns in Q n u ll are an orthonormal basis for . __
The
142
Chapter 2 A Framework for Applied Mathematics
G RA P H M O D E LS AND K I RC H H O F F ' S LAWS
2.4
This section will develop the most important model in applied mathematics. We begin with a graph, consisting of n nodes connected (or not) by m edges. Those connections are recorded in an m by n "incidence matrix" A. In row j of A, the nonzeros -1 and 1 indicate which two nodes are connected by the jth edge. A line of springs is a special case. Then A is a first difference matrix, and AT A is a second difference matrix (it has - 1 , 2, -1 on the inside rows) . I can name right away the key matrices for any graph, starting with the "Laplacian" AT A:
(1)
AT A = D - W = (diagonal) - (off-diagonal)
Graph Laplacian
W is the adjacency matrix and D is the degree matrix. The number w,1 tells whether nodes i and j are connected by an edge. The number di1 tells how many edges meet node j. For four springs, AT A is the free-free second difference matrix B4 :
Degrees
Adjacency
Laplacian
For other graphs the edges are no longer in a line, and AT A is no longer tridiagonal. You will expect ATCA to appear, when C is a diagonal matrix of m weights: Wei gh ! ed ATCA L ap l ac1an
[
=
D - W = (node weight matrix) - (edge weight matrix) (2)
] [� ] [
If three edges in a line have weights
a b -b ATCA = !:.a --: -b b + c -c
-c c
Weighted Laplacian
a, b, c in C, those numbers enter W and D: W=
� b b 0
c
c
D=
0
Edge weights
a
a+b
b+c c
Node weights
Notice especially the sums along every row of these matrices: Row sums of W are in D
l
Row sums of ATA and ATCA are zero
Those zero row sums put (1, 1 , 1 , 1) into the nullspace of A and A T A and AT CA. These are great matrices to work with. This section creates the matrices; Section * 2.9 on Graph Cuts and Gene Clustering uses the eigenvalues.
2.4 Graph Models and Kirchhoff's Laws
143
The graph in Figure 2.16 shows m = 6 edges connecting n = 4 nodes. This is a complete graph ( all possible edges ) . It is also a directed graph ( each edge has a direction arrow ) . Those arrows will determine the signs in the incidence matrix A, but they don't affect AT A or ATCA. For this graph model, our framework can have
three equations or two or one:
e = b - Au w = Ce f = ATw
(3)
These equations will soon extend to finite differences and finite elements for differen tial equations. I think of (3) as the ''fundamental problem of scientific computing. " The I ncidence Matrix The incidence matrix A has m = 6 rows and n = 4 columns. Each row corresponds to an edge in the graph, and each column corresponds to a node. We do have to number the edges and nodes, and also choose directions for the arrows, in order to construct A. But the numbering and edge directions are arbitrary. Flows can travel both ways, and a different choice of arrows will not change the reality of the model. The entries -1 and 1 in each row of A give a record of the corresponding edge: Row 1
The first edge leaves node 1 and goes to node 2. The first row has - 1 in column 1 and + 1 in column 2.
Row 5 is typical. Edge 5 leaves node 2 ( by -1 in column 2) , and it enters node 4 (+1 in column 4) . We chose arrows from lower-numbered nodes to higher-numbered nodes, for simplicity. Then the - 1 comes before the +1 in each row. In all cases, you can write down A immediately by looking at the graph. The graph and the matrix have the same information. node
CD ® ® CD
-1
A=
1
0
0
-1 0 1 0 -1 1 -1 0 0 0 -1 0 0 0 -1
0 0 1 1 1
1
2
3
4 5 6
edges 1 to 6
Incidence matrix
Figure 2.16: Complete graph with m = 6 edges and
n
= 4 nodes. A is 6 by 4.
144
Chapter 2 A Framework for Applied Mathematics
Our second example is a subgraph of the first. It has the same four nodes but only three edges 1 , 3, and 6. Its incidence matrix is 3 by 4. Removing three edges from the graph just removes three rows from the incidence matrix. This graph is a tree. It has no closed loops. The tree has only m = n - 1 edges, the minimum to connect all n nodes. The rows of A are linearly independent! A complete graph has the maximum number of edges m = �n(n - 1 ) , to connect every pair of nodes. Other subgraphs are also trees; the three edges 1 , 2, 4 come out from one node. (The six edges contain a total of 16 trees . ) The rank of Atree is r = 3.
[
Atree =
node
CD ® ® @
1 0 -1 0 0
0 1
-1
n
1 3
edge
6
-1 Incidence matrix
Figure 2 . 17: A tree has no loops. With 4 nodes it has 3 edges. The matrix A has two purposes. It gives a record of all connections in the graph (it is a topology matrix) . At the same time, we can multiply A times a vector u. The matrix can act. When A multiplies u, you see it as a difference matrix:
0 0 1 0 0 -1 1 0 -1 0 0 1 0 -1 0 1 0 0 -1 1 -1 -1
Differences across edges
Au
=
1
0
[
��]
u2 - u1 u3 - u1 u3 - u2 u4 - u1 u4 - u2 u4 - u3
(4)
The numbers u1 , u2 , u3, u4 could represent the heights of the nodes, or the pres sures at the nodes, or the voltages at the nodes. Most often they are simply called potentials. Then the vector Au contains the "potential difference" across each edge:
U =
{
heights pressures voltages potentials
Au =
{
height differences pressure differences voltage differences potential differences
This model of nodes and edges is everywhere. The main point is that the n component node vector u leads to an m-component edge vector Au.
2.4 Graph Models and Kirchhoff's Laws
145
The N u llspace of A The nullspace of A contains the vectors that solve Au = 0. When the columns of A are independent, the only solution is u = 0 and the nullspace contains only that one "zero vector." Otherwise the nullspace might be a line of u's, or a plane, depending on how many combinations of the columns of A lead to Au = 0. For incidence matrices, the nullspace is a line. Constant vectors solve Au = 0:
u=
m
�d �y u =
[ �]
will satfficy
Au = 0 .
(5)
In every row of Au, -C is canceled by +C and we get Au = 0. More intuitively, we see Au as a vector of differences. When the components of u are all equal to C, every difference is zero in Au. Thus u = ( C, C, C, C) is a vector in the nullspace of A . This applies to the complete graph and the tree example and all connected graphs. AT A has the same nullspace as A, containing the constant vectors. The word "connected" means that each pair of nodes is connected by a path of edges. The graph does not break up into two or more separate pieces. If it did break up, the vector u could be all ones in the first piece and all zeros in the other pieces. This would still have differences Au = 0 across all existing edges; it would be in the nullspace. The dimension of the nullspace N(A) is the number of separate pieces, and we always assume that this number is one : a connected graph. The rank of A is r = n - 1. Any n - 1 columns of the incidence matrix are linearly independent. But the n columns are linearly dependent: their sum is the zero column. We will have to remove one column ( ground one node ) to produce independent columns in A. Then AT A is invertible (and positive definite) . We can only solve for the n - 1 potentials after one node is grounded: say u4 = 0.
Looking ahead For m currents and n- 1 voltages, we will need m+n- 1 equations. We have Ohm's Law on m edges (involving A) and Kirchhoff's Law at n - 1 nodes (involving AT) . The right sides are voltage sources (batteries b 1 , . . . , bm) and current sources f. Here is the framework and the all-important block matrix ( KKT matrix ) : Ground U4 = 0
Batteries
b e
=
b - Au
w=
Ce (Ohm's Law)
[ �;1 � ] [ : ] [;] =
146
Chapter 2 A Fra mework for Applied Mathematics
Kirchhoff's Current Law A T w
=
0
ATw = 0 enforces zero net flow into every node: Flow in equals flow out . These are the balance equations for the currents w 1 , . . . , Wm along the edges. There are n equations in ATw = 0, one for each node. We are looking for currents that "balance themselves" without any current sources from outside. The nullspace of AT is more interesting than the line of constant vectors in the nullspace of A. ATw = 0 is Kirchhoff's Current Law ( KCL ) . It is crucial for our framework that transposing A produces the correct statement ATw = 0 of Kirchhoff's Law. -WI - w2 - w4 = 0 at node 1 -1 -1 0 -1 0 0 1 0 1 0 1 0 2 WI - W3 - W 5 = 0 AT = 0 1 1 0 0 -1 3 (6) w 2 + w3 - w 6 = 0 0 0 0 1 1 1 4 w4 + w 5 + w6 = 0
[
l
The plus and minus signs in the equations are consistent with the arrows. At node 1 , all arrows go outward ( the flows WI , w2 , w4 can go either way! ) . Kirchhoff's Law says that those flows add to zero ( no net flow ) . But the four equations are not independent. If we add the equations, everything cancels to give 0 0. The rows of AT add to the zero row-because the columns of A add to the zero column. When we remove column 4 of A ( by grounding node 4) this removes row 4 of AT. That fourth equation w4 + w 5 + w6 = 0 comes from the other three equations. So ATw = 0 has n - 1 = 3 independent equations in m = 6 unknowns WI , . . . , w6 . We expect 6 - 3 = 3 independent solutions. This is m - ( n - 1) . What are the solutions to AT w = 0 ? Which flows on the six edges balance at every node? It is certainly possible to solve by elimination, but fortunately there is a direct way to visualize a flow that "balances itself." Suppose one unit of flow goes around a closed loop. Let the flow be zero on all other edges not in the loop. Kirchhoff's Law is satisfied by this loop flow w: =
Loop flow
+ 1 when edge i is in the loop, in the arrow direction - 1 when edge i is in the loop; flow against the arrow 0 when edge i is not in the loop 1
Loop flows
0
0 0
-1
1 0
0
W = -1
0 1
-1
(7)
0
0 1
0
-1 1
Figure 2. 18: Three independent loop flows solve Kirchhoff's Current Law ATw = 0.
2.4 Graph Models and Kirchhoff's Laws
147
The loop of nodes 1 - 2 - 4 - 1 in Figure 2.18 consists of edge 1 then edge 5 then backward on edge 4. Thus W I = 1 , w5 = 1 , w4 = - 1 solves Kirchhoff's Current Law.
Two independent solutions come from the other two small loops in the graph. The graph has other loops! One possibility is the big loop around the outside, from nodes 1 - 2 - 3 - 1 . This gives the solution w b i g = ( 1 , - 1 , 1 , 0, 0, 0) . That is the sum of the three w 's from the small loops. The three small loops give a basis for the nullspace of AT. The Fundamental Theorem of Linear Algebra confirms that the dimension of the nullspace ( number of basis vectors ) is 6 - 3 = 3: Number of independent solutions = (Number of unknowns) - (Rank) .
There are six unknowns W I , . . . , w6 ( six columns in AT) . There are three independent equations, counted by the rank. Apparently ATw = 0 gives four equations, but they add to 0 = 0. Three equations for six unknowns leaves a three-dimensional nullspace. The tree has no loops at all. The only flow in a tree that satisfies KCL is a zero flow. AT has three columns, and they are independent ( rank = 3 ) . So this nullspace has dimension 3 - 3