Matrix operations are the foundation of linear algebra, which we define here. First we define matrix addition. In order to do so, the number of row vectors of A and B have to be the same and the number of column vectors A and B have to be the same.

Example 1

v1 <- c(2, -1, 3)
v2 <- c(-1, 0, 4)

Then the sum of these vectors is R outputs the following

v1 + v2
## [1]  1 -1  7

Examplle 2 Suppose we have two 2 × 3 matrices

A <- matrix(c(3, 0, -5, -1, -3, 4), nrow = 2, ncol = 3, byrow = TRUE)
B <- matrix(c(-5, 5, 2, 1, -2, 0), nrow = 2, ncol = 3, byrow = TRUE)

Then the sum of these matrices can be computed by

A + B
##      [,1] [,2] [,3]
## [1,]   -2    5   -3
## [2,]    0   -5    4

Example 3 we can do the scalar multiplication

A <- matrix(c(3, 0, -5, -1, -3, 4), nrow = 2, ncol = 3, byrow = TRUE)

Then we can do the scalar multiplication in R as

A * 3
##      [,1] [,2] [,3]
## [1,]    9    0  -15
## [2,]   -3   -9   12

Example 4 Multiplication

v1 <- c(2, -1, 3)
v2 <- c(-1, 0, 4)

Then the dot product of these vectors in R is

v1 %*% v2
##      [,1]
## [1,]   10

Example 5 Transpose

A <- matrix(c(4, -1, -5, 0, 1, -2), 2, 3, byrow = TRUE)

Then we type in R

t(A)
##      [,1] [,2]
## [1,]    4    0
## [2,]   -1    1
## [3,]   -5   -2