C# Sparse Vector Example

← All NMath Code Examples

 

using System;

using CenterSpace.NMath.Core;


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

    static void Main( string[] args )
    {
      // Construct a sparse vector from a set of nonzero values and the indices for
      // those values. Indices are 0-based.
      var indices = new IndexArray( 1, 12, 2, 15 );
      double[] values = { 2, 3.14, -4, -.6 };
      var v = new DoubleSparseVector( values, indices );

      Console.WriteLine();

      Console.WriteLine( "v = " + v );

      // Dot product with a dense vector.
      var w = new DoubleVector( 66, 1.2 );
      double dot = MatrixFunctions.Dot( w, v );
      Console.WriteLine( "w dot v = " + dot );

      // Some miscellaneous sparse vector functions...
      double sumOfAbsValues = MatrixFunctions.AbsSum( v );
      Console.WriteLine( "Sum of the absolute values in v = " + sumOfAbsValues );
      double maxAbsValueIndex = MatrixFunctions.MaxAbsIndex( v );
      Console.WriteLine( "Index of the largest absolute values in v = " + maxAbsValueIndex );


      // Construct a sparse vector from a dense vector by specifying the indices in the 
      // dense vector to "gather" into the sparse vector.
      var t = new DoubleVector( 200, 1, 1.3 );
      DoubleSparseVector tSparse = MatrixFunctions.Gather( t, indices.Length, indices );
      Console.WriteLine( "tSparse = " + tSparse );

      // Construct a dense vector from a sparse vector by specifying the length of the
      // dense vector and "scattering" the nonzero values from the sparse vector into the 
      // dense vector.
      DoubleVector denseT = MatrixFunctions.Scatter( tSparse, 20 );
      Console.WriteLine( "denseT = " + denseT );

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

← All NMath Code Examples
Top