Write a function to solve for x in a system of equations with 3 variables and 3 constraints
systemSolution3by3 <- function(matrixA, vectorB){
newA <- cbind(matrixA,vectorB)
r <- nrow(newA)
c <- ncol(newA)
i <- 2
j <- 1
k <- 1
while(k <= r) {
while (i <= r) {
if (newA[i,j]!=0) {
multiplier <- (-newA[i,j]/newA[k,j])
while (j <= c) {
newA[i,j] <- newA[i,j] + newA[k,j]*multiplier
j <- j+1
}
}
i <- i+1
j <- 1
}
k <- k+1
i <- k+1
j <- k
}
solution_vectorX <- c(1:r)
solution_vectorX[3] <- newA[r,c]/newA[r,c-1]
solution_vectorX[2] <- (newA[2,4]-newA[2,3]*solution_vectorX[3])/newA[2,2]
solution_vectorX[1] <- (newA[1,4]-newA[1,3]*solution_vectorX[3]-newA[1,2]*solution_vectorX[2])/newA[1,1]
return(solution_vectorX)
}
Test the function with an example system
testA <- matrix(c(1,2,-1,1,-1,-2,3,5,4),nrow=3)
testB <- c(1,2,6)
systemSolution3by3(testA,testB)
## [1] -1.5454545 -0.3181818 0.9545455
testsolutionX <- solve(testA)%*%testB #testing the answer with built-in function