mathru/algebra/linear/vector/index.rs
1use std::ops::{Index, IndexMut};
2
3use crate::algebra::linear::vector::Vector;
4
5impl<T> Index<usize> for Vector<T> {
6 type Output = T;
7
8 /// Returns the component
9 ///
10 /// # Panics
11 ///
12 /// if index is out of bounds
13 ///
14 /// # Example
15 ///
16 /// ```
17 /// use mathru::algebra::linear::vector::Vector;
18 ///
19 /// let mut a: Vector<f64> = Vector::new_row(vec![1.0, 0.0, 3.0, -2.0]);
20 ///
21 /// assert_eq!(-2.0, a[3])
22 /// ```
23 fn index(&self, index: usize) -> &Self::Output {
24 let num_rows = self.data.m;
25
26 if num_rows == 1 {
27 debug_assert!(
28 index < self.data.n,
29 "index out of bounds: is a 1x{} vector but the index is 0x{}",
30 self.data.n,
31 index
32 );
33 &self.data[[0, index]]
34 } else {
35 debug_assert!(
36 index < num_rows,
37 "index out of bounds: is a {}x1 vector but the index is {}x0",
38 num_rows,
39 index
40 );
41 &self.data[[index, 0]]
42 }
43 }
44}
45
46impl<T> IndexMut<usize> for Vector<T> {
47 /// Returns the component
48 ///
49 /// # Panics
50 ///
51 /// if index is out of bounds
52 ///
53 /// # Example
54 ///
55 /// ```
56 /// use mathru::algebra::linear::vector::Vector;
57 ///
58 /// let mut a: Vector<f64> = Vector::new_row(vec![1.0, 0.0, 3.0, -2.0]);
59 ///
60 /// assert_eq!(-2.0, a[3])
61 /// ```
62 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
63 let num_rows = self.data.m;
64
65 if num_rows == 1 {
66 debug_assert!(
67 index < self.data.n,
68 "index out of bounds: is a 1x{} vector but the index is 0x{}",
69 self.data.n,
70 index
71 );
72 &mut self.data[[0, index]]
73 } else {
74 debug_assert!(
75 index < num_rows,
76 "index out of bounds: is a {}x1 vector but the index is {}x0",
77 num_rows,
78 index
79 );
80 &mut self.data[[index, 0]]
81 }
82 }
83}