Testing
# Tesing fo rbad matrices
A<- "Not a matrix"
b<- "Not a matrix"
solve_matrix(A,b)
## [1] " A is not a matrix. Please provide a mtrix"
## Testing for 3x3 matrix
A<- matrix(c(0,2))
b<- matrix(c(1, 2, 6))
solve_matrix(A,b)
## [1] "please provide 3x3 matrix"
## Testing if the first Pivot element is zero
A <- matrix(nrow = 3, ncol = 3, data = c(0, 1, 3, 2, -1, 5, -1, -2, 4), byrow=TRUE)
A
## [,1] [,2] [,3]
## [1,] 0 1 3
## [2,] 2 -1 5
## [3,] -1 -2 4
b<- matrix(c(1, 2, 6))
b
## [,1]
## [1,] 1
## [2,] 2
## [3,] 6
solve_matrix(A,b)
## [1] "First Pivot cannot be 0. Please provide anoher matrix"
## Testing if the second Pivot element is zero
A <- matrix(nrow = 3, ncol = 3, data = c(1, 1, 3, 2, 0, 5, -1, -2, 4), byrow=TRUE)
A
## [,1] [,2] [,3]
## [1,] 1 1 3
## [2,] 2 0 5
## [3,] -1 -2 4
b<- matrix(c(1, 2, 6))
b
## [,1]
## [1,] 1
## [2,] 2
## [3,] 6
solve_matrix(A,b)
## [1] "Second Pivot cannot be 0. Please provide anoher matrix"
## Testing if the third Pivot element is zero
A <- matrix(nrow = 3, ncol = 3, data = c(1, 1, 3, 2, -1, 5, -1, -2, 0), byrow=TRUE)
A
## [,1] [,2] [,3]
## [1,] 1 1 3
## [2,] 2 -1 5
## [3,] -1 -2 0
b<- matrix(c(1, 2, 6))
b
## [,1]
## [1,] 1
## [2,] 2
## [3,] 6
solve_matrix(A,b)
## [1] "Third Pivot cannot be 0. Please provide anoher matrix"
## Successfull Test
A <- matrix(nrow = 3, ncol = 3, data = c(1, 1, 3, 2, -1, 5, -1, -2, 4), byrow=TRUE)
A
## [,1] [,2] [,3]
## [1,] 1 1 3
## [2,] 2 -1 5
## [3,] -1 -2 4
b<- matrix(c(1, 2, 6))
b
## [,1]
## [1,] 1
## [2,] 2
## [3,] 6
solve_matrix(A,b)
## [,1]
## [1,] -1.5454545
## [2,] -0.3181818
## [3,] 0.9545455
An alternative method is to use the built in function ginv()
solve_matrix_ginv <- function (A,b){
# Checkin if the input values are matrices
if (!(is.matrix(A))) return(" A is not a matrix. Please provide a mtrix")
if (!(is.matrix(b))) return(" b is not a matrix. Please provide a mtrix")
# Checking if the input matrix is 3x3 matrix
if (!(isTRUE(all.equal(dim(A), c(3, 3))))) return("please provide 3x3 matrix")
# Checking if the pivot element is 0.
if (is.matrix(A)) if (A[1,1] == 0) return("First Pivot cannot be 0. Please provide anoher matrix")
if (is.matrix(A)) if (A[2,2] == 0) return("Second Pivot cannot be 0. Please provide anoher matrix")
if (is.matrix(A)) if (A[3,3] == 0) return("Third Pivot cannot be 0. Please provide anoher matrix")
library(MASS)
ginv(A,0) %*% b
}
## Successfull Test
A <- matrix(nrow = 3, ncol = 3, data = c(1, 1, 3, 2, -1, 5, -1, -2, 4), byrow=TRUE)
A
## [,1] [,2] [,3]
## [1,] 1 1 3
## [2,] 2 -1 5
## [3,] -1 -2 4
b<- matrix(c(1, 2, 6))
b
## [,1]
## [1,] 1
## [2,] 2
## [3,] 6
solve_matrix_ginv(A,b)
## [,1]
## [1,] -1.5454545
## [2,] -0.3181818
## [3,] 0.9545455