C
C#3w ago
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:
C#
// //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();
}
}
}
C#
// //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.
3 Replies
Angius
Angius3w ago
The best way to find errors, is to use the debugger It lets you observe values at any point, step through the code line by line, all the good stuff $debug
MODiX
MODiX3w ago
Tutorial: Debug C# code and inspect data - Visual Studio (Windows)
Learn features of the Visual Studio debugger and how to start the debugger, step through code, and inspect data in a C# application.
Faker
FakerOP3w ago
yep noted, will just have a look how to use a debugger, thanks !!

Did you find this page helpful?