Matrix Algebra: Exercises


1. Defining matrices. The function matrix(x, nrow, ncol) can be used to create a matrix object in R. The nrow and ncol parameters specify the number of rows and columns of the matrix. Additionally, x is a vector of values that is transformed into the matrix.

Start by defining a variable, vector, that consists of the integers from 1 to 20 using 1:20. Use matrix() to transform that variable into a 4x5 matrix.


# Define a vector of integers from 1 to 20. vector <- c(___:___) # Convert the vector into a 4x5 matrix. matrix45 <- ___(___, nrow = 4, ncol = ___) # Print the matrix. print(matrix45) # Define a vector of integers from 1 to 20. vector <- c(1:20) # Convert the vector into a 4x5 matrix. matrix45 <- matrix(vector, nrow = 4, ncol = 5) # Print the matrix. print(matrix45) test_error() test_object("vector", incorrect_msg="Did you use `1:20` to define the vector of integers?") test_object("matrix45", incorrect_msg="Did you use the `matrix()` function correctly?") success_msg("Excellent work. Do you notice anything about the way the elements of the vector are ordered in the matrix?")
Check that you used the correct arguments for `matrix()`.

Previous Exercise Next Exercise