array_matrix/matrix/
det.rs

1use std::ops::{Mul, Sub, Add};
2
3use crate::SquareMatrix;
4
5use super::Matrix;
6use super::minor::Minor;
7
8pub trait Det: SquareMatrix
9{
10    type Output;
11
12    /// Returns the determinant of the given matrix
13    /// 
14    /// |A|
15    /// 
16    /// # Examples
17    /// 
18    /// ```rust
19    /// let a = [
20    ///     [1.0, 0.0],
21    ///     [0.0, 1.0]
22    /// ];
23    /// assert_eq!(a.det(), 1.0);
24    /// ```
25    fn det(&self) -> Self::Output;
26}
27
28impl<F: Clone> Det for [[F; 1]; 1]
29where Self: SquareMatrix
30{
31    type Output = F;
32
33    fn det(&self) -> Self::Output
34    {
35        self[0][0].clone()
36    }
37}
38
39impl<F: Clone + Mul<F, Output = F> + Sub<F, Output = F>> Det for [[F; 2]; 2]
40where Self: SquareMatrix
41{
42    type Output = F;
43
44    fn det(&self) -> Self::Output
45    {
46        self[0][0].clone()*self[1][1].clone() - self[0][1].clone()*self[1][0].clone()
47    }
48}
49
50macro_rules! det {
51    ($i:expr) => {
52        impl<F> Det for [[F; $i]; $i]
53        where
54            F: Clone + Mul<F, Output = F> + Add<F, Output = F>,
55            Self: SquareMatrix + Minor<Output = F, Index = (usize, usize)>
56        {
57            type Output = F;
58        
59            fn det(&self) -> Self::Output
60            {
61                (0..self.length())
62                    .map(|i| self[i][0].clone()*self.minor((i, 0)))
63                    .reduce(|a, b| a + b)
64                    .unwrap()
65            }
66        }
67    };
68}
69
70det!(3);
71det!(4);
72det!(5);
73det!(6);
74det!(7);
75det!(8);
76det!(9);
77det!(10);
78det!(11);
79det!(12);
80det!(13);
81det!(14);
82det!(15);
83det!(16);