u <- c(0.5, 0.5)
v <- c(3, -4)
library(pracma)
uv.dot <- dot(u,v) #or u %*% v
uv.dot
## [1] -0.5
u.len <- sqrt(sum(u^2))
u.len
## [1] 0.7071068
v.len <- sqrt(sum(v^2))
v.len
## [1] 5
3*u - 2*v
## [1] -4.5 9.5
rad <- acos(uv.dot / (u.len * v.len))
# in degrees
rad * 180/pi
## [1] 98.1301
A <- matrix(c(1,1,3,2,-1,5,-1,-2,4), 3, byrow=T)
b <- matrix(c(1,2,6), nrow=3, ncol=1)
# Elimination Function
elimination <- function(A,b){
aug.mat <- cbind(A,b) # bind A,b to create an Augmented matrix
# devide the first row by the coef of the first row and first column
aug.mat[1,] <- aug.mat[1,]/aug.mat[1,1]
print("the coef [1,1] should be 1.")
print(aug.mat)
p <- nrow(A)
i <- 2 # start with a second row
while (i < p+1) { # iterate through all rows in augmented matrix
j <- i # assign row num to col
while (j < p+1) { # iterate through all columns in augmented matrix
# multiply the prev row by coef of current row,col
# that equals the num of prev row,
# then subtract it from the current row
aug.mat[j, ] <- aug.mat[j, ] - aug.mat[i-1, ] * aug.mat[j, i-1]
j <- j+1 # iterate next column
}
# bind augmented matrix that contains current row only
# with augmented matrix that doesn't contain current row
# while the coef in current row, current row equals 0
while (aug.mat[i,i] == 0) {
aug.mat <- rbind(aug.mat[-i,],aug.mat[i,])
}
aug.mat[i,] <- aug.mat[i,]/aug.mat[i,i]
i <- i+1 # iterate next row
}
print("the coefficients located in [1,1],[2,2],[3,3] etc. (where row=column) should equal to 1")
print(aug.mat)
for (i in p:2){ # iterate through rows from last row to the second row
for (j in i:2-1) { # iterate through columns (from the first)
# multiply the current row by coef located in the same row and current col
# then subtract it from the row that equals to the current col
aug.mat[j, ] <- aug.mat[j, ] - aug.mat[i, ] * aug.mat[j, i]
}
}
print("the coefficients located in [1,1],[2,2],[3,3] etc. (where row=column) should equal to 1 while all other coefficients shoud equal to 0")
print(aug.mat)
}
elimination(A,b)
## [1] "the coef [1,1] should be 1."
## [,1] [,2] [,3] [,4]
## [1,] 1 1 3 1
## [2,] 2 -1 5 2
## [3,] -1 -2 4 6
## [1] "the coefficients located in [1,1],[2,2],[3,3] etc. (where row=column) should equal to 1"
## [,1] [,2] [,3] [,4]
## [1,] 1 1 3.0000000 1.0000000
## [2,] 0 1 0.3333333 0.0000000
## [3,] 0 0 1.0000000 0.9545455
## [1] "the coefficients located in [1,1],[2,2],[3,3] etc. (where row=column) should equal to 1 while all other coefficients shoud equal to 0"
## [,1] [,2] [,3] [,4]
## [1,] 1 0 0 -1.5454545
## [2,] 0 1 0 -0.3181818
## [3,] 0 0 1 0.9545455
# compare the result with solve function
solve(A,b)
## [,1]
## [1,] -1.5454545
## [2,] -0.3181818
## [3,] 0.9545455