##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
length_u <- sqrt(u[1]**2+u[2]**2)
length_v <- sqrt(v[1]**2+v[2]**2)lin_combo <- 3*(u)-2*(v)
print (lin_combo)## [1] -4.5 9.5
\(cosθ =(\vec{u}\cdot\vec{v})/ ( length(u)*length(v))\)
##
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"
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])
}solve_by_hand(A,b)## [1] -1.5454545 -0.3181818 0.9545455
solve(A,b)## [1] -1.5454545 -0.3181818 0.9545455