rust_linear_algebra/matrix/
inverse.rs1use super::identity::identity_mat;
2use super::Matrix;
3use crate::num::MinusOne;
4use crate::num::One;
5use std::fmt::Debug;
6use std::ops::{Add, Div, Mul, Sub, SubAssign};
7
8impl<K> Matrix<K>
9where
10 K: Debug
11 + Copy
12 + One
13 + MinusOne
14 + Default
15 + PartialEq
16 + Add<Output = K>
17 + Sub<Output = K>
18 + SubAssign<K>
19 + Mul<Output = K>
20 + Div<Output = K>,
21{
22 pub fn inverse(&self) -> Result<Matrix<K>, &str> {
23 if self.cols() != self.rows() {
24 return Err("Matrix must be a square");
25 }
26 let det = self.determinant();
27 if det == K::default() {
28 return Err("Matrix is singular and cannot be inverted");
29 }
30 let mut identity = identity_mat::<K>(self.cols(), self.rows());
31 let _ = self.gaussian_elimination(None, Some(&mut identity));
32 Ok(identity)
33 }
34}