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
sum(u*v)
## [1] -0.5
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 -4.5,9.5
lin_combo <- 3*(u)-2*(v)
print (lin_combo)
## [1] -4.5  9.5

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

  • Wrong answer with norm function Answer 81.87
  • Correct answer by simply plugging in values 98.13
##
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"
##
### less fancy 
b <- acos(-.5/(length_u%*%length_v))
paste("converted to degrees the angle is", round(b*180/pi,2))
## [1] "converted to degrees the angle is 98.13"

Problem Set 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){
## Input matrix and vector, returns solved coefficent solution vector
my_matrix <- cbind(A,b)

## Attempt initial 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

## Step_1 create 1 value
if (my_matrix[1,1]!= 1)
    my_matrix[1,] <- my_matrix[1,] / my_matrix[1,1]
## Step 2 create 0 values 
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

## Row swap if [2,2]==0
if (my_matrix[2,2]==0)
    my_matrix=my_matrix[c(1,3,2),]
## Step 1 create 1 value   
if (my_matrix[2,2]!= 1)
    my_matrix[2,] <- my_matrix[2,] / my_matrix[2,2]
## Step 2 create 0 values 
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
## Step 1 create 1 value
if (my_matrix[3,3]!= 1)
    my_matrix[3,] <- my_matrix[3,] / my_matrix[3,3]
## Step 2 create 0 values 
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])
}

Compare solve_by_hand and built in solve

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