#1
u <- matrix (c(0.5,0.5),nrow=1,ncol=2,byrow=T)
v <- matrix (c(3,-4),nrow=2,ncol=1,byrow=T)
u %*% v
## [,1]
## [1,] -0.5
#2
cat("lengths of u is:", len_u <- sqrt(u[1]^2 + u[2]^2), "\n")
## lengths of u is: 0.7071068
cat("lengths of v is:", len_v = sqrt(v[1]^2+v[2]^2))
## lengths of v is: 5
#3
# since we're no longer dealing square matrix, we need to make v into a matrix of the same shape as u for a linear combination to work
v <- t(v)
x = 3 * u - 2 * v
x
## [,1] [,2]
## [1,] -4.5 9.5
Ans: Linear combination fo 3u-2v = [-4.5; 9.5]
#4
# angle between u and v (need to transpose v back to the original setup)
v <- t(v)
angle(as.vector(u), as.vector(v)) # degrees
## [,1]
## [1,] 98.1301
angle(as.vector(u), as.vector(v), degree = FALSE) # in radians
## [,1]
## [1,] 1.712693
Ans: The angle between u and v is 98.13 degrees, or 1.71 radians.
# Reference algo can be found in the Python code section of the following URL
# https://martin-thoma.com/solving-linear-equations-with-gaussian-elimination/
gauss_elimination_soln <- function(A, b){
# stores number of rows of matrix A into n
n = nrow(A)
# append the columns of b to matrix A
matrix <- cbind(A, b)
# find out the max.row
for (i in (1:n)){
max <- abs(matrix[i,i])
max.row <- i
if (i+1 <= n) {
for (k in ((i+1): n)){
if (abs(matrix[k,i]) > max){
max = abs(matrix[k,i])
max.row <- k
}
}
}
# Swap maximum row (max.row) with current row (column by column)
for (k in (i: (n+1))){
tmp = matrix[max.row,k]
matrix[max.row,k] = matrix[i,k]
matrix[i,k] = tmp
}
# Make all rows below this one 0 in current column
if (i+1 <= n){
for (k in ((i+1): n)){
c = -matrix[k,i]/matrix[i,i]
for (j in (i: (n+1))){
if (i == j){
matrix[k,j] = 0
}
else{
matrix[k,j] = matrix[k,j] + (c * matrix[i,j] )
}
}
}
}
}
# Solve equation Ax=b for an upper triangular matrix A
x = matrix(0, 1, n)
for (i in (n:1)){
x[i] = matrix[i,(n+1)]/matrix[i,i]
for (k in ((i-1): 1)){
matrix[k,(n+1)] = matrix[k,(n+1)] - matrix[k,i] * x[i]
}
}
return(round(x,digits=2))
}
A <- matrix(c(1,1,3,2,-1,5,-1,-2,4), nrow=3, ncol=3, byrow=T)
b <- matrix(c(1,2,6), nrow=3, ncol=1)
gauss_elimination_soln(A, b)
## [,1] [,2] [,3]
## [1,] -1.55 -0.32 0.95