Matrices Flashcards
What is a matrix?
Two dimensional array
Can a single matrix hold elements of multiple data types?
No
What is the function to create a matrix?
matrix()
Ex: matrix(1:9, byrow = TRUE, nrow = 3)
What are the arguments to matrix() aside from the collection of elements, and what do they do?
The argument byrow indicates whether the matrix is filled by the rows or the columns.
The argument nrow indicates the number of rows the matrix should have.
What is the function to name the rows and columns of a matrix?
rownames() and colnames().
Ex: rownames(my_matrix) <- c(“name1”, “name2”)
Ex: colnames(my_matrix) <- c(“name1”, “name2”)
Which functions calculate the totals for each row or column of a matrix?
rowSums() and colSums()
Ex: new_vector <- rowSums(my_matrix)
Ex: new_vector <- colSums(my_matrix)
Which functions add columns or rows to a matrix, merging matrices and/or vectors together?
cbind() and rbind()
Ex: big_matrix <- cbind(matrix1, matrix2, vector1 …)
Ex: big_matrix <- rbind(matrix1, matrix2, vector1 …)
How can you select a single element from a matrix?
[num1, num2]
Ex: my_matrix[1,2]
How can you select multiple in-sequence elements from a matrix?
[num1:num2, num3:num4]
Ex: my_matrix[1:3, 2:4]
How can you select an entire column or row from a matrix?
[,num] and [num,]
Ex: my_matrix[,1]
Ex: my_matrix[1,]
When selecting an element(s) from a matrix, is it written [rows, columns], or [columns, rows]?
[rows, columns]
What happens when a matrix is added, subtracted, etc. by a single object?
Ex: matrix(1:9, byrow = TRUE, nrow = 3) * 5
The result is calculated element-wise.
Ex Result: 5 10 15
20 25 30
35 40 45 is printed
What happens when two matrices are added, subtracted, etc.?
Ex: matrix(1:9, byrow = TRUE, nrow = 3) * matrix(1:9, byrow = TRUE, nrow = 3)
The result is calculated with each element being calculated with the element of the corresponding index in the other matrix.
Ex Result: 1 4 9
16 25 36
49 64 81 is printed