1. Problem set 1

Q1. 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)
z <- u %*% v
print(z)
##      [,1]
## [1,] -0.5

Q2. What are the lengths of u and v?

sqrt(u[1]^2 + u[2]^2)
## [1] 0.7071068
sqrt(v[1]^2 + v[2]^2)
## [1] 5

Q3. What is the linear combination: 3u - 2v?

z <- 3*u - 2*v
print(z)
## [1] -4.5  9.5

Q4. What is the angle between u and v?

z <- acos(sum(u*v) / ( sqrt(sum(u * u)) * sqrt(sum(v * v)) ) )
print(z)
## [1] 1.712693

2. Problem set 2

Set up a system of equations with 3 variables and 3 constraints and solve for x. Please write a function in R that will take two variables (matrix A & constraint vector b) and solve using elimination. Your function should produce the right answer for the system of equations for any 3-variable, 3-equation system. You donโ€™t have to worry about degenerate cases and can safely assume that the function will only be tested with a system of equations that has a solution. Please note that you do have to worry about zero pivots, though. Please note that you should not use the built-in function solve to solve this system or use matrix inverses. The approach that you should employ is to construct an Upper Triangular Matrix and then back-substitute to get the solution. Alternatively, you can augment the matrix A with vector b and jointly apply the Gauss Jordan elimination procedure.

img

img

solution_function <- function(m, constraintB) {
  
  #Construct an upper triangular matrix
  z1 <- m[2,1] / m[1,1]
  
  m[2,] = m[2,] - z1*m[1,]
  constraintB[2] = constraintB[2] - z1*constraintB[1]
  
  z2 <- m[3,1] / m[1,1]
  
  m[3,] = m[3,] - z2*m[1,]
  constraintB[3] = constraintB[3] - z2*constraintB[1]
  
  z3 <- m[3,2] / m[2,2]
  
  m[3, ] = m[3,] - z3*m[2,]
  constraintB[3] = constraintB[3] - z3*constraintB[2]
  
  
  #Perform a back subsitution
  z = round(constraintB[3] / m[3,3],3)
  
  y = round((constraintB[2] - z*m[2,3])/m[2,2], 3)
  
  x = round((constraintB[1] - z*m[1,3] - y*m[1,2])/m[1,1],3)
  
  #return a vector with results
  return(c(round(x, 2), round(y, 2), round(z,2)))
}


c <- c(1,2,-1, 1, -1, -2,3,5,4)
m <- matrix(c, 3, 3)
constraintB <- c(1, 2, 6)

print(solution_function(m, constraintB))
## [1] -1.55 -0.32  0.96