fork(9) download
  1. /*
  2.  * File: main.cpp
  3.  * Author: piter cf16 eu
  4.  *
  5.  * Created on March 7, 2014, 12:01 AM
  6.  * http://stackoverflow.com/questions/22237322/solve-ax-b-a-lower-triangular-matrix-in-c/22237724?noredirect=1#comment33770886_22237724
  7.  */
  8.  
  9. #include <iostream>
  10. #include <algorithm>
  11. #include <iterator>
  12.  
  13. /**
  14.  * solve linear equation system by forward
  15.  * substitution on lower triangular matrix
  16.  * @param n matrix rank (dimension of solution space)
  17.  * @param a lower triangular matrix
  18.  * @param b right side
  19.  * @param x solution
  20.  * http://k...content-available-to-author-only...u.tr/~pehlivan/numerical_analysis/chap02/BackSubstitution.pdf
  21.  */
  22. void solve( int n, float a[4][4], float b[], float x[]) {
  23. float s;
  24.  
  25. for( int i = 0; i < n; i++) {
  26. s = 0;
  27. for( int j = 0; j < i; j++) {
  28. s = s + a[ i][ j] * x[ j];
  29. }
  30. x[ i] = ( b[ i] - s) / a[ i][ i];
  31. }
  32. }
  33.  
  34. /*
  35.  *
  36.  */
  37. int main(int argc, char** argv) {
  38.  
  39. int n = 4;
  40. float a[4][4] = { 3, 0, 0, 0, -1, 1, 0, 0, 3, -2, -1, 0, 1, -2, 6, 2};
  41. float b[4] = { 5, 6, 4, 2};
  42. float res[4];
  43. solve( n, a, b, res);
  44. std::copy( res, res + 4, std::ostream_iterator<float>( std::cout, ","));
  45. return 0;
  46. }
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
1.66667,7.66667,-14.3333,50.8333,