1/*
2 * File: main.cpp
3 * Author: Bangonkali
4 *
5 * Created on March 23, 2012, 8:14 PM
6 */
7#include <iostream>
8#include <cmath>
9#include <cstdlib>
10
11// based on discussions from here http://j.mp/GILnX3
12// example taken from here http://j.mp/GILphB
13
14using namespace std;
15
16void printMatrix(int N, float A[20][21]) {
17 for (int i = 0; i < N; i++)
18 {
19 for (int j = 0; j <= N; j++)
20 {
21 cout << A[i][j] << '\t';
22 }
23
24 cout << endl;
25 }
26
27 cout << endl;
28}
29
30int gauss_jordan(int N, float A [20] [21], float r[20]) {
31 float scale;
32
33 for (int p = 0; p < N; p++) {
34 float divider = A[p][p];
35 for (int i = 0; i <= N; i++) {
36 if (i != p) {
37 scale = A[i][p];
38 for (int j = 0; j <= N; j++) {
39 A[i][j] = (A[p][j] * scale / divider) - A[i][j];
40// printMatrix (3, A);
41 }
42 }
43 }
44 }
45
46 for (int p = 0; p < N; p++) {
47 scale = A[p][p];
48 for (int j = 0; j <= N; j++) {
49// cout << "A[p][j] = ";
50// cout << "A[" << p << "][" << j << "] / ";
51// cout << "A[" << p << "][" << p << "] = ";
52// cout << A[p][j] << "/" << scale << " = ";
53
54 if (A[p][j] != 0 && scale != 0)
55 A[p][j] = A[p][j] / scale;
56 else
57 A[p][j] = 0;
58
59// cout << A[p][j];
60// cout << endl;
61// printMatrix (3, A);
62
63 }
64
65 r[p] = A[p][N];
66 }
67}
68
69int main(int argc, char** argv) {
70 float A[20][21]; // input
71 float X[20]; // result
72
73 A[0][0] = 1;
74 A[0][1] = 2;
75 A[0][2] = 3;
76 A[0][3] = 3;
77
78 A[1][0] = -3;
79 A[1][1] = 1;
80 A[1][2] = 5;
81 A[1][3] = -2;
82
83 A[2][0] = 2;
84 A[2][1] = 4;
85 A[2][2] = -1;
86 A[2][3] = -1;
87
88 printMatrix (3, A);
89 gauss_jordan(3, A, X);
90 printMatrix (3, A);
91
92 for (int i=0; i<3; i++) cout << X[i] << " ";
93 return 0;
94}
95