NMath User's Guide

TOC |  Previous |  Next |  Index

6.8 Generic Functions (.NET, C#, CSharp, Visual Basic, VB.NET)

NMath provides generic functions that apply a given function delegate to every element in a matrix, or to every column in a matrix.

Applying Elementwise Functions

NMath provides convenience methods for applying unary and binary functions to elements of a matrix. Each of these methods takes a function Delegate. The Apply() method returns a new matrix whose contents are the result of applying the given function to each element of the matrix. The Transform() method modifies a matrix object by applying the given function to each of its elements. For example, assuming MyFunc is a function that takes a double and returns a double:

DoubleMatrix A = new DoubleMatrix( 5, 5, 0, Math.Pi/4 );

DoubleUnaryFunction MyFuncDelegate = 
   new DoubleUnaryFunction( MyFunc );
 
DoubleMatrix B = A.Apply( MyFuncDelegate );

NMath provides delegates for many commonly used math functions in the NMathFunctions class.

Applying Columnwise Functions

NMath provides the ApplyColumns() method on the matrix classes for applying a vector function to columns of a matrix. This function takes a function delegate that accepts a vector and returns a single value.

For instance, assuming MyFunc takes a FloatVector and returns a float:

FloatMatrix A = new FloatMatrix( 5, 5, 0, Math.Pi/4 );

FloatVectorFunction MyFuncDelegate =
   new FloatVectorFunction( MyFunc );

FloatVector v = A.ApplyColumns( MyFuncDelegate );

To apply a function to the rows of matrix, just Transpose() the matrix first. Transpose() simply swaps the number of rows and the number of columns, as well as the row strides and column strides. No data is copied, so it's a relatively cheap operation. For instance:

FloatVector v = A.Transpose().ApplyColumns( MyFuncDelegate );
A.Transpose();   // return A to original view

NMath provides delegates for many commonly used math functions in the NMathFunctions class.

TOC |  Previous |  Next |  Index