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. Additional factory methods copy or wrap existing diagonal values.
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:
var t1 = Matrix.CreateDiagonal<double>(5);You can also specify both the number of rows and columns. The following creates a 5x7 matrix:
var t2 = Matrix.CreateDiagonal<double>(5, 7);To initialize the elements of the matrix from a Vector<T>, use WrapDiagonal or CopyFromDiagonal. WrapDiagonal shares storage with the vector. CopyFromDiagonal creates independent storage. The following creates a 3x3 matrix with the numbers 1, 2, and 3 on the diagonal:
var elements = Vector.Create(1.0, 2.0, 3.0);
var t3 = Matrix.WrapDiagonal(elements);
// t3 -> [[ 1 0 0 ]
// [ 0 2 0 ]
// [ 0 0 3 ]]It is also possible to specify the size of the matrix when wrapping existing diagonal values. In this case, the first argument is the vector on the diagonal, followed by the number of rows and columns of the matrix.
var t4 = Matrix.WrapDiagonal(elements, 3, 5);
// 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. Legacy CreateDiagonal overloads that take a vector may still appear in older code, but new code should use WrapDiagonal or CopyFromDiagonal to make storage sharing explicit.
Rows and Columns
The GetRow and GetColumn methods of a DiagonalMatrix<T> return a vector of type BlockVector<T>.