Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Matrix inversion using Gauss-Jordan elimination: Write a function that reads fro

ID: 3553674 • Letter: M

Question

Matrix inversion using Gauss-Jordan elimination:

Write a function that reads from a file (named "A.txt") arbitrary row and column dimensions for a matrix,

followed by the elements of that matrix, as below:

3 4

1 2 3 4
5 6 7 8
9 10 11 12

Write a function that implements the matrix inversion algorithm (Gauss-Jordan elimination) as described in lecture. Report an error if appropriate (A not square or otherwise not invertible).

Write a function that writes to a file ("Ainv.txt") a matrix per the input format (include the dimensions in the first line of the file).

In your main program:

o Call the first function to establish matrix A.
o Print the matrix to screen to confirm (may use function from HW4).
o Use the second function to invert A if possible.
o Print A-1 to the screen and also write it to the output file using the third function.

Explanation / Answer

#include<iostream>

#include <fstream>

#define MAX 10

using namespace std;

int lcm(int x,int y);

int main()

{

int i,j,k,r,c,a[MAX][MAX],b[MAX][MAX],det=1,l,d1,d2;

ifstream myfile;

myfile.open ("A.txt");

myfile>>r;

myfile>>c;


if(r==c)

{

//cout<<" Enter the Elements of the Matrix: ";

for(i=0;i<r;i++)

{

for(j=0;j<c;j++)

{

myfile>>a[i][j];

}

}

cout<<" The given Matrix before Gauss Elimination is: ";

for(i=0;i<r;i++)

{

for(j=0;j<c;j++)

{

cout<<a[i][j]<<" ";

}

cout<<" ";

}

for(i=0;i<r-1;i++)

{

for(j=i+1;j<r;j++)

{

l=lcm(a[i][i],a[j][i]);

if(l!=0&&(a[i][i]!=0&&a[j][i]!=0))

{

l=(a[i][i]*a[j][i])/l;

d1=l/a[i][i];

d2=l/a[j][i];

a[j][i]=0;

for(k=i+1;k<r;k++)

{

a[j][k]=(d2*a[j][k])-(d1*a[i][k]);

}

}

}

}

cout<<" The given Matrix after Gauss Elimination is: ";

for(i=0;i<r;i++)

{

for(j=0;j<c;j++)

{

cout<<a[i][j]<<" ";

}

cout<<" ";

}

ofstream f2;


f2.open("Ainv.txt");


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


for(int j=0;j<c;j++) {


f2<<a[i][j]<<" ";


}


f2<<endl;


}

}

else

{

cout<<" This is not a Square Matrix!!! ";

}


myfile.close();

return 0;

}

int lcm(int x,int y)

{

int t;

while (y != 0)

{

t=y;

y=x%y;

x=t;

}

return x;

}