Page 304 - Excel for Scientists and Engineers: Numerical Methods
P. 304

CHAPTER 12         PARTIAL DIFFERENTIAL EQUATIONS                    28 1



                  3ption Explicit
                  3ption Base 1
                  Function CrankNicholson(coeff, delta-x,  delta-t,  prev-values)
                  Solves a parabolic PDE by the Crank-Nicholson method.
                  Dim I As Integer, J As Integer, N As Integer
                  Dim F As Double
                  Dim CoeffMatrixO As Double, ConstantsVector() As Double

                  N = prev-values.Count
                  ReDim CoeffMatrix(N - 2, N - 2), ConstantsVector(N - 2, 1)
                  F = coeff * delta-t  I delta-x  A  2
                  'Create coefficients matrix.  This is an N x N matrix.
                  For I = 1 To N - 2
                  ForJ=l TON-2
                   Select Case J
                   Case I
                       CoeffMatrix(1, J) = 2 + 2  F
                   Case I - 1
                       CoeffMatrix(1, J) = -F
                   Case I + 1
                       CoeffMatrix(1, J) = -F
                   Case Else
                       CoeffMatrix(1, J) = 0
                   End Select
                  Next J, I
                  'Create constants vector.  This is a COLUMN vector.
                  ForJ=l TON-2
                   ConstantsVector(J, 1) = F * prev-values(J)  + (2 - 2 * F) * prev-values(J  + 1) + F * -
                   prev-values(J  + 2)
                  Next J
                  ConstantsVector(1, 1) = ConstantsVector(1, 1) + F *   prev-values(1)
                  ConstantsVector(N - 2, 1) = ConstantsVector(N - 2, IF+ F * prev-values(N)

                  'Return results as an array in a row, thus use Transpose.
                  CrankNicholson = Application.Transpose(App1ication. -
                  MMult(Application.MInverse(CoeMVlatrix),ConstantsVector))

                  End Function
                            Figure 12-12.  VBA fbnction procedure to evaluate a PDE
                                       by the Crank-Nicholson method.
                     (folder 'Chapter 12 (PDE) Examples, workbook 'Parabolic PDE', module 'Modulel')
   299   300   301   302   303   304   305   306   307   308   309