array_matrix/matrix/trace.rs
1use std::ops::Add;
2use num_traits::Zero;
3
4use super::SquareMatrix;
5
6pub trait Trace: SquareMatrix
7{
8 type Output;
9
10 /// Returns the trace of a given matrix
11 ///
12 /// tr(A)
13 ///
14 /// # Examples
15 ///
16 /// ```rust
17 /// let a = [
18 /// [1.0, 2.0, 3.0],
19 /// [4.0, 5.0, 6.0],
20 /// [7.0, 8.0, 9.0]
21 /// ];
22 /// let t = a[0][0] + a[1][1] + a[2][2];
23 /// assert_eq!(a.trace(), t);
24 /// ```
25 fn trace(&self) -> Self::Output;
26}
27
28impl<F, const N: usize> Trace for [[F; N]; N]
29where
30 Self: SquareMatrix,
31 F: Add<F, Output = F> + Clone + Zero
32{
33 type Output = F;
34 fn trace(&self) -> Self::Output
35 {
36 (0..N).map(|i| self[i][i].clone()).reduce(|a, b| a + b).unwrap_or(F::zero())
37 }
38}