1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use ndarray::prelude::*;
use ndarray::LinalgScalar;
use num_traits::float::Float;
use matrix::Matrix;
use error::{LinalgError, NotSquareError};
use qr::ImplQR;
use svd::ImplSVD;
use norm::ImplNorm;
use solve::ImplSolve;
pub trait SquareMatrix: Matrix {
fn inv(self) -> Result<Self, LinalgError>;
fn trace(&self) -> Result<Self::Scalar, LinalgError>;
fn check_square(&self) -> Result<(), NotSquareError> {
let (rows, cols) = self.size();
if rows == cols {
Ok(())
} else {
Err(NotSquareError {
rows: rows,
cols: cols,
})
}
}
}
impl<A> SquareMatrix for Array<A, (Ix, Ix)>
where A: ImplQR + ImplNorm + ImplSVD + ImplSolve + LinalgScalar + Float
{
fn inv(self) -> Result<Self, LinalgError> {
try!(self.check_square());
let (n, _) = self.size();
let is_fortran_align = self.strides()[0] > self.strides()[1];
let a = try!(ImplSolve::inv(n, self.into_raw_vec()));
let m = Array::from_vec(a).into_shape((n, n)).unwrap();
if is_fortran_align {
Ok(m)
} else {
Ok(m.reversed_axes())
}
}
fn trace(&self) -> Result<Self::Scalar, LinalgError> {
try!(self.check_square());
let (n, _) = self.size();
Ok((0..n).fold(A::zero(), |sum, i| sum + self[(i, i)]))
}
}