12,701,601 members (33,749 online)
alternative version

122.6K views
36 bookmarked
Posted

# Matrix Calculator

, 8 Sep 2006
 Rate this:
An article on complex numbers and matrix functions.

## 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();

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
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.

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

## About the Author

 Software Developer Rontal Applications Israel
Born and raised in Israel, I've caught the programming virus at the age of 15.
Since than I can't stop coding.

## Comments and Discussions

 First Prev Next
 HELP PLS 21hiromi13-Mar-14 16:57 21hiromi 13-Mar-14 16:57
 My vote of 5 Benjamin Uboegbu26-Sep-11 1:33 Benjamin Uboegbu 26-Sep-11 1:33
 spelling error dcknckl4k9-Apr-08 6:09 dcknckl4k 9-Apr-08 6:09
 Simplex Optimization Method rachel_bowles10-Mar-07 13:20 rachel_bowles 10-Mar-07 13:20
 Re: Simplex Optimization Method JadBenAutho14-Mar-07 11:53 JadBenAutho 14-Mar-07 11:53
 Re: Simplex Optimization Method milo808018-Feb-08 8:04 milo8080 18-Feb-08 8:04
 Re: Simplex Optimization Method cornilius4-May-08 23:44 cornilius 4-May-08 23:44
 Re: Simplex Optimization Method hit_lubin20-May-08 22:46 hit_lubin 20-May-08 22:46
 An advice to improve your code of "Matrix calculator". [modified] gloval27-May-06 2:31 gloval 27-May-06 2:31
 Re: An advice to improve your code of "Matrix calculator". JadBenAutho4-Sep-06 11:44 JadBenAutho 4-Sep-06 11:44
 Compiler Error Elco Grobler6-Nov-05 20:24 Elco Grobler 6-Nov-05 20:24
 Re: Compiler Error JadBenAutho7-Nov-05 8:42 JadBenAutho 7-Nov-05 8:42
 error in calculation in example zouris30-Jun-04 8:44 zouris 30-Jun-04 8:44
 Re: error in calculation in example JadBenAutho4-Sep-06 11:47 JadBenAutho 4-Sep-06 11:47
 correction Johnwallis26-May-04 21:54 Johnwallis 26-May-04 21:54
 Singular matrix(reply to Johnwallis) s699285528-May-04 8:55 s6992855 28-May-04 8:55
 Re: Singular matrix(reply to Johnwallis) johnwallis28-May-04 23:50 johnwallis 28-May-04 23:50
 I blame my broken English :) s699285529-May-04 1:15 s6992855 29-May-04 1:15
 Last Visit: 31-Dec-99 19:00     Last Update: 23-Jan-17 18:22 Refresh 1

General    News    Suggestion    Question    Bug    Answer    Joke    Praise    Rant    Admin

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