Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <math.h>
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct {
- int r, c;
- double *m;
- } matrix;
- //static matrix *matrix_new(int r, int c) {
- // matrix *m = (matrix *)calloc(sizeof(*m), 1);
- // m->r = r;
- // m->c = c;
- // m->m = (double *)calloc(sizeof(m->m), r * c);
- // return m;
- //}
- //static void matrix_delete(matrix *m) {
- // free(m->m);
- // free(m);
- //}
- static double matrix_at(matrix *m, int x, int y) {
- return m->m[m->c * x + y];
- }
- static void matrix_as(matrix *m, int x, int y, double v) {
- m->m[m->c * x + y] = v;
- }
- static void pivot(matrix *m, int k) {
- for (int i = k; i < m->r; ++i) {
- double row_i_max = matrix_at(m, i, k);
- for (int j = k + 1; j < m->c; ++j) {
- double e = matrix_at(m, i, j);
- if (fabs(row_i_max) < fabs(e)) {
- row_i_max = e;
- }
- }
- for (int j = k; j < m->c; ++j) {
- double e = matrix_at(m, i, j);
- matrix_as(m, i, j, e / row_i_max);
- }
- }
- double col_k_max = matrix_at(m, k, k);
- int x = k;
- for (int i = k; i < m->r; ++i) {
- double e = matrix_at(m, i, k);
- if (col_k_max < e) {
- col_k_max = e;
- x = i;
- }
- }
- if (x == k) {
- return;
- }
- for (int i = k; i < m->c; ++i) {
- double e = matrix_at(m, k, i);
- double f = matrix_at(m, x, i);
- matrix_as(m, k, i, f);
- matrix_as(m, x, i, e);
- }
- }
- static void gauss_jordan_elimination(matrix *m) {
- for (int k = 0; k < m->r; ++k) {
- pivot(m, k);
- double p = matrix_at(m, k, k);
- for (int j = 0; j < m->c; ++j) {
- double e = matrix_at(m, k, j);
- matrix_as(m, k, j, e / p);
- }
- for (int i = 0; i < m->r; ++i) {
- if (i == k) {
- continue;
- }
- double e = matrix_at(m, i, k);
- for (int j = 0; j < m->c; ++j) {
- double f = matrix_at(m, i, j);
- double g = matrix_at(m, k, j);
- matrix_as(m, i, j, f - e * g);
- }
- }
- }
- }
- static void matrix_print(matrix *m) {
- for (int i = 0; i < m->r; ++i) {
- for (int j = 0; j < m->c; ++j) {
- printf("%s%lf", ((j == 0) ? "" : " "), matrix_at(m, i, j));
- }
- puts("");
- }
- }
- int main() {
- double v[] = {
- 2., 1., 3., 1., 0., 0.,
- 1., 3., 2., 0., 1., 0.,
- 3., 2., 1., 0., 0., 1.
- };
- matrix m = { 3, 6, v };
- matrix_print(&m);
- gauss_jordan_elimination(&m);
- matrix_print(&m);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement