This project has moved. For the latest updates, please go here.

How to Create Matrix using Vector as the Diagonal

Nov 19, 2012 at 4:17 AM

Is there a Math.NET function (or does anyone have C# code) to diagonal-ize a vector into a matrix - where the vector given becomes the diagonal and all other cells are set to 0?

I'm new to Math.NET and it looks like Matrix.Diagonal *outputs* the diagonal of a matrix as a vector ... but I need to *input* the vector as diagonal to create the matrix.

Any help is appreciated!

Nov 19, 2012 at 6:21 AM

You cannot directly create a diagonal matrix from a vector, but you can create an empty matrix of the right size and then use matrix.SetDiagonal(vector).


Nov 19, 2012 at 6:34 AM

Thanks for the quick reply, Christoph!

Nov 19, 2012 at 6:49 AM

Btw, I forgot, we actually do have a special sparse diagonal matrix type, which of course then does allow direct creation:

new DiagonalMatrix(rows, columns, diagonalVector)


Nov 19, 2012 at 6:50 AM
Edited Nov 19, 2012 at 7:17 AM

Great ... I'll try that!


Actually, first option sets up fine with no errors: 

                // option 1: per Christoph at Math.Net discussion group

                SparseMatrix X = new SparseMatrix(m,m,0);


 P = B * X;

Using your second suggestion, I got syntax error on the first statement which tells me that DiagonalMatrix expects int, int, double[] and the method has some invalid arguments:

m is an int, xvector is defined as SparseVector, P and B are both defined as SparseMatrix

                // option 2: per Christoph at Math.Net discussion group               

          SparseMatrix X = new DiagonalMatrix(m, m, xvector); 

              P = B * X;

Any ideas ?