Homework 1, DATA 605:
1:
1. Calculate the dot product u.v where u = [0.5; 0.5] and v = [3; −4]
knitr::opts_chunk$set(echo = TRUE)
my_u <- c(0.5, 0.5)
my_v <- c(3, -4)
dot_uv <- my_v %*% my_u # or we could calculate using sum(a*b):
dot_uv
## [,1]
## [1,] -0.5
alt_dot_uv <- sum(my_u*my_v)
alt_dot_uv
## [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.
mag_u <- sqrt(my_u[1]^2 + my_u[2]^2)
mag_v <- sqrt(my_v[1]^2 + my_v[2]^2)
mag_u
## [1] 0.7071068
mag_v
## [1] 5
3. What is the linear combination: 3u − 2v?
lin_combo <- 3*my_u - 2*my_v
lin_combo
## [1] -4.5 9.5
4 What is the angle between u and v?
given the dot prodcut provides:
\(\vec{u}\cdot\vec{v} = ||\vec{u}||||\vec{v}||cos\theta\)
\(cos\theta = \frac{\vec{u}\cdot\vec{v}}{|\vec{u}||\vec{v}|}\)
\(\theta = \arccos{\frac{\vec{u}\cdot\vec{v}}{|\vec{u}||\vec{v}|}}\)
Then, using the definitions I’ve previously calculated:
my_theta = dot_uv/(mag_v * mag_u)
my_theta
## [,1]
## [1,] -0.1414214
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…
solve_Ab <- function(A, b){
# Create augmented matrix and create rows of A for ease of coding:
aug_mtrx <- cbind(A,b)
R1 <- aug_mtrx[1,]
R2 <- aug_mtrx[2,]
R3 <- aug_mtrx[3,]
# get rid of x1 in R2 and R3 for aug_mtrx
aug_mtrx[2,] <- R2 - ((aug_mtrx[2,1]/aug_mtrx[1,1])*R1)
aug_mtrx[3,] <- R3 - ((aug_mtrx[3,1]/aug_mtrx[1,1])*R1)
# get rid of x2 in R3, update aug_mtrx
aug_mtrx[3,] <- aug_mtrx[3,] - ((aug_mtrx[3,2]/aug_mtrx[2,2])*aug_mtrx[2,])
# empty vector for x1,x2, and x3
x <- rep(0,3)
# find x3 from augmented matrices
x[3] <- aug_mtrx[3,4] / aug_mtrx[3,3]
# find x2 with some substition:
x[2] <- (aug_mtrx[2,4] - x[3]*aug_mtrx[2,3]) / aug_mtrx[2,2]
# find x1 with further substituion:
x[1] <- (aug_mtrx[1,4] - x[2]*aug_mtrx[1,2] - x[3]*aug_mtrx[1,3]) / aug_mtrx[1,1]
# return the vector solution:
return(x)
}
Below, please find an example of the function in use:
my_A <- matrix(c(4,1,-4,10,-11,-1,4,6,1), nrow = 3, ncol=3)
my_b <- c(-3,6,100)
solve_Ab(my_A,my_b)
## [1] -22.957778 4.011111 12.180000
#solve(my_A,my_b) # for checking only.
Below, please find an example of the function in use with the provided system test to show that it works.
my_A <- matrix(c(1,2,-1,1,-1,-2,3,5,4), nrow = 3, ncol=3)
my_b <- c(1,2,6)
solve_Ab(my_A,my_b)
## [1] -1.5454545 -0.3181818 0.9545455