Search code examples
c#numericmath.netmathnet-numerics

c# Mathnet Numerics -- get index of non-zero sparse matrix elements


I want to create a custom optimized matrix operation (a smart kronecker product based on what I know about the sparse matrices i'm using) using MathNet.numerics for csharp.

Is there an accessor to get the non-zero elements of a sparse matrix? (or indexes? Or iterator thereof? or CSR representation?)


Solution

  • You can use IndexedEnumerator to access only the non-zero elements in your matrix. Method signature is:

    public override IEnumerable<Tuple<int, int, double>> IndexedEnumerator()
    

    For example, the following code:

    var mtx = new SparseMatrix(new DiagonalMatrix(3, 3, new[] {1.0, 1, 1}));
    Console.WriteLine(mtx.NonZerosCount);
    
    foreach (var tuple in mtx.IndexedEnumerator())
    {
        Console.WriteLine("({0},{1}) = {2}", tuple.Item1, tuple.Item2, tuple.Item3);
    }
    

    will yield the following output:

    3
    (0,0) = 1
    (1,1) = 1
    (2,2) = 1