C# Sparse Matrix Example

← All NMath Code Examples

 

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.IO;

using CenterSpace.NMath.Core;


namespace CenterSpace.NMath.Examples.CSharp
{
  /// <summary>
  /// A .NET example in C# showing simple sparse matrix functionality.
  /// </summary>
  class SparseMatrixExample
  {

    static void Main( string[] args )
    {
      Thread.CurrentThread.CurrentCulture = new CultureInfo( "en-US", false );

      Console.WriteLine();
      DoubleComplexCsrSparseMatrix A = ReadComplexMtxFile();
      Console.WriteLine( "A is a {0}x{1} complex-valued sparse matrix with {2} nonzero entries.",
        A.Rows, A.Cols, A.Data.NumberNonZero );
      DoubleComplexCsrSparseMatrix AHA = MatrixFunctions.ConjTransposeProduct( A, A );
      Console.WriteLine( "The conjugate transpose product of A with itself has {0} nonzero entries.",
        AHA.Data.NumberNonZero );
      var v = new DoubleComplexVector( A.Cols, 1 );
      DoubleComplexVector Av = MatrixFunctions.Product( A, v );
      Console.WriteLine( "The product of a with a dense vector, v, has length {0}", Av.Length );

      Console.WriteLine();
      Console.WriteLine( "Press Enter Key" );
      Console.Read();
    }

    static DoubleComplexCsrSparseMatrix ReadComplexMtxFile()
    {
      var reader = new StreamReader( new FileStream( "sparseMatData.mtx", FileMode.Open ) );
      string line = reader.ReadLine();
      char[] delimiters = { };
      int lineCount = 0;
      int rows = 0, cols = 0, numberNonzero = 0;
      // Eat comments.
      while ( line.Contains( "%" ) ) line = reader.ReadLine();
      var coordValues = new Dictionary<IntPair, DoubleComplex>();
      for ( ;;)
      {
        if ( line == null ) break;
        if ( lineCount == 0 ) // First non-comment, read rows, columns, and number nonzero
        {
          string[] matrixInfo = line.Split( delimiters, StringSplitOptions.RemoveEmptyEntries );
          if ( matrixInfo.Length != 3 )
          {
            throw new Exception( "Invalid MTX file" );
          }
          rows = Int32.Parse( matrixInfo[0] );
          cols = Int32.Parse( matrixInfo[1] );
          numberNonzero = Int32.Parse( matrixInfo[2] );
        }
        else
        {
          // Line should have 4 entries, a row index, a column index, real and imaginary 
          // parts of the value.
          string[] rowColValue = line.Split( delimiters, StringSplitOptions.RemoveEmptyEntries );
          if ( rowColValue.Length != 4 )
          {
            throw new Exception( "Invalid MTX file" + line );
          }
          int row = Int32.Parse( rowColValue[0] ) - 1; // mtx files use one-based indexing.
          int col = Int32.Parse( rowColValue[1] ) - 1;
          double re = Double.Parse( rowColValue[2] );
          double im = Double.Parse( rowColValue[3] );
          coordValues.Add( new IntPair( row, col ), new DoubleComplex( re, im ) );
        }
        ++lineCount;
        line = reader.ReadLine();
      }

      return new DoubleComplexCsrSparseMatrix( coordValues, cols );
    }
  }
}

← All NMath Code Examples
Top