Skip to content

Instantly share code, notes, and snippets.

@jiunbae
Created November 1, 2015 14:28
Show Gist options
  • Save jiunbae/fa6a440c87b31b1c809b to your computer and use it in GitHub Desktop.
Save jiunbae/fa6a440c87b31b1c809b to your computer and use it in GitHub Desktop.
//
// rREF.h
//
// Reduced row echelon form via Gauss-Jordan elimination
// with partial pivoting.
//
// INPUT: vector<vector<T>> nxm matrix
//
// OUTPUT: rank
//
// Time: O(n^3)
//
//
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
const double EPSILON = 1e-10;
typedef double T;
typedef vector<T> VT;
typedef vector<VT> VVT;
int rref(VVT &a) {
int n = a.size();
int m = a[0].size();
int r = 0;
for (int c = 0; c < m && r < n; c++) {
int j = r;
for (int i = r+1; i < n; i++)
if (fabs(a[i][c]) > fabs(a[j][c])) j = i;
if (fabs(a[j][c]) < EPSILON) continue;
swap(a[j], a[r]);
T s = 1.0 / a[r][c];
for (int j = 0; j < m; j++) a[r][j] *= s;
for (int i = 0; i < n; i++) if (i != r) {
T t = a[i][c];
for (int j = 0; j < m; j++) a[i][j] -= t * a[r][j];
}
r++;
}
return r;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment