# NMath User's Guide

5.5 Arithmetic Operations on Vectors (.NET, C#, CSharp, VB, Visual Basic, F#)

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 5 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 53.)

For example, this C# code uses the overloaded operators:

Code Example – C# vector

```var v = new FloatVector(5,0,1);  // [0,1,2,3,4]
```
```var u = new FloatVector(5,1,1);  // [1,2,3,4,5]
```
```float scalar = 2;

```

```FloatVector w = v + scalar*u;
```

This Visual Basic code uses the equivalent named methods:

Code Example – VB vector

```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:

Code Example – C# vector

```var v = new DoubleVector( "[ 0 1 2 3 4 ]" );
```
```var u = new DoubleVector( 5, 1 );
```
```var 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
```

Code Example – VB vector

```Dim V As New DoubleVector("[ 0 1 2 3 4 ]")
```
```Dim U As New DoubleVector(5, 1)
```
```Dim W As New DoubleVector(U.Length)

```

```DoubleVector.Add(V, U, W)
```
```DoubleVector.Add(V, U.Increment(), 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.

Note that the third vector argument can also be the same as one of the first two arguments, in which case it is overwritten with the result:

Code Example – C# vector

```DoubleVector.Subtract( u, v, v );
```

Code Example – VB vector

```DoubleVector.Subtract(U, V, V)
```

Top

Top