Main Example
Compute the product of the matrices below (Question C21, Page 190).
Question C21, Page 190
Matrix A:
## [,1] [,2] [,3]
## [1,] 1 3 2
## [2,] -1 2 1
## [3,] 0 1 0
Matrix B:
## [,1] [,2] [,3]
## [1,] 4 1 2
## [2,] 1 0 1
## [3,] 3 1 5
Product
I created a custom function to generate the matrix product of any two matrices. This function iterates between rows of matrix A and columns of matrix B to find the dot product.
matrix_mult <- function(matrix_A, matrix_B){
C = matrix(nrow = nrow(matrix_A), ncol = ncol(matrix_B))
for (b in 1:ncol(matrix_B)){
for (a in 1:nrow(matrix_A)){
C[a,b] = sum(matrix_A[a,]*matrix_B[,b])
}
}
return(C)
}
print(matrix_mult(A,B))## [,1] [,2] [,3]
## [1,] 13 3 15
## [2,] 1 0 5
## [3,] 1 0 1