1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
|
#include "stdafx.h"
#include <iostream>
using namespace std;
void Gauss(int n, double a[][100], double b[], double a_inv[][100], double s[])
{
// 1. Initialize matrix c that contains a, identity marix, and b.
double c[100][201], temp;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
c[i][j] = a[i][j];
if (i == j)
{
c[i][n + j] = 1;
}
else
{
c[i][n + j] = 0;
}
}
c[i][2 * n] = b[i];
}
// 2. Normalize matrix a so that it is a matrix of diagonal 1's with
// zeros on all the columns directly below.
for (int pivot = 0; pivot < n; pivot++)
{
// Look for an element in the column which is not zero,
// divide the whole row by this pivot element
temp = c[pivot][pivot];
for (int j = 0; j <= 2 * n; j++) c[pivot][j] = c[pivot][j] / temp;
//MULTIPLY PIVOT ROW BY c[][] AND ADD TO THE REAMINING ROWS.
for (int i = 0; i < n; i++)
{
if (pivot != i) {
for (int j = 0; j <= 2 * n; j++)
{
c[i][j] = c[i][j] - c[i][pivot] * c[pivot][j];
}
}
}
}
// 3. Solve matrix a so that it is an identity matrix.
// 4. Fill in array a_inv with the inverse matrix.
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
a_inv[i][j] = 1 / ((a[i][j] * a[i + 1][j + 1]) - (a[i][j + 1] * a[i + 1][j]));
}
}
// 5. Fill in array s with the variable solutions.
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
s[i] = a[i][j] * b[i];
}
}
}
//===================================================================================
// MAIN EXECUTION
//===================================================================================
int _tmain(int argc, _TCHAR* argv[])
{
const int n = 2;
const int m = 3;
double a1[n][n]={{1, 2},{3,4}};
double b1[n]={3, 7};
double a_inv1[n][n];
double s1[n];
Gauss(n,a1,b1,a_inv1,s1);
double a2[m][m] = { { 1, 2, 3 }, { 2, 3, 4 }, { 3, 4, 5 } };
double b2[m] = { 6, 9, 12 };
double a_inv2[m][m];
double s2[m];
Gauss(m, a2, b2, a_inv2, s2);
return 0;
}
| |