Data Stucture: Matrices

\[m1 =\begin{bmatrix}1&2&3\\4&5&6\\7&8&9\end{bmatrix} \] ::: {.cell exercise=‘ex1’}

Create a 3x3 matrix with values from 1 to 9. Assign it to a variable m1 and display the matrix.

Solution:

m1 <- matrix(1:9, nrow = 3, byrow = TRUE)
m1

:::

Use m1 and add row names “Row1”, “Row2”, “Row3” and column names “Col1”, “Col2”, “Col3”. Display the matrix to confirm.

Solution:

rownames(m1) <- c("Row1", "Row2", "Row3")
colnames(m1) <- c("Col1", "Col2", "Col3")
m1

Retrieve the element in the second row and third column of m1.

Solution:

m1["Row2", "Col3"]

\[m1 =\begin{bmatrix}1&3\\2&4\end{bmatrix} \] ::: {.cell exercise=‘ex4’}

Create a 2x2 matrix m2 with values 1 to 4, and add 5 to each element. Then, multiply each element by 3.

Solution:

m2 <- matrix(1:4, nrow = 2)

# Add 5 to each element
m2_add <- m2 + 5
m2_add

# Multiply each element by 3
m2_mult <- m2 * 3
m2_mult

:::

Transpose m1 to get the columns as rows and rows as columns. Assign it to a variable m1_transpose.

Solution:

m1_transpose <- t(m1)
m1_transpose

Calculate the sum of each row and each column in m1 using rowSums() and colSums() functions.

Solution:

rowSums_m1 <- rowSums(m1)
rowSums_m1

colSums_m1 <- colSums(m1)
colSums_m1

\[m3 =\begin{bmatrix}9&8&7\\6&5&4\\3&2&1\end{bmatrix} \] ::: {.cell exercise=‘ex7’}

Create another 3x3 matrix m3 with values 9 to 1. Multiply m1 and m3 using matrix multiplication (%*%).

Solution:

m3 <- matrix(9:1, nrow = 3, byrow = TRUE)
m1_m3_mult <- m1 %*% m3
m1_m3_mult

:::

Extract the second row and then the third column of m1.

Solution:

# Second row of m1
m1[2, ]

# Third column of m1
m1[, 3]

Create two 2x2 matrices, m4 <- matrix(c(1, 2, 3, 4), nrow = 2) and m5 <- matrix(c(5, 6, 7, 8), nrow = 2). Combine them by row using rbind() and by column using cbind().

Solution:

m4 <- matrix(c(1, 2, 3, 4), nrow = 2)
m5 <- matrix(c(5, 6, 7, 8), nrow = 2)

# Combine by row
rbind_m4_m5 <- rbind(m4, m5)
rbind_m4_m5

# Combine by column
cbind_m4_m5 <- cbind(m4, m5)
cbind_m4_m5

Create a 2x2 matrix m6 <- matrix(c(4, 7, 2, 6), nrow = 2). Find the inverse of m6 using the solve() function.

Solution:

m6 <- matrix(c(4, 7, 2, 6), nrow = 2)
m6_inv <- solve(m6)
m6_inv