You are on page 1of 2

Matrix exercises

Exercises about matrices

Matrices are multidimensional vectors; it is a data structure for storing objects of the same type.

1. Creation and initialization

a. Run the following code:

data <- 1:6


print(data)
data_matrix <- matrix(data)
print(data_matrix)

b. Replace all “x” in the following code and run line by line and inspect output:

# By columns
matrix(data, ncol = x, byrow = FALSE) # byrow = FALSE by default

matrix(data, ncol = x, nrow = x) # Equivalent

matrix(data, nrow = x) # Equivalent

# By rows
matrix(data, ncol = x, byrow = TRUE)

c. Create a matrix of two vectors using cbind() and rbind(). You can use the two vectors below.

x <- c(2, 7, 3, 6, 1)
y <- c(3, 7, 3, 5, 9)

d. Use dim() to change dimensions of a vector:

A <- c(3, 1, 6, 1, 2, 9)
dim(A) <- c(3, 2)

2. Inspection

a. Examine the matrices by using class(), typeof() and dim()

3. Manipulation

a. Add and remove columns:

1
# Add column
A <- cbind(A, c(6, 1, 7))

# Add two columns


A <- cbind(A, c(6, 1, 7), c(1, 6, 1))

# Remove first column


A <- A[, -1]

# Remove first and third column


A <- A[, -c(1, 3)]

b. Add and remove rows:

# Add row
A <- rbind(A, c(6, 1))

# Add row of fives


A <- rbind(A, 5)

# Remove second row


A <- A[-2, ]

c. Run the below code creating “my_matrix”.


c1. Get the first element of the first column. Use “[]”, “[[]]” and “[row,column]”
c2. Second row, third column
c3. First row
c4. Second column

my_matrix <- matrix(c(1, 5, 8, 1, 3, 2), ncol = 3)

4. Calculus
Since matrices are vectors with multiple dimensions, the same math operators as for vectors applies
for matrices as well.

You might also like