multiply matrices in csharp

Here's a code snippet that demonstrates how to multiply two matrices using C# and arrays:

main.cs
public static double[,] MatrixMultiplication(double[,] matrix1, double[,] matrix2)
{
    int rows1 = matrix1.GetLength(0);
    int cols1 = matrix1.GetLength(1);
    int rows2 = matrix2.GetLength(0);
    int cols2 = matrix2.GetLength(1);

    if (cols1 != rows2)
    {
        throw new Exception("Matrices cannot be multiplied.");
    }

    double[,] result = new double[rows1, cols2];

    for (int i = 0; i < rows1; i++)
    {
        for (int j = 0; j < cols2; j++)
        {
            double sum = 0;

            for (int k = 0; k < cols1; k++)
            {
                sum += matrix1[i, k] * matrix2[k, j];
            }

            result[i, j] = sum;
        }
    }

    return result;
}
706 chars
32 lines

To use this function, simply create two double arrays with the same number of columns in the first and rows in the second, then call the function:

main.cs
double[,] matrix1 = { { 1, 2 }, { 3, 4 } };
double[,] matrix2 = { { 5, 6 }, { 7, 8 } };
double[,] result = MatrixMultiplication(matrix1, matrix2);
147 chars
4 lines

The resulting result array will contain the multiplied matrix.

gistlibby LogSnag