## ProblemYou need to calculate the determinant of a matrix. ## SolutionSample code folder: Chapter 06\Matrix Add the MatrixHelper module to your application, and pass your matrix to the ## DiscussionThe determinant of a matrix is a single number derived from a matrix. It helps determine if a matrix is invertible, and it also comes into play when using matrices to solve simultaneous equations. (A full description of matrices and their operations is beyond the scope of this book.) The following sample code creates a square matrix of double-precision numbers and passes it to the Dim matrixA(,) As Double = { _ {1, 2, 3}, _ {5, 4, 6}, _ {9, 7, 8}} Dim determinant As Double = MatrixHelper.Determinant(matrixA) MsgBox(MatrixHelper.MakeDisplayable(matrixA) & _ vbNewLine & vbNewLine & "Determinant: " & _ determinant.ToString) The complete Public Function Determinant(ByVal sourceMatrix(,) _ As Double) As Double ' ----- Calculate the determinant of a matrix. Dim result As Double Dim pivots As Integer Dim count As Integer ' ----- Only calculate the determinants of square matrices. If (UBound(sourceMatrix, 1) <> _ UBound(sourceMatrix, 2)) Then Throw New Exception("Determinant only " & _ "calculated for square matrices.") End If Dim rank As Integer = UBound(sourceMatrix, 1) ' ----- Make a copy of the matrix so we can work ' inside of it. Dim workMatrix(rank, rank) As Double Array.Copy(sourceMatrix, workMatrix, _ sourceMatrix.Length) ' ----- Use LU decomposition to form a ' triangular matrix. Dim rowPivots(rank) As Integer Dim colPivots(rank) As Integer workMatrix = FormLU(workMatrix, rowPivots, _ colPivots, count) ' ----- Get the product at each of the pivot points. result = 1 For pivots = 0 To rank result *= workMatrix(rowPivots(pivots), _ colPivots(pivots)) Next pivots ' ----- Determine the sign of the result using ' LaPlace's formula. result = (-1) ^ count * result Return result End Function A very useful technique for copying one array into another is shown in one of the program lines in the Array.Copy(a, b, a.Length) The Figure 6-33 shows the calculated determinant of a 3 x 3 matrix. ## Figure 6-33. Finding the determinant of a square matrix with the MatrixHelper.Determinant( ) function## See AlsoSee the full MatrixHelper.vb listing in Recipe 6.35. |

Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))

ISBN: 0596101775

EAN: 2147483647

EAN: 2147483647

Year: 2006

Pages: 400

Pages: 400

Authors: Tim Patrick, John Craig

Similar book on Amazon

- Using SQL Data Manipulation Language (DML) to Insert and Manipulate Data Within SQL Tables
- Understanding SQL Transactions and Transaction Logs
- Performing Multiple-table Queries and Creating SQL Data Views
- Working with Comparison Predicates and Grouped Queries
- Working with SQL Database Data Across the Internet

flylib.com © 2008-2017.

If you may any questions please contact us: flylib@qtcs.net

If you may any questions please contact us: flylib@qtcs.net