Reputation: 1
I want to know how to multiply 2D arrays (matrices) and show them as a matrix.
The current output is
1 1 1
1 1 1
1 1 1
which is not the correct result.
The code is below:
static void Main(string[] args)
{
int[,] metrix1 = new int[3, 3] { { 2, 0, 2 }, { 0, 1, 2 }, { 1, 2, 1 } };
int[,] metrix2 = new int[3, 3] { { 1, 1, 1 }, { 0, 1, 0 }, { 0, 0, 1 } };
int[,] result = new int[3, 3];
int m1 =0;
int m2 =0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
m1 = metrix1[i, j];
}
}
// metrix 2
for (int y = 0; y < 3; y++)
{
for (int z = 0; z < 3; z++)
{
m2 = metrix2[y, z];
}
}
//m
for (int a = 0; a < 3; a++)
{
for (int b = 0; b < 3; b++)
{
result[a, b] = m1 *m2;
Console.Write(result[a, b] );
}Console.WriteLine();
}Console.ReadLine();
}
}
}
Upvotes: -2
Views: 3634
Reputation: 12181
You're approaching this incorrectly.
for (int y = 0; y < 3; y++)
{
for (int z = 0; z < 3; z++)
{
m2 = metrix2[y, z];
}
}
After this, m2 will contain the lower right-hand value of the array (matrix[2, 2]
). You're literally multiplying the same value over and over again for your multiplication. You need to put all of this in one for
loop.
Also, that's not the correct way to do matrix multiplication. To begin with, your code will only work for a 3x3 matrix; not only can you have other sizes of matrices (4x4, 5x5, etc.), matrices don't even have to be square to be able to multiply them (as long as the number of columns of one equals the number of rows of the other). Even if they are both 3x3 matrices, the calculation would still be wrong. Wikipedia has some good examples of the proper way to do this.
2 0 2 1 1 1 (2*1)+(0*0)+(2*0) (2*1)+(0*1)+(2*0) ...
0 1 2 x 0 1 0 = (0*1)+(1*0)+(2*0) (0*1)(1*1)(2*0) ...
1 2 1 0 0 1 ..
Upvotes: 0