Problem set 2

Set up a system of equations with 3 variables and 3 constraints and solve for x. Please write a function in R that will take two variables (matrix A & constraint vector b) and solve using elimination. Your function should produce the right answer for the system of equations for any 3-variable, 3-equation system. You don’t have to worry about degenerate cases and can safely assume that the function will only be tested with a system of equations that has a solution. Please note that you do have to worry about zero pivots, though. Please note that you should not use the built-in function solve to solve this system or use matrix inverses. The approach that you should employ is to construct an Upper Triangular Matrix and then back-substitute to get the solution. Alternatively, you can augment the matrix A with vector b and jointly apply the Gauss Jordan elimination procedure.
Please test it with the system below and it should produce a solution x = [ -1.55, -0.32, 0.95]

Defining Matrix A and Vector b

A <- matrix(data=c(1,2,-1,1,-1,-2,3,5,4), nrow=3, ncol=3, byrow=FALSE)
b <- matrix(data=c(1,2,6), nrow=3, ncol=1, byrow=FALSE)
A
##      [,1] [,2] [,3]
## [1,]    1    1    3
## [2,]    2   -1    5
## [3,]   -1   -2    4
b
##      [,1]
## [1,]    1
## [2,]    2
## [3,]    6

Defining Solve Function Logic

solve_eq_3X3 <- function(A, b)  {
  
  M <- cbind(A, b)
  tmp <- (M[2,1]/M[1,1])*(M[1,])
  M[2,] <- M[2,] - tmp
  
  tmp <- (M[3,1]/M[1,1])*(M[1,])
  M[3,] <- M[3,] - tmp
  
  tmp <- (M[3,2]/M[2,2])*(M[2,])
  M[3,] <- M[3,] - tmp
  
  z <- M[3,4]/M[3,3]
  y <- (M[2,4]-(M[2,3]*z))/M[2,2]
  x <- (M[1,4]-(M[1,3]*z)-(M[1,2]*y))/M[1,1]
  
  z <- round(z,2)
  y <- round(y,2)
  x <- round(x,2)
  
  return(c(x, y, z))
}

Testing Solve Function

solve_eq_3X3(A,b)
## [1] -1.55 -0.32  0.95