Advertisement
gaz_lloyd

Untitled

Nov 6th, 2011
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. ########################
  2. # Question 5 #
  3. # Gaussian Elimination #
  4. ########################
  5. maxInCol := proc(M,c,r)
  6. local i, locMax:
  7. locMax := 1:
  8. for i from r to RowDimension(M) do
  9. if abs(M[i,c]) >= abs(M[locMax,c]) then
  10. locMax := i:
  11. fi:
  12. od:
  13. RETURN(locMax):
  14. end proc:
  15. GaussElimPP := proc(A) #input augmented matrix A|b of coefficients of eqs and solutions, such that Ax=b
  16. local n, m, x, p, k, lk, i, s, f, j: #local variables (n, m dimensions, lk multipluer, s sum, others loop vars)
  17. #Dimensions of A
  18. n := RowDimension(A):
  19. m := ColumnDimension(A):
  20.  
  21. #set up a list x for back substitution
  22. x := []:
  23. for i from 1 to n do
  24. x := [op(x),0]:
  25. od:
  26.  
  27. for p from 1 to (m-2) do
  28. #find the largest magnitude in column, swap that row with row p
  29. A[p],A[maxInCol(A,p,p)] := A[maxInCol(A,p,p)],A[p]:
  30.  
  31. #row ops
  32. for k from p+1 to n do
  33. lk := A[k,p]/A[p,p]: #multiplier
  34. for i from p to m do
  35. A[k,i] := A[k,i] - lk*A[p,i]: #row operation
  36. od: #for i p to m
  37. od: #for k p+1 to n
  38. od: #for p 1 to (m-2)
  39.  
  40. #check for solveability
  41. s := 0:
  42. for f from 1 to m-1 do
  43. s := s + A[n,f]:
  44. od:
  45. if s = 0 then
  46. if A[n,m] = 0 then
  47. printf("There are no unique solutions"):
  48. RETURN(0):
  49. else
  50. printf("There are no solutions"):
  51. RETURN(0):
  52. fi:
  53. else
  54. #back substitution
  55. for j from n to 1 by -1 do
  56. x[j] := (A[j,m] - add(A[j,h]*x[h],h=j+1..n))/A[j,j]:
  57. od:
  58. RETURN(x):
  59. fi:
  60. end proc:
  61. GaussElimPP(Matrix([[1,3,2,3],[2,-1,-3,-8],[5,-2,1,9]]));
  62. GaussElimPP(Matrix([[1,1,1,2],[1,-1.1,1,-1],[1,1,1.1,3]]));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement