C# - Matrix - Find product of 2 matrix


C# - Matrix - Find product of 2 matrix

CODE
using System; class Program { public static void Main(string[] args) { //The number of columns of Matrix a should be same as the number of rows of Matrix b int[,] matrixA = { { 1, 4, 2 }, { 2, 5, 1 } }; int[,] matrixB = { { 3, 4, 2 }, { 3, 5, 7 }, { 1, 2, 1 } }; Console.WriteLine("Matrix A"); printMatrix(matrixA); Console.WriteLine("\nMatrix B"); printMatrix(matrixB); if (matrixA.GetLength(1) == matrixB.GetLength(0)) { int[,] productMatrix = new int[matrixA.GetLength(0), matrixB.GetLength(1)]; for (int i = 0; i < matrixA.GetLength(0); i++) { for (int j = 0; j < matrixB.GetLength(1); j++) { productMatrix[i, j] = 0; for (int k = 0; k < matrixA.GetLength(1); k++) { productMatrix[i, j] += matrixA[i, k] * matrixB[k, j]; } } } Console.WriteLine("\nProduct Matrix"); printMatrix(productMatrix); } else Console.WriteLine("Matrix multiplication not possible"); Console.ReadKey(); } private static void printMatrix(int[,] matrix) { for (int i = 0; i < matrix.GetLength(0); i++) { for (int j = 0; j < matrix.GetLength(1); j++) { Console.Write("{0}\t", matrix[i, j]); } Console.WriteLine(""); } } }

Comments