Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I'm having trouble computing the magnitude of residual of solution (error vector) after gaussian elimination for matrices. My program is supposed to solve for matrices

I'm having trouble computing the magnitude of residual of solution (error vector) after gaussian elimination for matrices. My program is supposed to solve for matrices of the form A*x=b, where A and b are given. My code does this just fine, but I'm having trouble computing the error vector. I know the formula should be b-A*x, but I'm having trouble getting it right with the vectors I have. Any suggestions?

Here's my code:

#include #include #include #include #include "assignment1.h" using namespace std;

vector gaussianElimination ( vector< vector > A ) { int n = A.size();

for ( int i = 0; i < n; i++ ) { double maxElement = abs ( A[i][i] ); int maxRow = i; for ( int k = i + 1; k < n; k++ ) { if ( abs ( A[k][i] ) > maxElement ) { maxElement = abs ( A[k][i] ); maxRow = k; } }

for ( int k = i; k < n + 1; k++ ) { double tmp = A[maxRow][k]; A[maxRow][k] = A[i][k]; A[i][k] = tmp; }

for ( int k = i + 1; k < n; k++ ) { double c = -A[k][i] / A[i][i]; for ( int j = i; j < n + 1; j++ ) { if ( i == j ) { A[k][j] = 0; } else { A[k][j] += c * A[i][j]; } } } }

vector x ( n ); for ( int i = n - 1; i >= 0; i-- ) { x[i] = A[i][n] / A[i][i]; for ( int k = i - 1; k >= 0; k-- ) { A[k][n] -= A[k][i] * x[i]; } }

return x; }

void print ( vector< vector > A ) { int n = A.size();

for ( int i = 0; i < n; i++ ) { for ( int j = 0; j < n + 1; j++ ) { cout << A[i][j] << "\t"; outputFile << A[i][j] << "\t"; if ( j == n - 1 ) { cout << "| "; outputFile << "| "; } } cout << " "; outputFile << " "; } cout << endl; outputFile << endl; }

int main() { int n; cin >> n; vector line ( n + 1, 0 ); vector< vector > A ( n,line );

// Read data from the input file for ( int i = 0; i < n; i++ ) { for ( int j = 0; j < n; j++ ) { cin >> A[i][j]; } }

for ( int i = 0; i < n; i++ ) { cin >> A[i][n]; }

//Print the data from the input file print(A);

//Compute the solution vector x ( n ); x = gaussianElimination ( A );

// Print the result to the screen and the output file cout << "The unknown matrix: "; outputFile << "The unknown matrix: "; for ( int i = 0; i < n; i++ ) { cout << "| " << x[i] << " | "; outputFile << "| " << x[i] << " | "; } cout << endl; outputFile << endl;

return 0; }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions