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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
use std::ops::{Deref, DerefMut};
use {Element, Matrix, Size};
#[derive(Clone, Debug, PartialEq)]
pub struct Diagonal<T: Element> {
pub rows: usize,
pub columns: usize,
pub values: Vec<T>,
}
macro_rules! new(
($rows:expr, $columns:expr, $values:expr) => (
Diagonal { rows: $rows, columns: $columns, values: $values }
);
);
mod convert;
mod operation;
#[cfg(debug_assertions)]
impl<T: Element> ::format::Validate for Diagonal<T> {
fn validate(&self) {
assert_eq!(self.values.len(), min!(self.rows, self.columns))
}
}
size!(Diagonal);
impl<T: Element> Diagonal<T> {
pub fn new<S: Size>(size: S) -> Self {
let (rows, columns) = size.dimensions();
new!(rows, columns, vec![T::zero(); min!(rows, columns)])
}
pub fn from_slice<S: Size>(size: S, values: &[T]) -> Self {
let (rows, columns) = size.dimensions();
debug_assert_eq!(values.len(), min!(rows, columns));
new!(rows, columns, values.to_vec())
}
pub fn from_vec<S: Size>(size: S, values: Vec<T>) -> Self {
let (rows, columns) = size.dimensions();
debug_assert_eq!(values.len(), min!(rows, columns));
new!(rows, columns, values)
}
pub unsafe fn with_uninitialized<S: Size>(size: S) -> Self {
let (rows, columns) = size.dimensions();
new!(rows, columns, buffer!(min!(rows, columns)))
}
}
impl<T: Element> Matrix for Diagonal<T> {
type Element = T;
fn nonzeros(&self) -> usize {
self.values.iter().fold(0, |sum, &value| if value.is_zero() { sum } else { sum + 1 })
}
#[inline]
fn zero<S: Size>(size: S) -> Self {
Diagonal::new(size)
}
}
impl<T: Element> Deref for Diagonal<T> {
type Target = [T];
#[inline]
fn deref(&self) -> &Self::Target {
self.values.deref()
}
}
impl<T: Element> DerefMut for Diagonal<T> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
self.values.deref_mut()
}
}
#[cfg(test)]
mod tests {
use prelude::*;
#[test]
fn nonzeros() {
let matrix = Diagonal::from_vec(4, vec![1.0, 2.0, 0.0, 3.0]);
assert_eq!(matrix.nonzeros(), 3);
}
}