Question

In: Computer Science

C++ program to implement Matrix Class with following requirements, Classes :- matrix.cpp and main.cpp (to test...

C++ program to implement Matrix Class with following requirements,

Classes :- matrix.cpp and main.cpp (to test it) with following requirements: -

Please use Vectors of double.

  1. Declare and define an matrix class: -
  • The matrix stores doubles. Implement a default constructor which initializes square 1 x 1 matrix that contains  0.0.
  • Implement a constructor that accepts a positive integer n and creates a square n x n matrix that contains 0.0s. Throw an exception if the integer passed to the constructor is zero or negative.
  • Implement a constructor that accepts two positive integers r and c and creates matrix with r rows and c columns that contains 0.0s. Throw an exception if either integer passed to the constructor is zero or negative.
  • Implement a constructor that accepts a one-dimensional array/vector of double. If you use an array, it might be helpful to also pass in the size of the array to indicate the number of elements in the array. The size of the array/double must have an integer square root, i.e., the size of the array/double must be 1, or 4, or 9, or 16, etc. Create a square matrix of size 1 x 1, or 2 x 2, or 3 x 3, or 4 x 4, etc., and populate it using the values from the array/double. If the size of the array/double does not have an integer square root, throw an exception.
  • Implement a 3-parameter Setter that accepts two integers representing row and column and a double representing new value for specified location. Throw an exception if integers are negative or too large.
  • Implement a 2-parameter Getter that accepts two integers representing row and column and returns value in the matrix from specified location. Throw an exception if the integers are negative or too large.
  • Implement a function called clear which sets all values in the matrix to 0.0.
  • Implement a destructor called ~matrix.
  • Implement an overloaded insertion operator so we can print the matrix to std::cout or other streams.
  • Implement == and != operators. The equality operators must check if the matrices are same size and contain the same values in the same locations.
  • Implement unary increment and decrement operators. You will need a prefix and a postfix version of each. The operators should (respectively) increment or decrement each value in the matrix by 1.0.
  • Implement the assignment operator using the copy-and-swap algorithm.
  • Overload operator +=, operator +, operator - =, and operator - .These will only work if the matrices are the same size otherwise throw an exception. Do not overload operator / or operator/=
  • Overload operator* and operator*= . For operator* and operator*= , be careful. You will need to remember that for 2 matrices a and b, the product matrix c is possibly a different size. If matrix a is 1 x 4 and matrix b is 4 x 3, the size of the product matrix c will be 1 x 3. If the number of columns of the first operand is not equal to the number of rows of the second operand, throw an exception.

Solutions

Expert Solution

matrix.h

============

#pragma once
#include <iostream>
#include <vector>
using namespace std;

class Matrix {
private:
   vector<vector<double> > matrix; // 2-D vector to store matrix data
public:
   // constructors
   Matrix(); // creates a matrix of 1 X 1
   Matrix(int n); // creates a matrix of n X n
   Matrix(int r, int c); // creates a matrix with r rows and c columns
   Matrix(vector<double>& v); // create a matrix with given values
   ~Matrix(); // destructor
   void setValue(int row, int col, double value); // set given value at given position in matrix
   double getValue(int row, int col); // returns a value from given location
   void clear(); // sets all values in the matrix to 0.0
   bool operator==(const Matrix& mt); // return true if 2 matrix are equal otherwise return false
   bool operator!=(const Matrix& mt); // return true if 2 matrix are not equal otherwise return false
   Matrix& operator++(int); // increase each element in vector by 1.0
   Matrix& operator--(int); // decrease each element in vector by 1.0
   Matrix& operator+(const Matrix& mt); // add two matrices and return resulting matrix
   Matrix& operator-(const Matrix& mt); // substract second matrix from first matrix and return resulting matrix
   Matrix& operator+=(const Matrix& mt); // add second matrix to first one
   Matrix& operator-=(const Matrix& mt); // substract second matrix from first one
   Matrix& operator*(const Matrix& mt); // multyply first matrix with seecond matrix and return resulting matrix
   Matrix& operator*=(const Matrix& mt); // multyply and modify first matrix with seecond matrix
   Matrix& operator=(const Matrix& mt); // creates a copy of given matrix and assign to the matrix

   friend ostream& operator<<(ostream& os, const Matrix& mt);
};


=============

matrix.cpp

=============

#include "matrix.h"

Matrix::Matrix() {
   // create a matrix of 1X1 filled with 0.0
   // create a vactor of row
   vector<double> row;
   // add elemnt to the row vector
   row.push_back(0.0);
   // add row vector to the matrix
   matrix.push_back(row);
}

Matrix::Matrix(int n) {
   // check if n is negative or 0
   if (n > 0) {
       // create a vector of size n
       for (int i = 0; i < n; i++) {
           vector<double> row;
           // fill vector with 0.0
           for (int j = 0; j < n; j++) {
               row.push_back(0.0);
           }
           // add each row to matrix
           matrix.push_back(row);
       }
   }
   else {
       // throw an exception
       throw -1;
   }
}

Matrix::Matrix(int r, int c) {
   // check if r or c is negative or 0
   if (r > 0 && c > 0) {
       // create matrix of r row
       for (int i = 0; i < r; i++) {
           // each row contains c elements
           vector<double> row;
           for (int j = 0; j < c; j++) {
               // fill each row with 0.0
               row.push_back(0.0);
           }
           // add each row to thee matrix
           matrix.push_back(row);
       }
   }
   else {
       // throw an exception
       throw - 1;
   }
}

Matrix::Matrix(vector<double>& v) {
   // check if given vector is of perfect square
   // get size of vector
   int size = v.size();
   int row = -1;
   // get sqrt of size if its perfect square
   for (int i = 1; i <= size; i++) {
       if ((size % i == 0) && (size / i == i)) {
           row = i;
           break;
       }
   }
   // check if row is -1
   if (row == -1) {
       // thow exception
       throw - 1;
   }
   else {
       for (int i = 0; i < row; i++) {
           // get each row
           vector<double> r;
           for (int j = 0; j < row; j++) {
               r.push_back(v.at(i*row + j));
           }
           // add each row to the matrix
           matrix.push_back(r);
       }
   }
}

Matrix::~Matrix() {
   // delete matrix
   for (int i = 0; i < matrix.size(); i++) {
       matrix.at(i).clear();
   }
   matrix.clear();
}

void Matrix::setValue(int row, int col, double value) {
   // check for vaild location
   if (row <= 0 || row > matrix.size()) {
       // throw exception
       throw - 1;
   }
   else if (col <= 0 || col > matrix.at(0).size()) {
       // throw exception
       throw - 1;
   }
   else {
       // set new value to the location
       matrix.at(row-1).at(col-1) = value;
   }
}

double Matrix::getValue(int row, int col) {
   // check for vaild location
   if (row <= 0 || row > matrix.size()) {
       // throw exception
       throw - 1;
   }
   else if (col <= 0 || col > matrix.at(0).size()) {
       // throw exception
       throw - 1;
   }
   else {
       // return value from the location
       return matrix.at(row-1).at(col-1);
   }
}

void Matrix::clear() {
   // reset all elemets in matrix to 0.0
   for (int i = 0; i < matrix.size(); i++) {
       for (int j = 0; j < matrix.at(i).size(); j++) {
           matrix.at(i).at(j) = 0.0;
       }
   }
}

ostream& operator<<(ostream& os, const Matrix& mt) {
   // get number of rows
   int rows = mt.matrix.size();
   // output each row to stream
   for (int i = 0; i < rows; i++) {
       os << "| ";
       // out put each element of row
       for (int j = 0; j < mt.matrix.at(i).size(); j++) {
           os << mt.matrix.at(i).at(j) << " ";
       }
       os << "|" << endl;
   }
   return os;
}

bool Matrix::operator==(const Matrix& mt) {
   // check for row size
   if (this->matrix.size() != mt.matrix.size()) {
       return false;
   }
   // check fro column size
   else if (this->matrix.at(0).size() != mt.matrix.at(0).size()) {
       return false;
   }
   else {
       // check for each elements
       for (int i = 0; i < matrix.size(); i++) {
           for (int j = 0; j < matrix.at(i).size(); j++) {
               if (this->matrix.at(i).at(j) != mt.matrix.at(i).at(j)) {
                   return false;
               }
           }
       }
       return true;
   }
}

bool Matrix::operator!=(const Matrix& mt) {
   // check for row size
   if (this->matrix.size() != mt.matrix.size()) {
       return true;
   }
   // check fro column size
   else if (this->matrix.at(0).size() != mt.matrix.at(0).size()) {
       return true;
   }
   else {
       // check for each elements
       for (int i = 0; i < matrix.size(); i++) {
           for (int j = 0; j < matrix.at(i).size(); j++) {
               if (this->matrix.at(i).at(j) != mt.matrix.at(i).at(j)) {
                   return true;
               }
           }
       }
       return false;
   }
}

Matrix& Matrix::operator++(int) {
   for (int i = 0; i < matrix.size(); i++) {
       for (int j = 0; j < matrix.at(i).size(); j++) {
           // increament each value by 1.0
           matrix.at(i).at(j) = matrix.at(i).at(j) + 1.0;
       }
   }
   return *this;
}

Matrix& Matrix::operator--(int) {
   for (int i = 0; i < matrix.size(); i++) {
       for (int j = 0; j < matrix.at(i).size(); j++) {
           // decrease each value by 1.0
           matrix.at(i).at(j) = matrix.at(i).at(j) - 1.0;
       }
   }
   return *this;
}

Matrix& Matrix::operator=(const Matrix& mt) {
   // clear current matrix
   matrix.clear();
   // copy and assign given matrix
   for (int i = 0; i < mt.matrix.size(); i++) {
       vector<double> row; // build each row
       for (int j = 0; j < mt.matrix.at(i).size();j++) {
           row.push_back(mt.matrix.at(i).at(j)); // copy each element
       }
       // add each row to the current matrix
       matrix.push_back(row);
   }
   return *this;
}

Matrix& Matrix::operator+(const Matrix& mt) {
   // create a new matrix
   Matrix* m = new Matrix();
   m->matrix.clear();
   for (int i = 0; i < matrix.size(); i++) {
       // build each row
       vector<double> row;
       for (int j = 0; j < matrix.at(i).size(); j++) {
           double sum = matrix.at(i).at(j) + mt.matrix.at(i).at(j);
               row.push_back(sum);
       }
       // add each row to martix
       m->matrix.push_back(row);
   }
   return *m;
}

Matrix& Matrix::operator-(const Matrix& mt) {
   // create a new matrix
   Matrix* m = new Matrix();
   m->matrix.clear();
   for (int i = 0; i < matrix.size(); i++) {
       // build each row
       vector<double> row;
       for (int j = 0; j < matrix.at(i).size(); j++) {
           double sub = matrix.at(i).at(j) - mt.matrix.at(i).at(j);
           row.push_back(sub);
       }
       // add each row to martix
       m->matrix.push_back(row);
   }
   return *m;
}

Matrix& Matrix::operator+=(const Matrix& mt) {
   for (int i = 0; i < matrix.size(); i++) {
       // build each row
       vector<double> row;
       for (int j = 0; j < matrix.at(i).size(); j++) {
           matrix.at(i).at(j) = matrix.at(i).at(j) + mt.matrix.at(i).at(j);
       }
   }
   return *this;
}

Matrix& Matrix::operator-=(const Matrix& mt) {
   for (int i = 0; i < matrix.size(); i++) {
       // build each row
       vector<double> row;
       for (int j = 0; j < matrix.at(i).size(); j++) {
           matrix.at(i).at(j) = matrix.at(i).at(j) - mt.matrix.at(i).at(j);
       }
   }
   return *this;
}

Matrix& Matrix::operator*(const Matrix& mt) {
   // multiplication is done by dot product
   // create a empty mmatrix
   Matrix* m = new Matrix();
   m->matrix.clear();
   for (int i = 0; i < matrix.size(); i++) {
       // build each row
       vector<double> row;
       for (int j = 0; j < mt.matrix.at(i).size(); j++) {
           // multiply first matrix's row with second matrix's column
           // add the total sum
           double sum = 0.0;
           for (int k = 0; k < matrix.at(i).size(); k++) {
               sum = sum + (matrix.at(i).at(k) * mt.matrix.at(k).at(j));
           }
           // add sum to the row
           row.push_back(sum);
       }
       // add each row to martix
       m->matrix.push_back(row);
   }
   return *m;
}

Matrix& Matrix::operator*=(const Matrix& mt) {
   // multiplication is done by dot product
   // create a empty mmatrix
   Matrix* m = new Matrix();
   m->matrix.clear();
   for (int i = 0; i < matrix.size(); i++) {
       // build each row
       vector<double> row;
       for (int j = 0; j < mt.matrix.at(i).size(); j++) {
           // multiply first matrix's row with second matrix's column
           // add the total sum
           double sum = 0.0;
           for (int k = 0; k < matrix.at(i).size(); k++) {
               sum = sum + (matrix.at(i).at(k) * mt.matrix.at(k).at(j));
           }
           // add sum to the row
           row.push_back(sum);
       }
       // add each row to martix
       m->matrix.push_back(row);
   }
   // reassign new matrix to this
   this->matrix.clear();
   this->matrix = m->matrix;
   return *m;
}


=================

main.cpp

=================

#include "matrix.h"

int main() {
   // print each step
   cout << "Testing default constructor:" << endl;
   Matrix* m1 = new Matrix();
   cout << *m1;
   cout << "Testing destructor:" << endl;
   delete m1;
   cout << "Testing Matrix(3):" << endl;
   Matrix m2(3);
   cout << m2;
   cout << "Testing Matrix(3,4):" << endl;
   Matrix m3(3,4);
   cout << m3;
   vector<double> v;
   v.push_back(1.5);
   v.push_back(2.7);
   v.push_back(3.1);
   v.push_back(1.4);
   cout << "Testing coonstructor with vector parameter:" << endl;
   Matrix m4(v);
   cout << m4;
   cout << "getValue(1,2) at matrix 4 returns: " << m4.getValue(1, 2) << endl;
   cout << "Setting value 4.6 at 1st row and 2nd col of matrix 2:" << endl;
   m2.setValue(1, 2, 4.6);
   cout << m2;
   cout << "creating matrix 5 with assignment operaton on matrix 4:" << endl;
   Matrix* m5 = new Matrix();
   *m5 = m4;
   cout << "matrix 5: " << endl;
   cout << *m5;
   cout << "Testing == " << endl;
   if (m4 == *m5) {
       cout << "m4 and m5 are equal" << endl;
   }
   else {
       cout << "m4 and m5 are not equal" << endl;
   }
   cout << "Testing ++ operator on matrix 4:" << endl;
   m4++;
   cout << m4;
   cout << "Testing != " << endl;
   if (m4 != *m5) {
       cout << "m4 and m5 are not equal" << endl;
   }
   else {
       cout << "m4 and m5 are equal" << endl;
   }
   cout << "Adding matrix 4 and 5 to make matrix 6:" << endl;
   Matrix m6 = m4 + *m5;
   cout << m6;
   cout << "Adding matrix 4 to 6: " << endl;
   m6 += m4;
   cout << m6;
   cout << "Testing -- operator on matrix 4:" << endl;
   m4--;
   cout << m4;
   cout << "Substracting matrix 4 from 6:" << endl;
   m6 -= m4;
   cout << m6;
   cout << "making matrix 7 by substracting matrix 4 from 6:" << endl;
   Matrix m7 = m6 - m4;
   cout << m7;
   cout << "matrix 4: " << endl;
   cout << m4;
   cout << "Multiplication of m7 and m4:" << endl;
   m7 *= m4;
   cout << m7;
   cout << "Creating matrix with 2 row and 1 colum:" << endl;
   Matrix m9(2, 1);
   m9.setValue(1, 1, 2);
   m9.setValue(2, 1, 5);
   cout << m9;
   cout << "Multilpication of matrix 4 and 9:" << endl;
   Matrix m10 = m4 * m9;
   cout << m10;
   cout << "Testing clear on matrix 7:" << endl;
   m7.clear();
   cout << m7 << endl;

   return 0;
}

let me know if you have any doubt or problem running code.


Related Solutions

Write and test a C program to implement Bubble Sort. . In your C program, you...
Write and test a C program to implement Bubble Sort. . In your C program, you should do: Implement the array use an integer pointer, get the size of the array from standard input and use the malloc function to allocate the required memory for it. Read the array elements from standard input. Print out the sorted array, and don’t forget to free the memory. Debug your program using Eclipse C/C++ CDT.
C++ Program: Create a 3x3 matrix of int values. Implement five functions, each expecting the matrix...
C++ Program: Create a 3x3 matrix of int values. Implement five functions, each expecting the matrix as parameter input. The first function must use a nested loop to prompt a user to enter each value. Show the indices when prompting for input and populate the matrix with these values. The second function outputs the matrix and formats the output to align all columns and rows to accommodate values up to 1000. The third function finds and returns the minimum value...
For this program you will implement the following utility functions to test mastery of C strings....
For this program you will implement the following utility functions to test mastery of C strings. *******you MUST use these these function***** void removeBlanks(char *src, char *dest); void replaceChar(char *src, char oldChar, char newChar); char *flipCase(const char *src); Please read the description of these functions carefully. In the removeBlanks function you will implement a routine that takes a string in as src and outputs the same string into dest but removing any blank space character encountered. For example, if the...
Please Use C++ to finish as the requirements. Implement a class called SinglyLinkedList. In the main...
Please Use C++ to finish as the requirements. Implement a class called SinglyLinkedList. In the main function, instantiate the SinglyLinkedList class. Your program should provide a user loop and a menu so that the user can access all the operators provided by the SinglyLinkedList class. DestroyList InitializeList GetFirst InsertFirst, InsertLast, Insert DeleteFirst, DeleteLast, Delete IsEmpty Length Print, ReversePrint
For this computer assignment, you are to write a C++ program to implement a class for...
For this computer assignment, you are to write a C++ program to implement a class for binary trees. To deal with variety of data types, implement this class as a template. Most of the public member functions of the BinaryTree class call private member functions of the class (with the same name). These private member functions can be implemented as either recursive or non-recursive, but clearly, recursive versions of these functions are preferable because of their short and simple implementations...
For this computer assignment, you are to write a C++ program to implement a class for...
For this computer assignment, you are to write a C++ program to implement a class for binary trees. To deal with variety of data types, implement this class as a template. Most of the public member functions of the BinaryTree class call private member functions of the class (with the same name). These private member functions can be implemented as either recursive or non-recursive, but clearly, recursive versions of these functions are preferable because of their short and simple implementations...
in C++ Requirements: Write a program that creates a new class called Customer. The Customer class...
in C++ Requirements: Write a program that creates a new class called Customer. The Customer class should include the following private data: name - the customer's name, a string. phone - the customer's phone number, a string. email - the customer's email address, a string. In addition, the class should include appropriate accessor and mutator functions to set and get each of these values. Have your program create one Customer objects and assign a name, phone number, and email address...
C++ tree program (do NOT use STRUCT, use classes)    Program 1 Implement a Binary tree...
C++ tree program (do NOT use STRUCT, use classes)    Program 1 Implement a Binary tree using an array    Program 2 Implement a tree using linked list - pointer Binary Tree    Program 3 - Convert program 1 to a template
JAVA PROGRAM Question : Design and implement two classes called InfixToPostfix and PostFixCalculator. The InfixToPrefix class...
JAVA PROGRAM Question : Design and implement two classes called InfixToPostfix and PostFixCalculator. The InfixToPrefix class converts an infix expression to a postfix expression. The PostFixCalculator class evaluates a postfix expression. This means that the expressions will have already been converted into correct postfix form. Write a main method that prompts the user to enter an expression in the infix form, converts it into postfix, displays the postfix expression as well as it's evaluation. For simplicity, use only these operators,...
Write the following classes: Class Entry: 1. Implement the class Entry that has a name (String),...
Write the following classes: Class Entry: 1. Implement the class Entry that has a name (String), phoneNumber (String), and address (String). 2. Implement the initialization constructor . 3. Implement the setters and getters for all attributes. 4. Implement the toString() method to display all attributes. 5. Implement the equals (Entry other) to determine if two entries are equal to each other. Two entries are considered equal if they have the same name, phoneNumber, and address. 6. Implement the compareTo (Entry...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT