Correct determinant for nxn matrices

main
Micke Nordin 2 years ago
parent 401e097a84
commit 24e8b2bcc1
Signed by: micke
GPG Key ID: 014B273D614BE877

@ -3,6 +3,7 @@
#include "vector.hpp"
#include <cstdint>
#include <iostream>
#include <ostream>
#include <sstream>
#include <string>
class matrix {
@ -12,6 +13,31 @@ private:
vector *entries;
bool err;
bool augmented = false;
// recursive determinant
const cnumber rdeterminant(matrix m) const {
if (m.get_num_entries() == 2) {
cnumber dsum(1, 0);
cnumber osum(1, 0);
vector diag = m.get_diagonal();
vector odiag = m.get_off_diagonal();
for (uint64_t i = 0; i < diag.get_dimention(); i++) {
dsum = dsum * diag[i];
osum = osum * odiag[i];
}
return dsum - osum;
} else {
cnumber sum = 0;
cnumber sign(1);
for (uint64_t i = 0; i < m.entry_dimension; i++) {
matrix n = m.remove_first_row_and_column(i);
if(i % 2 == 0)
sum = sum + (m[0][i] * rdeterminant(n));
else
sum = sum - (m[0][i] * rdeterminant(n));
}
return sum;
}
}
public:
// Constructors/destructor
@ -76,15 +102,9 @@ public:
return n;
}
const cnumber determinant() const {
cnumber dsum(1, 0);
cnumber osum(1, 0);
vector diag = this->get_diagonal();
vector odiag = this->get_off_diagonal();
for (uint64_t i = 0; i < diag.get_dimention(); i++) {
dsum = dsum * diag[i];
osum = osum * odiag[i];
}
return dsum - osum;
if (this->num_entries != this->entry_dimension)
return 0;
return rdeterminant(*this);
}
// switch row i with row j
const matrix exchange_row(uint64_t i, uint64_t j) {
@ -122,6 +142,15 @@ public:
if (!m.is_invertible()) {
m.err = true;
} else {
uint64_t num_entries = m.get_num_entries();
for (uint64_t i = 0; i < num_entries - 1; i++) {
for (uint64_t j = i; j < num_entries; j++) {
cnumber ratio = m[j][i] / m[i][i];
for (uint64_t k = i; k < num_entries; k++) {
m[j][k] = m[j][k] - (ratio * m[i][k]);
}
}
}
}
return m;
}
@ -153,6 +182,7 @@ public:
}
return m;
}
const bool is_broken() const { return this->err; }
const bool is_diagonal() const {
bool result = true;
if (this->num_entries != this->entry_dimension)
@ -192,6 +222,21 @@ public:
return m;
}
const matrix remove_first_row_and_column(uint64_t column) const {
matrix m(this->num_entries - 1, this->entry_dimension - 1);
uint64_t add = 0;
for (uint64_t i = 1; i < this->num_entries; i++) {
for (uint64_t j = 0; j < this->entry_dimension; j++) {
if (j != column) {
m[i - 1][j - add] = this->get_entry(i)[j];
} else {
add = 1;
}
}
add = 0;
}
return m;
}
const matrix rotate() const {
matrix m = this->transpose();
matrix n = matrix(m.entry_dimension, m.num_entries);

Loading…
Cancel
Save