Assume two matrices are to be multiplied (the generalization to any number is discussed below). If A is an n×m matrix and B is an m×p matrix, the result AB of their multiplication is an n×p matrix defined only if the number of columns m in A is equal to the number of rows m in B.

image

where necessarily the number of columns in A equals the number of rows in B, in this case m, the matrix product AB is denoted without symbol (no multiplication signs or dots) to be the n×p matrix

image

 

Code

 

        public static void Multiply(int[,] matrixA, int[,] matrixB)
        {
            int columnA = matrixA.GetLength(1);
            int columnB = matrixB.GetLength(1);

            int rowA = matrixA.GetLength(0);
            int rowB = matrixB.GetLength(0);


            if (columnA != rowB)
            {
                Console.WriteLine("Matrix cannot be multiplied");
                return;
            }

            Console.WriteLine("matrix A");
            PrintMatrix(matrixA);

            Console.WriteLine("matrix B");
            PrintMatrix(matrixB);

            int k = 0;
            int[,] result = new int[rowA, columnB];
            int sum = 0;

            for (int i = 0; i < rowA; i++)
            {
                for (int j = 0; j < columnB; j++)
                {
                    result[i, j] = 0;
                    sum = 0;
                    for (k = 0; k < columnA; k++)
                        sum = sum + matrixA[i, k] * matrixB[k, j];
                    result[i, j] = sum;
                }
            }
            Console.WriteLine("Result Matrix");
            PrintMatrix(result);
        }