Multiplication of c++ matrices [closed]

Closed. This question is off-topic. Answers to it are not accepted at the moment.

Want to improve this question? Update the question so that it it fit into the theme of Stack Overflow in Russian.

Closed 1 month ago.

Improve the question

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

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

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

Author: Harry, 2021-01-11

1 answers

You don't need a new loop, you need the function to know about all the sizes of the matrices, now you pass n and l this is only enough to multiply the square matrices by the type 4 на 4.

When multiplying the matrix 3 на 4 with 4 на 2, note that you have 3 numbers that are 3, 4, 2, and your function can only know about two of them at the moment.

Here is a proper example of your function:

//row1 - кол-во строк в матрице a1, col1 - кол-во столбцов в 1 
матрице, col2 - кол-во столбвоц во 2 матрице
void multiplication(int(&a1)[4][4], int(&b)[4][4], int(&c)[4][4], int row1, int col1, int col2) {
    for (int i = 0; i < row1; i++) {
        for (int j = 0; j < col2; j++) {
            c[i][j] = 0;
            for (int k = 0; k < col1; k++)
                c[i][j] += a1[i][k] * b[k][j];
        }
    }
}

For more understanding, I renamed the variables and signed in the comments that they are denote.

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

multiplication(a, b, c, 3, 4, 2);
 1
Author: Павел Ериков, 2021-01-11 17:50:36