Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using namespace std;
- void getCfactor(vector<vector<float >> &M, vector<vector<float >> &t, int p, int q, int n) {
- int i = 0, j = 0;
- for (int r = 0; r < n; r++) {
- for (int c = 0; c < n; c++) //Copy only those elements which are not in given row r and column c: {
- if (r != p && c != q) {
- t[i][j++] = M[r][c]; //If row is filled increase r index and reset c index
- if (j == n - 1) {
- j = 0;
- i++;
- }
- }
- }
- }
- float DET(vector<vector<float >> &matrix, int n) {
- float D = 0;
- if (n == 1)
- return matrix[0][0];
- vector<vector<float>> t = vector<vector<float>> (matrix.size());
- for (int i = 0; i < matrix.size(); i++) {
- t[i] = vector<float > (matrix.size());
- }
- float s = 1; //store sign multiplier //
- for (int f = 0; f < n; f++) {
- getCfactor(matrix, t, 0, f, n);
- D += s * matrix[0][f] * DET(t, n - 1);
- s = -s;
- }
- return D;
- }
- void ADJ(vector<vector<float >> &M, vector<vector<float >> &adj) {
- if (M.size() == 1) {
- adj[0][0] = 1;
- return;
- }
- float s = 1;
- vector<vector<float>> t = vector<vector<float>> (M.size());
- for (int i = 0; i < M.size(); i++) {
- t[i] = vector<float > (M.size());
- }
- for (int i = 0; i < M.size(); i++) {
- for (int j = 0; j < M.size(); j++) {
- getCfactor(M, t, i, j, M.size());
- s = ((i + j) % 2 == 0) ? 1 : -1; //sign of adj[j][i] positive if sum of row and column indexes is even.
- adj[j][i] = (s) * (DET(t, M.size() - 1)); //Interchange rows and columns to get the transpose of the cofactor matrix
- }
- }
- }
- bool INV(vector<vector<float>> &matrix, vector<vector<float>> &res) {
- float det = DET(matrix, matrix.size());
- if (det == 0) {
- cout << "can't find its inverse";
- return false;
- }
- vector<vector<float>> adj = vector<vector<float>>(matrix.size());
- for (int i = 0; i < matrix.size(); i++) {
- adj[i] = vector<float > (matrix.size());
- }
- ADJ(matrix, adj);
- for (int i = 0; i < matrix.size(); i++) for (int j = 0; j < matrix.size(); j++) res[i][j] = adj[i][j] / float(det);
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement