Answer to Question #187065 in C++ for Maizurah

Question #187065

Write a complete c++ program code which can multiply any two matrices.

The two matrices must be any size.

The elements of the two matrices is read from a file ex:matrix.dat

The result will be kept in a separate file call ex:matrix.res

Your program must be able to check whether the multiplication of the matrix can be done.



1
Expert's answer
2021-04-29T06:09:06-0400
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Matrix{
    int rows, cols, mat[10][10];
    public:
    Matrix(){
        rows = 0;
        cols = 0;
    }
    void getdata(string filename){
        fstream matfile;
        string s;
        matfile.open(filename, ios::in);
        if(!matfile){
            cout<<"Error opening file";
        }
        else while(getline(matfile, s)){
            int col = 0;
            rows++;
            string element = "";
            for(int i = 0; i < s.length(); i++){
                if(s[i] == ',' || i == (s.length() - 1)){
                    if(i == (s.length() - 1)) element += s[i];
                    mat[rows - 1][col] = stoi(element);
                    element = "";
                    col++;
                    if(col > cols) cols = col;
                }
                else element += s[i];
            }
        }
        matfile.close();
    }
    void putdata(string filename){
        fstream matfile;
        matfile.open(filename, ios::out | ios:: trunc);
        if(rows == 0 && cols == 0)
            matfile<<endl<<"\nNo data present";
        else{
            for(int i = 0; i < cols; i++){
                for(int j = 0; j < rows; j++)
                    matfile<<mat[i][j]<<"\t";
                matfile<<endl;
            }
        }
    }
    Matrix operator*(const Matrix& M){
        Matrix result;
        result.rows = this->rows;
        result.cols = M.cols;
        if(this->cols == M.rows){
        for(int i = 0; i < this->rows; i++)
            for(int j = 0; j < M.cols; j++){
                result.mat[i][j] = 0;
                for(int k = 0; k < this->cols; k++){
                    result.mat[i][j] += this->mat[i][k] * M.mat[k][j];
                }
            }
        return result;
        }
        else{
            cout<<"Cannot multiply these matrices";
            return result;
        }
    }
};
int main(){
    Matrix A, B;
    A.getdata("matrix.dat");
    B.getdata("matrix.dat");
    Matrix C = A * B;
    C.putdata("matrix.res");
    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

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS