You can think of vectors representing many dimensions of related information. For instance, Netflix might store all the ratings a user gives to movies in a vector. This is clearly a vector of very large dimensions (in the millions) and very sparse as the user might have rated only a few movies. Similarly, Amazon might store the items purchased by a user in a vector, with each slot or dimension representing a unique product and the value of the slot, the number of such items the user bought. One task that is frequently done in these settings is to find similarities between users. And, we can use dot-product between vectors to do just that. As you know, the dot-product is proportional to the length of two vectors and to the angle between them. In fact, the dot-product between two vectors, normalized by their lengths is called as the cosine distance and is frequently used in recommendation engines. (1) Calculate the dot product u.v where u = [0.5; 0.5] and v = [3; −4]
u <- c(0.5, 0.5)
v <- c(3, -4)
dotpr<-u %*% v
dotpr
## [,1]
## [1,] -0.5
#Length of u
ul<-sqrt(sum(u * u))
ul
## [1] 0.7071068
#Length of v
vl<-sqrt(sum(v * v))
vl
## [1] 5
3*u - 2*v
## [1] -4.5 9.5
theta <- acos( dotpr / ( ul * vl))
as.numeric(theta)
## [1] 1.712693
solfunc <- function(A, b) {
combm = cbind(A, b)
#Handling zero pivots by exchanging the rows if the 1st row starts with a 0
if (combm[1,1] == 0) {
if (combm[2,2] != 0) {
combm = combm[c(2,1,3),]
}
else {
combm = combm[c(3,2,1),]
}
}
# Zero out row 2 column 1
if (combm[2,1] !=0) {
combm[2,] <- -combm[2,] + combm[2,1] * combm[1,]
}
# Zero out row 3 column 1
if (combm[3,1] !=0) {
combm[3,] <- -combm[3,] + combm[3,1] * combm[1,]
}
#Handling zero pivots by exchanging the rows if [2,2] is a 0
if (combm[2,2] == 0) {
combm = combm[c(1,3,2),]
}
# divide 2nd row by [2,2]
combm[2,] <- combm[2,] / combm[2,2]
# Zero out row 3 column 2
combm[3,] <- -combm[3,] + combm[3,2] * combm[2,]
# Use back subsitution to solve
x3 <- combm[3,4] / combm[3,3]
x2 <- (combm[2,4] - combm[2,3]*x3) / combm[2,2]
x1 <- (combm[1,4] - combm[1,2]*x2 - combm[1,3]*x3) / combm[1,1]
return(c(x1,x2,x3))
}
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)
solfunc(A,b)
## [1] -1.5454545 -0.3181818 0.9545455