Problem Set 1

—————————————————————————————————
—————————————————————————————————

u <- c(0.5, 0.5)
v <- c(3, -4)

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

dp <- u %*% v
dp  
##      [,1]
## [1,] -0.5

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.

Length of Vector u is

length_u <- sqrt(sum(u^2))
length_u
## [1] 0.7071068
length_v <- sqrt(sum(v^2))
length_v
## [1] 5

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

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

What is the angle between u and v?

rad <- acos(dp / (length_u * length_v))
# in degrees
rad * 180/pi
##         [,1]
## [1,] 98.1301

Problem Set 2

—————————————————————————————————
—————————————————————————————————

A <- matrix(c(1,1,3,2,-1,5,-1,-2,4), 3, byrow=T)
b <- matrix(c(1,2,6))
A
##      [,1] [,2] [,3]
## [1,]    1    1    3
## [2,]    2   -1    5
## [3,]   -1   -2    4
b
##      [,1]
## [1,]    1
## [2,]    2
## [3,]    6

Create augmented matrix

bind <- function(A,b){
    Augmented <- cbind(A,b)
}

Create upper triangle matrix

## Note - doesn't handle rows with 0 pivots 
## Ref : https://www.math.uh.edu/~jmorgan/Math6397/day13/LinearAlgebraR-Handout.pdf
triangle <- function(Aug){
    for (i in 2:nrow(Aug)){
        for(j in 1:(i - 1)){
            Aug[i,] <-  Aug[i,] - (Aug[j,] * (Aug[i, j]/Aug[j, j])) 
        }
    }
    Aug
}

Back solve upper triangle matrix, return vector x

back_solve <- function(UT){
  x <- c(NA*3)
  x[3] <- UT[3,4] / UT[3,3]
  x[2] <- (UT[2,4] - UT[2,3] * x [3]) / UT[2,2]
  x[1] <- (UT[1,4] - UT[1,2] * x[2] - UT[1,3] * x[3]) / UT[1,1]
  x <- round(x, 2)
  x
}

Function to Solve

## cal functions to produce x that solves Ax = b for 3*3 matrix w/ no zero pivots
solve_3X3_nozero_pivot <- function(A,b){
    Ab <- bind(A,b)
    UT <- triangle(Ab)
    x <- back_solve(UT)
    x
}
solve_3X3_nozero_pivot(A,b)
## [1] -1.55 -0.32  0.95

Double Check

A <- matrix(c(2,4,-2,4,9,-3,-2,-3,7), 3, byrow=T)
b <- matrix(c(2,8,10))
solve_3X3_nozero_pivot(A,b)
## [1] -1  2  2