R: Matrices and Matrix Computations
I. Constructing Matrices
Constructing a matrix can be done with the matrix() function as shown below. The default is to fill in the matrix by column. However, one can change this by setting byrow = TRUE which will fill in the matrix by row. To define the number of rows and columns, use the nrow and ncol arguments. You can define both nrow and ncol, but as shown below, if only one is given, R will infer what the other one is by default. Lets begin by making two matrices as shown below:
Constructing a matrix can be done with the matrix() function as shown below. The default is to fill in the matrix by column. However, one can change this by setting byrow = TRUE which will fill in the matrix by row. To define the number of rows and columns, use the nrow and ncol arguments. You can define both nrow and ncol, but as shown below, if only one is given, R will infer what the other one is by default. Lets begin by making two matrices as shown below:
\(a = \begin{bmatrix} 1 & 4 \\[0.3em] 2 & 4 \\[0.3em] 3 &6 \end{bmatrix}\)
> # Construct a 3 by 2 marix - fill in by column
> a = matrix(c(1,2,3,4,5,6),
+ nrow = 3)
> a
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
>
> # Construct a 3 by 2 marix - fill in by row
> b = matrix(c(1,2,3,4,5,6),
+ nrow = 3,
+ byrow = TRUE)
> b
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6
>
> # Construct a 2 by 3 matrix - fill in by row
> c = matrix(c(1,2,3,4,5,6),
+ nrow = 2,
+ byrow = TRUE)
> c
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
II. Adding and Subtracting Matrices
Adding and subtracting matrices can be done as shown below.
\(m = \begin{bmatrix} 0 & 1 & 2 \\[0.3em] 9 & 8 & 7 \\[0.3em] \end{bmatrix}\) \(n = \begin{bmatrix} 6 & 5 & 4 \\[0.3em] 3 & 4 & 5 \\[0.3em] \end{bmatrix}\)
> # create two matrices with the same dimensions
> m = matrix(c(0 ,1 ,2, 9, 8, 7),nrow = 2, byrow = 2)
> m
[,1] [,2] [,3]
[1,] 0 1 2
[2,] 9 8 7
> n = matrix(c(6, 5, 4, 3, 4, 5),nrow = 2, byrow = 2)
> n
[,1] [,2] [,3]
[1,] 6 5 4
[2,] 3 4 5
>
> # add two matrices
> m + n
[,1] [,2] [,3]
[1,] 6 6 6
[2,] 12 12 12
>
> # subtract two matrices
> m - n
[,1] [,2] [,3]
[1,] -6 -4 -2
[2,] 6 4 2
III. Multiplying matrices Matrices
Multiplying matrices can be done using the following code as shown below: %*%
> c = matrix(c(1, 0, -2, 0, 3, -1), nrow = 2, byrow = 2)
> c
[,1] [,2] [,3]
[1,] 1 0 -2
[2,] 0 3 -1
> d = matrix(c(0, 3, -2, -1, 0, 4), nrow = 3, byrow = 2)
> d
[,1] [,2]
[1,] 0 3
[2,] -2 -1
[3,] 0 4
>
> c%*%d
[,1] [,2]
[1,] 0 -5
[2,] -6 -7
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.