# C# Vector Arithmetic Example

← All NMath Code Examples

using System;

using CenterSpace.NMath.Core;

namespace CenterSpace.NMath.Core.Examples.CSharp
{
/// <summary>
/// A .NET example in C# showing the element-wise operators overloaded for
/// vector/vector and vector/scalar operations.
///
/// These are the Arithmetic operators +,-,*,/ are overloaded
/// for vector/vector and vector/scalar operations. These operators
/// have their usual meanings. For example, if u, v, and w are
/// vectors, s is a scalar and op is one of +,-,*,/, then
///
///   w = u op v
///
/// produces a vector w such that
///
///   w[i] = u[i] op v[i]
///
/// and
///
///   w = s op v
///
/// produces a vector w such that
///
///   w[i] = s op v[i].
/// </summary>
class VectorArithmeticExample
{
static void Main( string[] args )
{
int length = 5;

Console.WriteLine();

// Create two vectors v1 and v2. v1 alternates values 1, 0, 1,...
// and v2 alternates values 0, 1, 0,...
var v1 = new FloatVector( length );
var v2 = new FloatVector( length );
var everyOther = new Range( 0, Position.End, 2 );
v1.Set( everyOther, 1 );
everyOther.Set( 1, Position.End, 2 );
v2.Set( everyOther, 1 );
Console.WriteLine( "v1 = {0}", v1.ToString() ); // v1 = [1 0 1 0 1]
Console.WriteLine( "v2 = {0}", v2.ToString() ); // v2 = [0 1 0 1 0]

// Summing v1 and v2 will yield a vector of all 1's.
FloatVector sum = v1 + v2;
Console.WriteLine( "v1 + v2 = {0}", sum.ToString() ); // v1 + v2 = [1 1 1 1 1]

// Vector scalar operators are also provided.
float a = 2;
FloatVector asum = v1 + a * v2;
Console.WriteLine( "v1 + a*v2 = {0}", asum.ToString() ); // v1 + a*v2 = [1 2 1 2 1]

// If we increase the length of v1 and try to multiply with v2, we
// will get a MismatchedSizeException. Vectors must have the same
// length to be combined using the element-wise operators.
v1.Resize( length + 1 );
FloatVector product;
try
{
product = v1 * v2;
}
catch ( MismatchedSizeException e )
{
Console.WriteLine( "Oops - " + e.Message );
}

// Increment and decrement operators have been overloaded too.
Console.WriteLine( "v2 = {0}", v2.ToString() );
v2++;
Console.WriteLine( "v2++ = {0}", v2.ToString() );

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