how to multiply matrices in csharp

To multiply matrices in C#, first we need to check if the number of columns in the first matrix is equal to the number of rows in the second matrix. If not, the matrices cannot be multiplied.

If they can be multiplied, we create a new matrix with the number of rows of the first matrix and the number of columns of the second matrix. We then use three nested loops to calculate each element in the new matrix. Here's the code:

main.cs
public static int[,] MultiplyMatrices(int[,] matrix1, int[,] 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 ArgumentException("Matrices cannot be multiplied");
    }

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

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

    return result;
}
641 chars
28 lines

In this code, we first get the number of rows and columns for both matrices. We then check if they can be multiplied by comparing the number of columns in the first matrix with the number of rows in the second matrix.

If the matrices can be multiplied, we create a new matrix with the appropriate dimensions, and then use three nested loops to calculate each element in the new matrix using the formula for matrix multiplication.

Finally, we return the new matrix.

gistlibby LogSnag