# Matrix algebra examples

############################################################################
# Example #1

  A <- matrix(data = c(1, 2, 3,
                     4, 5, 6), nrow = 2, ncol = 3, byrow = TRUE)
  class(A)
  B <- matrix(data = c(-1, 10, -1, 5, 5, 8), nrow = 2, ncol = 3, byrow = TRUE)

  A + B
  A - B

  #Show what happens with the byrow = TRUE option
  matrix(data = c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3)
  

#############################################################################
# Example #2

  A <- matrix(data = c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3, byrow = TRUE)
  B <- matrix(data = c(3, 0, 1, 2, 0, 1), nrow = 3, ncol = 2, byrow = TRUE)
  
  C <- A%*%B
  D <- B%*%A

  C
  D

  #What is A*B?
  A*B
  
  #Show what happens with *
  E <- A
  A*E

  # Tranpose of A
  t(A)


#############################################################################
# Example #3

  A <- matrix(data = c(1, 2, 3, 4), nrow = 2, ncol = 2, byrow = TRUE)
  solve(A)
  A%*%solve(A)
  solve(A)%*%A

  round(solve(A)%*%A, 2)


#############################################################################
# Vector example

  y <- matrix(data = c(1,2,3), nrow = 3, ncol = 1, byrow = TRUE)
  y
  class(y)

  x <- c(1,2,3)
  x
  class(x)
  is.vector(x)

  A <- matrix(data = c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3, byrow = TRUE)

  # Multiplication with y
  y%*%y # Does not work
  t(y)
  t(y)%*%y  # y'y
  y%*%t(y)  # yy’
  A%*%y
  y%*%A # Does not work

  # Multiplication with x
  x%*%x  # x’x, inner product
  t(x)
  A%*%x

  x%o%x  # xx’, outer product


#############################################################################
# solve() example

  A <- matrix(data = c(2, 4, 4, 10), nrow = 2, ncol = 2, byrow = TRUE)
  b <- matrix(data = c(0, 2), nrow = 2, ncol = 1, byrow = TRUE)
  solve(A, b)
  solve(A)%*%b
























#
