HW1

  1. Calculate the dot product for u=[.5,.5] and v = [3, -4].
u=c(.5,.5)
v=c(3,-4)
udotv=t(u)%*%v
udotv
##      [,1]
## [1,] -0.5
  1. What are the lengths of u and v?
lenu=sqrt(t(u)%*%u)
lenv=sqrt(t(v)%*%v)
lenu
##           [,1]
## [1,] 0.7071068
  1. What is the linear combination of 3u-2v?
3*u-2*v
## [1] -4.5  9.5
  1. What is the angle between u and v?
costheta=udotv/(lenu*lenv)
acos(costheta)*180/pi
##         [,1]
## [1,] 98.1301

Next, you are asked to build a simple elimination program for a 3x3 LHS with no error checking. Here is a very quick and dirty solution.

myf=function(A){

if(det(A[,1:3])==0){return("singular")} else{

if(A[1,1]==0){A=rbind(A[2,],A[3,],A[1,],A[4,])}  #Quick sort (2 lines)
if(A[1,1]==0){A=rbind(A[3,],A[2,],A[1,],A[4,])}

A=rbind(A[1,]/A[1,1], A[2,],A[3,])                #Divide by Pivot
A=rbind(A[1,], A[2,]-A[1,]*A[2,1]/A[1,1], A[3,])  #Zero out 2d Row
A=rbind(A[1,], A[2,], A[3,]-A[1,]*A[3,1]/A[1,1])  #Zero out 3d Row
  
if (A[2,2]==0){A=rbind(A[1,],A[3,],A[2,])}        #Quick sort

A=rbind(A[1,], A[2,]/A[2,2], A[3,])               #Divide by Pivot
A=rbind(A[1,],A[2,], A[3,]-A[2,]*A[3,2]/A[2,2])   #Zero out 3d Row

x3=A[3,4]/A[3,3]                                  #Solve w. UT
x2=A[2,4]-A[2,3]*x3 
x1=A[1,4]-A[1,3]*x3-A[1,2]*x2

mylist=list(x1,x2,x3)                             #Return Solution
names(mylist)=c("x1","x2","x3")
return(mylist)
}
}

Test the Function.

All we have left to do is test the function.

A=matrix(c(3,5,5,5,2,-1,0,-2,-2, 3,4,5),nrow=3,byrow=T)
myf(A)
## $x1
## [1] -0.46875
## 
## $x2
## [1] 1.0625
## 
## $x3
## [1] 0.21875
solve(A[,1:3],A[,4]) #verify
## [1] -0.46875  1.06250  0.21875
B=matrix(runif(12,1,10),nrow=3) #verify again
myf(B)
## $x1
## [1] -21.07543
## 
## $x2
## [1] 20.74172
## 
## $x3
## [1] -3.723295
solve(B[,1:3],B[,4])
## [1] -21.075428  20.741717  -3.723295
C=matrix(c(0,5,5,5,0,0,1,-2,0, 1,0,5),nrow=3,byrow=T)  #verify singular
myf(C)
## [1] "singular"