0

Hello ,

I want to scan each row and find in each column the max element and the corresponding index.

Then , swap this column with the column which belongs to the main diagonal ( if a condition is valid ).

Finally , do the same for the rest rows.

In my code , I can't find the right index which corresponds to the max value!!!

Then,I can't figure how to use the column index in order to make the swap.

Finally , I can't figure how to continue with 1 row less.

```
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <iomanip>
using namespace std;
void swapCols( const int ColIdx , const int N, double * const a, double * const b );
int main()
{
const int N = 3;
double * a = new double[ N * N ];
double * b = new double[ N ];
double * x = new double[ N ];
a[ 0 ] = 9;
a[ 1 ] = 3;
a[ 2 ] = 1;
a[ 3 ] = 0;
a[ 4 ] = 4;
a[ 5 ] = 5;
a[ 6 ] = 8;
a[ 7 ] = 1;
a[ 8 ] = 4;
b[ 0 ] = 7;
b[ 1 ] = 8;
b[ 2 ] = 9;
//matrix before
for ( int i = 0; i < N; i++ )
{
for ( int j = 0; j < N; j++ )
{
cout << a[ i * N + j ] << setw(4);
}
cout << b[ i ] << endl;
}
//start the algorithm
double Max;
for ( int i = 0; i < N; i++ )
{
int ColIdx = 0;
Max = fabs( a[ i * N ] );
for ( int j = 1; j < N; j++ )
{
// Find the max element in a row and the index
if ( fabs( a[ i * N + j ] ) > Max )
{
Max = fabs( a[ i * N + j ] );
ColIdx = j;
}
else
{
Max = Max;
ColIdx = j;
}
} // j
cout << "max = " << Max << " idx = " << ColIdx << endl;
// for this index ,compare to the element of the main diagonal
// if it > main diagonal , then swap cols
//I inserted a 3rd loop (k) because I can't figure how to use the column index
for ( int k = 0; k < N; k++ )
{
if ( i == k )
{
if ( fabs( a[ i * N + k ] ) < Max )
swapCols( ColIdx ,N, a ,b );
}
}
// now we must go to the 2nd row and do the same but leave aside the first element of main diagonal!
// that's why the dimensions to be scanned now ,will be 1 row less
} // i
//matrix after
for ( int i = 0; i < N; i++ )
{
for ( int j = 0; j < N; j++ )
{
cout << a[ i * N + j ] << setw(4);
}
cout << b[ i ] << endl;
}
//free memory
delete [] a;
delete [] b;
delete [] x;
return 0;
}
void swapCols(
const int ColIdx,
const int N,
double * const a,
double * const b )
{
double tA , tB;
for ( int i = 0; i < N; i++ )
{
for ( int j = 0; j < N; j++ )
{
tA = a[ i * N + 0 ];
tB = b[ 0 ];
a[ i * N + 0 ] = a[ i * N + ColIdx ];
b[ 0 ] = b[ ColIdx ];
a[ i * N + ColIdx ] = tA;
b[ ColIdx ] = tB;
}
}
}
```

Thank you!

--------

Sorry , I uploaded in C ,but I don't have a problem using either ( I don't want to use libraries though)

*Edited
by glao*