Matrix
  • the elements are arranged in a two-dimensional rectangular layout
  • elements are the same atomic types
  • index starts from 1
  • Create Matrix
    M <- matrix(c(3:14), nrow = 4, byrow = TRUE) # elements are arranged by row
    print(M)
    
    N <- matrix(c(3:14), nrow = 4, byrow = FALSE) # elements are arranged by column
    print(N)
    
    rownames = c("row1", "row2", "row3", "row4")
    colnames = c("col1", "col2", "col3")
    P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames))
    print(P)
    		
    Accesing
    rownames = c("row1", "row2", "row3", "row4")
    colnames = c("col1", "col2", "col3")
    
    P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames))
    print(P)
    
    print(P[1, 2]) # 4, first row, second column
    print(P[1, ]) # first row
    print(P[, 2]) # second column
    		
    Operations
    M = matrix(1:12, nrow = 4)
    print(M)
    
    N = matrix(seq(2, 24, by = 2), nrow = 4)
    print(N)
    
    print(M+N) # addition
    print(N-M) # substraction
    print(M*N) # multiplication, elementwise
    print(M/N) # division, elementwise
    
    print(dim(M)) # dimension
    
    print(M %*% t(N)) # matrix multiplication
    		
    Reference
  • Matrix Algebra