NMath User's Guide

TOC | Previous | Next | Index

38.11 Logical Functions (.NET, C#, CSharp, VB, Visual Basic, F#)

The static If() method on class StatsFunctions creates an array of boolean values determined by applying a given logical function to the elements in a data set.

For example, suppose OnInterval01() is a method that returns true if a given numeric value is between 0 and 1:

Code Example – C#

public bool OnInterval01( double x )
{
  return ( ( x >= 0 ) && ( x <= 1 ) );
}

Code Example – VB

Public Function OnInterval01(X As Double) As Boolean
  Return ((X >= 0) & (X <= 1))
End Function

This code creates an array of boolean values by applying the criterion to a data set:

Code Example – C#

bool[] bArray = StatsFunctions.If( data, new 
  new Func<double, bool>( OnInterval01 ) );

Code Example – VB

Dim BArray() As Boolean = StatsFunctions.If(MyData,
  New Func(Of Double, Boolean)(AddressOf OnInterval01))

As described in Section 37.7, the resultant boolean array could be used to create a Subset containing the indices of all true elements in the array. The subset could then be used to create a sub-frame from a DataFrame containing the rows or columns than meet the criterion.

An overload of If() creates a new data set by applying a logical function to the elements of another data set. Elements in the original data set that return true are set to a given true value in the new data set; elements that return false are not changed.

For instance, suppose GreaterThan100() is a method that returns true if a given numeric value is greater than 100. This code creates a new data in which all values in DoubleVector data that are greater than 100 are set to NaN:

Code Example – C#

DoubleVector data2 = StatsFunctions.If( data,
  new Func<double, bool>( GreaterThan100 ),   
  Double.NaN );

Code Example – VB

Dim MyData2 As DoubleVector = StatsFunctions.If(MyData,
  New Func(Of Double, Boolean)(AddressOf GreaterThan100), 
  Double.NaN)

You can also supply a false value, in which case elements in the original data set that return false are set to that value.

Static CountIf() and SumIf() methods are also provided on class StatsFunctions. See Section 38.3 for more information.


Top

Top