Search code examples
c++algorithmmathlinear-algebraequation-solving

Solve Ax = b, A = lower triangular matrix in c++


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];
 }
}

Solution

  • 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