/*
rowreduction_myversion.cpp
12/12/2010
1. if the current elemet of matrix[temp] have value zero, swap
2. divide by itself -> 1 -> leading entries
3. add multiply all next rows to make every element under leading entries as 0
the result of reduced matrix will be stored in the same matrix. print for each step.
Last matrix is the result
*/
#include <iostream>
using namespace std;
int i,j, ROW_SQUARE, COL_SQUARE;
void print(double ** matrix, int ROW, int COL);
void checksquare(int ROW, int COL);
void swaprow(double ** matrix,int ROW,int COL,int row);
int main()
{
int ROW,COL,row=0,col=0,leadingrow, currentrow,posOrNeg;
cout << "Enter height: ";
cin >> ROW;
cout << "Enter column: ";
cin >> COL;
checksquare(ROW,COL);
double ** matrix ;
matrix = new double * [ROW]; //2D array
for (i=0; i<ROW; i++)
matrix[i] = new double[COL];
cout << "Enter each row of the matrix separated by spaces" << endl;
for (i=0;i<ROW;i++)
for (j=0;j<COL;j++)
cin >> *(*(matrix+i)+j);
do
{
//divide by self to get 1
double temp=*(*(matrix+row)+col);//current part to be leading entry of the column
if (temp==0)
{
//swap row part
if (row+1 == ROW_SQUARE)
break;
else
{
swaprow(matrix,ROW,COL,row);
temp=*(*(matrix+row)+col);
print (matrix,ROW,COL);
}
}//if
if (temp!=0)
{ for (j=col;j<COL;j++)
{
*(*(matrix+row)+j)/=temp;
}
print (matrix,ROW,COL);
//addmultiply next row to get 0 below the leading entry
leadingrow=row;
// this for() is to have diff process over different row
for (currentrow=leadingrow+1;currentrow<ROW_SQUARE;currentrow++)
{
temp = *(*(matrix+currentrow)+col);
posOrNeg=1;//multiply by positive or negative
if ( posOrNeg*temp* *(*(matrix+leadingrow)+col)+temp == 0)
{
for (j=0;j<COL;j++)
{
*(*(matrix+currentrow)+j)= posOrNeg*temp* (*(*(matrix+leadingrow)+j))+*(*(matrix+currentrow)+j);
}
}
else
{
posOrNeg=-1;
if ( posOrNeg*temp* *(*(matrix+leadingrow)+col)+temp == 0)
{
for (j=0;j<COL;j++)
{
*(*(matrix+currentrow)+j)= posOrNeg*temp* (*(*(matrix+leadingrow)+j))+*(*(matrix+currentrow)+j);
}
}
}
print (matrix,ROW,COL);
}//if
}//if (temp!=0)
row++,col++;
}while(row!=ROW_SQUARE&&col!=COL_SQUARE);
print (matrix,ROW,COL);
for (i=0;i<ROW;i++)
delete [] matrix[i];
delete[] matrix;
matrix = NULL;
cin.ignore(100,\'\\n\');
cin.get();
return 0;
}
void print(double ** matrix, int ROW, int COL)
{
cout << "-----------" << endl;
for (i=0;i<ROW;i++)
{ for (j=0;j<COL;j++)
cout << *(*(matrix+i)+j) << \' \';
cout << endl;}
}
void checksquare(int ROW, int COL)
{
if (ROW==COL)
{
ROW_SQUARE=ROW;
COL_SQUARE=COL;
}
else if (ROW<COL)
{
ROW_SQUARE=ROW;
COL_SQUARE=ROW;
}
else if (COL<ROW)
{
ROW_SQUARE=COL;
COL_SQUARE=COL;
}
}
void swaprow(double ** matrix,int ROW,int COL,int row)
{
double temp;
for (j=0;j<COL;j++)
{
temp=*(*(matrix+row+1)+j);
*(*(matrix+row+1)+j)=*(*(matrix+row)+j);
*(*(matrix+row)+j)=temp;
}
}