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
use crate::algebra::linear::{Vector, Matrix};
use crate::algebra::abstr::{Field, Scalar};
use crate::algebra::linear::matrix::{Substitute};


pub trait Solve<T>
{
    /// A * x = b
    ///
    ///
    fn solve(self: &Self, rhs: &T) -> Option<T>;
}

impl<T> Solve<Vector<T>> for  Matrix<T>
    where T: Field + Scalar
{
    /// Solves Ax = y
    ///  where A \in R^{m * n}, x \in R^n, y \in R^m
    ///
    ///
    fn solve(self: &Self, rhs: &Vector<T>) -> Option<Vector<T>>
    {
        let (l, u, p): (Matrix<T>, Matrix<T>, Matrix<T>) = self.dec_lu().lup();

        let b_hat: Vector<T> = &p * rhs;

        let y: Vector<T> = l.substitute_forward(b_hat);

        let x: Vector<T> = u.substitute_backward(y);

        return Some(x);
    }

}

impl<T> Solve<Matrix<T>> for Matrix<T>
    where T: Field + Scalar
{
    fn solve(self: &Self, rhs: &Matrix<T>) -> Option<Matrix<T>>
    {
        return self.dec_lu().solve(rhs);
    }
}