My for loop doesn't work?
I'm creating a program that solves linear systems using the Gauss-Jordan method by following this algorithm:
for each row ri of the matrix (i from 1 to n)
replace ri with ri / rii
for each row rk of the matrix (k!=i)
replace rk with rk - rki * ri
Apparently I'm not doing it right because only th开发者_如何学Goe first element in the row is being divided by itself. I'm still new to C, so any help would be appreciated. Thanks!
for (k = 0; k < n; k++) {
for (m = 0; m < n+1; m++) {
if (matrix[k][m] < TOLERANCE) {
printf("Error, pivot is 0\n");
exit(0);
}
matrix[k][m] = matrix[k][m] / matrix[k][k];
}
for (l = 0; l != k; l++) {
printMatrix(n, n+1, matrix);
for (o = 0; o < n+1; o++) {
matrix[l][o] = matrix[l][o] - matrix[l][k] * matrix[k][o];
}
}
}
Any other input? It's still not quite right and I'm pulling my hair out lol
For a start, the l != k
in your inner loop is a continue condition. In other words, that loop will exit when l
is equal to k
.
That's not how it works in the original code. It keeps going for all other values of l
.
You can use something like this instead:
for(l = 0; l < n; l++) {
if (l != k) {
printMatrix(n, n+1, matrix);
for (o = 0; o < n+1; o++) {
matrix[l][o] = matrix[l][o] - matrix[l][k] * matrix[k][o];
}
}
}
And, as an aside, you should probably try to move away from one-letter variable names, especially l
, which can bite you quite badly the first time you mistake it for 1
:-)
You will be dividing matrix[k][k]
by itself (thus setting it to 1) and then dividing the rest of the row by 1. Use a temporary variable to store the original pivot instead of using matrix[k][k]
Edit: While the above is a bug in the code, that's probably not causing what you are experiencing, as others have pointed out, you also need to use continue
, rather than terminating the loop when l=k
.
You should replace
for(l = 0; l != k; l++){
with
for(l = 0; l < n; l++){
if (l == k) continue;
The first one stops as soon as l
reaches k
, so only processes rows 0..k-1
. The second one processes rows 0..n-1
except row k
(which fits to your pseudocode "for each row rk of the matrix (k!=i)
")
Also:
for(m = 0; m < n+1; m++){
This means you have a matrix with n rows and n+1 columns, is this correct? If it is, everything else looks good as far as I can say.
精彩评论