Matrix Algebra: Exercises


2. Matrix addition. The matrix, A, and the vector, b have been defined for you. Use the functions nrow() and ncol() to calculate the number of rows and columns of the matrix. Use this information to convert b into a matrix, C, that can be added to A.


A <- matrix(1:30, nrow = 5, ncol = 6) b <- c(31:60) # Compute number of rows in A. rowsA <- nrow(___) # Compute number of columns in A. colsA <- ___(___) # Reshape vector, b, into matrix, C, with same dimensions as A. C <- ___(___, nrow = rowsA, ncol = ___) # Print sum of A and C. print(A+C) # Compute number of rows in A. rowsA <- nrow(A) # Compute number of columns in A. colsA <- ncol(A) # Reshape vector, b, into matrix, C, with same dimensions as A. C <- matrix(b, nrow = rowsA, ncol = colsA) # Print sum of A and C. print(A+C) test_error() test_object("rowsA", incorrect_msg="Did you use the function `nrows()`?") test_object("colsA", incorrect_msg="Did you use the function `ncols()`?") test_object("C", incorrect_msg="Did you use `nrowsA` and `ncolsA` as arguments?") success_msg("Good work.")
Recall that the matrix() function can specify a number of rows and a number of columns.

Previous Exercise Next Exercise