russo mike matrix mult

5
typescript Fri Dec 09 22:09:51 2011 1 Script started on Fri 09 Dec 2011 10:05:16 PM CST \033]0;m_russo9@mars:˜\007[m_russo9@mars ˜]$ pwd /home/students/m_russo9 \033]0;m_russo9@mars:˜\007[m_russo9@mars ˜]$ pwd exit cat String_ArgumentTPQ1-3.tpq [m_russo9@mars ˜]$ \033[9P./stringargument.out \033[2PCPP stringargument cat stringargument.cpp \033[1PStringArguments.h stringarguments.info [m_russo9@mars ˜]$ pwd\033[K exit cat StringArguments.h stringarguments.info [m_russo9@mars ˜]$ pwd\033[K exit cat common_functions.cpp stringarguments.info \033[1P.info [m_russo9@mars ˜]$ pwd\033[K exit cat String_ArgumentTPQ1-3.tpq [m_russo9@mars ˜]$ \033[9P./stringargument.out \033[2PCPP stringarguments cat stringargument.cpp \033[1PStringArguments.h stringarguments.info [m_russo9@mars ˜]$ pwd\033[K exit cat stringarguments.info [m_russo9@mars ˜]$ pwd\033[K exit\033[K\033[K\033[K\033[K\007\007cat Matrix.info ******************************************************************************* * * Name: Mike Russo * * Date: 12/09/11 * * Level 3: Matrix Multiplation Lab * * Levels Attempted: * * Base: 3.5 * * Total: 3.5 * * Description: This assignment is a combination of strings, classes, and * 2D vectors, designed to multiply two matrices. I included some extra * functions in case a user wants any of the other three basic math * functions at a later date, even though this was not a level-earning * option. * ******************************************************************************* \033]0;m_russo9@mars:˜\007[m_russo9@mars ˜]$ cat common_fincti\033[K \033[K \033[K \033[K \033[ Kunctions.cppp\033[K #include <iostream> #include <string> #include <sstream> #include <vector> using namespace std; vector<string> &split(const string &s, char delim, vector<string> &elems) { stringstream ss(s); string item; while (getline(ss, item, delim)) { elems.push_back(item); } return elems; } vector<string> split(const string &s, char delim) { vector<string> elems; return split(s, delim, elems); } //function to check if a given string //meets our vector format (3x4, etc) bool isValidFormat(string str) { //split the string on the X std::vector<std::string> my_vec = split(str, ’x’); //if there are less than two elements then return false if ( my_vec.size() < 2) { return false; } /* //if both elements aren’t integers then return false int height = atoi( my_vec.at(0).c_str() ); int width = atoi( my_vec.at(1).c_str() ); if( !isdigit(height) || !isdigit(width)){ return false; } */ //if we got here we can return true return true; } void askYesNoQuestion() { string input_string = ""; cout << "Are you having a nice day? Enter Y or N :\n>"; //save the input into a variable getline(cin, input_string); //if they entered Y if (input_string == "Y") { cout << "I am glad you are having a nice day." << endl << endl; } else { cout << "I am sorry you are not having a nice day." << endl << endl; } } void askNumHigherThanZero() { int myNumber = 0; string input_string = ""; while (true) { cout << "Please enter a valid number greater than zero: "; getline(cin, input_string); //convert from string to number stringstream myStream(input_string); //make sure the conversion took and that the arg is greater than zero if ( (myStream >> myNumber) && ( atoi(input_string.c_str() ) > 0)) { break; } //try again cout << "Invalid number, please try again" << endl; } cout << "You entered a valid number: " << myNumber << endl << endl; } void askNumBetweenOneAndOneHundred() { int myNumber = 0; string input_string = ""; while (true) { cout << "Please enter a valid number between 1 and 100: "; getline(cin, input_string); //convert from string to number stringstream myStream(input_string); //make sure the conversion took if ( (myStream >> myNumber) && (atoi(input_string.c_str() ) > 0) && ( atoi(input_string.c_str() ) < 100) ) { break; } //try again

Upload: mfr1003

Post on 30-Sep-2014

29 views

Category:

Documents


1 download

DESCRIPTION

This is a matrix multiplication program I wrote. it is primed for addition, subtraction, and division as well.

TRANSCRIPT

Page 1: Russo Mike Matrix Mult

typescript Fri Dec 09 22:09:51 2011 1

Script started on Fri 09 Dec 2011 10:05:16 PM CST\033]0;m_russo9@mars:˜\007[m_russo9@mars ˜]$ pwd/home/students/m_russo9\033]0;m_russo9@mars:˜\007[m_russo9@mars ˜]$ pwdexitcat String_ArgumentTPQ1-3.tpq[m_russo9@mars ˜]$ \033[9P./stringargument.out\033[2PCPP stringargumentcat stringargument.cpp\033[1PStringArguments.hstringarguments.info[m_russo9@mars ˜]$ pwd\033[Kexitcat StringArguments.hstringarguments.info[m_russo9@mars ˜]$ pwd\033[Kexitcat common_functions.cppstringarguments.info\033[1P.info[m_russo9@mars ˜]$ pwd\033[Kexitcat String_ArgumentTPQ1-3.tpq[m_russo9@mars ˜]$ \033[9P./stringargument.out\033[2PCPP stringargumentscat stringargument.cpp\033[1PStringArguments.hstringarguments.info[m_russo9@mars ˜]$ pwd\033[Kexitcat stringarguments.info[m_russo9@mars ˜]$ pwd\033[Kexit\033[K\033[K\033[K\033[K\007\007cat Matrix.info********************************************************************************* Name: Mike Russo** Date: 12/09/11** Level 3: Matrix Multiplation Lab ** Levels Attempted:** Base: 3.5** Total: 3.5** Description: This assignment is a combination of strings, classes, and * 2D vectors, designed to multiply two matrices. I included some extra* functions in case a user wants any of the other three basic math* functions at a later date, even though this was not a level-earning* option. ********************************************************************************

\033]0;m_russo9@mars:˜\007[m_russo9@mars ˜]$ cat common_fincti\033[K\033[K\033[K\033[K\033[Kunctions.cppp\033[K#include <iostream>#include <string>#include <sstream>#include <vector>

using namespace std;

vector<string> &split(const string &s, char delim, vector<string> &elems){ stringstream ss(s); string item; while (getline(ss, item, delim)) { elems.push_back(item); } return elems;}vector<string> split(const string &s, char delim){ vector<string> elems; return split(s, delim, elems);}//function to check if a given string//meets our vector format (3x4, etc)bool isValidFormat(string str){//split the string on the X std::vector<std::string> my_vec = split(str, ’x’); //if there are less than two elements then return false if ( my_vec.size() < 2) { return false; } /* //if both elements aren’t integers then return false int height = atoi( my_vec.at(0).c_str() );

int width = atoi( my_vec.at(1).c_str() ); if( !isdigit(height) || !isdigit(width)){ return false; } */ //if we got here we can return true return true;}

void askYesNoQuestion(){ string input_string = ""; cout << "Are you having a nice day? Enter Y or N :\n>"; //save the input into a variable getline(cin, input_string); //if they entered Y if (input_string == "Y") { cout << "I am glad you are having a nice day." << endl << endl; } else { cout << "I am sorry you are not having a nice day." << endl << endl; }}

void askNumHigherThanZero(){ int myNumber = 0; string input_string = ""; while (true) { cout << "Please enter a valid number greater than zero: "; getline(cin, input_string); //convert from string to number stringstream myStream(input_string); //make sure the conversion took and that the arg is greater than zero if ( (myStream >> myNumber) && ( atoi(input_string.c_str() ) > 0)) { break; } //try again cout << "Invalid number, please try again" << endl; } cout << "You entered a valid number: " << myNumber << endl << endl;}

void askNumBetweenOneAndOneHundred(){ int myNumber = 0; string input_string = ""; while (true) { cout << "Please enter a valid number between 1 and 100: "; getline(cin, input_string); //convert from string to number stringstream myStream(input_string); //make sure the conversion took if ( (myStream >> myNumber) && (atoi(input_string.c_str() ) > 0) && (atoi(input_string.c_str() ) < 100) ) { break; } //try again

Page 2: Russo Mike Matrix Mult

typescript Fri Dec 09 22:09:51 2011 2

cout << "Invalid number, please try again" << endl; } cout << "You entered a valid number: " << myNumber << endl << endl;}

\033]0;m_russo9@mars:˜\007[m_russo9@mars ˜]$ s\033[Kcat matrix.h//this is matrix.husing namespace std;class matrix{public: matrix(); matrix(int m, int n); int getRow(); int getCol(); double& operator()(int, int); //the operator used in the matrix class which are (addition operator, multiplication operator,substraction operator, and divide operator). friend ostream& operator<<(ostream& os, matrix& m); matrix operator + (matrix&); matrix operator * (matrix&); matrix operator - (matrix&); matrix operator / (matrix&);private: void init(int, int); int nrows, ncols; double *data;};matrix::matrix(){ init(1, 1);}matrix::matrix(int m, int n){ init(m, n);}//destructor to delete the used dynamic memory.void matrix::init(int m, int n){ nrows = m; ncols = n; data = new double[m*n]; for (int i = 0; i < m*n; i++) data[i] = 0;}int matrix::getRow(){ return nrows;}int matrix::getCol(){ return ncols;}double& matrix::operator ()(int r, int c){ if (r < 0 || r > nrows) { cout << "Illegal row index"; return data[0]; } else if (c < 0 || c > ncols) { cout << "Illegal Column Index:"; return data[0];

} else return data[r*ncols+c];}ostream& operator<<(ostream& os, matrix &m){ int mval = m.getRow(); int nval = m.getCol(); for (int i = 0; i < mval; i++) { for (int j = 0; j < nval; j++) os << m(i, j) << " "; os << endl; } return os;}//To compute the summationmatrix matrix::operator+(matrix& a){ matrix sum(nrows, ncols); for (int i = 0; i < nrows; i++) for (int j = 0; j < ncols; j++) sum(i, j) = (i, j) + a(i, j); return sum;}//To compute the multiplicationmatrix matrix::operator*(matrix& a){ matrix product(nrows, ncols); for (int i = 0; i < nrows; i++) for (int j = 0; j < ncols; j++) product(i, j) = (i, j) * a(i, j); return product;}//To compute the substractionmatrix matrix::operator-(matrix& a){ matrix difference(nrows, ncols); for (int i = 0; i < nrows; i++) for (int j = 0; j < ncols; j++) difference(i, j) = (i, j) - a(i, j); return difference;}//To compute the divisionmatrix matrix::operator/(matrix& a){ matrix divide(nrows, ncols); for (int i = 0; i < nrows; i++) for (int j = 0; j < ncols; j++) divide(i, j) = (i, j) / a(i, j); return divide;}

\033]0;m_russo9@mars:˜\007[m_russo9@mars ˜]$ cat matrix_mult.cpp#include <iostream>#include <string>#include <sstream>#include <vector>#include"common_functions.cpp"#include "matrix.h"using namespace std;int main(){ string input_string = ""; ///////////////////////////////////////

Page 3: Russo Mike Matrix Mult

typescript Fri Dec 09 22:09:51 2011 3

/////////////////////////////////////// //MATRIX 1 //make sure they entered a number, an x, and a number while (true) { cout << "Please enter the size of your first matrix: "; getline(cin, input_string); //convert from string to number stringstream myStream(input_string); //make sure the conversion took if ( isValidFormat(input_string) ) { break; } //try again cout << "Invalid matrix format, please try again" << endl; } //now we can split the string on the X and examine the values //to convert to pig latin, we will first split up the line on spaces std::vector<std::string> mat_vector = split(input_string, ’x’); //here’s the first number string str1 = mat_vector.at(0); //convert to int int height = atoi( str1.c_str() ); //cout << "height is: " << height << endl << endl; //second number string str2 = mat_vector.at(1); //convert to int int width = atoi( str2.c_str() ); //////////////////////// //here we can make sure each number is //within a certain range or whatever //////////////////////// //////////////// //create the first matrix object matrix matrix1(height, width); //////////////// //create a loop to fill to iterate the //same number of times as their height for (int i = 0; i < height; i++) { //a nested loop to populate this row for (int j = 0; j < width; j++) { cout << "Enter the next number for row: " << (i + 1) << endl << endl; //get the input getline(cin, input_string); //convert the string and add the value to the matrix int my_int = atoi( input_string.c_str() ); matrix1(i, j) = my_int; } } /////////////////////////////////////// /////////////////////////////////////// /////////////////////////////////////// /////////////////////////////////////// //MATRIX 2 //make sure they entered a number, an x, and a number while (true) { cout << "Please enter the size of your second matrix: "; getline(cin, input_string); //convert from string to number

stringstream myStream(input_string); //make sure the conversion took if ( isValidFormat(input_string) ) { break; } //try again cout << "Invalid matrix format, please try again" << endl; } //now we can split the string on the X and examine the values //to convert to pig latin, we will first split up the line on spaces mat_vector = split(input_string, ’x’); //here’s the first number str1 = mat_vector.at(0); //convert to int height = atoi( str1.c_str() ); //cout << "height is: " << height << endl << endl; //second number str2 = mat_vector.at(1); //convert to int width = atoi( str2.c_str() ); //////////////////////// //here we can make sure each number is //within a certain range or whatever //////////////////////// //////////////// //create the first matrix object matrix matrix2(height, width); //////////////// //create a loop to fill to iterate the //same number of times as their height for (int i = 0; i < height; i++) { //a nested loop to populate this row for (int j = 0; j < width; j++) { cout << "Enter the next number for row: " << (i + 1) << endl << endl; //get the input getline(cin, input_string); //convert the string and add the value to the matrix int my_int = atoi( input_string.c_str() ); matrix2(i, j) = my_int; } } //create a new matrix and do the multiplication matrix matrix3 = (matrix1 * matrix2); cout << "matrix matrix1*matrix2\n"; cout << matrix3 << endl; cout << "all done!" << endl; return 0;}

\033]0;m_russo9@mars:˜\007[m_russo9@mars ˜]$ CPP matric\033[Kx_multmatrix_mult.cpp***In file included from matrix_mult.cpp:5:common_functions.cpp:14: instantiated from herecommon_functions.cpp:14: instantiated from herecommon_functions.cpp:14: instantiated from hereIn file included from matrix_mult.cpp:6:matrix.h:4: warning: ‘class matrix’ has pointer data membersmatrix.h:4: warning: but does not override ‘matrix(const matrix&)’matrix.h:4: warning: or ‘operator=(const matrix&)’matrix.h: In constructor ‘matrix::matrix()’:

Page 4: Russo Mike Matrix Mult

typescript Fri Dec 09 22:09:51 2011 4

matrix.h:23: warning: ‘matrix::nrows’ should be initialized in themember initialization listmatrix.h:23: warning: ‘matrix::ncols’ should be initialized in themember initialization listmatrix.h:23: warning: ‘matrix::data’ should be initialized in themember initialization listmatrix.h: In constructor ‘matrix::matrix(int, int)’:matrix.h:27: warning: ‘matrix::nrows’ should be initialized in themember initialization listmatrix.h:27: warning: ‘matrix::ncols’ should be initialized in themember initialization listmatrix.h:27: warning: ‘matrix::data’ should be initialized in themember initialization listmatrix.h: In member function ‘matrix matrix::operator+(matrix&)’:matrix.h:79: warning: left-hand operand of comma has no effectmatrix.h: In member function ‘matrix matrix::operator*(matrix&)’:matrix.h:88: warning: left-hand operand of comma has no effectmatrix.h: In member function ‘matrix matrix::operator-(matrix&)’:matrix.h:97: warning: left-hand operand of comma has no effectmatrix.h: In member function ‘matrix matrix::operator/(matrix&)’:matrix.h:106: warning: left-hand operand of comma has no effectcommon_functions.cpp:14: instantiated from herecommon_functions.cpp:21: instantiated from here

\033]0;m_russo9@mars:˜\007[m_russo9@mars ˜]$ ./matric\033[Kx_mult.outPlease enter the size of your first matrix: 3x5Enter the next number for row: 1

3Enter the next number for row: 1

4Enter the next number for row: 1

56Enter the next number for row: 1

87Enter the next number for row: 1

32Enter the next number for row: 2

21Enter the next number for row: 2

34Enter the next number for row: 2

1Enter the next number for row: 2

2Enter the next number for row: 2

34Enter the next number for row: 3

56Enter the next number for row: 3

6Enter the next number for row: 3

54Enter the next number for row: 3

43Enter the next number for row: 3

4Please enter the size of your second matrix: 4Invalid matrix format, please try againPlease enter the size of your second matrix: 4Invalid matrix format, please try againPlease enter the size of your second matrix: 45Invalid matrix format, please try againPlease enter the size of your second matrix: 4x4 5x4Enter the next number for row: 1

21Enter the next number for row: 1

32Enter the next number for row: 1

32Enter the next number for row: 1

45Enter the next number for row: 2

35Enter the next number for row: 2

2Enter the next number for row: 2

2Enter the next number for row: 2

2Enter the next number for row: 3

3Enter the next number for row: 3

3Enter the next number for row: 3

3Enter the next number for row: 3

2Enter the next number for row: 4

3Enter the next number for row: 4

3Enter the next number for row: 4

3Enter the next number for row: 4

2Enter the next number for row: 5

Page 5: Russo Mike Matrix Mult

typescript Fri Dec 09 22:09:51 2011 5

3Enter the next number for row: 5

Enter the next number for row: 5

2Enter the next number for row: 5

23matrix matrix1*matrix20 32 64 135 140 0 2 4 6 12 0 3 6 6 12

all done!\033]0;m_russo9@mars:˜\007[m_russo9@mars ˜]$ 2bash: 2: command not found\033]0;m_russo9@mars:˜\007[m_russo9@mars ˜]$ 2bash: 2: command not found\033]0;m_russo9@mars:˜\007[m_russo9@mars ˜]$ 3bash: 3: command not found\033]0;m_russo9@mars:˜\007[m_russo9@mars ˜]$ 3\033[K\007\007cat matrix\033[1P\007\007\007\007\033[4h˜\033[4l\007\007\007\033[4h[\033[4l\033[4hA\033[4lbash: ˜[Aat: command not found\033]0;m_russo9@mars:˜\007[m_russo9@mars ˜]$ cat Matrix.tpqThought Provoking Questions - Matrix

1 How can you test force them to enter a valid dimension for their matrix -- not letting the program continue without a usable size?

ANSWER: As you can see, in this function, the number of rows is controlled by fail-falsifying branches.The two accessors above it in the library access the nrows and ncols values, and then we compare r and c to those values for valid responses, as shown:

double& matrix::operator ()(int r, int c){ if (r < 0 || r > nrows) { cout << "Illegal row index"; return data[0]; } else if (c < 0 || c > ncols) { cout << "Illegal Column Index:"; return data[0]; } else return data[r*ncols+c];}

How can you read in their matrix values row by row?

ANSWER: Use a serious of statements involving the array to integer (atoi) function. Not common in c++,but still legal, if you read it into a string, then turn that string into an integer.

How can you test whether each of the possible orderings is valid or not? (Hint: There are 4 orderings: f*f, f*s, s*f, s*s. Where f is the first matrix and s the second.)

How can you be sure that if the two matrices fit that their products will also fit in your maximum dimensions? Is there something you should do with your maximum dimensions to make this work?

How exactly does matrix multiplication work again? For each ____ of the left-hand matrix, I multiply element-wise by the ____ of the right-hand matrix -- summing the results and placing it in the answer matrix. Then I proceed through each such pair of ____ and ____. Hmm...Oh, yeah...

ANSWER:To find this multiply matrices, you have to compute each entry in the third matrix one at a time. So to find the entry (a,b) in the third matrix, you take the sum of the products of the elements in the ath row in the first matrix and the bth column in second matrix. Suppose the ath row equals [a1,a2,...,an] and the bth column equals [b1,b2,...,bn]. Then we can compute every entry (a,b) of the third matrix as (a,b) = a1*b1 + a2*b2 + ... + an*bn.

How many loops are implied by the matrix multiplication traversal pattern? (Hint: There are at least 2 since matrices are 2D...)

How can you print a 2D vector row by row?

ANSWER: The &ostream. will display a matrix. This is one way:

bool Matrix::display(ostream &out[]){ bool rv=init; if(init=true) { for(int r=0,r<rows;r++) { for (int c=0,c<cols;c++) { cout.width(10); cout.percision(2); cout.setf(ios::fixed); cout.ios::showpoint); cout<<matrix[r][c]; }

cout<<endl; } } return rv;}&

later, pass the resultant matrix through this member function.

How many answer matrices do you need? There are four possible orderings, each of which would give its own answer. But do you need them all at once?

ANSWER:There is only one answer matrix. It is the result of M1xM2.

\033]0;m_russo9@mars:˜\007[m_russo9@mars ˜]$ exot\033[K\033[Kitexit

Script done on Fri 09 Dec 2011 10:09:51 PM CST