Question

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?)

Was it helpful?

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

OTHER TIPS

Since v2.2.1 you can also access the raw CSR representation directly:

var m = new SparseMatrix(1000,1000);
var csr = (SparseCompressedRowMatrixStorage<double>) m.Storage;

Beware that currently our CSR does not store the non-zero ValueCount in the last field of the row-pointer array, although we'll likely change that in near future (to become fully compliant and also for code simplifications)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top