65.9K
CodeProject is changing. Read more.
Home

RtwMatrix Class

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.32/5 (8 votes)

Oct 11, 2004

CPOL

2 min read

viewsIcon

62966

downloadIcon

1335

A general purpose matrix class.

Sample Image - rtwmatrix.jpg

Introduction

I thought of writing this matrix class because I needed a matrix class with more features and that can be used in a different syntax than the System.Drawing.Drawing2D.Matrix provided by the .NET class libraries.

Description

Unlike the System.Drawing.Drawing2D.Matrix which only has a limited usage, this class is a general purpose class that can be used in any matrix manipulation purposes. Most of the code in the class is self explanatory, so I'll jump straight to the properties and methods exposed by the class.

Properties

  • Rows (get) - Number of rows in the matrix.
  • Columns (get) - Number of columns in the matrix.

Methods

  • Determinant() - Returns the determinant of the matrix.
  • Adjoint() - Returns the adjoint matrix.
  • Minor(int row, int column) - Returns the minor with respect to the elements represented by the row and the column.
  • IsIdentity() - Returns true if the matrix is an identity matrix otherwise false.
  • IsInvertible() - Returns true if the matrix is invertible, otherwise false.
  • Reset() - Makes the matrix an identity matrix.
  • Clear() - Makes the matrix a zero matrix.

Operators

  • == Equals
  • != Not equal
  • * Multiply (3 overloads)
  • + Addition
  • - Subtract
  • / Division
  • ^ Power of
  • ~ Transpose
  • ! Inverse

An indexer is also implemented so the elements of a matrix instance can be accessed as a multidimensional array. This provides a more natural way of accessing elements than implementing separate GetElement() and SetElement() methods.

private float[,] m_matrix;

public float this[int row, int column]
{
    get
    {
        return m_matrix[row,column];
    }

    set
    {
        m_matrix[row,column] = value;
    }
}

Using the class

The way to create an instance of the RtwMatrix class is shown below:

int rows = 3;    //specify the number of rows
int cols = 3;    //specify the number of columns

RtwMatrix mtx = new RtwMatrix(rows, cols);

//the matrix is a zero matrix by default
//add code to initialize the elements

An example of using a RtwMatrix instance follows:

RtwMatrix mtx1, mtx2, mtxResult;

//code to initialize mtx1 and mtx2 goes here

try
{
    mtxResult = mtx1 * mtx2;        //multiply and store the result

    Console.WriteLine(!mtxResult);  //print the inverse to screen
}
catch(RtwMatrixException ex)
{
    Console.WriteLine(ex.Message);
}

More code can be found in the demo project on using the RtwMatrix class. I hope this class can be found useful. All comments and bug reports are welcome.