- Calculate the dot product u.v where u = [0.5; 0.5] and v = [3; -4]
U = c(.5,.5)
V = c(3,-4)
crossprod(V,U)
## [,1]
## [1,] -0.5
- What are the lengths of u and v?
vectorlength = function(vm){
return(sqrt( (vm[1]**2)+vm[2]**2) )
}
lengthU = vectorlength(U)
lengthV = vectorlength(V)
print (c(lengthU,lengthV))
## [1] 0.7071068 5.0000000
- What is the linear combination of 3u - 2v?
simplelinearcombo = function(U,V,c1,c2){
return((c1*U) - (c2*V))
}
simplelinearcombo(U,V,3,2)
## [1] -4.5 9.5
- What is the angle between u and v?
vectorangle = function(U, V){
return( acos( (crossprod(U,V) / ((vectorlength(U)) * (vectorlength(V) ))))[1] * (180/3.1416))
}
vectorangle(U,V)
## [1] 98.12987
- Problem set two; disregarding degenerative equations and zero pivots, create a function to solve a 3 variable, 3 constraint system.
A = matrix(c(1,2,-1,1,-1,-2,3,5,4),nrow=3,ncol = 3)
b = c(1,2,6)
solver = function(A){
# Combine into one matrix
A = cbind(A,b)
#Choose pivot, the first non-zero element in the row ... Meaning this function does not work when rows start with 0
multiplier = (A[2,1]/A[1,1]*(A[1,]))
A[2,] = A[2,]-multiplier
multiplier = (A[3,1]/A[1,1]*(A[1,]))
A[3,] = A[3,]-multiplier
multiplier = (A[3,2]/A[2,2]*(A[2,]))
A[3,] = A[3,]-multiplier
#Substitute accordingly
l = (A[3,4]/A[3,3])
h = (A[2,4]-A[2,3]*l)/A[2,2]
m = (A[1,4]-A[1,3]*l - A[1,2]*h)/A[1,1]
return(c(m,h,l))
}
solver(A)
## b b b
## -1.5454545 -0.3181818 0.9545455