# Matrix Operations¶

Now that we've learned how to create a matrix, let's learn how to use functions and perform operations on it!

Run the following code to create the stock.matrix from earlier

In [18]:

    # Prices
    goog <- c(450,451,452,445,468)
    msft <- c(230,231,232,236,228)

    # Put vectors into matrix
    stocks <- c(goog,msft)
    stock.matrix <- matrix(stocks,byrow=TRUE,nrow=2)

    # Name matrix
    days <- c('Mon','Tue','Wed','Thu','Fri')
    st.names <- c('GOOG','MSFT')
    colnames(stock.matrix) <- days
    rownames(stock.matrix) <- st.names

    # Display
    stock.matrix

Out[18]:

| Mon | Tue | Wed | Thu | Fri
--- | --- | --- | --- | --- | ---
GOOG | 450 | 451 | 452 | 445 | 468
MSFT | 230 | 231 | 232 | 236 | 228

We can perform functions across the columns and rows, such as colSum:

In [19]:

    colSums(stock.matrix)

Out[19]:

Mon
  680
Tue
  682
Wed
  684
Thu
  681
Fri
  696

In [20]:

    # Doesn't really make sense for stocks, but just to show how it works
    rowSums(stock.matrix)

Out[20]:

GOOG
  2266
MSFT
  1157

We can also do other mathematical operations, check this reference for all functions available.

In [21]:

    rowMeans(stock.matrix)

Out[21]:

GOOG
  453.2
MSFT
  231.4

# Binding columns and rows¶

Let's go ahead and see how we can add columns and rows to a matrix, we can use the cbind() to bind a new column, and rbind() to bind a new row. For example, let's bind a new row with Facebook stock:

In [22]:

    FB <- c(111,112,113,120,145)

In [23]:

    tech.stocks <- rbind(stock.matrix,FB)

In [24]:

    tech.stocks

Out[24]:

| Mon | Tue | Wed | Thu | Fri
--- | --- | --- | --- | --- | ---
GOOG | 450 | 451 | 452 | 445 | 468
MSFT | 230 | 231 | 232 | 236 | 228
FB | 111 | 112 | 113 | 120 | 145

Now let's add an average column to the matrix:

In [25]:

    avg <- rowMeans(tech.stocks)

In [26]:

    avg

Out[26]:

GOOG
  453.2
MSFT
  231.4
FB
  120.2

In [27]:

    tech.stocks <- cbind(tech.stocks,avg)

In [28]:

    tech.stocks

Out[28]:

| Mon | Tue | Wed | Thu | Fri | avg
--- | --- | --- | --- | --- | --- | ---
GOOG | 450.0 | 451.0 | 452.0 | 445.0 | 468.0 | 453.2
MSFT | 230.0 | 231.0 | 232.0 | 236.0 | 228.0 | 231.4
FB | 111.0 | 112.0 | 113.0 | 120.0 | 145.0 | 120.2

Great! We've gone over some basic matrix operations! Up next we will talk about selecting and indexing matrix elements!