← All NMath Code Examples
using System;
using CenterSpace.NMath.Core;
namespace CenterSpace.NMath.Examples.CSharp
{
/// <summary>
/// A .NET example in C# showing the element-wise operators overloaded
/// for matrix-matrix and matrix-scalar operations.
///
/// These arithmetic operators +,-,*,/ are overloaded
/// for matrix/matrix and matrix/scalar operations. These operators
/// have their usual meanings. For example, if A, B, and C are
/// matrices, s is a scalar and op is one of +,-,*,/, then
///
/// C = A op B
///
/// produces a matrix C such that
///
/// C[i,j] = A[i,j] op B[i,j]
///
/// and
///
/// C = s op B
///
/// produces a matrix C such that
///
/// C[i,j] = s op B[i,j].
/// </summary>
class MatrixArithmeticExample
{
static void Main( string[] args )
{
int rows = 3, cols = 3;
Console.WriteLine();
// Create a matrix containing all (1,0)s
var A = new DoubleComplexMatrix( rows, cols, new DoubleComplex( 1, 0 ) );
// Create a matrix containing all (0,1)s
var B = new DoubleComplexMatrix( rows, cols, new DoubleComplex( 0, 1 ) );
Console.WriteLine( "A = {0}", A.ToString() );
Console.WriteLine( "B = {0}", B.ToString() );
// Adding them together will yield a matrix of the same size containing
// all (1,1)s
DoubleComplexMatrix S = A + B;
Console.WriteLine( "A + B = {0}", S.ToString() );
// Vector scalar operators are also provided.
var a = new DoubleComplex( 2, 0 );
// Produces a matrix containing all (1,2)s
DoubleComplexMatrix aSum = A + a * B;
Console.WriteLine( "A + a*B = {0}", aSum.ToString() );
// If we increase the number of rows of A and try to multiply with B, we
// will get a MismatchedSizeException. Matrices must have the same
// dimensions to be combined using the element-wise operators.
A.Resize( rows + 1, cols );
DoubleComplexMatrix P;
try
{
P = A * B;
}
catch ( MismatchedSizeException e )
{
Console.WriteLine( "Oops - " + e.Message );
}
// Put A back the way it was.
A.Resize( rows, cols );
// Increment and decrement operators have been overloaded too
// (for real types only).
DoubleMatrix Are = NMathFunctions.Real( A );
Console.WriteLine( "Are = {0}", Are.ToString() );
Are++;
Console.WriteLine( "Are++ = {0}", Are.ToString() );
Console.WriteLine();
Console.WriteLine( "Press Enter Key" );
Console.Read();
} // Main
}// class
}// namespace
← All NMath Code Examples