Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "matrix.h"
- Matrix::Matrix(ifstream& input) {
- string inputRow;
- string iString;
- std::stringstream ss;
- while(!input.eof()) {
- vector<long double> newVec;
- getline(input,inputRow);
- std::stringstream ss;
- ss << inputRow;
- while(!ss.eof()) {
- ss >> iString;
- if(iString != "") {
- newVec.push_back(stold(iString));
- }
- ss.flush();
- iString = "";
- }
- if(!newVec.empty()) {
- mat.push_back(newVec);
- }
- }
- }
- void Matrix::transpose(){
- vector<vector<long double> > newVecR;
- vector<long double> newVecC;
- for(uint i = 0; i < mat.size(); ++i) {
- newVecC.push_back(0);
- }
- for(uint i = 0; i < mat[0].size(); ++i) {
- newVecR.push_back(newVecC);
- }
- for(uint i = 0; i < mat.size(); ++i) {
- for(uint j = 0; j < mat[i].size(); ++j) {
- newVecR[j][i] = mat[i][j];
- }
- }
- setMatrix(newVecR);
- }
- Matrix Matrix::operator/(long double denom) {
- vector<long double> newVec;
- Matrix m;
- for (uint i = 0; i < mat.size(); ++i) {
- for(uint j = 0; j < mat[i].size(); ++j){
- newVec.push_back((mat[i][j]/denom));
- }
- m.mat.push_back(newVec);
- newVec.clear();
- }
- return m;
- }
- Matrix Matrix::operator*(Matrix& lhs) {
- if(mat.size() > 0) {
- if(mat[0].size() != lhs.getMatrix().size()) {
- cerr << "Matrix size mismatch." << endl;
- return Matrix();
- }
- }
- long double sum = 0;
- vector<long double> newVec;
- vector<vector<long double> > lhsMat = lhs.getMatrix();
- Matrix m;
- for (uint i = 0; i < mat.size(); ++i) {
- for(uint j = 0; j < lhsMat[0].size(); ++j){
- for(uint k = 0; k < mat[i].size(); ++k){
- sum += mat[i][k]*lhsMat[k][j];
- }
- newVec.push_back(sum);
- sum = 0;
- }
- m.mat.push_back(newVec);
- newVec.clear();
- }
- return m;
- }
- long double Matrix::sum(){
- long double s = 0;
- for(auto r: mat) {
- for (auto c: r) {
- s += c;
- }
- }
- return s;
- }
- vector<vector<long double> > Matrix::getMatrix() {
- return mat;
- }
- void Matrix::setMatrix(vector<vector<long double> > matrix) {
- mat.clear();
- mat = matrix;
- }
- void Matrix::setMatrix(Matrix matrix) {
- mat.clear();
- mat = matrix.getMatrix();
- }
- void Matrix::printMatrix() {
- for (uint i = 0; i < mat.size(); ++i) {
- for(vector<long double>::iterator it = mat[i].begin(); it != mat[i].end(); ++it){
- cout << setprecision(2)<< setw(7) << *it << " ";
- }
- cout << endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement