C
C#2y ago
moshimoshi

❔ Matrix Multiplication

Hi there, I need help understanding the following source code, I have added my questions in the comments.
namespace SolH
{
class H7
{
static int[,] MatrixMultiply(int[,] A, int[,] B)
{
int[,] R = new int[A.GetLength(0), B.GetLength(1)];

for (int i = 0; i < A.GetLength(0); i++)
{
for (int j = 0; j < B.GetLength(1); j++)
{
for (int k = 0; k < A.GetLength(1); k++) // why are we looping through A's columns?
{
R[i, j] = R[i, j] + A[i, k] * B[k, j]; //why do we need to add R[i, j]? Isnt it an empty array after we initialize it?
}
}
}
return R;
}
namespace SolH
{
class H7
{
static int[,] MatrixMultiply(int[,] A, int[,] B)
{
int[,] R = new int[A.GetLength(0), B.GetLength(1)];

for (int i = 0; i < A.GetLength(0); i++)
{
for (int j = 0; j < B.GetLength(1); j++)
{
for (int k = 0; k < A.GetLength(1); k++) // why are we looping through A's columns?
{
R[i, j] = R[i, j] + A[i, k] * B[k, j]; //why do we need to add R[i, j]? Isnt it an empty array after we initialize it?
}
}
}
return R;
}
Here is the question: Write a static method MatrixMultiply(int[,] A, int [,] B) that will perform a matrix multiplication and return another 2 dimensional array.
4 Replies
HimmDawg
HimmDawg2y ago
// why are we looping through A's columns?
Because the first loop here
for (int i = 0; i < A.GetLength(0); i++)
for (int i = 0; i < A.GetLength(0); i++)
loops over the rows. If we then loop over the columns, then we can get the values in each row. Since B has a much rows as A has columns, this will work out to build the sum for the respective cell in C
// Isnt it an empty array after we initialize it?
No. It's just a bunch of integers. the default value for int is 0
.logik.
.logik.2y ago
You also need to add R[i, j] because the way you create x_12 (using the wiki image) is starting with x_12=0 x_12 = x_12 + a_11b_12 And then x_12 = x_12 + a_12b_22 Which gives you the proper cross product
moshimoshi
moshimoshiOP2y ago
Thank you!!! I get it now!!! Thank you for breaking it down so clearly 🙂
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server