//----------------------------------------------------------------- // orthog.cpp (Gram-Schmidt Orthogonalization Algorithm) // // This program implements the Gram-Schmidt orthogonalization // process applied to the row-vectors in a matrix of rational // numbers which are typed in by the user. // // compile using: $ g++ orthog.cpp -o orthog // // programmer: ALLAN CRUSE // written on: 28 APR 2011 // revised on: 29 APR 2011 -- to fix prompt and verify basis //----------------------------------------------------------------- #include "vmatrix.h" int input_components( void ) { int m; cout << "\nHow many vector-components? "; cin >> m; cout << endl; return m; } int input_dimensions( void ) { int n; cout << "\nHow many basis-vectors? "; cin >> n; cout << endl; return n; } int main( void ) { system( "clear " ); int n = input_dimensions(); int m = input_components(); FractionMatrix a(n,m); cin >> a; cout << "\nThe matrix of row-vectors appears below:\n" << a; cout << endl; getchar(); // Here's we copy from a[] to b[] FractionMatrix b(n,m); for (int r = 0; r < n; r++) for (int k = 0; k < m; k++) { Fraction f; f = a.obtain( r, k ); b.assign( r, k, f ); } // confirm linear independence of matrix row-vectors Fraction det = 1; while ( !a.row_reduced( det ) ); if ( det == 0 ) { cout << "\nReduced row-echelon form: " << endl << a << endl; cout << "determinant = " << det << endl; cout << "Quitting: row-vectors are not independent" << endl; cout << endl; exit(1); } getchar(); // main loop to orthogonalize the rows in b[] for (int k = 0; k < n; k++) { for (int r = 0; r < k; r++) { Fraction dot_rk = 0; Fraction dot_rr = 0; for (int j = 0; j < m; j++) { dot_rk += b.obtain( r, j ) * b.obtain( k, j ); dot_rr += b.obtain( r, j ) * b.obtain( r, j ); } Fraction x = dot_rk / dot_rr; b.combine_rows( x, r, k ); } cout << "\nApplying step " << k+1; cout << " of Gram-Schmidt algorithm:" << endl; cout << b << endl; getchar(); } }