NMath User's Guide

TOC | Previous | Next | Index

6.2 Creating Matrices (.NET, C#, CSharp, VB, Visual Basic, F#)

This section describes how to create instances of the matrix classes.

Creating Matrices from Numeric Values

You can construct matrix objects from numeric values in a variety of ways. All such constructors create a new view of a new data block.

The simplest constructor creates a matrix of the specified dimensions, with all values initialized to zero. For example, this code creates a 4x5 matrix of floating point values:

Code Example – C# matrix

var v = new FloatMatrix( 4, 5 );

Code Example – VB matrix

Dim V As New FloatMatrix(4, 5)

Another constructor enables you to set the initial value of all elements in the matrix. This creates a 3x3 matrix of FloatComplex instances with all values initialized to 1.0 - 3.0i:

Code Example – C# matrix

var c = new FloatComplex( 1.0, -3.0 );
var A = new FloatComplexMatrix( 3, 3, c );

Code Example – VB matrix

Dim C As New FloatComplex(1.0F, -3.0F)
Dim A As New FloatComplexMatrix(3, 3, c)

Similarly, the matrix classes provide a constructor that lets you specify the dimensions of the matrix, the value of the first element, and an amount to increment each successive element. That is:

Code Example – C# matrix

A[i,j] = initialValue + (i+j) * increment

Code Example – VB matrix

A(I, J) = InitialValue + (I + J) * Increment

For instance:

Code Example – C# matrix

var A = new DoubleMatrix( 5, 5, 0, 1 );



//     | 0 5 10 15 20 |
//     | 1 6 11 16 21 |
// A = | 2 7 12 17 22 |
//     | 3 8 13 18 23 |
//     | 4 9 14 19 24 |

Code Example – VB matrix

Dim A As New DoubleMatrix(5, 5, 0, 1)



'     | 0 5 10 15 20 |
'     | 1 6 11 16 21 |
' A = | 2 7 12 17 22 |
'     | 3 8 13 18 23 |
'     | 4 9 14 19 24 |

You can easily create a matrix from a 2-dimensional array of values. For example:

Code Example – C# matrix

float[,] data = new float[10,17];
for ( i = 0; i < 10; ++i )
{
  for ( j = 0; j < 17; ++j )
  {
    data[i,j] = 3.1415*i + j;
  }
}
var A = new FloatMatrix( data );

Code Example – VB matrix

Dim Data(10, 17) As Single
For I As Integer = 0 To 9
  For J As Integer = 0 To 16
    Data(I, J) = 3.1415 * I + J
  Next
Next
Dim A As New FloatMatrix(Data)

You can also create a matrix from a 1-dimensional array of values, but in this case you must also specify the dimensions of the matrix, and whether the given array is laid out in row-major or column-major order. NMath provides the StorageType enumeration for indicating the storage scheme. For instance:

Code Example – C# matrix

double[] data = { 0.0, 2.0,  4.0, 1.0,  3.0, 5.0 };
DoubleMatrix A =
   new DoubleMatrix( 3, 2, data, StorageType.ColumnMajor );



//     |  0.0  1.0  |
// A = |  2.0  3.0  |
//     |  4.0  5.0  |

Code Example – VB matrix

Dim Data() As Double = {0.0, 2.0, 4.0, 1.0, 3.0, 5.0}
Dim A As New DoubleMatrix(3, 2, Data, StorageType.ColumnMajor)



'     |  0.0  1.0  |
' A = |  2.0  3.0  |
'     |  4.0  5.0  |

NOTE—Once in a matrix, all data is stored in the underlying data block in column-major order.

You can also tile a matrix by replicating an existing matrix or vector using the NMathFunctions RepMat() methods. For example, this code creates a large matrix B consisting of an m-by-n tiling of copies of A:

Code Example – C# matrix

var A = new DoubleMatrix( 15, 3, -0.4, 0.3 );
int m = 4;
int n = 8;
DoubleMatrix B = NMathFunctions.RepMat( A, m, n );

Code Example – VB matrix

Dim A As New DoubleMatrix(15, 3, -0.4, 0.3)
Dim M As Integer = 4
Dim N As Integer = 8
Dim B As DoubleMatrix = NMathFunctions.RepMat(A, M, N)

Lastly, you can use a random number generator to fill a matrix with random values. See Chapter 9 for more information.

Creating Matrices from Strings

You can also construct matrices from a string representation. The string must contain the number of rows, followed by an optional separator character such as x, followed by the number of columns. The matrix values, separated by white space, are then read in row by row. If the sequence of numbers begins with a left bracket '[', then the numbers are read until a matching right bracket ']' is encountered. If no brackets are used, numbers are read until the end of the string. For example:

Code Example – C# matrix

var A = new DoubleMatrix( "3x3 [1 2 3 4 5 6 7 8 9]" );
var B =
   new FloatComplexMatrix( "2 2 (1,0) (2,1.2) (3.3,0) (4,3.12)" );

Code Example – VB matrix

Dim A As New DoubleMatrix("3x3 [1 2 3 4 5 6 7 8 9]")
Dim B As New FloatComplexMatrix(
  "2 2 (1,0) (2,1.2) (3.3,0) (4,3.12)")

An optional second parameter accepts values from the System.Globalization.NumberStyles enumeration. These styles are used by the Parse() methods of the numeric base types. For instance:

Code Example – C# matrix

using System.Globalization;



string s = " 2 x 2 [ 1.1e+001 2.2e+000 4.4e+002 8.8e+000 ]";
var A = new DoubleMatrix( s, NumberStyles.Number |  
  NumberStyles.AllowExponent );

Code Example – VB matrix

Imports System.Globalization



Dim S As String = " 2 x 2 [ 1.1e+001 2.2e+000 4.4e+002 8.8e+000 ]"
Dim A As New DoubleMatrix(S, NumberStyles.Number Or 
  NumberStyles.AllowExponent)

Finally, you can construct a matrix from a given text reader. Just position the text reader at the start of a valid text representation of a matrix. In this case, the brackets are required, since the text reader reads the stream until a closing bracket is encountered.

For example:

Code Example – C# matrix

var reader = new StreamReader( "data.txt" );

// Read until the start of the matrix

var A = new FloatMatrix( reader );

Code Example – VB matrix

Dim Reader As New StreamReader("data.txt")
' Read until the start of the matrix
Dim A As New FloatMatrix(Reader)

Again, an optional second parameter accept values from the System.Globalization.NumberStyles enumeration.

Instead of using a constructor, you can also create a matrix from a string representation using the static Parse() method. The matrix class provide overloads of the Parse() method that accept a string, a string plus number styles, a text reader, and a text reader plus number styles. Thus:

Code Example – C# matrix

string s = "2x2 [ [1 2 3 4 ]";
DoubleMatrix A = DoubleMatrix.Parse( s );

Code Example – VB matrix

Dim S As String = "2x2 [ [1 2 3 4 ]"
Dim A As DoubleMatrix = DoubleMatrix.Parse(S)

Conversely, the overridden ToString() member function returns a string representation of a matrix of the form:



[number of rows] x [number of columns] [ matrix values row by row] 

A variant of the ToString() method also accepts a standard .NET numeric format string. For instance, the format string "C" indicates currency notion:

Code Example – C# matrix

var A = new FloatMatrix( "2x2 [4.523 4.323 4.555 -9.943]" );
Console.WriteLine(A.ToString("C"));
// prints out "2x2 [ $4.52 $4.32 $4.56 ($9.94) ]" in en-US locale

Code Example – VB matrix

Dim A As New FloatMatrix("2x2 [4.523 4.323 4.555 -9.943]")
Console.WriteLine(A.ToString("C"))
' prints out "2x2 [ $4.52 $4.32 $4.56 ($9.94) ]" in en-US locale  

The Write() member function writes a text representation of a matrix to a given text writer. Again, a numeric format string is an optional second parameter.

Creating Matrices from ADO.NET Objects

You can create a matrix object from an ADO.NET object such as a DataTable, an array of DataRow objects, a DataRowCollection, or a DataView­­. See Chapter 52 for more information.

Implicit Conversion

The implicit conversion operators for the matrix classes are shown in Figure 3. An arrow indicates implicit promotion.

Figure 3 – Implicit conversion for matrices

Copying Matrices

The matrix classes provide three copy methods:

Clone() returns a deep copy of a matrix. Data is copied, so each matrix references different data.

ShallowCopy() returns a shallow copy of a matrix. Data is not copied. Both matrices reference the same data.

DeepenThisCopy() copies the data viewed by a matrix to new data block. This guarantees that there is only one reference to the underlying data, and that this data is in contiguous storage.

For instance:

Code Example – C# matrix

var A = new FloatMatrix( 4, 5, 1.0 );
FloatMatrix B = A.ShallowCopy();



B[0,0] = 0;   // A[0,0] == B[0,0]
B.DeepenThisCopy();
B[0,1] = 0;   // A[0,1] != B[0,1]

Code Example – VB matrix

Dim A As New FloatMatrix(4, 5, 1.0)
Dim B As FloatMatrix = A.ShallowCopy()



B(0, 0) = 0   ' A[0,0] == B[0,0]
B.DeepenThisCopy()
B(0, 1) = 0   ' A[0,1] != B[0,1]

Matrix Views

Another way to create matrices in NMath is to create a new matrix view of data already referenced by another matrix. This is achieved using Slice and Range objects, as described in Section 4.2. Here's an example using a Range object to create a new matrix view of the top left corner of a matrix:

Code Example – C# matrix

var A = new DoubleMatrix( 8, 8 );
var topLeft = new Range( 0, 3 );
DoubleMatrix AtopLeft = A[ topLeft, topLeft ];

Code Example – VB matrix

Dim A As New DoubleMatrix(8, 8)
Dim TopLeft As New Range(0, 3)
Dim ATopLeft As DoubleMatrix = A(TopLeft, TopLeft)

Notice that the matrix indexer is overloaded to accept indexing objects, and return a new view of the indexed data.


Top

Top