GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 25-Jan-2007, 22:24
TransformedBG TransformedBG is offline
Member
 
Join Date: Oct 2006
Posts: 118
TransformedBG is on a distinguished road

Multiplying a Matrix???


CPP / C++ / C Code:
Matrix multiply (const Matrix&) const

CPP / C++ / C Code:
Matrix Matrix::multiply(Matrix& matrix) const
{
	int tempRow=0, tempCol=0, tempAns1=0
		tempAns2=0, tempAns=0, answer=0;

		for(;tempRow<rows;tempRow++)
		{
			for(;temCols<cols;tempCol++)
			{
				//takes c2 r1 of element1 and stores them
				tempAns1=(elements[tempCol][tempRow]);

				//takes r2 c1 of element2 and stores them
				tempAns2=(matrix.elements[tempRow][tempCol]);

				//multiplies tempAns1 to tempAns2
				tempAns=tempAns1*tempAns2;

				//takes the answer of that sums total 
				answer=tempAns+answer;
				
				//loop till no more elements
			}
			
			//put answer in new matrix
			matrix[tempRow][tempCol]=answer;
		}

}

Does this seem like the right logic to anyone else? im just currious. I think im on the right path

My logic is this:

i have a matrix:

matrix (1)
01 02 03
04 05 06

X

matrix(2)
01 02 03 04
05 06 07 08
09 10 11 12

=

matrix(3)
[(1x1)+(1x5)+(1x9)] [(1x2)+(1x6)+(1x10)] [(1x3)+(1x7)+(1x11)] [(1x4)+(1x8)+(1x12)]
[(2x1)+(2x5)+(2x9)] [(2x2)+(2x6)+(2x10)] [(2x3)+(2x7)+(2x11)] [(2x4)+(2x8)+(2x12)]
  #2  
Old 26-Jan-2007, 04:07
davis
 
Posts: n/a

Re: Multiplying a Matrix???


You may want to review your operation signature a bit. You are returning a Matrix by value, but you have no return statement in your code. Depending on the size of the Matrix, it may be an issue. We generally expect to return a reference to the Matrix.

Your prototype declares a constant Matrix reference argument, but your impl loses the const modifier.

Your "new matrix" is not declared before it is used, however you are using the variable name of the argument Matrix, which supposedly is going to be (and should be!) const.

"rows" and "cols" are undeclared as well. We can assume that you mean matrix.rows and matrix.cols in your conditional statements.

Usually, instead of: answer=tempAns+answer;
...we'd use: answer += tempAns;

Noting that it is okay to use whitespace between operators, too.


:davis:
  #3  
Old 26-Jan-2007, 06:12
TransformedBG TransformedBG is offline
Member
 
Join Date: Oct 2006
Posts: 118
TransformedBG is on a distinguished road

Re: Multiplying a Matrix???


Quote:
Originally Posted by davis
You may want to review your operation signature a bit. You are returning a Matrix by value, but you have no return statement in your code. Depending on the size of the Matrix, it may be an issue. We generally expect to return a reference to the Matrix.

Your prototype declares a constant Matrix reference argument, but your impl loses the const modifier.

Your "new matrix" is not declared before it is used, however you are using the variable name of the argument Matrix, which supposedly is going to be (and should be!) const.

"rows" and "cols" are undeclared as well. We can assume that you mean matrix.rows and matrix.cols in your conditional statements.

Usually, instead of: answer=tempAns+answer;
...we'd use: answer += tempAns;

Noting that it is okay to use whitespace between operators, too.


:davis:

Yeah i hadnt worked on the return, i was just working out the basic logic of mulitplying two matrices together. But i stopped working on it last night, cause after so long you start hurting code vs helping it. lol.
  #4  
Old 26-Jan-2007, 09:17
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 6,147
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Multiplying a Matrix???


Quote:
Originally Posted by TransformedBG
[c++]
Does this seem like the right logic to anyone else? im just currious. I think im on the right path

My logic is this:
.
.
.

i have a matrix:

matrix (1)
01 02 03
04 05 06

X

matrix(2)
01 02 03 04
05 06 07 08
09 10 11 12

=

matrix(3)
[(1x1)+(1x5)+(1x9)] [(1x2)+(1x6)+(1x10)] [(1x3)+(1x7)+(1x11)] [(1x4)+(1x8)+(1x12)]
[(2x1)+(2x5)+(2x9)] [(2x2)+(2x6)+(2x10)] [(2x3)+(2x7)+(2x11)] [(2x4)+(2x8)+(2x12)]
The math is wrong. That is not how matrix multiplication is defined.


In general if a is an m x k matrix

and

b is a k x n

then

the product is an m x n matrix, and I show the calculations below. (You got the dimensions correct, but not the calculations.)

Example a is 2 x 3 and b is 3 x 4


Code:
+- -+ | 1 2 3 | a = | | | 4 5 6 | +- -+

In the usual C matrix notation:
Code:
a[0][0] = 1 a[0][1] = 2 a[0][2] = 3 a[1][0] = 4 a[1][1] = 5 a[1][2] = 6

Code:
+- -+ | 7 8 9 10 | | | b = |11 12 13 14 | | | |15 16 17 18 | +- -+

Code:
b[0][0] = 7 b[0][1] = 8 . . . b[2][3] = 18

Let c = the matrix product of a x b

Then c will be a 2 x 4 matrix:

Code:
+- -+ | c[0][0] c[0][1] c[0][2] c[0][3] | | | c = | | | c[1][0] c[1][1] c[1][2] c[1][3] | +- -+

Calculations for the elements of c are like this:
Code:
c[0][0] = a[0][0] * b[0][0] + a[0][1] * b[1][0] + a[0][2] * b[2][0] c[0][1] = a[0][0] * b[0][1] + a[0][1] * b[1][1] + a[0][2] * b[2][1]
.
.
and, in general for each i, j:
Code:
c[i][j] = sum over k of a[i][k] * b[k][j]

For example:
Let arows be equal to the number of rows of a
Let acols be equal to the number of columns of a
Let bcols be equal to the number of columns of b
Notes:

1. The number of columns of a must be equal to the number of rows of b.

2. The number of rows of c is equal to the number of rows of a

3. The number of columns in c is equal to the number of columns in

That's the math; here's the logic:

Code:
Make a loop that lets i go from 0 up to and including arows-1 Make a loop that lets j go from 0 up to and including bcols-1 set c[i][j] = 0 Make a loop that lets k go from 0 up to and including acols-1 add a[i][k] * b[k][j] to c[i][j] End of k loop End of j loop End of i loop

For my example, I think the product goes like this:
Code:
a[0][0] = 1 a[0][1] = 2 a[0][2] = 3 a[1][0] = 4 a[1][1] = 5 a[1][2] = 6 b[0][0] = 7 b[0][1] = 8 b[0][2] = 9 b[0][3] = 10 b[1][0] = 11 b[1][1] = 12 b[1][2] = 13 b[1][3] = 14 b[2][0] = 15 b[2][1] = 16 b[2][2] = 17 b[2][3] = 18 c[0][0] = 74 c[0][1] = 80 c[0][2] = 86 c[0][3] = 92 c[1][0] = 173 c[1][1] = 188 c[1][2] = 203 c[1][3] = 218
But: Don't take my word for it! Work out your own example and make sure your program agrees with your known calculations.

I suggest that you make a standalone program that you can use to test the matrix calculations and throroughly test it. Then you can try putting it your real application (class function definition, or whatever).

My sequence for program development alway puts functionality first: Make sure you can get the right answer!

Regards,

Dave
Last edited by davekw7x : 26-Jan-2007 at 10:07.
  #5  
Old 26-Jan-2007, 11:01
TransformedBG TransformedBG is offline
Member
 
Join Date: Oct 2006
Posts: 118
TransformedBG is on a distinguished road

Re: Multiplying a Matrix???


woops your right, it should have been:

Quote:
i have a matrix:

matrix (1)
01 02 03
04 05 06

X

matrix(2)
01 02 03 04
05 06 07 08
09 10 11 12

=

matrix(3)
[(1x1)+(2x5)+(3x9)] [(1x2)+(2x6)+(3x10)] [(1x3)+(2x7)+(3x11)] [(1x4)+(2x8)+(3x12)]
[(4x1)+(5x5)+(6x9)] [(4x2)+(5x6)+(6x10)] [(4x3)+(5x7)+(6x11)] [(4x4)+(5x8)+(6x12)]
  #6  
Old 26-Jan-2007, 11:37
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 6,147
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Multiplying a Matrix???


Quote:
Originally Posted by TransformedBG
woops your right, it should have been:
OK.

I gave what I think is a good logic sequence for multiplying two matrices. Does your logic agree? It seems to me that for every element in the product matrix we need a loop that adds some stuff.

That makes a total of three loops:

1. One loop steps through the rows of the result
2. For each row of the result a loop steps through the columns of the result
3. An inner loop adds the product terms of left-hand row and right-hand column
elements to obtain the value of each element of the result.
If you had defined a function that would, somehow, allow multiplication of vectors consisting of a row of the left-hand matrix and a column of the right-hand matrix, then the innermost loop could have been hidden in it, but I don't see any way, in general, to multiply two matrices with two loops.

Other programming languages may multiply matrices with no loops in the user program, but internally, they have loops. That's what you are doing with your Matrix class multiplication member function: making it easy for an application program to multiply matrix objects so that the user program doesn't have those messy and error-prone loops.

Furthermore, the loop for going through the columns needs to be re-initialized for each row, doesn't it? In general I can't see any advantage in using something like this, as you do in your program:

CPP / C++ / C Code:

int tempcols = 0;
.
.
.
    for (;tempcols < xxxx; tempcols++)
    {
.
.
.

I would rather use the following:

CPP / C++ / C Code:
    int tempcols;
.
.
.
    for (tempcols = 0; tempcols < xxxx; tempcols++)
    {
.
.
.

Or, in some cases the following may be appropriate:
CPP / C++ / C Code:
    for (int tempcols = 0; tempcols < xxxx; tempcols++)
    {
.
.
.
If you were only going to execute that loop one time, then my objection would be a matter of style not substance, and if you wanted to do it your way instead of mine, then it would be your decision to make. (And to defend in a design review.)

However, since this loop, in this program, can be traversed multiple times, it won't work your way. It will either crash as you try to go beyond the end of the array or it will give the wrong answer.

Regards,

Dave
  #7  
Old 26-Jan-2007, 20:11
TransformedBG TransformedBG is offline
Member
 
Join Date: Oct 2006
Posts: 118
TransformedBG is on a distinguished road

Re: Multiplying a Matrix???


My matrix.cpp
CPP / C++ / C Code:
#include "Matrix.h"

//initializes matrixCount to 0
int Matrix::matrixCount=0;

Matrix::Matrix(int r=0, int c=0)
{
	matrixCount++;
	this -> rows = r;
	this -> cols = c;
	element = NULL;
	if(rows*cols > 0 && cols > 0)
	{
		element = new int* [rows];
		for(int r1=0; r1<rows; r1++)
		{
			element[r1] = new int[cols];
		}
	}
}


Matrix::Matrix(const Matrix& m)
{
	matrixCount++;
	rows = m.rows;
	cols = m.cols;

	if(rows > 0 && cols > 0)
	{
		element = new int* [rows];
		for(int r=0; r<rows; r++)
		{
			element[r] = new int [cols];
		}

		for(int r1 = 0; r1 < rows; r1++)
		{
			for(int c = 0; c <= cols; c++)
				{
					element[r1][c] = m.element[r1][c];
				}
		}
	}
}


Matrix::~Matrix()
{
	delete [] element;
}



Matrix Matrix::operator=(Matrix& m)
{
	delete[] element;
	rows=m.rows;
	cols=m.cols;
	element=NULL;
	for(int i=0; i<rows; i++)
	{
		element[rows][cols]=m.element[rows][cols];
	}
	return *this;
}


int Matrix::getRows() const
{
	return rows;
}


int Matrix::getColumns() const
{
	return cols;
}

int* Matrix::operator [](int n)
{
	return element[n];
}


int Matrix::getElement(int r, int c) const
{
	return element[r][c];
}

void Matrix::setElement(int r, int c, int v)  const 
{
	//sets v to the meaning of element[r][c] 
	v = element[r][c]; 
}

Matrix Matrix::add(const Matrix& m) const
{
	//matrix to be returned
	Matrix newMatrix(rows, m.cols);
 	return newMatrix;
}

Matrix Matrix::subtract(const Matrix& m) const
{
	//matrix to be returned
	Matrix newMatrix (rows, m.cols);
	return newMatrix;
}

Matrix Matrix::multiply(const Matrix& m) const
{
	//matrix to be returned
	Matrix newMatrix(rows, m.cols); 
 /*
	//row count
 	int tempRow; 

	//col count
 	int tempCol=0, tempCol2; 

	//tempory and final answer
 	int	tempAns=0, tempAns1=0, tempAns2=0, answer=0; 
	
	//counts rows 1
 		for(tempRow = 0;tempRow<rows;tempRow++) 
 		{
			//count cols 1
 			for(tempCol2 =0;tempCol2<matrix.cols;tempCol++)
 			{
 				newMatrix[tempRow][tempCol]		;
 
 				for(;tempCol2<cols;tempCol2++)
 				{
 					//takes c2 r1 of element1 and stores them
 					tempAns1=(element[tempCol][tempRow]);
 
 					//takes r2 c1 of element2 and stores them
 					tempAns2=(matrix.element[tempRow][tempCol]);
 
 					//multiplies tempAns1 to tempAns2
 					tempAns=tempAns1*tempAns2;
 
 					//takes the answer of that sums total 
 					answer=tempAns+answer;
 				
 					//loop till no more elements
 				}
			}
 			
 	}
 */
 	return newMatrix;
}

int Matrix::get_matrixCount()
{	
	return matrixCount;
	
}


My Matrix.h
CPP / C++ / C Code:
#ifndef MATRIX_H
#define MATRIX_H
#include <iostream>
using namespace std;



class Matrix 
{
private:
	//matrix dimensions
	int rows, cols; 

	//element array
	int **element; 

	//declares int matrixCount
	static int matrixCount;
public:
	//default 0x0 matrix
	Matrix(int, int); 

	//copy constructor
	Matrix(const Matrix&); 

	//Destructor
	~Matrix(); 

	//changes the meaning of "="
	Matrix operator=(Matrix&); 

	//changes the meaning of "[]"
	int* operator[](int n);
	
	//returns the number or rows
	int getRows() const; 

	//returns the number of cols
	int getColumns() const; 
	
	//returns the value of the element in r row and c column
	int getElement(int, int) const;

	//store the value (v) in the martix of location r,c
	void setElement(int, int, int) const;

	//return the sum of two matices
	Matrix add (const Matrix&) const;

	//return the diff of two matrices
	Matrix subtract (const Matrix&) const;

	//return the prod or two matricies
	Matrix multiply (const Matrix&) const;

	//return the value of matrixCount
	static int get_matrixCount();

};


#endif

this is the driver my teacher wrote soo i didnt write it:
Quote:
CPP / C++ / C Code:
#include <iostream>
#include <iomanip>
#include "Matrix.h"

using namespace std;

ostream& printMatrix(Matrix m, ostream& out);
void TestFunction1(Matrix, Matrix, Matrix);



int main(void)
{

//check to see if the static variable matrixCount has been created and init

    cout << "matrixCount = " << Matrix::get_matrixCount() << endl;
    cout << "(matrixCount should be zero)\n\n";
    
    
//create 3 matrices, check matrixCount, .and print matrix dimension

    Matrix A(2,3),B(2,3),C(3,3);
    
    A = B;
    
    cout << "Matrix A\n";
    cout << "\t Rows = " << A.getRows()    << endl;
    cout << "\t Cols = " << A.getColumns() << endl;

    cout << "Matrix B\n";
    cout << "\t Rows = " << B.getRows()    << endl;
    cout << "\t Cols = " << B.getColumns() << endl;

    cout << "Matrix C\n";
    cout << "\t Rows = " << C.getRows()    << endl;
    cout << "\t Cols = " << C.getColumns() << endl;


    cout << endl;
    cout << "matrixCount = " << Matrix::get_matrixCount() << endl;
    cout << "(matrixCount should be three (3))\n\n";
  
//Test the copy constructor and destructor
    cout << endl;
    cout << "matrixCount = " << Matrix::get_matrixCount() << endl;
    cout << "(before call the TestFunction1)\n\n";

    TestFunction1(A,B,C);
    
    cout << endl;
    cout << "matrixCount = " << Matrix::get_matrixCount() << endl;
    cout << "(after call the TestFunction1)\n\n";
    
 
//create some data arrays

	int row, col, index;
	int data1[]={1,2,3,4,5,6};
	int data2[]={10,20,30,40,50,60};
	int data3[]={-5,-10,-15,0,5,10,15,36,42};
	
	

//Fill Matricies A, B will initial values
//Test setElement
	index = 0;
	for(row = 0; row < 2; row++)
	  for(col = 0 ; col < 3; col++)
	  {
	    A.setElement(row, col, data1[index]);
	    B.setElement(row,col,data2[index]);
	    index++;
	  }

//Fill Matricies C will initial values
//Test overloaded []
    index = 0;
	for(row = 0; row < 3; row++)
	  for(col = 0 ; col < 3; col++)
	  {
	    //C.setElement(row, col, data3[index++]);
	    C[row][col] = data3[index++];
	  }


//Print Matricies A, B, C

	cout<<"Matrix A\n\n";
	printMatrix(A,cout);
    cout << endl << endl;
    
	cout<<"Matrix B\n\n";
	printMatrix(B,cout);
    cout << endl << endl;
    
	cout<<"Matrix C\n\n";
	printMatrix(C,cout);
    cout << endl << endl;
    
   

//Addition

	cout<<"Matrix A + B\n\n";
	printMatrix(A.add(B),cout);
    cout << endl << endl;
    



//Test Subtraction

	cout<<"Matrix A - B\n\n";
	printMatrix(A.subtract(B),cout);
    cout << endl << endl;
    



//Test Multiplication	
    
 	cout<<"Matrix A * C\n\n";
	printMatrix(A.multiply(C),cout);
    cout << endl << endl;
    
 
	return 0;
}




//Function to print a Matrix
ostream& printMatrix(Matrix m, ostream& out)
{
    int row, col;
    int r,c;
    
    row = m.getRows();
    col = m.getColumns();
  
  	for(r = 0; r < row; r++)
	{
	  for(c = 0 ; c < col; c++)
	    out <<setw(4)<< m.getElement(r, c)<<" ";
	  out<<endl;
	}

    return out;
}


//Test Function 1, test copy constructor
void TestFunction1(Matrix x, Matrix y, Matrix z)
{
    cout << endl;
    cout << "matrixCount = " << Matrix::get_matrixCount() << endl;
    cout << "(In TestFunction1)\n\n";
  
   return;
}

okay so i have nooo idea what i did wrong, but i think it has something to do with my Constructor and/or copy constructor. But im getting an error after i go to copy a constructor i believe. Im not worried about the addition, subtraction or multiplication right now, just want to get it working. Can anyone see where i screwed up?
  #8  
Old 26-Jan-2007, 20:26
TransformedBG TransformedBG is offline
Member
 
Join Date: Oct 2006
Posts: 118
TransformedBG is on a distinguished road

Re: Multiplying a Matrix???


After reviewing i think my problem actully is in the overloading in the "=" sign

any suggestions?
  #9  
Old 26-Jan-2007, 23:16
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 6,147
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Multiplying a Matrix???


Quote:
Originally Posted by TransformedBG
After reviewing i think my problem actully is in the overloading in the "=" sign

any suggestions?

Make the program tell you how far it got:

CPP / C++ / C Code:
    cout << "matrixCount = " << Matrix::get_matrixCount() << endl;
    cout << "(matrixCount should be zero)\n\n";


//create 3 matrices, check matrixCount, .and print matrix dimension

    Matrix A(2, 3), B(2, 3), C(3, 3);

    cout << "Before assignment" << endl;

    A = B;
    cout << "After assignment" << endl;
    

If it seems to be crashing here, then go into the operator function and look at the code. If you still don't see it, put some cout statements to see how far it gets there.

What is the assignment operator supposed to do? What is it doing?

Regards,
Last edited by davekw7x : 27-Jan-2007 at 00:27.
  #10  
Old 27-Jan-2007, 10:02
TransformedBG TransformedBG is offline
Member
 
Join Date: Oct 2006
Posts: 118
TransformedBG is on a distinguished road

Re: Multiplying a Matrix???


Yeah this leads me to think the problem lays in:
CPP / C++ / C Code:
Matrix Matrix::operator=(Matrix& m)
{
	delete[] element;
	rows=m.rows;
	cols=m.cols;
	element=NULL;
	for(int i=0; i<rows; i++)
	{
		element[rows][cols]=m.element[rows][cols];
	}
	return *this;
}

So im thinking it needs to be more like:
CPP / C++ / C Code:
Matrix Matrix::operator=(Matrix& m)
{
	delete[] element;
	rows=m.rows;
	cols;m.cols;
	element = new int* [rows];

	for(int row = 0; row<rows; row++)
	{
		element[row] = new int [cols];

		for(int cCol= 0; cCol<cols; cCol++)
		{
			element[row][cCol]=m.element[row][cCol];
		}
	}


	return *this;
}
but im coping arbitrary trash in to it now.
 
 

Recent GIDBlogCompress Your Web Site by gidnetwork

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Need Help... A small problem with allocating memory Cristovao C++ Forum 4 17-Jan-2007 15:17
i need help in C++ PLZ its_me C++ Forum 3 04-Dec-2006 21:51
how to initialize a char matrix matrix with empty elements? swedenguy C Programming Language 4 22-Aug-2006 11:43
debugging multi-dimensional vector/ matrix class counterflow C++ Forum 1 15-Mar-2006 12:14
Combining Vectors and References Frankg C++ Forum 7 14-Jan-2006 06:17

Network Sites: GIDNetwork · GIDApp · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 09:26.


vBulletin, Copyright © 2000 - 2013, Jelsoft Enterprises Ltd.