Click here to Skip to main content
15,881,172 members
Articles / Programming Languages / C++
Article

Matrix Calculator

Rate me:
Please Sign up or sign in to vote.
2.84/5 (16 votes)
8 Sep 20064 min read 151.3K   7.3K   36   18
An article on complex numbers and matrix functions.

Image 1

Image 2

Introduction

Matrixes are useful for so many things. My code demonstrates a small part of it, like solving sets of many equations, finding connections between vectors, multiplying, adding matrixes, and more. I thought that it will be most useful if matrixes wouldl come with the ability to handle complex numbers as well as rationals. I have split the code to the following headers to make it more simple: the main part RationalComlpexMatrix is based on the RationalComplex class, that is based on the Rational class, and the power of RationalComplexMatrix class is demonstrated in the RationalComplexMatrixCalculator class. The full documentation is included.

Background

Basics of matrixes:

The entire matrixes operations are based on the Gauss ranking method, here is a simple example for a set of equations:

 x1+2x2=4,  2x1=3  can be written:
{ 1 2 4}
{ 2 0 3}
  x1 x2 b 

As you can see, the first column is x1's, the second is x2's, and the third (b) belongs to the solution part. Gauss said that one can use elementary rows or cols actions on cols and rows, and still keep the basic form of the equation set. I may multiply row, col with a scalar value (rational non-zero value number), add a row to another row, or col to other col. Let's do r2(row 2) /-2 -> now r2 is: (-1, 0, -3/2) and add it to r1. Now, we'll do r2*(-1):

{1 0 3/2} 

Next, we will do r1 /2 or r1*(1/2) now r1= {0, 1, 5/4}:

{0  1  5/4}
{1  0  3/2}

Take a look at the first row and solve col(third). We see that x1=3/2 and that x2=5/4. To make it more easy to see, we can arrange the rows so that the solution of x1 will be in r1 and x2's solution will be at r2. To do so, we will arrange the matrix so that the row with most "zeros" from the left will be at the bottom and so on... in our case: we will swap r1 with r2 (r1<->r2):

{0 1 5/4}

How nice is that... :-)

As you can see, we ignored the solution col(vector). But one may ask when to stop ranking (that's how this process is called), the answer ý16:02 ý28/ý04/ý2004 is: one should stop ranking when every Gauss's action, he can do that to null a number, will cause adding a new number. For example, if I'll do now r2+r1 into r1, not only will I null nothing (not needed action in its own), I will also destroy the zero I have in the first row second column and replace it with 1.

As you can see, we are ignoring the solution vector. All we care about are the variable vectors, but the ordinary rows and cols actions will work on them too due to the fact that they are part of the row. That might seems useless in our case but try to solve a set of 5 equations with 4 variables without ranking the matrix (it can take a while). And what about 300 equations with 400 variables.

Using the code

As written above, the main class is RationalComplexMatrix. It is a most useful class and the RationalComplexMatrix merely shows its abilities and usages. Simply open the source code zip file, compile, and link. If you're using VC++ 6, make sure you have the service pack 5 and later (a bug when using friend functions). For your convenience, I've also included a "clean" directory of the RationalComplexMatrix class without the RationalComplexMatrix Calculator files. In addition, I have put in an expanded version of the RationalComplexMatrix. The expanded version can not deal with complex numbers, but it can deal with large scale matrixes. Accuracy cannot be promised when using large scale matrixes (6 x 6.. and above) with the Standard version. The accuracy at the expanded version of the RationalComplexMatrix is gained thanks to another class, named Mint (multi-integer). The Mint class works just like the regular int object (32 bits); only it has 337 bits!!!. For further information, read the documentations included. You might like to take a good look at the header of the RationalComplexMatrix class:

class RationalComplexMatrix
{
	short rows, columns;
	/*"rows" is the number of complex 
	or rational numbers in ache row
	Therefor it is equal to number of cols in the matrix 
	columns is the number of complex 
	or rational numbers in ache col
	Therefor it is equal to number of the rows in the matrix 
	*/


	char *MatrixName;
	//A pointer to unique name for the matrix, 
	//that doesn't created by default
	//it's not transfered with the '=' operator 
	//nor does it make any different
	//in then the '==' operator is called

	RationalComplex **matrix;
	//Pointer to array of pointers that points on arrays of 
	//complex numbers that makes the matrix rows

	//This one is part of the *operator overloading;
	RationalComplex Vmulmatrix(RationalComplexMatrix leftmatrix , 
	                           RationalComplexMatrix ob , 
	                           int row, int col);

	//**********************************************
	// MATRIX RANKING PRIVATE FUNCTIONS
	
	//  REMEMBER THAT ALMOST ALL THE FUNCTION 
	//  GET A POINTER TO ANOTHER 
	//  MATRIX OBJECT THIS IS FOR THE ABILITY TO
	//  RANK THE POINTED MATRIX WITH OUR MATRIX
	//**********************************************


	/*this one  gets line number and give true if the 
	line has canonic pivot (like 0 1 0 )
	else returns false*/
	bool vAmIPivot(short CurrantRow, 
	     RationalComplexMatrix *MyParalalMatrix);


	/*this one takes all the rows with 
	  canonic pivots and nulls all the numbers
	  below and above their leading number(pivot).
	  IT MAKES ALL THE WORK ALOT FASTER BUT CURENTLY DISABLED*/
	void PivotNullity(RationalComplexMatrix *MyParalalMatrix);


	//swapping two given rows
	void SwapMatrixRows(short RowA,short RowB, 
	     RationalComplexMatrix *Myparalelmatrix);


	//gets two cols and swap them
	void SwapMatrixCols(short ColA, short ColB);


	//dividing every number in the matrix in his leading number
	void vBreakDownRow(RationalComplexMatrix *MyParalalmatrix);


	//this one receive the current row 
	//and use it to null the other lines
	void vCutDownRow(short CurrentRow,short CurrentCol, 
	     RationalComplexMatrix *MyParalalmatrix);


	/*sort the matrix lines by the number of zeros from the left,
	the more zeros you have, go lower*/
	void vMoveZerosDown(RationalComplexMatrix *Myparalelmatrix);


	/*this nice one searches for copys of lines and delete them
	it take int value if it is negative regular job.
	but if get positive value it will be 
	row index, if finds copy of the row,
	he will remove the row he got and not the copy he found*/
	void RemoveEqual(short rowtodelete, 
	     RationalComplexMatrix *MyParalalmatrix);


	//works with RemoveEqual(int rowtodelete) function.
	void CheckDuplicate(short row, 
	     RationalComplexMatrix *MyParalalmatrix);


	//return 1 if the row in the index he got is all 
	//zero equal numbers else returns 0
	bool AmIAllZeros(short CurrentRow) const;


	//reversing the order of rows in matrix, 
	//and then the order of cols
	void SwapMatrix(RationalComplexMatrix *MyParalalmatrix);

	/*Returns 1 if the matrix have at least
	  1 row that all her numbers equal to 0.
	  Else it returns 0*/
	bool DoIHaveAllZeroLine() const;

public:

	//constructor default creat objects with 0 cols, 0
	// rows and no memory allocation of pointers
	RationalComplexMatrix();

	//Parameters Constructor to build 
	//mxn matrix with memory allocation
	RationalComplexMatrix(int m_NumberOfRow, 
	                      int n_NumberOfColumn);

	//copy constructor
	RationalComplexMatrix(const RationalComplexMatrix &ob);

	//destructor
	~RationalComplexMatrix();

	/*getting access to matrix A's 
	  organ like A(1,2) for input/output
	  when 1 and 2 are coordinates*/
	RationalComplex &operator()(int RowNumber, int ColumnNumber);

	friend std::ostream &operator <<(std::ostream &, 
	                    RationalComplexMatrix &);

	friend std::istream &operator >>(std::istream &, 
	                    RationalComplexMatrix &);

	bool operator==(const RationalComplexMatrix &ob) const;

	bool operator!=(RationalComplexMatrix &ob) const;

	RationalComplexMatrix &operator=(RationalComplexMatrix &ob) ;

	RationalComplexMatrix operator+(RationalComplexMatrix &ob) const;

	RationalComplexMatrix operator-(RationalComplexMatrix &ob) const;

	RationalComplexMatrix operator*(RationalComplexMatrix ob);

	//Sets unique name for the matrix or deletes one
	void vSetMatrixName(const char *name);

	/*return pointer to the matrix name and if it has
	no name returns "Anonimus_Matrix"*/
	const char* vGetMatrixName() const;

	//returns the amount of numbers in column(number of rows)
	int vGetMatrixColumns() const;

	//returns the amount of numbers in row(number of columns)
	int vGetMatrixRows() const;

	//runs the input operator on the matrix 
	//(JUST LIKE >> OPERATOR OVERLOADING)
	void vFillMatrix();

	//get's reed of all the fractions in a matrix
	void MakeSimpler();
	//************************************************

	//  THIS PUBLIC FUNCTIONS BELOW BELONG
	//  TO THE RANKING MATRIX PROCESS

	//   REMEMBER THAT ALMOST ALL THE FUNCTION
	//   GET A POINTER TO ANOTHER 
	//   MATRIX OBJECT THIS IS FOR THE ABILITY TO
	//   RANK THE POINTED MATRIX WITH OUR MATRIX

	//************************************************

	//the current matrix becomes her own 
	//singular matrix if her order is mxm.
	void TurnSingularMatrix();

	//Current matrix becomes T base 
	//matrix of her self A(j,i)=A(i,j)...
	void TurnTransposeMatrix();

	/*this function operates the whole matrix
	  ranking to canonic process
	  according to another given matrix*/
	void vArrangeMatrix(RationalComplexMatrix &MyParalalmatrix);

	//this function operates the whole 
	//matrix ranking to canonic process
	void vArrangeMatrix();

	/*swaps between the part of matrix above the main diagonal 
	and the part below it*/
	void SwapMatrixDir();

	/*returns 1 if matrix is singular, 0 if not
	  e.g       1 0 0
	    0 1 0
	    0 0 1 will return 1  */
	bool IsSingular() const;


	//Current matrix A becomes A(^-1) matrix of her 
	//self(her Inverse matrix) if inverse able
	void TurnInverseMatrix ();

	void RemoveCol(short ColNumber);

	void RemoveRow(short RowNumber);

};

Points of Interest

This is the first "real" code I'm writing without getting any help from any source, I'm very proud of this piece. The real nice part was to implement the ranking algorithm, and the most time consuming was the debugging and optimizing part. You might be interested to know that I've built a class that implements the simplex optimization method, and it should be here soon.

History

This is the third and improved version of the RationalComplexMatrix Calculator.

  • The ranking algorithm is working faster than ever, with minimum iterations.
  • Far better documentation.
  • Several bugs fixed.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Team Leader
Israel Israel
Born and raised in Israel, caught the programming virus at the age of 15.
Since than I can't stop coding.

Comments and Discussions

 
QuestionHELP PLS Pin
21hiromi13-Mar-14 15:57
21hiromi13-Mar-14 15:57 
GeneralMy vote of 5 Pin
Benjamin Uboegbu26-Sep-11 0:33
professionalBenjamin Uboegbu26-Sep-11 0:33 
Generalspelling error Pin
dcknckl4k9-Apr-08 5:09
dcknckl4k9-Apr-08 5:09 
GeneralSimplex Optimization Method Pin
rachel_bowles10-Mar-07 12:20
rachel_bowles10-Mar-07 12:20 
AnswerRe: Simplex Optimization Method Pin
JadBenAutho14-Mar-07 10:53
JadBenAutho14-Mar-07 10:53 
GeneralRe: Simplex Optimization Method Pin
milo808018-Feb-08 7:04
milo808018-Feb-08 7:04 
Hello,

can u send me too the code of simplex method, pls.

bye
milo8080 Smile | :)
GeneralRe: Simplex Optimization Method Pin
cornilius4-May-08 22:44
cornilius4-May-08 22:44 
GeneralRe: Simplex Optimization Method Pin
hit_lubin20-May-08 21:46
hit_lubin20-May-08 21:46 
GeneralAn advice to improve your code of &quot;Matrix calculator&quot;. [modified] Pin
gloval27-May-06 1:31
gloval27-May-06 1:31 
GeneralRe: An advice to improve your code of &quot;Matrix calculator&quot;. Pin
JadBenAutho4-Sep-06 10:44
JadBenAutho4-Sep-06 10:44 
GeneralCompiler Error Pin
Elco Grobler6-Nov-05 19:24
Elco Grobler6-Nov-05 19:24 
GeneralRe: Compiler Error Pin
JadBenAutho7-Nov-05 7:42
JadBenAutho7-Nov-05 7:42 
Generalerror in calculation in example Pin
zouris30-Jun-04 7:44
zouris30-Jun-04 7:44 
GeneralRe: error in calculation in example Pin
JadBenAutho4-Sep-06 10:47
JadBenAutho4-Sep-06 10:47 
Generalcorrection Pin
johnwallis26-May-04 20:54
johnwallis26-May-04 20:54 
GeneralSingular matrix(reply to Johnwallis) Pin
JadBenAutho28-May-04 7:55
JadBenAutho28-May-04 7:55 
GeneralRe: Singular matrix(reply to Johnwallis) Pin
johnwallis28-May-04 22:50
johnwallis28-May-04 22:50 
GeneralI blame my broken English :) Pin
JadBenAutho29-May-04 0:15
JadBenAutho29-May-04 0:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.