NMath User's Guide

TOC | Previous | Next | Index

6.5 Arithmetic Operations on Matrices (.NET, C#, CSharp, VB, Visual Basic, F#)

NMath provides overloaded arithmetic operators for matrices with their conventional meanings for those .NET languages that support them, and equivalent named methods for those that do not. Table 6 lists the equivalent operators and methods.

Table 6 – Arithmetic operators


Equivalent Named Method









Unary -






Unary negation, increment, and decrement operators are applied to every element in a matrix. The Negate() method returns a new matrix object; Increment() and Decrement() do not.

All binary operators and equivalent named methods work either with two matrices, or with a matrix and a scalar.

NOTE—Matrices must have the same dimensions to be combined using the element-wise operators. Otherwise, a MismatchedSizeException is thrown. (See Chapter 38.)

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

Code Example – C# matrix

int rows = 3, cols = 3;

var A =
   new DoubleComplexMatrix( rows, cols, new DoubleComplex(1,0) );
var B =
   new DoubleComplexMatrix( rows, cols, new DoubleComplex(0,1) );
var s = new DoubleComplex( 2, 0 );

DoubleComplexMatrix result = A + s*B;

This Visual Basic code uses the equivalent named methods:

Code Example – VB matrix

Dim rows As Integer = 3
Dim cols As Integer = 3

Dim A As _
   New DoubleComplexMatrix(rows, cols, New DoubleComplex(1, 0))
Dim B As _
   New DoubleComplexMatrix(rows, cols, New DoubleComplex(0, 1))
Dim s As New DoubleComplex(2, 0)

Dim result As DoubleComplexMatrix = _
   DoubleComplexMatrix.Add(A, DoubleComplexMatrix.Multiply(s, B))

NMath also provides overloads of the arithmetic named methods that accept three matrix arguments. The third matrix holds the result of applying the appropriate operation to the first two matrices. Because no new memory is allocated, efficiency is increased. This is especially useful for repeated operations, such as within loops. For instance, this code multiplies two matrices and stores the result in a third:

Code Example – C# matrix

int rows = size;
int cols = size;
var A = new DoubleMatrix( rows, cols, 0, 1);
var B = new DoubleMatrix( rows, cols, 1, 1 );
var C = new DoubleMatrix( rows, cols );

FloatMatrix.Multiply( A, B, C );
FloatMatrix.Multiply( A--, B, C );
FloatMatrix.Multiply( B, B, C );
// Still only three matrices allocated

Code Example – VB matrix

Dim Rows As Integer = Size
Dim Cols As Integer = Size
Dim A As New DoubleMatrix(Rows, Cols, 0, 1)
Dim B As New DoubleMatrix(Rows, Cols, 1, 1)
Dim C As New DoubleMatrix(Rows, Cols)

FloatMatrix.Multiply(A, B, C)
FloatMatrix.Multiply(A.Decrement(), B, C)
FloatMatrix.Multiply(B, B, C)
' Still only three matrices allocated

If the three matrices do not have the same dimensions, a MismatchedSizeException is thrown.