NMath provides overloaded arithmetic operators for vectors with their conventional meanings for those .NET languages that support them, and equivalent named methods for those that do not. Table 3 lists the equivalent operators and methods.
| Operator |
Equivalent Named Method |
|---|---|
| + |
Add() |
| - |
Subtract() |
| * |
Multiply() |
| / |
Divide() |
| Unary - |
Negate() |
| ++ |
Increment() |
| -- |
Decrement() |
Unary negation, increment, and decrement operators are applied to every element in a vector. The Negate() method returns a new vector object; Increment() and Decrement() do not.
All binary operators and equivalent named methods work either with two vectors, or with a vector and a scalar.
NOTE- Vectors must have the same length to be combined using the element-wise operators. Otherwise, a MismatchedSizeException is thrown. (See Chapter 32.)
For example, this C# code uses the overloaded operators:
FloatVector v = new FloatVector(5,0,1); // [0,1,2,3,4] FloatVector u = new FloatVector(5,1,1); // [1,2,3,4,5] float scalar = 2; FloatVector w = v + scalar*u;
This Visual Basic.NET code uses the equivalent named methods:
Dim v As New FloatVector(5,0,1) Dim u As New FloatVector(5,1,1) Dim scalar As Single = 2 Dim w As FloatVector = FloatVector.Add(v, FloatVector.Multiply(scalar, u))
NMath also provides overloads of the arithmetic named methods that accept three vector arguments. The third vector holds the result of applying the appropriate operation to the first two vectors. Because no new memory is allocated, efficiency is increased. This is especially useful for repeated operations, such as within loops. For instance, this code adds two vectors and stores the result in a third:
DoubleVector v = new DoubleVector( "[ 0 1 2 3 4 ]" ); DoubleVector u = new DoubleVector( 5, 1 ); DoubleVector w = new DoubleVector( u.Length ); DoubleVector.Add( v, u, w ); DoubleVector.Add( v, u++, w ); DoubleVector.Add( v, v, w ); // Still only three vectors allocated
If the three vectors are not all of the same length, a MismatchedSizeException is thrown.
TOC | Previous | Next | Index