u <- c(0.5, 0.5)
v <- c(3, -4)
dot.prod <- u%*%v; dot.prod
## [,1]
## [1,] -0.5
# length of u
norm.x <- norm(u,type="2");norm.x
## [1] 0.7071068
# length of v
norm.y <- norm(v,type="2");norm.y
## [1] 5
3*u - 2*v
## [1] -4.5 9.5
#theta <- acos(dot.prod / (norm.x * norm.y))
atan2(v[2],v[1]) - atan2(u[2],u[1])
## [1] -1.712693
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.
solve_for_x <- function(vars,cons){
m <- cbind(vars,cons)
#r2,c1
m[2,] <- m[2,] - (m[1,] * (m[2,1]/m[1,1]))
#r3,c1
m[3,] <- m[3,] - (m[1,] * (m[3,1]/m[1,1]))
#r3,c2
m[3,] <- m[3,] - (m[2,] * (m[3,2]/m[2,2]))
z <- m[3,4]/m[3,3]
y <- (m[2,4] - (m[2,3]*z)) / m[2,2]
x <- (m[1,4] - (m[1,2]*y) - (m[1,3]*z )) / m[1,1]
return(round(c(x, y, z),2))
}
# Example 1
A <- matrix(c(1, 2, -1, 1, -1, -2, 3, 5, 4), nrow=3, ncol=3)
b <- c(1, 2, 6)
# Run using assignment function
solve_for_x(A,b)
## cons cons cons
## -1.55 -0.32 0.95
# Run using R built in function
solve(A,b)
## [1] -1.5454545 -0.3181818 0.9545455
# Example 2
A <- matrix(c(2, 7, -5, 3, -1, -4, -1, 6, -2), nrow=3, ncol=3)
b <- c(1, 20, 9)
# Run using assignment function
solve_for_x(A,b)
## cons cons cons
## 10.24 -9.92 -10.27
# Run using R built in function
solve(A,b)
## [1] 10.243243 -9.918919 -10.270270