C# Sparse Vector Example

[TOC]

using System;

using CenterSpace.NMath.Core;
using CenterSpace.NMath.Matrix;

namespace CenterSpace.NMath.Matrix.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.
      IndexArray indices = new IndexArray(1, 12, 2, 15);
      double[] values = { 2, 3.14, -4, -.6 };
      DoubleSparseVector v = new DoubleSparseVector(values, indices);
      Console.WriteLine("v = " + v);

      // Dot product with a dense vector.
      DoubleVector 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 specifing the indices in the 
      // dense vector to "gather" into the sparse vector.
      DoubleVector 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 specifing 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();
    }
  }
}

[TOC]