In: Computer Science
For this lab, you will write a C++ program that will calculate the
matrix inverse of a matrix no bigger than 10x10. I will guarantee
that the matrix will be invertible and that you will not have a
divide by 0 problem.
For this program, you are required to use the modified Gaussian
elimination algorithm. Your program should ask for the size (number
of rows only) of a matrix. It will then read the matrix, calculate
the inverse, and print the inverse, and quit. I do not care if you
use two separate matrices one for the original and one for the
inverse or if you combine the two. Note: the matrix should be a
float, and you will need to use the cmath round function to get the
output below.
Sample Run:
./a.out input row size 3 input the matrix to invert -1 2 -3 2 1 0 4 -2 5 the inverse is: -5 4 -3 10 -7 6 8 -6 5
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int row;
float mat[10][10], temp;
cout << "Input row size\n";
cin >> row; // read the row
cout << "Input the matrix to invert" << endl;
for (int i = 1; i <= row; i++)
for (int j = 1; j <= row; j++)
cin >> mat[i][j]; // read the matrix
for (int i = 1; i <= row; i++)
for (int j = 1; j <= 2 * row; j++)
if (j == (i + row))
mat[i][j] = 1;
for (int i = row; i > 1; i--)
{
if (mat[i - 1][1] < mat[i][1])
for (int j = 1; j <= row * 2; j++)
{
temp = mat[i][j];
mat[i][j] = mat[i - 1][j];
mat[i - 1][j] = temp;
}
}
for (int i = 1; i <= row; i++) // converting them into the
diagonal matrix
{
for (int j = 1; j <= row * 2; j++)
if (j != i)
{
temp = mat[j][i] / mat[i][i];
for (int k = 1; k <= row * 2; k++)
mat[j][k] -= mat[i][k] * temp;
}
}
for (int i = 1; i <= row; i++) // converting them into the unit
matrix
{
temp = mat[i][i];
for (int j = 1; j <= row * 2; j++)
mat[i][j] = mat[i][j] / temp;
}
cout << "the inverse is: " << endl; // print the
inverse
for (int i = 1; i <= row; i++)
{
for (int j = row + 1; j <= row * 2; j++)
cout << round(mat[i][j]) << " ";
cout << endl;
}
return 0;
}
OUTPUT :