Solution-HW3

# Solution-HW3 - Write a program in a language of your choice...

This preview shows pages 1–3. Sign up to view the full content.

Write a program in a language of your choice to implement Naïve Gaussian Elimination. SOLUTION: Option Explicit Sub Gauss() ' ' Declarations ' Dim A() As Variant, b() As Variant, x() As Variant Dim nrows As Integer, ncols As Integer, n As Integer Dim rng1 As Range, rng2 As Range, rng3 As Range Dim i As Integer, j As Integer, k As Integer Dim factor As Double, sum As Double ' ' Get input ranges, check for correct shape, and set arrays ' Call GetRange(rng1, "Enter n by n input range for matrix of coefficients") Call GetRange(rng2, "Enter n by 1 input range for RHS") Call GetRange(rng3, "Enter n by 1 output range for solution") ncols = rng1.Columns.Count nrows = rng1.Rows.Count If (nrows <> ncols) Then MsgBox "Matrix not square" Exit Sub End If n = nrows If ((rng2.Rows.Count <> n) Or (rng3.Rows.Count <> n) Or _ (rng2.Columns.Count <> 1) Or (rng3.Columns.Count <> 1)) Then MsgBox "RHS or output range not n by 1" Exit Sub End If A = rng1.Value b = rng2.Value x = b ' ' Elimination ' k = 0 For k = 1 To n - 1 Step 1 For i = k + 1 To n Step 1 factor = A(i, k) / A(k, k) For j = k + 1 To n Step 1 A(i, j) = A(i, j) - factor * A(k, j) Next j b(i, 1) = b(i, 1) - factor * b(k, 1) Next i Next k

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
' ' Back substitution ' x(n, 1) = b(n, 1) / A(n, n) For i = n - 1 To 1 Step -1 sum = 0 For j = i + 1 To n Step 1 sum = sum + A(i, j) * x(j, 1) Next j x(i, 1) = (b(i, 1) - sum) / A(i, i) Next i rng3.Value = x End Sub Sub GetRange(rng As Range, msg As String) Dim srng As String srng = InputBox(msg) Set rng = Range(srng) End Sub Use your program to solve the linear system Ax = b , where = 9 / 1 8 / 1 7 / 1 6 / 1 5 / 1 8 / 1 7 / 1 6 / 1 5 / 1 4 / 1 7 / 1 6 / 1 5 / 1 4 / 1 3 / 1 6 / 1 5 / 1
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 01/20/2011 for the course ENG 115 taught by Professor Rocke during the Spring '10 term at UC Davis.

### Page1 / 7

Solution-HW3 - Write a program in a language of your choice...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online