Reputation: 109
This is my matrix code. I am multiplying two matrices. One of the matrices is scalar (meaning diagonal elements are the same), but when I run this code, I am getting the wrong answer.
static void Main(string[] args)
{
int[,] matrix1 = new int[3, 3];
int[,] matrix2 = new int[3, 3];
int[,] result = new int[3, 3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.WriteLine("Enter 1st Matrix: ");
matrix1[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.ReadLine();
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++)
{
Console.WriteLine("Enter 2nd Matrix: ");
matrix2[k, l] = Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine();
Console.WriteLine("Matrix 1: ");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write(matrix1[i, j] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine("Matrix 2: ");
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++)
{
Console.Write(matrix2[k, l] + " ");
}
Console.WriteLine();
}
Console.WriteLine("Matrix 1 * Matrix 2: ");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
result[i, j] = result[i, j] + matrix1[i, j] * matrix2[i, j];
Console.Write(result[i, j] + " ");
}
Console.WriteLine();
}
Console.ReadLine();
Console.ReadLine();
}
Upvotes: 1
Views: 1188
Reputation: 9912
You're not multiplying the matrices, you're multiplying their values. See https://en.wikipedia.org/wiki/Matrix_multiplication
E.g. {{1, 1}, {0, 0}} x {{1, 0}, {1, 0}}
should result in {{2, 0}, {0, 0}}
, not {{1, 0}, {0, 0}}
.
Here is the right code for matrix multiplication (note that it has the complexity of O(n^3), not O(n^2)):
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
result[i, j] = 0;
for(int k = 0; k < 3; k++)
{
result[i, j] = result[i, j] + matrix1[i, k] * matrix2[k, j];
}
Console.Write(result[i, j] + " ");
}
Console.WriteLine();
}
Upvotes: 4