Problem Set 1

  • 1 Calculate the dot product u:v where u = [0.5;0.5] and v = [3;􀀀4]
    • Answer .5
##initialize vectors
u=c(.5,.5)
v=c(3,-4)

## long hand
sum(u%*%v)
## [1] -0.5
## using a dot product function

dot(u,v)
## [1] -0.5
  • 2 What are the lengths of u and v?
    • Answer u= .71
    • Answer v=5
length_u <- sqrt(u[1]**2+u[2]**2)
length_v <- sqrt(v[1]**2+v[2]**2)
  • 3 What is the linear combination: 3u 􀀀 2v?
    • Answer 7.5,-6.5
lin_combo <- 3*(u)+2*(v)
print (lin_combo)
## [1]  7.5 -6.5
  • 4 What is the angle between u and v

\(cosθ =(\vec{u}\cdot\vec{v})/ ( length(u)*length(v))\)

  • Answer 81.87
a <-  acos(   .5/ (norm(u,type="2")*norm(v,type="2")))

paste("converted to degrees the angle is", round(a*180/pi,2))
## [1] "converted to degrees the angle is 81.87"

Problem 2

Create function

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

#solve_by_hand <- function(A,b)
# let xyz be variables & row1,2,3 be formulas





solve_by_hand <- function(A,b){
## Create augmented matrix
my_matrix <- cbind(A,b)
my_matrix
### Attempt row swaps
if (my_matrix[1,1]==0){
    if (my_matrix[2,2]==0|my_matrix[3,1]!=1|my_matrix[3,3]!=0){
        my_matrix=my_matrix[c(2,1,3),]
    }else {my_matrix=my_matrix[c(3,2,1),]
    }
}
### create pivot column 1
if (my_matrix[1,1]!= 1)
    my_matrix[1,] <- my_matrix[1,] / my_matrix[1,1]
  
if (my_matrix[2,1]!=0)
    my_matrix[2,]<- -(my_matrix[2,1])*(my_matrix[1,])+my_matrix[2,]
if (my_matrix[3,1]!=0)
    my_matrix[3,]<- -(my_matrix[3,1])*(my_matrix[1,])+my_matrix[3,]


## Create pivot column 2
if (my_matrix[2,2]!= 1)
    my_matrix[2,] <- my_matrix[2,] / my_matrix[2,2]
if (my_matrix[1,2]!=0)
     my_matrix[1,]<- -(my_matrix[1,2])*(my_matrix[2,])+my_matrix[1,]
if (my_matrix[3,2]!=0)
     my_matrix[3,]<- -(my_matrix[3,2])*(my_matrix[2,])+my_matrix[3,]

## Create pivot column 3
if (my_matrix[3,3]!= 1)
    my_matrix[3,] <- my_matrix[3,] / my_matrix[3,3]
if (my_matrix[1,3]!=0)
     my_matrix[1,]<- -(my_matrix[1,3])*(my_matrix[3,])+my_matrix[1,]
if (my_matrix[2,3]!=0)
      my_matrix[2,]<- -(my_matrix[2,3])*(my_matrix[3,])+my_matrix[2,]

return(my_matrix[,4])
}

solve_by_hand(A,b)
## [1] -1.5454545 -0.3181818  0.9545455
solve(A,b)
## [1] -1.5454545 -0.3181818  0.9545455