Home c++ C++ matrix multiplication

C++ matrix multiplication

Author

Date

Category

I noticed that my function skips the last row if the matrix is ​​not square when multiplying. I don’t see an error yet, so please help.

void multiplication (int (& amp; a1) [4] [4], int (& amp; b) [4] [ 4], int (& amp; c) [4] [4], int n, int l) {
  for (int i = 0; i & lt; n; i ++) {
    for (int j = 0; j & lt; l; j ++) {
      for (int k = 0; k & lt; n; k ++) {
        int save = a1 [i] [k] * b [k] [j];
        c [i] [j] + = save;
        save = 0;
      }
    }
  }
}

The condition for matrix multiplication (the number of rows in one = the number of columns in the second) is checked in another function.


Answer 1, authority 100%

You don’t need a new loop, you need the function to know about all matrix sizes, now you pass n and l this is enough only for multiplying square matrices like 4 by 4 .

When multiplying the 3 by 4 matrix from 4 by 2 , notice that you have 3 numbers that are 3, 4, 2 , and yours the function can currently only learn about two of them.

Here is a correct example of your function:

// row1 - number of rows in matrix a1, col1 - number of columns in 1
matrix, col2 - number of columns in matrix 2
void multiplication (int (& amp; a1) [4] [4], int (& amp; b) [4] [4], int (& amp; c) [4] [4], int row1, int col1, int col2 ) {
  for (int i = 0; i & lt; row1; i ++) {
    for (int j = 0; j & lt; col2; j ++) {
      c [i] [j] = 0;
      for (int k = 0; k & lt; col1; k ++)
        c [i] [j] + = a1 [i] [k] * b [k] [j];
    }
  }
}

For better understanding, I renamed the variables and signed in the comments what they mean.

Now, to multiply the matrix 3 by 4 and 4 by 2 , you need to call the function like this:

multiplication (a, b, c, 3, 4, 2);

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions