Julia Tutorial: Diagonal vs diagm

This tutorial discusses the three ways to make diagonal matrices in Julia:
Diagonal and diagm and spdiag

Of these, the Diagonal command is by far the most efficient.
Always use Diagonal instead of diagm for a pure diagonal matrix!

Jeff Fessler, University of Michigan
2019-01-15, Julia 1.0.3
2020-08-05, Julia 1.5.0
2021-08-23, Julia 1.6.2

The Diagonal function

The Diagonal function in the LinearAlgebra package creates a diagonal "matrix" from a vector of its diagonal elements.

I put "matrix" in quotes because the data type of the output of Diagonal is not an ordinary 2D Array but rather a special Diagonal type that behaves like a matrix but is stored efficiently.

The diagm function

The diagm function in the LinearAlgebra package creates a diagonal matrix from a vector of its diagonal elements, or a banded matrix from multiple band vectors.

Here, matrix means a standard 2D Array in Julia.

The spdiagm function

The spdiagm function in the SparseArrays package creates a diagonal "matrix" from a vector of its diagonal elements, or a banded matrix from multiple band vectors.

Here, "matrix" is quoted again because it is not a standard 2D Array in Julia, but rather a special SparseMatrix type that efficiently stores only the nonzero elements and their array indexes. However, for the special case of a diagonal matrix the sparse data type is not as efficient.

Comparing matrix multiplication speeds

Next we compare the execution times of multiplying each of the above 3 diagonal matrix data types by a vector. The differences are dramatic!

The preceding test has to reallocate y everytime, which is inefficient. Here is a faster version that overwrites y each time:

So what use is diagm then?

For making banded matrices with multiple diagonals, as follows. NOT for making an ordinary diagonal matrix!

Rectangular Diagonal matrices

The Diagonal function in the LinearAlgebra package can also create a diagonal matrix from the diagonal elements of a (possibly rectangular) matrix.

One must again be careful with the difference between a 1D vector and a 2D array that happens to have one dimension equal to 1, as follows.