Problem Set 2
solve_3_var_equation <- function(A, b){
# augment the matrix
A_aug <- cbind(A, b)
# make sure position 1,1 is not 0
if (A_aug[1,1]==0){
A_aug <- rbind(c(0,1,0),
c(1,0,0),
c(0,0,1)) %*% A_aug
}
if (A_aug[1,1]==0){
A_aug <- rbind(c(0,0,1),
c(0,1,0),
c(1,0,0)) %*% A_aug
}
# clean up first column by getting a 1 in first position and a 0 in the other two
if (A_aug[1,1]!=1){A_aug[1,] <- A_aug[1, ]/A_aug[1,1]}
if (A_aug[2,1]!=0){A_aug[2,] <- A_aug[2, ] - A_aug[1, ]*A_aug[2,1]}
if (A_aug[3,1]!=0){A_aug[3,] <- A_aug[3, ] - A_aug[1, ]*A_aug[3,1]}
# make sure position 2,2 is not 0
if (A_aug[2,2]==0){
A_aug <- rbind(c(1,0,0),
c(0,0,1),
c(0,1,0)) %*% A_aug
}
# clean up second column by getting a 1 in second position and a 0 in the other two
if (A_aug[2,2]!=1){A_aug[2,] <- A_aug[2, ]/A_aug[2,2]}
if (A_aug[1,2]!=0){A_aug[1,] <- A_aug[1, ] - A_aug[2, ]*A_aug[1,2]}
if (A_aug[3,2]!=0){A_aug[3,] <- A_aug[3, ] - A_aug[2, ]*A_aug[3,2]}
# clean up third column by getting a 1 in third position and a 0 in the other two
if (A_aug[3,3]!=1){A_aug[3,] <- A_aug[3, ]/A_aug[3,3]}
if (A_aug[1,3]!=0){A_aug[1,] <- A_aug[1, ] - A_aug[3, ]*A_aug[1,3]}
if (A_aug[2,3]!=0){A_aug[2,] <- A_aug[2, ] - A_aug[3, ]*A_aug[2,3]}
A_aug
}
### Test the function
test_A <- rbind(c(1, 1, 3),
c(2, -1, 5),
c(-1, -2, 4))
test_b <- rbind(1, 2, 6)
solve_3_var_equation(test_A, test_b)
## [,1] [,2] [,3] [,4]
## [1,] 1 0 0 -1.5454545
## [2,] 0 1 0 -0.3181818
## [3,] 0 0 1 0.9545455
# try matrix with 0 in pivots
test_A <- rbind(c(0, 0, 3),
c(0, -1, 5),
c(-1, -2, 4))
test_b <- rbind(1, 2, 6)
solve_3_var_equation(test_A, test_b)
## [,1] [,2] [,3] [,4]
## [1,] 1 0 0 -4.0000000
## [2,] 0 1 0 -0.3333333
## [3,] 0 0 1 0.3333333
# try singular matrix
test_A <- rbind(c(1, 2, 3),
c(1, 2, 5),
c(1, 2, -4))
test_b <- rbind(1, 2, 6)
solve_3_var_equation(test_A, test_b)
## [,1] [,2] [,3] [,4]
## [1,] NaN NaN NaN -Inf
## [2,] NaN NaN NaN Inf
## [3,] 0 0 1 0.5