# NMath User's Guide

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

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:

Code Example – C# matrix

```var A = new DoubleMatrix( 5, 5, 0, Math.Pi/4 );
```
```var MyFuncDelegate = new Func<double, double>( MyFunc );
```
```DoubleMatrix B = A.Apply( MyFuncDelegate );
```

Code Example – VB matrix

```Dim A As New DoubleMatrix(5, 5, 0.0, Math.PI / 4.0)
```
```Dim MyFuncDelegate As New Func(Of Double, Double)(MyFunc)
```
```Dim B As DoubleMatrix = A.Apply(MyFuncDelegate)
```

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:

Code Example – C# matrix

```var A = new FloatMatrix( 5, 5, 0, Math.Pi/4 );
```
```var MyFuncDelegate = new Func<FloatVector, float>( MyFunc );
```
```FloatVector v = A.ApplyColumns( MyFuncDelegate );
```

Code Example – VB matrix

```Dim A As New FloatMatrix(5, 5, 0.0F, Math.PI / 4.0F)
```
```Dim MyFuncDelegate As New Func(Of FloatVector, Single)(MyFunc)
```
```Dim V As FloatVector = 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:

Code Example – C# matrix

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

Code Example – VB matrix

```Dim V As FloatVector = A.Transpose().ApplyColumns(MyFuncDelegate)
```
```A.Transpose()   ' return A to original view
```

Top

Top