Click here to Skip to main content
Licence CPOL
First Posted 29 Sep 2011
Views 4,794
Downloads 519
Bookmarked 13 times

MathLibrary for Matrix and Vector

By | 29 Sep 2011 | Article
It has all the operations of matrix, vector

Introduction

It has the all Matrix operations and vector operators. (e.g.: matrix Multiplication, Inverse, Determinant and vector DotProduct, CrossProduct). This program has separate exceptions to catch wrong inputs. These exceptions are MatrixException, VectorException and these classes extended from exception. This library is supporting for double, float, int values. But if a method accepts 2 matrices or 2 vectors, both should be same type. (E.g.: MathLibrary.Matrix.Multiply(double[,] matrix1,double[,] matrix2) accepts 2 matrices as input, both should be double, float or int. If one is double and the other one is float or int, it will not work.)

The functions get arrays as input (2D arrays for matrix, single dimension arrays for vector (It is supporting maximum 3 element vectors)).

Matrix Operations

Multiplication

It needs two matrices as input. The first matrix [i,j] and second matrix [n,m]. value of 'j' should be equal to 'n' to do the correct multiplication. Otherwise an exception will be thrown.

Determinant, inverse

These methods needs only one matrix as input. This matrix should be a square matrix (number of rows = number of columns), otherwise an exception will be thrown. Determinant should not be zero, to get an inverse matrix. Multiplication of a matrix with its inverse matrix will give Identity matrix.

Vector Operation

CrossProduct

This library is support only for 3D vector CrossProduct, if you give other vectors as input, the program will throw an exception.

Background

This library is used to the Mathematical Matrix and Vector operations. So the user should have the knowledge of the matrix and vector operation to understand the library. If he doesn't have the knowledge of matrix and vector operation, he can use the attached library in his program. But he needs to put the method inside a try catch method and catch MathLibrary.MatrixException to avoid crashing during the wrong input.

Using the Code

Since this is a library, users can use this DLL in their own program. It means that there is no need to copy paste the methods, they can attach the DLL and then call the methods (see the example below). To do that, build and get the DLL, then add the DLL in your program as reference. It is better to use the methods inside a try catch to avoid crashes when giving wrong input parameters, There is a MatrixException in the MathLibrary, it will catch the wrong input matrices for matrix functions. Then they can use the function as follows:

int lengh = 3;
double[,] mat1 = new double[,]{ { 5, 3, 2 }, { 4, 7, 2 }, { 7, 9, 4 } };

try
{
    double[,] invMat = Matrix.Inverse(mat1);
    double[,] ans = Matrix.Multiply(mat1, invMat);

    for (int i = 0; i < lengh; i++)
    {
        for (int j = 0; j < lengh; j++)
        {
            Console.Write(Math.Round(ans[i, j],3));
            Console.Write("  ");
        }
        Console.WriteLine();
    }
    Console.Read();
}
catch (MathLibrary.MatrixException e)
{
    Console.WriteLine(e.GetErrorMessage());
}

Matrix Determinant

Determinant is implemented using recursive function. The input should be square matrix, otherwise it will give an exception. Determinant is implemented as follows:

double ans = 0;
if (matrix.GetLength(0) == matrix.GetLength(1))
{
    int length = matrix.GetLength(0);
    if (length > 2)
    {
        double[,] tempMat = new double[length - 1, length - 1];
        for (int j = 0; j < length; j++)
        {
            int x = 0, y;
            for (int i1 = 1; i1 < length; i1++)
            {
                y = 0;
                for (int j1 = 0; j1 < length; j1++)
                {
                    if (j1 != j)
                    {
                        tempMat[x, y] = matrix[i1, j1];
                        y++;
                    }
                }
                x++;
            }
            ans += Math.Pow(-1, j) * matrix[0, j] * Determinant(tempMat);
        }
        return ans;
    }
    else if (length == 2)
    {
        ans = matrix[0, 0] * matrix[1, 1] - matrix[0, 1] * matrix[1, 0];
        return ans;
    }
    else if (length == 1)
    {
        return matrix[0, 0];
    }
    else
    {
        return 0;
    }
}

Matrix Inverse

The input matrix should be a square matrix for inverse operation and the determinant of the matrix also should not be zero. Therefore method determinant is used inside the inverse method. Inverse is implemented as follows:

if (matrix.GetLength(0) == matrix.GetLength(1))
{
    int length = matrix.GetLength(0);
    if (length > 1)
    {
        double[,] tempAnsMat = new double[length, length];
        double ans = 0;

        double[,] tempMat = new double[length - 1, length - 1];

        for (int i = 0; i < length; i++)
        {
            for (int j = 0; j < length; j++)
            {
                int x = 0, y;
                for (int i1 = 0; i1 < length; i1++)
                {
                    if (i != i1)
                    {
                        y = 0;
                        for (int j1 = 0; j1 < length; j1++)
                        {
                            if (j1 != j)
                            {
                                tempMat[x, y] = matrix[i1, j1];
                                y++;
                            }
                        }
                        x++;
                    }
                }
                //It is saved as transpose matrix in temporary matrix
                tempAnsMat[j, i] = Math.Pow(-1, i + j) * Determinant(tempMat);
                if (i == 0)
                    ans += matrix[i, j] * tempAnsMat[j, i];
            }
        }
        if (ans != 0)
            return ScalarMultiply(1 / ans, tempAnsMat);
        else
            throw new MatrixException("This matrix Determinant is 0. no inverse matrix");
    }
    else if (length == 1)
        return new double[,] { { 0 } };
    else
        throw new MatrixException("This is a Null matrix");
}

Matrix Multiplication

Multiply() method accepts 2 input matrix and returns a multiplied matrix.

int mRow1 = matrix1.GetLength(0);
int mCol1 = matrix1.GetLength(1);
int mRow2 = matrix2.GetLength(0);
int mCol2 = matrix2.GetLength(1);

double[,] ansMat;

if (mCol1 == mRow2)
{
    ansMat = new double[mRow1, mCol2];
    for (int i = 0; i < mRow1; i++)
    {
        for (int j = 0; j < mCol2; j++)
        {
           for (int k = 0; k < mRow2; k++)
           {
               ansMat[i, j] += matrix1[i, k] * matrix2[k, j];
           }
        }
    }
    return ansMat;
}

Vector Cross Product

CrossProduct() accepts two input vectors and returns a cross producted vector. This program can do it only for 3D vectors, otherwise it will give an VectorException. The implementation of CrossProduct() is as follows:

int length1 = vector1.GetLength(0);
int length2 = vector2.GetLength(0);

if (length1 == length2)
{
    if (length1 == 3)
    {
        double[] ansVec = new double[length1];
        ansVec[0] = vector1[1] * vector2[2] - vector1[2] * vector2[1];
        ansVec[1] = vector1[2] * vector2[0] - vector1[0] * vector2[2];
        ansVec[2] = vector1[0] * vector2[1] - vector1[1] * vector2[0];

        return ansVec;
    }
    else
        throw new VectorException("It is supporting only 3 dimension");
}

Vector DotProduct

DotProduct() accepts 2 input vectors and returns a dot producted vector. This program can do maximum 3D vectors, otherwise it will give an VectorException. The implementation of DotProduct() is as follows:

int length1 = vector1.GetLength(0);
int length2 = vector2.GetLength(0);

if (length1 == length2)
{
    if (length1 < 3)
    {
        if (length1 > 1)
        {
            double ansVal = 0;
            for (int i = 0; i < length1; i++)
            {
                ansVal += vector1[i] * vector2[i];
            }
            return ansVal;
        }
        else
            throw new VectorException("These vectors are Null or Numbers");
    }
    else
        throw new VectorException("It is supporting upto 3 dimension");
}

Points of Interest

This Library has its own Exception to throw exception during wrong inputs for Matrix, Vector operations. Therefore, the user can use that Exception and get the reason for the Exception from the method getErrorMessage().

History

  • 29th September, 2011: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

N.Banukobhan



Sri Lanka Sri Lanka

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 3 Pinmemberehsan23738:31 4 Oct '11  
QuestionChoice of the algorithm PinmemberYvesDaoust4:41 4 Oct '11  
AnswerRe: Choice of the algorithm PinmemberN.Banukobhan21:37 24 Oct '11  
GeneralRe: Choice of the algorithm PinmemberYvesDaoust22:34 24 Oct '11  
QuestionMath dotNet library PinmemberMike Giordano9:23 3 Oct '11  
AnswerRe: Math dotNet library Pinmemberjonsalmon1:56 5 Oct '11  
GeneralRe: Math dotNet library PinmemberAnsgar Hellwig2:36 5 Oct '11  
GeneralRe: Math dotNet library Pinmemberjonsalmon3:16 5 Oct '11  
GeneralSome tipps PinmemberGünther M. FOIDL11:44 29 Sep '11  
GeneralRe: Some tipps PinmemberMember 775181018:05 29 Sep '11  
GeneralRe: Some tipps PinmemberMR_SAM_PIPER12:53 3 Oct '11  
GeneralRe: Some tipps PinmemberGünther M. FOIDL0:07 4 Oct '11  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120517.1 | Last Updated 29 Sep 2011
Article Copyright 2011 by N.Banukobhan
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid