I’ve been learning the C++ programming language for about two months now. I invested in Mosh Hamidani’s Ultimate C++ online course, which you can enroll in from https://www.codewithmosh.com. I also purchased a license for the Linux version of CLion, the premier C, C++ IDE software package (used by Mosh Hamidani) which rivals MS Visual Code. You can download CLion for Linux from the website: https://www.jetbrains.com/clion/download/#section=linux. After completing the course, I took my knowledge of C++ to the next level by investing in several C++ Programming Language ebooks.

To learn more about matrix multiplication, visit: https://en.wikipedia.org/wiki/Matrix_multiplication.

With the knowledge I have acquired to date, I’ve constructed an object-oriented C++ program that multiplies two matrices.

As you may know, if you have a bachelor’s level mathematics background or simply an interest in the subject of matrices, a matrix is a 2-dimensional array of numbers. In order to multiply two matrices, their rows and columns must follow this rule: the matrix on the left-side of the product with x-rows and y-columns can only be multiplied by a matrix on the right-side of the product with y-rows and x-columns, with the resulting product matrix consisting of x-rows and x-columns. For example: a 2×4 matrix can only be multiplied by a 4×2 matrix with the product being a 2×2 matrix.

With this background, what I have done is to create a C++ program consisting of two header (.h) files and two implementation (.cpp) files. The primary header file is Matrix.h, the Matrix class whose constructor generates a Matrix object consisting of a vector<double>, a vector of type double representing the matrix rows, and a vector<vector<double>>, a vector of the row vectors representing the matrix itself. The Matrix.cpp implementation file contains the definitions for the Matrix class constructor, the Matrix row and column public member getter methods, and functions used to print matrices to the console. A special DoubleSubscript class is used to override the operator[]() function of the Matrix Class to permit access to individual elements of a Matrix object by the row and column subscripts. For example. Matrix M[x][y] refers to the xth row and yth column element in the matrix. The last file is the Main.cpp implementation file which is the method called to run the program itself. This file consists of a function to perform the multiplication of matrices and call the multPrint() function to print the product matrix to the console. The main() method itself contains code to call the Matrix class constructor twice to generate and store two matrices from input requested of the user by the program. Then, the main() function calls the multiply(A, B) function to perform the multiplication and display the product matrix to the console.

What follows is the C++ code for each of the files detailed above. You can copy and save these files to your C++ IDE and run the program yourself to see how it works.

Matrix.h:

//
// Created by donald on 10/27/22.
//

#ifndef MATRIXMULTIPLICATION_MATRIX_H
#define MATRIXMULTIPLICATION_MATRIX_H

#include <iostream>
#include <cstddef>
#include <utility>
#include <vector>
#include "DoubleSubscript.h"
using namespace std;

class Matrix {
public:
    // Matrix constructor definition
    explicit Matrix(int r, int c);
    // Matrix private attribute getter method definitions
    [[nodiscard]] int getCols() const;
    [[nodiscard]] int getRows() const;

    // Overridden operator[]() for double subscript of the Matrix class object
    DoubleSubscript operator[](int j) {
        DoubleSubscript secondSubscript(matrix, j);
        return secondSubscript;
    }
    // Matrix print methods declarations
    static void print(int r, int c, const vector<vector<double>>& M);
    static void multPrint(int r, int c, const vector<vector<double>>& M);

private:
    int rows;
    int cols;
    vector<double> row;
    vector<vector<double>> matrix;
};

#endif //MATRIXMULTIPLICATION_MATRIX_H

Matrix.cpp:

//
// Created by donald on 10/27/22.
//
#include <iostream>
#include <iomanip>
#include <vector>
#include "Matrix.h"
using namespace std;

// Definition of the Matrix constructor
Matrix::Matrix(int r, int c) : rows(r), cols(c) {
    double number;
    vector<double> _row;
    vector<vector<double>> M;
    for(int i=0; i<r; i++) {
        for(int j=0; j<c; j++) {
            cout << "Enter element [" << i << "]" << "[" << j << "]: ";
            cin >> number;
            _row.push_back(number);
        }
        M.push_back(_row);  // Store a vector<double> row of the Matrix
        _row.clear();
    }
    print(r, c, M);  // Print function call for Matrix object
    this->matrix = M; // Matrix object stored on the stack
}
// Definition of the function to print a constructed Matrix
void Matrix::print(int r, int c, const vector<vector<double>>& M){
    for (int i=0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            cout << setw(10) << M[i][j] << "   ";
        }
        cout << endl;
    }
}

// Definition of the function to print the product matrix passed by reference
void Matrix::multPrint(int r, int c, const vector<vector<double>>& M){
    for (int i=0; i < r; ++i) {
        for (int j = 0; j < c; ++j) {
            cout << setw(10) << M[i][j] << "   ";
            if (j == (c - 1))
                cout << endl;
        }
    }
}
// Definition of the Matrix cols getter method
int Matrix::getCols() const {
    return cols;
}
// Definition of the Matrix rows getter method
int Matrix::getRows() const {
    return rows;
}

DoubleSubScript.h:

//
// Created by donald on 10/30/22.
//

#ifndef MATRIXMULTIPLICATION_DOUBLESUBSCRIPT_H
#define MATRIXMULTIPLICATION_DOUBLESUBSCRIPT_H

#include <vector>
using namespace std;

class DoubleSubscript {
public:
    // DoubleSubscript constructor for matrix passed by reference
    DoubleSubscript(vector<vector<double>>& _matrix, int _j) : matrix(_matrix) {
        j = _j;
    }
    // DoubleSubscript operator[]() definition
    double& operator[](int i) {
        return matrix[j][i];
    }

private:
    vector<vector<double>>& matrix;
    int j;
};

#endif //MATRIXMULTIPLICATION_DOUBLESUBSCRIPT_H

Main.cpp:

//
// Created by donald on 10/27/22.
//
#include <iostream>
#include "Matrix.h"
using namespace std;

int row, col, i, j, k;
// Function to multiply two matrices
void multiply(Matrix& Alpha, Matrix& Beta) {
    vector<double> _multRow;
    vector<vector<double>> mult;
    // Zero-fill the mult matrix
    int number = 0;
    for (i = 0; i < Alpha.getRows(); ++i) {
        for (j = 0; j < Beta.getCols(); ++j) {
            _multRow.push_back(number);
        }
        mult.push_back(_multRow);
        _multRow.clear();
    }
    // Generate the mult matrix product from matrices A and B passed by reference
    for (i = 0; i < Alpha.getRows(); ++i) {
        for (j = 0; j < Beta.getCols(); ++j) {
            for (k = 0; k < Alpha.getCols(); ++k) {
                mult[i][j] += Alpha[i][k] * Beta[k][j];
            }
        }
    }
    // Function call to print the product matrix
    Matrix::multPrint(Alpha.getRows(), Beta.getCols(), mult);
}
int main() {
    cout << "How many rows and columns does your matrix have? ";
    cin >> row >> col;
    cout << "Enter " << row << "x" << col << " matrix elements: " << endl;
    Matrix A(row, col);  // Matrix constructor call for Matrix A
    cout << "Enter " << col << "x" << row << " matrix elements: " << endl;
    Matrix B(col, row); // Matrix constructor call for Matrix B
    cout << endl;
    cout << "The product of these matrices is the " << row << "x" << row << " matrix: " << endl;
    multiply(A, B);  // Function call to multiply Matrix A and Matrix B and generate the product matrix
    return 0;
}

Sample Output:

Left-hand matrix entries
Right-hand matrix entries with product matrix displayed

Leave a Reply

Your email address will not be published. Required fields are marked *