Matrix Multiplication

Hello everyone,
I recently tried to do a program to multiply 2 matrices. I did everything right with the exception of 3 lines(IN BOLD) that were missing on my code, but I dont really get the point of using them, I thought it was due to memory overload but I'd like to know exactly why. btw I know you can do it with pointers but I just want to know why these 3 lines.
Thank you very much.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
#include <vector>
using namespace std;
 
typedef vector < vector<double>> Matrix;
 
Matrix  read_matrix();
void  display_matrix(const Matrix& M);
Matrix  multiplication(const Matrix& M1, const Matrix& M2);
 
// ----------------------------------------------------------------------
int main()
{
    Matrix M1(read_matrix()), M2(read_matrix());
 
    if (M1[0].size() != M2.size()) 
        cout << "Matrix multiplication not possible !" << endl;
    else {
        cout << "Product :" << endl;
        display_matrix(multiplication(M1, M2));
    }
 
    return 0;
}
 
// ----------------------------------------------------------------------
Matrix  read_matrix()
{
    cout << "Enter a matrix :" << endl;
 
    size_t rows;
    do {
        cout << "  Number of Rows : " << flush;
        cin >> rows;
    } while (rows < 1);
 
    size_t columns;
    do {
        cout << "  Number of columns : " << flush;
        cin >> columns;
    } while (columns < 1);
 
    Matrix M(rows, vector<double>(columns));
 
    for (size_t i(0); i < rows; ++i) 
        for (size_t j(0); j < columns; ++j) {
            cout << "  M[" << i+1 << "," << j+1 << "]=" << flush;
            cin >> M[i][j];
        }
 
    return M;
}
 
// ----------------------------------------------------------------------
Matrix  multiplication(const Matrix& M1, 
                        const Matrix& M2)
{
    Matrix prod(M1.size(), vector<double>(M2[0].size()));
 
    for (size_t i(0); i < M1.size(); ++i) 
        for (size_t j(0); j < M2[0].size(); ++j) {
            prod[i][j] = 0.0;
            for (size_t k(0); k < M2.size(); k++) 
                prod[i][j] += M1[i][k] * M2[k][j];
        }
 
    return prod;
}

// ----------------------------------------------------------------------
void  display_matrix(const Matrix& M)
{
    for (auto row : M) {
        for (auto element : row) {
            cout << element << " ";
        }
        cout << endl;
    }
}
Topic archived. No new replies allowed.