Problem Set 1

  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)
dot_prod = u %*% v
dot_prod
##      [,1]
## [1,] -0.5
  1. What are the lengths of u and v?
len_u = sqrt(0.5**2 + 0.5**2)
len_v = sqrt(3**2 + (-4)**2)

len_u
## [1] 0.7071068
len_v
## [1] 5
  1. What is the linear combination: 3u − 2v?
3*u - 2*v
## [1] -4.5  9.5
  1. What is the angle between u and v?
angle = dot_prod / (len_u * len_v)
angle
##            [,1]
## [1,] -0.1414214

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.

A = rbind(c(1,1,3),c(2,-1,5),c(-1,-2,4))
b = c(1,2,6)

sys_eqn_solve <- function(matrix,b){
  
  combined = cbind(matrix,b)

  ##ROW ONE
  #make sure the value in top left position is 1
  combined[1,] = combined[1,]/combined[1,1]
  
  #make the value in position 2,1 and 3,1 be 0
  combined[2,] = -combined[2,1]*(combined[1,]) + combined[2,]
  combined[3,] = -combined[3,1]*(combined[1,]) + combined[3,]
  
  ##ROW TWO
  #make the value in the position 2,2 be 1
  combined[2,] = combined[2,]/combined[2,2]

  #make the value in position 1,2 and 3,2 be 0
  combined[1,] = -combined[1,2]*(combined[2,]) + combined[1,]
  combined[3,] = -combined[3,2]*(combined[2,]) + combined[3,]
    
  ##ROW THREE
  #make the value in the position 3,3 be 1
  combined[3,] = combined[3,]/combined[3,3]
  
  #make the value in position 1,3 and 2,3 be 0
  combined[1,] = -combined[1,3]*(combined[3,]) + combined[1,]
  combined[2,] = -combined[2,3]*(combined[3,]) + combined[2,]
  
  x = combined[,4]
  x
}
sys_eqn_solve(A,b)
## [1] -1.5454545 -0.3181818  0.9545455