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
use model::{Matrix, Vector};

/// Return the rows of the matrix as a Vec of Vectors.
pub fn as_rows<T: Copy>(m: Matrix<T>) -> Vec<Vector<T>> {
    m.outer_iter().map(|x| { x.to_owned() }).collect()
}

/// Given an n✕n matrix,return an n✕(n-1) matrix formed by removing the diagonal elements
pub fn remove_diagonal(x: Matrix<f32>) -> Matrix<f32> {
    let n = x.rows();
    let v: Vec<f32> = x.iter().enumerate().filter_map(|(i, e)| {
        if i % (n+1) == 0 { None } else { Some(*e) }
    }).collect();

    Matrix::from_shape_vec((n, n-1), v).ok().unwrap()
}

#[cfg(test)]
mod tests {
    use super::*;
    use super::super::model::{Matrix};

    #[test]
    fn rd_test() {
        let v: Vec<f32> = vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
        let m: Matrix<f32> = Matrix::from_shape_vec((3, 3), v).ok().unwrap();
        let rdm: Matrix<f32> = Matrix::from_shape_vec((3, 2), vec![1.0, 2.0, 3.0, 5.0, 6.0, 7.0]).ok().unwrap();
        assert_eq!(remove_diagonal(m).iter(), rdm.iter());
    }
}