11 Types of Special Matrices in R (and how to create them) [Examples]

Matrices play a vital role in many calculations. Especially in linear algebra, graph theory, and computer science. Each matrix is unique, but some are special.

In this article, we discuss 11 types of special matrices in R and how to create them:

  1. The All-Ones Matrix
  2. The Anti-Diagonal Matrix
  3. The Diagonal Matrix
  4. The Distance Matrix
  5. The Empty Matrix
  6. The Exchange Matrix
  7. The Identity Matrix
  8. The Random Matrix
  9. The Triangular Matrix
  10. The Tridiagonal Matrix
  11. The All-Zeros Matrix

You can create all these matrices with basic R code. So, no additional packages are required.

How to Create an All-Ones Matrix in R

A matrix of ones or all-ones matrix is a matrix whose elements are all equal to one. An all-ones matrix can be both a square and non-square matrix.

In R, you create an all-ones matrix with the matrix() function. This basic R function requires 3 arguments, namely the value (i.e., the number 1), the number of rows, and the number of columns. You can use the matrix() function to create square and non-square all-ones matrices.

In the example below, we create a 3-by-3 matrix of ones.

x <- matrix(data = 1, nrow = 3, ncol = 3)
x
How to Create an All-Ones Matrix in R

How to Create an Anti-Diagonal Matrix in R

The anti-diagonal matrix is a square matrix where all entries are zero except for those on the anti-diagonal. That is to say, the diagonal going from the lower-left corner to the upper-right corner.

Creating an anti-diagonal matrix in R is a 3 step process:

  1. Create a vector with the values that must become the entries of the anti-diagonal.
  2. Create a normal diagonal matrix of the vector.
  3. Mirror all rows of the diagonal matrix. In other words, the first row becomes the last row, the second row becomes the second-last row, etc.

This code combines the steps above and creates an anti-diagonal matrix in R.

a <- c(1, 2, 3)
a

b <- diag(a)
b

x <- b[length(a):1,]
x
How to Create an Anti-Diagonal Matrix in R

You can also create an anti-diagonal matrix from an existing, square matrix. In other words, to set all entries to zero, except for the anti-diagonal. Keeping only the entries on the anti-diagonal is a 2 step process.

First, you create an anti-diagonal matrix with only 1’s (also known as the exchange matrix). Then, you multiply the original matrix with this auxiliary matrix. See the example below.

a <- matrix(sample(1:20, 9), 3, 3)
a

b <- diag(1,3)[3:1,]
b

x <-  a * b
x

How to Create a Diagonal Matrix in R

A diagonal matrix is a square matrix whose entries outside the main diagonal are all zero. The main diagonal starts in the upper-left corner and ends in the lower-right corner.

You create a diagonal matrix in R with the diag() function. This function has one argument, namely the values for the diagonal, and returns the complete diagonal matrix.

In the example below, we first create a vector with the values that must be placed on the diagonal. Then, we use the diag() function to generate the 4-by-4 diagonal matrix.

a <- c(1, 3, 4, 2)
x <- diag(a)
x
How to Create a Diagonal Matrix in R

How to Create a Distance Matrix in R

A distance matrix is a square matrix containing the distances between two coordinates/entires of a data set. Normally, the Euclidian distance is used to measure the distance.

In R, you can create a distance matrix with the dist() function. The function takes as its argument a set of coordinates and returns a square matrix with the Eucledian distance between them. The dist() function can calculate the distance between points in all dimensiones.

The dist() function has two optional arguments, namely:

  • The upper=-option indicates whether the upper triangle of the distance matrix should be printed.
  • The diag=-option indicates whether the diagonal should be printed.

By default, the dist() function calculates the Eucledian distance between the coordinates. However, you can change the distance measure with the method=-option. Allowed values are “euclidean”, “maximum”, “manhattan”, “canberra”, “binary”, and “minkowski”.

In the example below, we create a 5-by-5 distance matrix. We use the upper=-option and the diag=-option to show the upper triangle and the diagonal of zeros.

dim_rows <- 5
dim_cols <- 2

set.seed(123)
x <- matrix(sample(-10:10, size = dim_rows * dim_cols),
            nrow = dim_rows,
            ncol = dim_cols)
x

dist(x, upper = TRUE, diag = TRUE)
How to Create a Distance Matrix in R

How to Create an Empty Matrix in R

An empty matrix is a square or non-square matrix where are the entries are missing values. In other words, all entries are NA´s. An empty matrix is not the same as a matrix of all zeros.

An empty matrix can be useful if you already know the dimensions of your matrix, but not yet the values of the elements.

In R, you create an empty matrix with the matrix() function. This native R function requires 3 arguments, namely:

  1. The values of the matrix. In case of an empty matrix, you use NA.
  2. A positive integer that specifies the number of rows.
  3. A positive integer that speicifies the number of columns.

We use the following R code to create a 3-by-3 empty matrix.

x <- matrix(data = NA, nrow = 3, ncol = 3)
x
How to Create an Empty Matrix in R

How to Create an Exchange Matrix in R

The exchange matrix is a square matrix with ones on the anti-diagonal and zeros on all other elements. Hence, it is a combination of the identity matrix and the anti-diagonal matrix.

An exchange matrix is also known as a reversal matrix, backward identity matrix, or standard involutory permutation matrix.

To create an exchange matrix in R, you first create a normal identity matrix with the diag() function. Then you mirror the rows of the identity matrix to create an exchange matrix. You mirror the rows of a matrix with the bracket notation.

The trick of creating an exchange matrix is to mirror (i.e., flip) the rows of the normal identity matrix. You can do this with the bracket notation. You select all rows of the identity matrix but in reversed order.

In R code below shows how to create a 3-by-3 exchange matrix.

dim <- 3
a <- diag(1, dim)
a

x <- a[dim:1,]
x
How to Create an Exchange Matrix in R

How to Create an Identity Matrix in R

The identity matrix is a square matrix with ones on the main diagonal and zeros on the remaining entries. Hence, it is a special type of diagonal matrix.

The identity matrix is widely used in linear algebra. You can use this matrix also to create an exchange matrix or an anti-diagonal matrix.

You create an identity matrix in R with the diag() function. This function creates a diagonal matrix and requires two arguments:

  1. The value for the main diagonal, i.e, the number 1.
  2. A positive integer that specifies the dimensions of the identity matrix.

Below we create a 3-by-3 identity matrix.

dim <- 3
x <- diag(1, dim)
x
How to Create an Identity Matrix in R

How to Create a Random Matrix in R

A random matrix is a square or non-square matrix where the elements are random numbers.

In R, you create a random matrix with the matrix() function and a function that generates random numbers. The matrix() function has 3 arguments, namely, the random numbers and two positive integers that define the dimensions of the matrix.

Many functions can generate random numbers in R. Keep in mind that the total number of random numbers is equal to the number of rows times the number of columns. For example, if you want to create a 3-by-3 random matrix, the total number of random numbers must be 9.

Below we create a 3-by-3 random matrix with values between -10 and 10 using the sample() function. We use the set.seed() function for replicability.

dim_rows <- 3
dim_cols <- 3

set.seed(123)
x <- matrix(sample(-10:10, size = dim_rows * dim_cols),
            nrow = dim_rows,
            ncol = dim_cols)
x
How to Create a Random Matrix in R

How to Create a Triangular Matrix in R

A triangular matrix is a square matrix where all entries below (upper triangular matrix) or above (lower triangular matrix) the main diagonal are zero.

Triangular matrices are very popular in linear algebra. Especially, for LU decomposition and matrix inversion.

In R, you create a triangular matrix with the lower.tri() function for a lower triangular matrix, or the upper.tri() function for the upper triangular matrix. Both functions require a square matrix as input.

Note that the lower.tri() and upper.tri() functions do not directly return a triangular matrix. Instead, these functions return a matrix containing either TRUE or FALSE for each entry. Hence, to create a triangular matrix, you need to multiply the outcome of these functions with the original matrix.

In the example below, we convert a 3-by-3 random matrix into a lower triangular matrix and an upper triangular matrix.

dim_rows <- 3
dim_cols <- 3

set.seed(123)
x <- matrix(sample(-10:10, size = dim_rows * dim_cols),
            nrow = dim_rows,
            ncol = dim_cols)
x

# Create a Lower Triangular Matrix
lower_x <- lower.tri(x, diag = TRUE) * x
lower_x

# Create an Upper Triangular Matrix
upper_x <- upper.tri(x, diag = TRUE) * x
upper_x
How to Create a Triangular Matrix in R

How to Create a Tridiagonal Matrix in R

A tridiagonal matrix is a band matrix with all entries equal to zero except the main diagonal, the first lower diagonal, and the first upper diagonal.

You can create a tridiagonal matrix in R with a simple bracket operation. You only need to identify the elements where the absolute difference between the row and column number is greater than 1 and set this element to 0.

In other words, you can find all the elements that must be zero when the following formula holds:

abs(row(x) - col(x)) > 1

The row() and col() function return the row and column number.

In the example below, we create a 5-by-5 random matrix and convert it into a tridiagonal matrix.

dim_rows <- 5
dim_cols <- 5

set.seed(123)
x <- matrix(sample(-20:20, size = dim_rows * dim_cols),
            nrow = dim_rows,
            ncol = dim_cols)
x

x[abs(row(x) - col(x)) > 1] <- 0
x
How to Create a Tridiagonal Matrix in R

How to Create a Zero Matrix in R

An all-zero matrix or matrix of zeros is a square or non-square matrix whose elements are all zero. A zero matrix is not the same as an empty matrix.

You create a zero matrix with the matrix() function. You only need to provide 3 arguments, namely a zero, the number of rows, and the number of columns. Both the number of rows and the number of columns must be a positive integer.

Below we create a 3-by-3 zero matrix.

x <- matrix(0, nrow = 3, ncol = 3)
x
How to Create a Zero Matrix in R