u = c(0.5,0.5)
v = c(3,-4)
u%*%v
## [,1]
## [1,] -0.5
sqrt(u%*%u)
## [,1]
## [1,] 0.7071068
sqrt(v%*%v)
## [,1]
## [1,] 5
(3*u) - (2*v)
## [1] -4.5 9.5
# angle = arccosine(dot product/norm a*norm b )
angle = acos(sum(u*v) / (sqrt(sum(u * u)) * sqrt(sum(v * v))))
round(angle* (180/pi),0)
## [1] 98
Set up a system of equations with 3 variables and 3 constraints and solve for x.
Steps:
Start with row 1 of the co-efficient matrix
Pivot: The first non-zero element in the row being evaluated
Multiplier: The element being eliminated divided by the Pivot
Subtract Multiplier times row n from row n+1
Advance to the next row and repeat
solution <- function(a,b){
# joining matrix and constraint vector
mtrx <- cbind(a,b)
# assigning a pivot - the first non-zero element of the matrix
pivot1 <- mtrx[1,1]
# calculating multiplier - the element being eliminated divided by the pivot
multiplier1 <- mtrx[2,1]/pivot1
# subtracting multiplier times row n from row n+1
mtrx[2,] <- mtrx[2,] - (multiplier1 * mtrx[1,])
# advance to the next row and repeat
multiplier2 <- mtrx[3,1]/pivot1
mtrx[3,] <- mtrx[3,] - (multiplier2 * mtrx[1,])
pivot2 <- mtrx[2,2]
multiplier3 <- mtrx[3,2]/pivot2
mtrx[3,] <- mtrx[3,] - (multiplier3 * mtrx[2,])
# performing back-substitution to get the solution
x3 <- mtrx[3,4]/mtrx[3,3]
x2 <- (mtrx[2,4] - (mtrx[2,3] * x3))/mtrx[2,2]
x1 <- (mtrx[1,4] - (mtrx[1,3] * x3) - (mtrx[1,2] * x2))/mtrx[1,1]
return(c(x1, x2, x3))
}
# testing the function
a<- matrix(c(1,1,3,2,-1,5,-1,-2,4), nrow = 3, ncol = 3, byrow = TRUE)
b <- matrix(c(1,2,6), nrow = 3, ncol = 1, byrow = TRUE)
solution (a, b)
## [1] -1.5454545 -0.3181818 0.9545455