# Diagonal Matrices

A diagonal matrix is a matrix whose only nonzero elements lie on a diagonal. Diagonal matrices are implemented by the DiagonalMatrix<T> class.

## Constructing diagonal matrices

Diagonal matrices are created using the CreateDiagonal method of the Matrix class. There are four overloads.

The first overload takes the size of the matrix as its only argument. It constructs a square matrix with the specified number of rows and columns. All elements are initially set to zero. The element type must be specified as the generic type argument. For example, for a 5x5 diagonal matrix, we have:

C#
``var t1 = Matrix.CreateDiagonal<double>(5);``

You can also specify both the number of rows and columns. The following creates a 5x7 matrix:

C#
``var t2 = Matrix.CreateDiagonal<double>(5, 7);``

The two remaining overloads let you initialize the elements of the matrix. The first one takes a Vector<T> as its only argument. It creates a square matrix with the vector on its diagonal. The following creates a 3x3 matrix with the numbers 1, 2, and 3 on the diagonal:

C#
``````var elements = Vector.Create(1.0, 2.0, 3.0);
var t3 = Matrix.CreateDiagonal(elements);
// t3 -> [[ 1 0 0 ]
//        [ 0 2 0 ]
//        [ 0 0 3 ]]``````

It is also possible to specify the size of the matrix. In this case, the overload has three arguments. The first two are the number of rows and columns of the matrix. The third argument is the vector on the diagonal.

C#
``````var t4 = Matrix.CreateDiagonal(3, 5, elements);
// t4 -> [[ 1 0 0 0 0 ]
//        [ 0 2 0 0 0 ]
//        [ 0 0 3 0 0 ]]``````

The length of the vector must be the same as the smallest dimension of the matrix, or a DimensionMismatchException is thrown.

## Rows and Columns

The GetRow and GetColumn methods of a DiagonalMatrix<T> return a vector of type BlockVector<T>.