Coding Gauss Jordan Elimination in C++ - Need Help with Swapping Rows

Click For Summary

Discussion Overview

The discussion revolves around coding the Gauss-Jordan elimination algorithm in C++, specifically focusing on how to swap rows in a matrix. Participants are sharing insights on array handling, matrix representation, and algorithmic approaches relevant to this task.

Discussion Character

  • Technical explanation
  • Conceptual clarification
  • Debate/contested
  • Homework-related

Main Points Raised

  • One participant seeks assistance with swapping rows in a 2D array while implementing Gauss-Jordan elimination in C++.
  • Another participant suggests that to swap rows, one must iterate through each column and swap the elements, given the current matrix definition.
  • It is proposed that using an array of pointers could simplify row swapping by allowing pointer manipulation instead of element-wise swapping.
  • A pseudocode example for swapping rows is provided, illustrating a straightforward algorithmic approach.
  • Discussion includes the concept of using a lookup table to facilitate faster row swapping without directly manipulating the matrix.
  • Clarification is provided regarding the terminology of "array of arrays" and the differences in memory handling between two-dimensional arrays and arrays of pointers.
  • Participants explain the use of a temporary variable, referred to as "tmp," in the context of swapping values during the row interchange process.

Areas of Agreement / Disagreement

There is no consensus on the best approach to swapping rows, as participants present multiple methods and perspectives on matrix representation and manipulation.

Contextual Notes

Participants express varying levels of familiarity with C++, and there are unresolved questions about the implementation details of the row swapping process and the handling of matrix data structures.

Who May Find This Useful

Individuals interested in learning about matrix operations in C++, particularly those working on educational projects or exploring algorithmic implementations in programming.

ur5pointos2sl
Messages
95
Reaction score
0
Hello all. I am designing a Gauss jordan elimination program using c++. I need a little help to code this as I am not too familiar with arrays and the operations you can perform on them.

The first question I have is how would I swap rows? I know its probably really simple but I cannot find and source code that might provide some insight. Could anyone please take a look at the following code and give me some insights. Thanks in advance

This is just what I have so far.

Code:
#include<iostream>
#include<cmath>
using namespace std;



int main()
{
    double x[50],a[50][50],c[50],d[50][50],max,loc;
    int i,j,n,ai;
   
    
    cout <<"\n\nPlease enter the number of rows/variables\n";
    cin >> n;
  
    cout<<"\nLet's now enter the row and column values\n"<<endl;
    cout<<endl;
  
for (i=1;i<=n;i++)
	{
		for (j=1;j<=n;j++)
		{
		cout <<"Row "<<i<<", Column "<<j<<"\n";
		cin >> a[i][j];
		}
		
	cout << "Please enter the constant for row "<<i<<"\n";
	cin >> c[i];
        
	}
	
    
    cout <<"\n\nThe matrix entered is as follows:\n";
	for (i=1;i<=n;i++)
	{
        cout<<"\n";
        
		for (j=1;j<=n;j++)
		{
		cout <<a[i][j]<<"\t";
		}
		
	    cout<<" ="<<c[i]<<"\n";
    }
   
   
//looks for the pivot  
max <= a[0][0];
loc <= 0;
for (i=1;i<=n;i++)
{
  if (a[i][0] > max);
  {
    max <= a[i][0];
    loc <= i;
}
}

   
system("pause");
return 0;  
    
    
}
 
Technology news on Phys.org
Given the way you have defined the matrix [a 2D array], the only way to swap rows will be to step over each column with a for loop and swap the items in those columns.

If you define your matrix the other way [as an array of arrays] you can swap rows by swapping the row pointers.

If you plan to be doing serious matrix math it may be best to not try to use raw C constructs as you are doing here-- especially if you are unfamiliar with C-- and instead find a matrix library. This article at IBM developerworks reviews several matrix libraries, and highlights at least one called "Cooperware Matrix" that I notice has a swap-rows method built in.
 
Well, if you're just doing it as a learning project and not for a super-intensive application, I think understanding how it can algorithmically be done is not such a bad idea.

Here's the pseudocode for what you want to do:

Code:
SwapRows( matrix[1...n,1...m], row1, row2 )

1.   for j := 1 ... m
2.      do tmp := matrix[row1, j]
3.      matrix[row1, j] := matrix[row2, j]
4.      matrix[row2, j] := tmp

Swapping columns is also straightforward.
 
Coin said:
Given the way you have defined the matrix [a 2D array], the only way to swap rows will be to step over each column with a for loop and swap the items in those columns.

If you define your matrix the other way [as an array of arrays] you can swap rows by swapping the row pointers.

If you plan to be doing serious matrix math it may be best to not try to use raw C constructs as you are doing here-- especially if you are unfamiliar with C-- and instead find a matrix library. This article at IBM developerworks reviews several matrix libraries, and highlights at least one called "Cooperware Matrix" that I notice has a swap-rows method built in.


This program will just be for educational use. What do you mean by an "array of arrays"?
 
Strictly speaking (or at least this is my understanding), a two-dimensional array in C *is* an array of arrays. But that's beside the point.

Another way to get fast swapping of rows is to use a trick similar to swapping pointers, but involving only a lookup table:

Code:
Initialize( n : number of rows )
1.   for i := 1 ... n
2.      do table[i] := i

Access( matrix[1...n, 1...m], row, col )
1.   row' := table[row]
2.   return matrix[row', col]

SwapRows( matrix[1...n, 1...m], row1, row2 )
1.   tmp := table[row1]
2.   table[row1] := table[row2]
3.   table[row2] := tmp

That's some pretty quick code. You'd do a little better with pointers, but then again, who wants to deal with those?
 
AUMathTutor said:
Well, if you're just doing it as a learning project and not for a super-intensive application, I think understanding how it can algorithmically be done is not such a bad idea.

Here's the pseudocode for what you want to do:

Code:
SwapRows( matrix[1...n,1...m], row1, row2 )

1.   for j := 1 ... m
2.      do tmp := matrix[row1, j]
3.      matrix[row1, j] := matrix[row2, j]
4.      matrix[row2, j] := tmp

Swapping columns is also straightforward.

Yes this is for a project. I am a little new to c++ so bear with me. What does tmp mean?

The problem I am having is that I need to find the pivot(the largest absolute value number in the first column). I then need to interchange row 1 with the row the pivot is in. I am still a little confused how I would need to code this. I understand what the pseudocode is doing. I just cannot figure out how to use what I have coded and make it swap the rows.
 
Last edited:
ur5pointos2sl said:
This program will just be for educational use. What do you mean by an "array of arrays"?

So first off, AUMathTutor is correct, I misspoke and this was not the right terminology.

But what I meant was that there are two ways to create a two-dimensional array in C. One is the way you did it:

Code:
double a[50][50];

The other is to create an array of pointers, and point the pointers to arrays:

Code:
double *a[50];
for(int c=0; c<50; c++) a[c] = new double[50];

Regardless of which of these two things you did, you access the values the same way:

Code:
cout << a[3][2];

However they are handled differently in memory. In case one, the compiler will just make a big 50x50 table in memory and do lookups into it. In case two, the compiler will have 50 arrays of doubles and one array of pointers to those arrays.

The difference is first off, case two will under some circumstances be easier to pass to functions; and second, in case two (and only case two) you are allowed to do this:

Code:
double *temp = a[3];
a[3] = a[2];
a[2] = temp;

However case one will be a good bit easier to handle if you are not yet familiar with C/C++ pointers.

Yes this is for a project. I am a little new to c++ so bear with me. What does tmp mean?
He's suggesting you make a temporary value, which he abbreviates "tmp", and use it to hold the value at matrix[row1, j] in order to swap it with another value. Like I do with the arrays in my final code example above.
 
"tmp" stands for "temporary". This is a pretty standard method of swapping two of any kind of things. If, for example, you want to swap A and B, you define "tmp" or "temporary", "t", or, in fact, anything, of the same "type" as A and B, then write
tmp= A;
A= B;
B= tmp;

I presume you understand why just "A= B; B= A;" would not work.
 
Coin said:
So first off, AUMathTutor is correct, I misspoke and this was not the right terminology.

But what I meant was that there are two ways to create a two-dimensional array in C. One is the way you did it:

Code:
double a[50][50];

The other is to create an array of pointers, and point the pointers to arrays:

Code:
double *a[50];
for(int c=0; c<50; c++) a[c] = new double[50];

Regardless of which of these two things you did, you access the values the same way:

Code:
cout << a[3][2];

However they are handled differently in memory. In case one, the compiler will just make a big 50x50 table in memory and do lookups into it. In case two, the compiler will have 50 arrays of doubles and one array of pointers to those arrays.

The difference is first off, case two will under some circumstances be easier to pass to functions; and second, in case two (and only case two) you are allowed to do this:

Code:
double *temp = a[3];
a[3] = a[2];
a[2] = temp;

However case one will be a good bit easier to handle if you are not yet familiar with C/C++ pointers.


He's suggesting you make a temporary value, which he abbreviates "tmp", and use it to hold the value at matrix[row1, j] in order to swap it with another value. Like I do with the arrays in my final code example above.

Case 2 sounds like it could possibly be easier for me to understand except that pointers aren't one of my strong points. Ok I guess I need to at least make an attempt to code this row swap so I can at least see where I am going wrong if I am at all.
 
  • #10
max <= a[0][0];
loc <= 0;
for (i=1;i<=n;i++)
{
if (a[0] > max);
{
max <= a[0];
loc <= i;
}
}

This is the part of the code that is throwing me off. I still cannot for the life of me seem to figure out how to use this and swap the rows. This piece of the code will find the maximum value, and give the location of that value..at least that's what I think its doing :-D...

Could someone please maybe give me a little shove in the right direction.

Again I have to look through the first column, pick out the largest value, swap the row that value is in with row 1.
 
  • #11
ur5:

<= in C++ means "less than or equal to". The statement "loc <= 0" will have no effect, it will only perform a test whether or not loc is less than 0 and then discard the results of that test. You're supposed to say "=" if you want assignment.
 
  • #12
If you want a function to give you the row number whose leading entry is greatest, perhaps something like the following?

Code:
Compare( matrix[1...n, 1...m], row1, row2 )

1.   result := 0
2.   while (j <= m) && (result = 0)
3.      do if matrix[row1, j] > matrix[row2, j]
4.         then result := 1
5.      if matrix[row1, j] < matrix[row2, j]
6.         then result := -1
7.      j := j + 1
8.   return result

Now that you can compare rows of a matrix, it should be relatively straightforward to find the biggest row.
 
  • #13
AUMathTutor said:
If you want a function to give you the row number whose leading entry is greatest, perhaps something like the following?

Code:
Compare( matrix[1...n, 1...m], row1, row2 )

1.   result := 0
2.   while (j <= m) && (result = 0)
3.      do if matrix[row1, j] > matrix[row2, j]
4.         then result := 1
5.      if matrix[row1, j] < matrix[row2, j]
6.         then result := -1
7.      j := j + 1
8.   return result

Now that you can compare rows of a matrix, it should be relatively straightforward to find the biggest row.

Thanks for this that makes it a whole lot clearer.
 
  • #14
HallsofIvy said:
I presume you understand why just "A= B; B= A;" would not work.
If memory was limited then there's the option, A ^= B, B ^= A, A ^= B.

In addition to using loops to move arrays, you can also use memcpy(dst, src, sizeof(array)). Swapping pointers as mentioned above to make the equivalent of a 2d array is the fastest. The previous example did a separate allocate (new) for each row of the array, but this could have been done with a single allocation (new) of the full 2d array, followed by a loop to fill an array of pointers to each row of the array.

C and C++ don't allow assignment of arrays but do allow assignment of structures containing arrays. You could define a row structure, typedef {char data[50]}ROW, and then use an instance of ROW to move an array via assignment, ROW row0, row1; ... row0 = row1; ...
 
  • #15
Just a reminder, btw, my row-table method is very nearly as fast as pointers, and requires zero knowledge of how pointers work.
 

Similar threads

Replies
12
Views
3K
  • · Replies 22 ·
Replies
22
Views
4K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 4 ·
Replies
4
Views
6K
  • · Replies 23 ·
Replies
23
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 3 ·
Replies
3
Views
4K
  • · Replies 1 ·
Replies
1
Views
2K