Click here to Skip to main content
11,632,571 members (82,201 online)
Click here to Skip to main content

MathLibrary for Matrix and Vector

, 29 Sep 2011 CPOL 13K 1.2K 17
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

N.Banukobhan
Sri Lanka Sri Lanka
No Biography provided

You may also be interested in...

Comments and Discussions

 
Questionaverage Pin
CIDev26-Sep-13 7:18
professionalCIDev26-Sep-13 7:18 
GeneralMy vote of 3 Pin
ehsan23734-Oct-11 8:31
memberehsan23734-Oct-11 8:31 
QuestionChoice of the algorithm Pin
YvesDaoust4-Oct-11 4:41
memberYvesDaoust4-Oct-11 4:41 
AnswerRe: Choice of the algorithm Pin
N.Banukobhan24-Oct-11 21:37
memberN.Banukobhan24-Oct-11 21:37 
GeneralRe: Choice of the algorithm Pin
YvesDaoust24-Oct-11 22:34
memberYvesDaoust24-Oct-11 22:34 
QuestionMath dotNet library Pin
Mike Giordano3-Oct-11 9:23
memberMike Giordano3-Oct-11 9:23 
AnswerRe: Math dotNet library Pin
jonsalmon5-Oct-11 1:56
memberjonsalmon5-Oct-11 1:56 
GeneralRe: Math dotNet library Pin
Ansgar Hellwig5-Oct-11 2:36
memberAnsgar Hellwig5-Oct-11 2:36 
GeneralRe: Math dotNet library Pin
jonsalmon5-Oct-11 3:16
memberjonsalmon5-Oct-11 3:16 
GeneralSome tipps Pin
Günther M. FOIDL29-Sep-11 11:44
memberGünther M. FOIDL29-Sep-11 11:44 
GeneralRe: Some tipps Pin
Member 775181029-Sep-11 18:05
memberMember 775181029-Sep-11 18:05 
GeneralRe: Some tipps Pin
MR_SAM_PIPER3-Oct-11 12:53
memberMR_SAM_PIPER3-Oct-11 12:53 
GeneralRe: Some tipps Pin
Günther M. FOIDL4-Oct-11 0:07
memberGünther M. FOIDL4-Oct-11 0:07 

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.

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