5

I`m trying to do this function that solves linear systems, A*x = b, where A = lower triangular matrix, linear independent matrix and with only one solution. But the results always show 0 0 0 0 ... I have printed the sum, s, and it always shows 0 as well...

 #include  <iostream>
 using namespace std;

void solve(int n, float a[][MAX], float b[], float x[]){
 int i,j;
 float s;

 for(i = 0; i < n; i++){
        s = 0;
        for(j = 0; j < n; j++){

            s = s + a[i][j]*x[j];
            cout<<s<<endl;
        }
    x[i] = (b[i] - s)/a[i][i];
 }
}
9
  • can't you use lapack? Mar 6, 2014 at 22:19
  • no, it has to be in c++, with "simple libraries and packs"...
    – user3369563
    Mar 6, 2014 at 22:20
  • This is a famous algorithm. It's called back substitution. Try google for a bit. I'm quite sure you will find it step by step :) If you're still stuck scream for help. Mar 6, 2014 at 22:23
  • @LVL can we use upper triangular matrix?
    – 4pie0
    Mar 6, 2014 at 22:33
  • 1
    Now i see... It`s working!
    – user3369563
    Mar 6, 2014 at 22:58

2 Answers 2

3
void solve(int n, float a[][MAX], float b[], float x[]){
  int i,j;
  float s;

  for(i = 0; i < n; i++) {
        s = 0;
        for(j = 0; j < i; j++) {
                       ^
            s = s + a[ i][ j] * x[ j];
        }
        x[ i] = ( b[ i] - s) / a[ i][ i];
   }
}

BackSubstitution.pdf

compiled example

1
  • the compiled example does not work (=not robust) for certain input. For instance, I enter $a[3][3]={0.2,-0.2,0,0,0.3,-0.2,0,0,0.25}$ and $b[3]={3,3,3}$. The codes compiles but leads to an incorrect answer as 15,10,12. Is it a way to fix the codes?
    – math101
    Mar 12, 2020 at 15:49
2

This line:

    for(j = 0; j < n; j++){

Should be:

    for(j = 0; j < i; j++){

Then it works fine - assuming your pivots are always non zero.

1
  • @lizusek Err... no? For instance when i=1 s should be A[1][0]*x[0] while in your code is simply 0. You have to sum all the A[i][j]*x[j] on the left of the diagonal, so basically for i < j.
    – sbabbi
    Mar 6, 2014 at 23:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.