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)
d <- u %*% v
d
##      [,1]
## [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.
lengthu <- sqrt(u%*%u)
lengthu
##           [,1]
## [1,] 0.7071068
lengthv <- sqrt(v%*%v)
lengthv
##      [,1]
## [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?
angle <- acos( sum(u*v) / ( sqrt(sum(u * u)) * sqrt(sum(v * v)) ) )
angle * 180/pi
## [1] 98.1301

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.

Please test it with the system below and it should produce a solution x = [???1.55, ???0.32, 0.95]

Create Matrices

A <- matrix(c(1,1,3,2,-1,5,-1,-2,4), 3, 3)
b <- matrix(c(1,2,6))

Create functions

# Augment matrix
Au <- cbind(A,b)
Au
##      [,1] [,2] [,3] [,4]
## [1,]    1    2   -1    1
## [2,]    1   -1   -2    2
## [3,]    3    5    4    6
# Upper triangle matrix with 0 pivots
triangle <- function(Au){
    for (i in 2:nrow(Au)){
        for(j in 1:(i - 1)){
            Au[i,] <-  Au[i,] - (Au[j,] * (Au[i, j]/Au[j, j])) 
        }
    }
    Au
}

Uc <- triangle(Au)
Uc
##      [,1] [,2]      [,3]     [,4]
## [1,]    1    2 -1.000000 1.000000
## [2,]    0   -3 -1.000000 1.000000
## [3,]    0    0  7.333333 2.666667
# backward function to solve x
back <- function(Uc){
  x <- c(NA*3)
  x[3] <- Uc[3,4] / Uc[3,3]
  x[2] <- (Uc[2,4] - Uc[2,3] * x [3]) / Uc[2,2]
  x[1] <- (Uc[1,4] - Uc[1,2] * x[2] - Uc[1,3] * x[3]) / Uc[1,1]
  x <- round(x, 2)
  x
}
back(Uc)
## [1]  2.27 -0.45  0.36

Checking by solve function:

A <- matrix(c(1,1,3,2,-1,5,-1,-2,4), 3, 3)
b <- c(1, 2, 6)
solve(A, b)
## [1]  2.2727273 -0.4545455  0.3636364