← All NMath Code Examples
using System;
using CenterSpace.NMath.Core;
namespace CenterSpace.NMath.Examples.CSharp
{
/// <summary>
/// A .NET example in C# showing how to use the indexing class Range with the vector classes.
/// </summary>
public class VectorRangeExample
{
static void Main( string[] args )
{
int length = 10;
Console.WriteLine();
var u = new DoubleVector( length, 0, 1 );
Console.WriteLine( "u = {0}", u.ToString() ); // u = [0 1 2 3 4 5 6 7 8 9]
// Last five elements of the vector u:
DoubleVector uLast5 = u[new Range( 5, length - 1 )];
Console.WriteLine( "uLast5 = {0}", uLast5.ToString() ); // uLast5 = [5 6 7 8 9]
// Could also get this by specifying all elements from the 6th to the end using
// the End value from the Position enum
uLast5 = u[new Range( 5, Position.End )];
Console.WriteLine( "uLast5 = {0}", uLast5.ToString() ); // uLast5 = [5 6 7 8 9]
// You can use negative strides too. Here is the vector u, reversed.
DoubleVector uRev = u[new Range( length - 1, Position.Start, -1 )];
Console.WriteLine( "uRev = {0}", uRev.ToString() ); // uRev = [9 8 7 6 5 4 3 2 1 0]
// Notice that when you create a new DoubleVector using the Range or Slice class,
// you are creating a different "view" of the vectors data. That is, the
// DoubleVector instance returned by the indexing operator taking a Range object,
// and the DoubleVector instance being indexed share the same data:
uRev[0] = 0;
Console.WriteLine( "uRev = {0}", uRev.ToString() ); // uRev = [0 8 7 6 5 4 3 2 1 0]
Console.WriteLine( "u = {0}", u.ToString() ); // u = [0 1 2 3 4 5 6 7 8 0]
// Finally, we use the DoubleVector method Set(Range) to change the contents of u
// to alternate values 0 and 1
var evenElts = new Range( 0, Position.End, 2 );
var oddElts = new Range( 1, Position.End, 2 );
u.Set( evenElts, 0 );
u.Set( oddElts, 1 );
Console.WriteLine( "u = {0}", u.ToString() ); // u = [0 1 0 1 0 1 0 1 0 1]
Console.WriteLine();
Console.WriteLine( "Press Enter Key" );
Console.Read();
} // Main
}// class
}// namespace
← All NMath Code Examples