Question 1
u <- c(0.5, 0.5)
v <- c(3, -4)
- Calculate the dot product u.v where u = [0.5; 0.5] and v = [3; −4]
dot <- function(u, v){
sum(u * v)
}
dot(u, v)
## [1] -0.5
- What are the lengths of u and v? Please note that the mathematical notion of the length of a vector is not the same as a computer science definition.
mag <- function(v){
sqrt(sum(v ** 2))
}
c(mag(u), mag(v))
## [1] 0.7071068 5.0000000
- What is the linear combination: 3u − 2v?
3*u - 2*v
## [1] -4.5 9.5
- What is the angle between u and v
vector.angle <- function(u, v){
acos(dot(u, v) / (mag(u) * mag(v)))
}
vector.angle(u, v)
## [1] 1.712693
Question 2
solver <- function(A, b){
#Place into augmented matrix
A <- cbind(A, b)
row <- 1
column <- 1
while(row <= nrow(A)){
#Find a pivot column
c <- column
while(c <= ncol(A)){
if(all(A[seq(row, nrow(A)), c] == 0)){
c <- c + 1
}else{
break
}
}
if(c > ncol(A)){
break
}
column <- c
#Swap rows if current row has 0
for(r in seq(row, nrow(A))){
if(A[r, column] != 0){
temp <- A[r, ]
A[r, ] <- A[row, ]
A[row, ] <- temp
break
}
}
#Reduce and Eliminate Column
A[row, ] <- A[row, ] / A[row, column]
constant <- A[seq(1, nrow(A)), column] * -1
constant[row] <- 0
mask <- matrix(rep(A[row, ], nrow(A)), ncol = ncol(A), byrow = TRUE) * constant
A <- mask + A
row <- row + 1
column <- column + 1
}
#Determine if Single Solution
if(identical(diag(nrow(A)), A[, seq(1, ncol(A)-1)])){
return(A[, ncol(A)])
}
print('Special Case')
return(A)
}
#One Solution
A <- matrix(c(1, 1, 3, 2, -1, 5, -1, -2, 4), 3, 3, byrow = TRUE)
b <- matrix(c(1, 2, 6), 3, 1)
solver(A, b)
## [1] -1.5454545 -0.3181818 0.9545455
#Free Variables
A <- matrix(c(0, 3, -6, 6, 4, 3, -7, 8, -5, 8, 3, -9, 12, -9, 6), 3, 5, byrow=TRUE)
b <- matrix(c(-5, 9, 15), 3, 1)
solver(A, b)
## [1] "Special Case"
## [,1] [,2] [,3] [,4] [,5] [,6]
## [1,] 1 0 -2 3 0 -24
## [2,] 0 1 -2 2 0 -7
## [3,] 0 0 0 0 1 4
#0 last row
A <- matrix(c(1, 3, 2, 1, 1, 1), 3, 2, byrow=TRUE)
b <- matrix(c(6, 7, 4), 3, 1)
solver(A, b)
## [1] "Special Case"
## [,1] [,2] [,3]
## [1,] 1 0 3
## [2,] 0 1 1
## [3,] 0 0 0