library(geometry)
## Warning: package 'geometry' was built under R version 3.6.3

Problem Set 1

(1)

Calculate the dot product u.v where u = [0.5; 0.5] and v = [3; −4]

u = c(.5,.5)
v = c(3,-4)

dot(u,v)
## [1] -0.5

(2)

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.

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

(3)

What is the linear combination: 3u − 2v?

3*u - 2*v
## [1] -4.5  9.5

(4)

What is the angle between u and v?

acos(dot(u,v))
## [1] 2.094395

(Above is in Radians)

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.

Write Function:

UpperTriangleSolve <- function(A,b){

#Converts matrix into Upper Triangle Form, solves for x. 
  
#Check inputs 
      if(!is.matrix(A)) stop("x must be a matrix")
      if(!is.vector(b)) stop("x must be a vector")
  
#Bind matrix 
      M <- cbind(A,b)
      colnames(M) <- NULL

#Upper triangle form
      M.a.2.1 <- M[2,1]/M[1,1]
      
      M[2,] <- M[2,] - M[1,]*M.a.2.1
      
      M.a.3.1 <- M[3,1]/M[1,1]
      
      M[3,] <- M[3,] - M[1,]*M.a.3.1
      
      M.b.3.2 <- M[3,2]/M[2,2]
      
      M[3,] <- M[3,] - M[2,]*M.b.3.2

#Solve for x
      x3 <- M[3,4]/M[3,3]

      x2 <- (M[2,4] - M[2,3]*x3)/M[2,2]
      
      x1 <- (M[1,4] - M[1,3]*x3 - M[1,2]*x2)/M[1,1]
      
      x <- c(x1,x2,x3)

#Return x
      return(x)

}

Test:

1x + 2y + 3z = 20

4x + 5y + 6z = 47

7x + 8y + 10z = 78

A <- matrix(c(1,2,3,4,5,6,7,8,10),nrow=3,byrow = TRUE)
b <- c(20,47,78)

UpperTriangleSolve(A,b)
## [1] 2 3 4