#include <iostream>
int main() {
int M = 0;
std::cout << "Enter M: ";
std::cin >> M;
int N = 0;
std::cout << "Enter N: ";
std::cin >> N;
if (M <= 0 || M < N || N < M) {
std::cout << "Oops, what a mess..." << std::endl;
return 1;
}
int i, k, j;
int **array = new int *[M];
i = 0;
while (i < M) {
array[i] = new int[N];
i++;
}
double **gauss = new double *[M], mult;
i = 0;
while (i < M) {
gauss[i] = new double[2 * N];
i++;
}
i = 0;
while (i < M) {
std::cout << "Enter " << i + 1 << "-th row (" << N
<< " numbers separated by a whitespace): ";
j = 0;
while (j < N) {
std::cin >> array[i][j];
gauss[i][j] = array[i][j];
gauss[i][j + N] = double(i == j);
j++;
}
i++;
}
i = 0;
while (i < M) {
mult = 1 / gauss[i][i];
j = i;
while (j < 2 * N) {
gauss[i][j] *= mult;
j++;
}
k = i + 1;
while (k < M) {
mult = gauss[k][i] / gauss[i][i];
j = i;
while (j < 2 * N) {
gauss[k][j] -= gauss[i][j] * mult;
j++;
}
k++;
}
i++;
}
// The left matrix is now in echelon form
i = M - 1;
while (i >= 0) {
k = i - 1;
while (k >= 0) {
mult = gauss[k][i] / gauss[i][i];
j = i;
while (j < 2 * N) {
gauss[k][j] -= gauss[i][j] * mult;
j++;
}
k--;
}
i--;
}
// The left matrix is now in reduced echelon form
std::cout << "\nInput matrix:\n";
i = 0;
while (i < M) {
j = 0;
while (j < N) {
std::cout.width(7);
std::cout << array[i][j] << ((j + 1 != N) ? ' ' : '\n');
j++;
}
i++;
}
std::cout << "\nInverse matrix:\n";
std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
std::cout.precision(4);
i = 0;
while (i < M) {
j = 0;
while (j < N) {
std::cout.width(7);
std::cout << gauss[i][j + N] << ((j + 1 != N) ? ' ' : '\n');
j++;
}
i++;
}
i = 0;
while (i < M) {
delete[] array[i];
delete[] gauss[i];
i++;
}
delete[] array;
delete[] gauss;
}
/*
Algorithm:
intmath.com/matrices-determinants/inverse-matrix-gauss-jordan-elimination.php
Input:
3
3
4 6 7
8 10 5
12 11 9
Output:
Enter M: 3
Enter N: 3
Enter 1-th row (3 numbers separated by a whitespace): 4 6 7
Enter 2-th row (3 numbers separated by a whitespace): 8 10 5
Enter 3-th row (3 numbers separated by a whitespace): 12 11 9
Input matrix:
4 6 7
8 10 5
12 11 9
Inverse matrix:
-0.2244 -0.1474 0.2564
0.0769 0.3077 -0.2308
0.2051 -0.1795 0.0513
*/
Comments
Leave a comment