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
Please, i have had two people answer this question but the output gives me Garbage. Please help solve this problem using C++.
#include <iostream>
#include <cmath>
using namespace std;
void inverse(float mat[][10], int order)
{
float temp;
// Creating the augmented matrix for gauss elemination method
for (int i = 0; i < order; i++) {
for (int j = 0; j < 2 * order; j++) {
if (j == (i + order))
mat[i][j] = 1;
}
}
// Interchanging of rows of the matrix
for (int i = order - 1; i > 0; i--) {
if (mat[i - 1][0] < mat[i][0])
{
for (int j = 0; j < 2 * order; j++)
{
temp = mat[i][j];
mat[i][j] = mat[i - 1][j];
mat[i - 1][j] = temp;
}
}
}
for (int i = 0; i < order; i++) {
for (int j = 0; j < order; j++) {
if (j != i) {
temp = mat[j][i] / mat[i][i];
for (int k = 0; k < 2 * order; k++) {
mat[j][k] -= mat[i][k] * temp;
}
}
}
}
// Multipling each row by a nonzero integer and then dividing a row element by the diagonal element
for (int i = 0; i < order; i++) {
temp = mat[i][i];
for (int j = 0; j < 2 * order; j++) {
mat[i][j] = round(mat[i][j] / temp);
}
}
// print the resultant Inverse matrix.
cout<<"\nthe inverse is\n";
for (int i = 0; i < order; i++)
{
for (int j = order; j < 2*order; j++)
{
cout<<mat[i][j]<<" ";
}
cout<<"\n";
}
return;
}
int main()
{
int r;
float mat[10][10];
cout<<"input row size ";
cin>>r;
cout<<"\ninput the matrix to invert\n";
for(int i=0;i<r;i++)
{
for(int j=0;j<r;j++)
{
cin>>mat[i][j];
}
}
inverse(mat,r);
return 0;
}
output: