C#C
C#12mo ago
5 replies
Faker

✅ Matrix multiplication in C#

Hello guys, sorry to disturb you all; I have an exercise where I need to perform matrix multiplication using 2D arrays. I try to implement the following code:
// //Matrix Multiplication
  public static void MultiplyMatrices(int[,] matrix1, int[,] matrix2)
  {
      // Check if multiplication is possible (columns of matrix1 must equal rows of matrix2)
      
      if (matrix1.GetLength(1) == matrix2.GetLength(0))
      {
          var result = new int[matrix1.GetLength(0), matrix2.GetLength(1)];
          // row * col
          var col = 0;
          for (int i = 0; i < matrix1.GetLength(0); i++)
          {
              var sum = 0;
              for (int j = 0; j < matrix2.GetLength(1); j++)
              {
                  sum += matrix1[i, j] * matrix2[j,i];
              }
              // store into result matrix
              result[i, col] = sum;
              if (matrix1.GetLength(1) >= col)
              {
                  col = 0;
              }
              else
              {
                  col++;
              }

          }

          for (int i = 0; i < result.GetLength(0); i++)
          {
              for (int j = 0; j < result.GetLength(1); j++)
              {
                  Console.Write($"{result[i,j]}");
              }

              Console.WriteLine();
          }
      }
  }

But it seems my logic is faulty because I'm not getting the required result. So basically, my code has some logic errors. What is the right way of knowing where my logic went wrong please.
Was this page helpful?