C# Apply Transform Example

← All NMath Code Examples

```using System;

using CenterSpace.NMath.Core;

namespace CenterSpace.NMath.Core.Examples.CSharp
{
/// <summary>
/// A .NET example in C# showing how to use the matrix and vector Apply and Transform
/// methods.
/// </summary>
class ApplyTransformExample
{

static void Main( string[] args )
{
int length = 4;

Console.WriteLine();

// Create a vector containing 0, PI/2, PI, 3PI/2, 2PI
var v = new DoubleVector( length, 0, Math.PI / 2.0 );
Console.WriteLine( "v = {0}", v.ToString() );

// Use the Apply method to create a new vector containing the
// cosines of the elements of v.
DoubleVector cosV = v.Apply( NMathFunctions.CosFunc );

// We should get cosV = [1 0 -1 0]
Console.WriteLine( "cosV = {0}", cosV.ToString() );

// Hmmm. Where there is supposed to zeros there are numbers
// on the order of 10^-17 and 10^-16 - which are zero, within
// machine precision.  Lets use the vector method Transform to
// round these values to what they are supposed to be.
var roundFunction = new Func<double, double>( Math.Round );
cosV.Transform( roundFunction );
Console.WriteLine( "cosV rounded = {0}", cosV.ToString() ); // [1 0 -1 0]

// The apply and transform functions are overloaded to take binary
// function delegates.
var baseValues = new FloatComplexMatrix( 2, 2, 1, 1 );
var exponents = new FloatComplexMatrix( 2, 2, 1, 1 );

// baseValues = | (1,0) (3,0) |
//              | (2,0) (4,0) |
//
// exponents =  | (1,0) (3,0) |
//              | (2,0) (4,0) |
Console.WriteLine( "baseValues = {0}", baseValues.ToString() );
Console.WriteLine( "exponents = {0}", exponents.ToString() );

FloatComplexMatrix powMatrix = baseValues.Apply( NMathFunctions.FloatComplexPowFunc, exponents );

// powerVector = | (1,0)^(1,0) (3,0)^(3,0) | = | (1,0) (27,0) |
//               | (2,0)^(2,0) (4,0)^(4,0) | = | (4,0) (256,0) |
Console.WriteLine( "baseValues^exponents = {0}", powMatrix.ToString() );

FloatComplexVector sums = baseValues.ApplyColumns( NMathFunctions.FloatComplexSumFunc );
Console.WriteLine( "sums of baseValues columns = {0}", sums.ToString() );

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