matrix

The matrix module provides the template Matrix type as well as exceptions thrown.

License:
Lastest LGPL

Authors:
Pedro Ferreira, silverclaw@users.sourceforge.net

class MatrixException: object.Exception;
This is the base class for all exceptions thrown by the matrix class

class MatrixSizeException: matrix.MatrixException;
This Exception is thrown when an operation is requested and the matrix's size makes such operation impossible

class Matrix(Type);
The Matrix class: instantiate with Matrix!(type).
It can be used has a vector, by declaring it with a single row.

Remarks:
the first element of a Matrix is matrix[0,0] and the last is matrix[m-1,n-1] on a mxn Matrix.
If you instanciate a Matrix with a non-numeric type, certain functions may behave erraticaly, fail to run or even to compile.

Examples:
 auto matrix=new Matrix!(int)(3,3); //create a 3x3 matrix
 auto another=new Matrix!(ulong)(3, 3); //same as above,for a different typy
 auto third=matrix*another; //create a third matrix by multiplying the previous 2
 delete matrix; //deleting a matrix will delete it's contents as well


this(in size_t degree);
this(in size_t rows, in size_t columns);
this(in size_t rows, in size_t columns, in Type fill);
this(in size_t rows, in size_t columns, in Type function() fill);
this(in size_t rows, in size_t columns, in Type delegate() fill);
this(in size_t rows, in size_t columns, in Type[] fill);
this(in size_t rows, in Type[] fill);
this(in Type[][] fill);
Creates a new Matrix of size (rows x columns) or degree degree and fills it using fill.

fill may be one of the following:
 * (none) this will cause the matrix to be initialized with Type's initializer;
 * a constant value (of the same type of the Matrix);
 * a function returning a value of the type of the Matrix, this function is called for every element;
 * an array containing the values of the Matrix;
 * an array containing the values for every row of the Matrix (in this case, the number of columns is the size of the vector);
 * an array of arrays. In this case, no size is specified (rows or columns).

Note:
The validity (non-nullity) of fill is only checked in debug version via "in contract".

See Also:
fill(), dup()

Throws:
MatrixSizeException if requested matrix has size==0

BUGS:
In the case of this(Type fill[][]) it is assumed that the size of the first array is less or equal to the remaining vectors. This is only checked in the debug version. If this assumption is invalid, the program will either end with "Access Violation" (on Windows), "Segmentation Fault" (or SIGSEV on Unix) or behave erraticaly.

void fill(in Type[][] data);
void fill(in Type[] data);
void fill(in Type value);
void fill(in Type function() func);
void fill(in Type delegate() del);
Fills the Matrix with the supplied buffer (data), value or return of the function func. If the buffer is of the size of a row, it is duplicated for every row in the Matrix.

Note:
The validity (non-nulity) of data and of the functions is only checked on the debug version.

Throws:
MatrixSizeException if the contents of the buffer are not conformant with this Matrix's size

See Also:
dup()

template dup(T = Type)
Returns:
a duplicate of this Matrix.

Note:
Instanciate it with a type to cast the Matrix. With Phobos, the elements are cast with std.conv.to!(T)() which may throw convertion errors.

Examples:
 auto matrix=new Matrix!(real)(4, 5, 5.3); //create a 4x5 matrix filled with "5.3"
 auto matrix2=new Matrix!(int)(4, 5, 5); //same as above for int
 assert(matrix.dup!(int)==matrix2); //this will evaluate to "true" (rounding of 5.3==5)
 auto another=matrix2.dup(); //simple duplication. "another" is now typed "Matrix!(int)"


Matrix!(Type) identity(in size_t size);
Returns an identity Matrix (main diagonal=1, others=0)

See Also:
setIdentity

void setIdentity();
Sets this matrix to identity Matrix

string toString();
Converts this Matrix to a string on the format [[value_1x1,...,value_1xn],...,[value_mx1,...,value_mxn]]

Examples:
 auto test=new Matrix!(int)(3, 3, 9); //create a 3x3 matrix filled with 9
 write(test.toString());


Output:
[[9,9,9],[9,9,9],[9,9,9]]

Note:
On Phobos, the function uses the std.conv.to!() function, which may throw convertion errors (to type string).

string toString(in string seperator);
Converts this Matrix to a string using seperator to seperate rows.
toString("; ") would create [row_1; row_2; ...; row_n]

Note:
this function requires review.

Type[] getDiagonal();
Returns:
a copy of the main diagonal of this Matrix.

Matrix!(Type) getTranspose();
Returns:
this Matrix's transposed Matrix. This doesn't change the current Matrix.

void transpose();
Transposes this Matrix.

void swapRow(in size_t row1, in size_t row2);
Swaps two rows

Throws:
ArrayBoundsError.

void swapCol(in size_t col1, in size_t col2);
Swaps two columns

Throws:
ArrayBoundsError.

Type[][] getData();
Returns:
this Matrix's data arrays

Note:
To obtain a copy, use "matrix.getData.dup();"
The data arrays are assumed to be accessible only by the current instance of Matrix, as such, when this instance is deleted, it's data arrays are deleted as well.

template determinant(T = Type)
Returns:
this Matrix's determinant.

Throws:
MatrixSizeException if this matrix has size less than 2 or if this matrix is not square

Note:
The determinant of a Matrix is calculated by:
Summation from i=0 to k of the value at [i,j] multiplied by it's cofactor and by the determinant of the minor matrix, formed by excluding column i and row j. The cofactor is -1 if (i+j) is even and 1 otherwise. The initial j would be 0 and is increased by 1 every new minor matrix.
It may be faster to .reduce() the matrix and multiplying the values on it's main diagonal.
You may instanciate the function with a specific return type. If not, it will default to the type with which the Matrix is instanciated. Note that even though the final determinant may be less than Type.max, it is possible that an overflow occurs during the calculation.
Even if the Matrix is instanciated to an unsigned type, it's determinant may be negative.

Remarks:
If two rows or columns on this matrix are equal, the determinant will be 0. If any row or column is made of zeroes, the determinant will be 0.
A Matrix with determinant 0 is singular (non-invertible).

See Also:
isSingular()

Matrix!(Type) minorMatrix(in size_t row, in size_t col);
Returns:
this Matrix's minor Matrix obtained by excluding row row and column col. The new Matrix's data is copied.

Throws:
MatrixSizeException if the current Matrix is too small or if the requested column or row is not valid.

template trace(T = Type)
Returns:
this Matrix's trace, being the summation of the values on it's main diagonal.

Note:
You may specify a return type for this function. If not, it will default to the type of the instanciated Matrix. Caution is needed for large matrices to prevent overflow.

Throws:
MatrixSizeException if this Matrix is not square.

void reduce();
Matrix getReduced();
Reduces a Matrix to a triangle Matrix (values below the main diagonal set to 0) using the Gaussian Elimination algorithm. The Matrix will then be in row echelon form (not to be confused with "reduced row echelon form"), meaning that all values along the main diagonal are 1.

Note:
The Gaussian Elimination algorithm is known to be unstable for some matrices.

template solve(T = Type)
Solves a system of linear equations defined by this Matrix.

Example:
 auto eqSys=new Matrix!(int)(3, 4);
 eqSys[0]=[2,3,5,3]; //2a+3b+5c=3
 eqSys[1]=[1,-3,0,5]; //1a-3b+0c=5
 eqSys[2]=[2,3,1,9]; //2a+3b+1c=9
 int solution[]=eqSys.solve();
 write(solution); //will print: "[-57 5 9]" -> a=-57, b=5, c=9


Output:
[-57 5 9]

Returns:
a single array of numbers representing the solution of the system. You may specify the resolution of the calculation (type of return). This is useful for bigger equation systems.

See Also:
reduce()

Throws:
MatrixSizeException if this Matrix is not of the form [m,m+1].

Type[] getVector();
Returns a single one-dimention array with a copy of this Matrix's data

template normalize(T = Type)
Divides all values of this matrix by it's determinant. You can specify the precision of the calculation by instanciating the function with a specific type (int, real...). If none is given, the Matrix's type is used.

template invert(T = Type)
Inverts this Matrix. Instanciate this function with a type to determine the resolution of the invertion.

Throws:
MatrixException if the determinant of the current matrix is 0 (matrix is not invertible).
MatrixSizeException if the matrix is not square (the determinant cannot be calculated)

See Also:
getInverse()

template getInverse(T = Type)
Returns:
this Matrix's inverted Matrix instantiated to the same type as this Matrix

Note:
Uses the .invert!(T)() routine.

Throws:
Same as invert()

See Also:
invert(), dup!(T)

template getCharPoly(T = Type)
Returns:
the characteristic polynom of this Matrix on a vector of the type specified. If none is given, the Matrix's type is used.

Note:
The returned vector contains the constant in decreasing degree: [a*t^(degree()), bt^(degree-1), ..., zt^(0)], so the number of factors is equal to the degree of the Matrix.
This method is faster if the Matrix's degree==2 in which case, the result is [1, -trace(), determinant()].

Throws:
MatrixSizeException if this Matrix is not square.

bool isSingular();
Returns:
true if this Matrix is singular (determinant equals 0)

Note:
Singular Matrices cannot be inverted.
The determinant is compared with std.numeric.approxEqual to cover for rounding errors in case of floating point matrices.

Throws:
MatrixSizeException if this Matrix is not square.

size_t degree();
Returns:
The degree of this Matrix or 0 if the Matrix is not square

alias isSquare;
If degree returns 0 (false) the Matrix is not square

size_t order();
Returns:
the order of this Matrix (mxn)

bool isSymmetric();
Returns:
true if this Matrix is symmetric: it's elements are mirrored along the main diagonal.

Throws:
MatrixSizeException if this matrix is not square (non-transposable).

bool isHermitian();
Returns:
True if this Matrix is Hermitian: it's elements mirrored along the main diagonal are each others conjugate.

Throws:
MatrixSizeException if this Matrix is not square.

Note:
Only Matrices instanciated to a complex type can be Hermitian.

bool isToeplitz();
Returns:
True if this Matrix is Toeplitz: the elements on it's diagonal are all equal.

You can specify a value to test against, as soon as DMD allows it.

Throws:
MatrixSizeException if this Matrix is not square.

bool isIdempotent();
Returns:
True if this Matrix is idempotent: it's square is equal to itself: "matrix*matrix==matrix"

Throws:
MatrixSizeException if this Matrix is not square.

Type opIndex(in size_t row, in size_t col);
Returns:
value at Matrix position [row, col].

Throws:
ArrayOutOfBounds if the requested element is not valid.

Type[] opIndex(in size_t row);
Returns:
this Matrix's row row. This allows matrix[x][y] operations to be valid, although for this case, matrix[x,y] should be used for clarity.

Throws:
ArrayOutOfBounds if the requested element is not valid.

See Also:
opIndex() (overload)

void opIndexAssign(in Type value, in size_t row, in size_t col);
Assigns value to Matrix element [row, col].

Throws:
ArrayOutOfBounds if required coordinates are too big.

void opIndexAssign(Type[] vector, in size_t row);
Assigns vector to Matrix position [row].

Note:
the data vector is not duplicated. This method will not modify vector, but subsquent calls to non-const funtions of this matrix may modify it. Deleting vector will invalidate the Matrix's row.

Throws:
ArrayOutOfBounds if the requested element is not valid. MatrixSizeException if the vectors' size is not conformant with this Matrix's n

bool opEquals(in Matrix matrix);
Checks two matrices for equality.

Note:
this function uses std.numeric.approxEqual() to compare floating point numbers

Throws:
MatrixSizeException if matrices have different sizes.

template opDiv(T)
template opDivAssign(T)
Divides all elements of this Matrix by a scalar. You cannot divide a Matrix by a Matrix.

template opMul(T)
template opMulAssign(T)
Multiplies this matrix by multiplier, being it a scalar or another Matrix.

Note:
You can only multiply matrices which inner size is equal (axb and bxc). The resulting Matrix will have outer dimensions (axc). Matrix multiplication is NOT commutative.

Throws:
Matrix size exception if inner matrix sizes are not equal

Matrix!(Type) opAdd(in Matrix adder);
void opAddAssign(in Matrix adder);
Adds two Matrices.

Throws:
MatrixSizeException if Matrices are not of the same size.

Matrix!(Type) opSub(in Matrix subtractor);
void opSubAssign(in Matrix subtractor);
Subtracts two Matrices.

Throws:
MatrixSizeException if Matrices are of unmatching size.

void opNeg();
Negates all values on this Matrix This operation may have unexpected results when the current Matrix is instanciated to an unsigned type or if the type does not have the opNeg function implemented.

template opShl(T)
template opShlAssign(T)
Adds columns to this Matrix (Shift Left Operator).

If you provide a single value, that value is repeated for every row of the new column. If you provide an array, that same array is interpreted as (a) new column(s), depending on it's size. If you provide another Matrix, that Matrix is joined with the current one.

Throws:
MatrixSizeException if the size of the vector passed is not a multiple of the number of rows on this Matrix (this.m()) or the number of rows of the adding Matrix is not the same. Values are converted using std.conv.to!(Type)() which may throw convertion errors.

Note:
all values of the incoming vector/matrix are cast to the type of the current Matrix using std.conv.to!().

BUGS:
if a vector is provided, it is assumed not to be null.

See Also:
dup!(T)()

Matrix opShr(in size_t num);
void opShrAssign(in size_t num);
Removes num columns from this Matrix (Shift Right Operator)

Throws:
MatrixSizeException if you try to remove all columns from this Matrix, or more than those available.

template opCat(T)
template opCatAssign(T)
Adds a value, array or Matrix to the current Matrix as rows. If types differ, they will be converted to the current Matrix's type

Throws:
MatrixSizeException if the size of the vector passed is not multiple of the number of columns on this Matrix (this.n()) or the number of columns of the adding Matrix is not the same.
Values are converted using std.to!() which may throw convertion errors.

bool opIn(in Type value);
Checks if value is inside the Matrix (use: 'Matrix in value')

Examples:
	auto matrix=new Matrix!(int)(2, 2, 3); //creates a 2x2 matrix filled with number '3'
	if (matrix in 3) writeln("matrix has number 3"); //this will evaluate to true
	if (matrix in 0) writeln("matrix has number 0"); //This will evaluate to false


Output:
'matrix has number 3'

int opApply(int delegate(ref Type) func);
int opApplyReverse(int delegate(ref Type) func);
Implements the foreach and foreach_reverse behaviour. Cycles through all values on the Matrix

Examples:
 foreach (ref value; matrix) value=5; //this will set all value of the matrix to 5
 int sum;
 foreach (value; matrix) sum+=value; //obtain the sum of all values on the matrix
 foreach (ref value; matrix) foo(value); //calls "foo" for every value of the function
 foreach_reverse (value; matrix) write(value); //prints all values of the matrix in reverse order


template getType()
Return:
the Type of this Matrix's data.

Examples:
 auto matrix=new Matrix!(int)(4, 4);
 matrix.getType foo; //foo is declared as "int"


size_t m();
Returns:
this Matrix's number of rows

size_t n();
Returns:
this Matrix's number of columns

Type[][] data;
Data arrays for this Matrix


Page generated by Ddoc.