## 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

## Other Examples

I also applied this function to non-square matrices to see if it still works.

#### Question C20, Page 190

Compute the product of the matrices below.

#matrix A
A <- rbind(c(2,5),c(-1,3),c(2,-2))
print(A)
##      [,1] [,2]
## [1,]    2    5
## [2,]   -1    3
## [3,]    2   -2
#matrix B
B <- rbind(c(1,5,-3,4),c(2,0,2,-3))
print(B)
##      [,1] [,2] [,3] [,4]
## [1,]    1    5   -3    4
## [2,]    2    0    2   -3
#matrix product
print(matrix_mult(A,B))
##      [,1] [,2] [,3] [,4]
## [1,]   12   10    4   -7
## [2,]    5   -5    9  -13
## [3,]   -2   10  -10   14

#### Question C23, Page 190

Compute the product of the matrices below.

#matrix A
A <- rbind(c(3,1),c(2,4),c(6,5), c(1,2))
print(A)
##      [,1] [,2]
## [1,]    3    1
## [2,]    2    4
## [3,]    6    5
## [4,]    1    2
#matrix B
B <- rbind(c(-3,1),c(4,2))
print(B)
##      [,1] [,2]
## [1,]   -3    1
## [2,]    4    2
#matrix product
print(matrix_mult(A,B))
##      [,1] [,2]
## [1,]   -5    5
## [2,]   10   10
## [3,]    2   16
## [4,]    5    5