Advertisement
Venciity

[ Telerik C#] MultidimArrays-Demos 4. Matrix Multiplication

Feb 26th, 2014
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.20 KB | None | 0 0
  1. using System;
  2.  
  3. class MatrixMultiplication
  4. {
  5.     static void Main()
  6.     {
  7.         int[,] firstMatrix = new int[4, 2]
  8.         {
  9.             { 1, 2 },
  10.             { 3, 4 },
  11.             { 5, 6 },
  12.             { 7, 8 }
  13.         };
  14.  
  15.         // Print the first matrix
  16.         for (int row = 0; row < firstMatrix.GetLength(0); row++)
  17.         {
  18.             for (int col = 0; col < firstMatrix.GetLength(1); col++)
  19.             {
  20.                 Console.Write("{0} ", firstMatrix[row, col]);
  21.             }
  22.             Console.WriteLine();
  23.         }
  24.         Console.WriteLine();
  25.  
  26.         int[,] secondMatrix = new int[2, 3]
  27.         {
  28.             { 1, 2, 3 },
  29.             { 4, 5, 6 }
  30.         };
  31.  
  32.         // Print the second matrix
  33.         for (int row = 0; row < secondMatrix.GetLength(0); row++)
  34.         {
  35.             for (int col = 0; col < secondMatrix.GetLength(1); col++)
  36.             {
  37.                 Console.Write("{0} ", secondMatrix[row, col]);
  38.             }
  39.             Console.WriteLine();
  40.         }
  41.         Console.WriteLine();
  42.  
  43.         // Multiply the first matrix with the second matrix
  44.         int width1 = firstMatrix.GetLength(1);
  45.         int height1 = firstMatrix.GetLength(0);
  46.         int width2 = secondMatrix.GetLength(1);
  47.         int height2 = secondMatrix.GetLength(0);
  48.  
  49.         if (width1 != height2)
  50.         {
  51.             throw new ArgumentException("Invalid dimensions!");
  52.         }
  53.  
  54.         int[,] resultMatrix = new int[height1, width2];
  55.         for (int row = 0; row < height1; row++)
  56.         {
  57.             for (int col = 0; col < width2; col++)
  58.             {
  59.                 resultMatrix[row, col] = 0;
  60.                 for (int i = 0; i < width1; i++)
  61.                 {
  62.                     resultMatrix[row, col] +=
  63.                         firstMatrix[row, i] * secondMatrix[i, col];
  64.                 }
  65.             }
  66.         }
  67.  
  68.         // Print the result matrix
  69.         for (int row = 0; row < resultMatrix.GetLength(0); row++)
  70.         {
  71.             for (int col = 0; col < resultMatrix.GetLength(1); col++)
  72.             {
  73.                 Console.Write("{0} ", resultMatrix[row, col]);
  74.             }
  75.             Console.WriteLine();
  76.         }
  77.         Console.WriteLine();
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement