Problem set #1

u = c(0.5,0.5)
v = c(3,-4)

1.1 u.v

u%*%v
##      [,1]
## [1,] -0.5

1.2. length of u+v

sqrt((u[1] +v[1])^2 + (u[2] +v[2])^2)
## [1] 4.949747

1.3. 3u-2v

3*u-2*v
## [1] -4.5  9.5

1.4. angle between u and v

top= u[1]*v[1] + u[2]*v[2] 
ulength = sqrt((u[1])^2 + (u[2])^2)
vlength = sqrt((v[1])^2 + (v[2])^2)
bottom =  ulength*vlength
acos(top/bottom)
## [1] 1.712693
#4 answer2

angle <- function(u,v){
  dot.prod <- u%*%v 
  norm.u <- norm(u,type="2")
  norm.v <- norm(v,type="2")
  theta <- acos(dot.prod / (norm.u * norm.v))
  as.numeric(theta)
}

angle(t(u),v)
## [1] 1.712693

Problem set #2

solutionMatrix <- function (a,b,nrow,ncol){
  A = matrix(a,nrow,ncol, byrow=TRUE)
  B = matrix(b,nrow,1, byrow=TRUE)
  M<- cbind(A,B)

  #checkPivor and Swap next nonzero row to replace zero-pivor row
  for(jcol in 1: (ncol-1)){
    irow=jcol
    if(M[irow,jcol] == 0){
       backupRow=M[irow, ]
       irow<-(irow+1)
       while(irow <= nrow){
         if(M[irow,jcol] != 0){
           M[jcol, ]= M[irow, ]
           M[irow, ]= backupRow
           i=(nrow+1)
         }
         irow<-(irow+1)
      }
    }
  }
  #M[,]


#find Uper matrix
  jcol = 1
  while(jcol <= ncol){
    irow=jcol
    if(M[irow,jcol] != 0){
       M[irow,] <- M[irow,]/(M[irow,jcol])
       
       k=ncol-irow
       if(k>0) {
          for(i in 1:k) {
            nextRow = irow + i
            if(M[nextRow,jcol] != 0){
              M[nextRow,] <- ((M[nextRow,]/(M[nextRow,jcol])) - M[irow,])
            }
          }
       }
    }
    jcol=jcol+1
  }
  
 # M[,]

  #backward calculation
  jcol = nrow
  while(jcol>1){
    for(irow in 1:(jcol-1) ){
      if(M[irow,jcol] != 0){
          M[irow,] <- (M[irow,] - (M[irow,jcol])*M[jcol,])
      }
    }
    jcol = jcol-1 
  }
  print(round( M[,],2))
}

#Sample matrix 1
nrow = 3
ncol = 3
a = c(1,1,3,2,-1,5,-1,-2,4)  #coefficient matrix of variables
b = c(1,2,6)                  #solution vector

M1<- solutionMatrix (a,b,nrow,ncol)
##      [,1] [,2] [,3]  [,4]
## [1,]    1    0    0 -1.55
## [2,]    0    1    0 -0.32
## [3,]    0    0    1  0.95
#Sample matrix 2

nrow = 4
ncol = 4
a = c(0,1,03,0,0,5,0,-2,4,2,6,0,0,0,0,0)  #coefficient matrix of variables
b = c(1,2,6,7)                  #solution vector

M2 <- solutionMatrix (a,b,nrow,ncol)
##      [,1] [,2] [,3]  [,4]  [,5]
## [1,]    1    0    0  0.00  1.00
## [2,]    0    1    0 -0.40  3.20
## [3,]    0    0    1  0.13 -0.73
## [4,]    0    0    0  0.00  7.00