Answer to Question #312529 in C++ for Raian

Question #312529

Create a class called 'Matrix' containing constructor that initializes the number of rows and the

number of columns of a new Matrix object. The Matrix class has the following information:

1 - number of rows of matrix

2 - number of columns of matrix

3 - elements of matrix (You can use 2D vector)

The Matrix class has functions for each of the following:

1 - get the number of rows

2 - get the number of columns

3 - set the elements of the matrix at a given position (i,j)

4 - Adding two matrices.

5 - multiplying the two matrices

You can assume that the dimensions are correct for the multiplication and addition.


1
Expert's answer
2022-03-16T10:23:53-0400
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;


class Matrix {
public:
    Matrix(int r, int c);
    int rows()    { return row; }
    int columns() { return col; }
    void set(int i, int j, double x);
    Matrix add(const Matrix& rhs) const;
    Matrix mul(const Matrix& rhs) const;
    void print();


private:
    int row;
    int col;
    vector<vector<double>> v;
};


Matrix::Matrix(int r, int c) {
    row = r;
    col = c;


    v.resize(row);
    for (int i=0; i<row; i++) {
        v[i].resize(col, 0.0);
    }
}


void Matrix::set(int i, int j, double x) {
    v[i][j] = x;
}


Matrix Matrix::add(const Matrix& rhs) const
{
    Matrix M(row, col);
    for (int i=0; i<row; i++) {
        for (int j=0; j<col; j++) {
            M.v[i][j] = v[i][j] + rhs.v[i][j];
        }
    }
    return M;
}


Matrix Matrix::mul(const Matrix& rhs) const
{
    Matrix M(row, rhs.col);
    for (int i=0; i<row; i++) {
        for (int j=0; j<rhs.col; j++) {
            for (int k=0; k<col; k++) {
                M.v[i][j] += v[i][k] * rhs.v[k][j];
            }
            cout << endl;
        }
    }
    return M;
}


void Matrix::print() {
    for (int i=0; i<row; i++) {
        for (int j=0; j<col; j++) {
            cout << setw(8) << v[i][j];
        }
    }
}


int main() {
    Matrix A(2, 2), B(2, 2);

    A.set(0,0, 1.0);
    A.set(0,1, 2.0);
    A.set(1,0, 3.0);
    A.set(1,1, 4.0);

    B.set(0,0, 10.0);
    B.set(0,1, 20.0);
    B.set(1,0, 30.0);
    B.set(1,1, 40.0);

    Matrix C = A.add(B);
    cout << "A + B =" << endl;
    C.print();

    Matrix D(2, 3);
    D.set(0,0, 1.0);
    D.set(0,1, 1.0);
    D.set(0,2, 1.0);
    D.set(1,0, 2.0);
    D.set(1,1, 2.0);
    D.set(1,2, 2.0);

    C = A.mul(D);
    cout << endl << "A*D =" << endl;
    C.print();

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment