Matrices are a very useful thing in computer programming – especially in 3D graphics programming. Out of all the mathematics I learned at University, matrices are the one thing that keep rearing their head over and over. mybloggingplanet.com

I am not going to go into major detail over what a matrix is – wikipedia can tell you that much better than I can – so will focus mainly on how to implement one in C#.

Essentially, a matrix is a 2-dimensional array of numbers, often representing a set of equations. The number of columns and rows is flexible.

Using the Matrix class below, the constructor can either take an x and y value or an array to determine how big to make the internal array for the matrix.

The Zero() function sets all entries in the matrix to zero by looping through the entire array.

The SetIdentity() function makes the matrix an identity matrix, which means that all the values are 0, except for the values along the diagonal from top left to bottom right being set to 1.

The Transpose function transforms the columns of the matrix into the rows, and vice versa.

The Scale function multiplies each value in the matrix by a scaling factor.

The determinant of an array is found by adding all the products of the entries of each diagonal sloping in a right direction, and subtracting the products of the entries of each diagonal sloping in a opposite direction. This is done with the Determinant function

The Trace function returns the sum of the main diagonal of the matrix.

The matrix class has also got a few overloaded operators, to make handling matrices easier.

The + operator is overloaded so that when passed two matrices, each value in the one matrix is added to the equivalent value in the second matrix. Both matrices need to be the same size for this to work.

A second overload for the + operator takes a scalar value and adds it to the matrix, which just adds that value to each value in the matrix.

The - operator performs identically to the + operator, except that it subtracts instead of adds the matrices.

The * operator multiplies the two matrices together, which is a little more involved than addition.

namespace MathLib
{
    public class Matrix
    {
        public double[,] val;
        public int Cols;
        public int Rows;

        public Matrix(int X, int Y)
        {
            Cols = X;
            Rows = Y;
            val = new double[Rows, Cols];
            Zero();
        }

        public Matrix(double[,] array)
        {
            val = array;
            Cols = val.GetLength(1);
            Rows = val.GetLength(0);
        }

        public void Zero()
        {
            for (int i = 0; i < Rows; i++)
            {
                for (int j = 0; j < Cols; j++)
                {
                    val[i, j] = 0;
                }
            }
        }
        public void SetIdentity()
        {
            for (int i = 0; i < Rows; i++)
            {
                for (int j = 0; j < Cols; j++)
                {
                    if (i == j)
                    {
                        val[i, j] = 1;
                    }
                    else
                    {
                        val[i, j] = 0;
                    }
                }
            }
        }
        public Matrix Transpose()
        {
            double[,] values = new double[Cols, Rows];
            for (int i = 0; i < Rows; i++)
            {
                for (int j = 0; j < Cols; j++)
                {
                    values[j, i] = val[i, j];
                }
            }
            return new Matrix(values);
        }

        public Matrix Scale(double factor)
        {
            double[,] values = new double[Rows, Cols];
            for (int i = 0; i < Rows; i++)
            {
                for (int j = 0; j < Cols; j++)
                {
                    values[i, j] = factor * val[i, j];
                }
            }
            return new Matrix(values);
        }

        public double Determinant()
        {
            double det = 0;
            int colIndex = 0;
            double dval = 1;
            int k;
            for (int i = 0; i < Cols; i++)
            {
                k = 0;
                dval = 1;
                for (int j = 0; j < Cols; j++)
                {
                    colIndex = (i + j) % 3;
                    dval *= val[colIndex, k];
                    k++;
                }
                det += dval;
            }
            for (int i = 0; i < Cols; i++)
            {
                k = 0;
                dval = 1;
                for (int j = Cols-1; j >= 0; j--)
                {
                    colIndex = (i + j) % 3;
                    val *= dval[colIndex, k];
                    k++;
                }
                det -= dval;
            }

            return det;
        }
        public double Trace()
        {
            if (Rows != Cols)
            {
                return 0;
            }
            double trace = 0;
            for (int i = 0; i < Rows; i++)
            {

               trace += val[i, i];
            }
            return trace;            
        }

        public override string ToString()
        {
            string str = "";
            for (int i = 0; i < Rows; i++)
            {
                for (int j = 0; j < Cols; j++)
                {
                    str += val[i, j].ToString() + ",";
                }
                str += Environment.NewLine;
            }
            return str;
        }

        public static Matrix operator +(Matrix left, Matrix right)
        {
            if ((left.Cols != right.Cols) || (left.Rows != right.Rows))
            {
                return left;
            }
            double[,] values = new double[left.Rows, left.Cols];

            for (int i = 0; i < left.Rows; i++)
            {
                for (int j = 0; j < left.Cols; j++)
                {
                    values[i,j] = left.val[i,j] + right.val[i,j];
                }
            }
            return (new Matrix(values));
        }

        public static Matrix operator +(double left, Matrix right)
        {
            double[,] values = new double[right.Rows, right.Cols];

            for (int i = 0; i < right.Rows; i++)
            {
                for (int j = 0; j < right.Cols; j++)
                {
                    values[i, j] = left + right.val[i, j];
                }
            }
            return (new Matrix(values));
        }

        public static Matrix operator -(Matrix left, Matrix right)
        {
            if ((left.Cols != right.Cols) || (left.Rows != right.Rows))
            {
                return left;
            }
            double[,] values = new double[left.Cols, left.Rows];

            for (int i = 0; i < left.Rows; i++)
            {
                for (int j = 0; j < left.Cols; j++)
                {
                    values[i, j] = left.val[i, j] - right.val[i, j];
                }
            }
            return (new Matrix(values));
        }

        public static Matrix operator *(Matrix left, Matrix right)
        {
            double[,] values = new double[left.Rows, right.Cols];

            for (int h = 0; h < left.Rows; h++)
            {
                for (int i = 0; i < right.Cols; i++)
                {
                    for (int j = 0; j < left.Cols; j++)
                    {
                            values[h, i] += left.val[h, j] * right.val[j, i];
                    }
                }
            }
            return (new Matrix(values));
        }

    }
}

Share