@@ -4,10 +4,23 @@ use std::iter::Sum;
4
4
use ndarray:: * ;
5
5
use num_traits:: Float ;
6
6
use super :: vector:: * ;
7
+ use std:: ops:: Div ;
8
+
9
+ /// construct matrix from diag
10
+ pub fn from_diag < A > ( d : & [ A ] ) -> Array2 < A >
11
+ where A : LinalgScalar
12
+ {
13
+ let n = d. len ( ) ;
14
+ let mut e = Array :: zeros ( ( n, n) ) ;
15
+ for i in 0 ..n {
16
+ e[ ( i, i) ] = d[ i] ;
17
+ }
18
+ e
19
+ }
7
20
8
21
/// stack vectors into matrix horizontally
9
22
pub fn hstack < A , S > ( xs : & [ ArrayBase < S , Ix1 > ] ) -> Result < Array < A , Ix2 > , ShapeError >
10
- where A : NdFloat ,
23
+ where A : LinalgScalar ,
11
24
S : Data < Elem = A >
12
25
{
13
26
let views: Vec < _ > = xs. iter ( )
@@ -21,7 +34,7 @@ pub fn hstack<A, S>(xs: &[ArrayBase<S, Ix1>]) -> Result<Array<A, Ix2>, ShapeErro
21
34
22
35
/// stack vectors into matrix vertically
23
36
pub fn vstack < A , S > ( xs : & [ ArrayBase < S , Ix1 > ] ) -> Result < Array < A , Ix2 > , ShapeError >
24
- where A : NdFloat ,
37
+ where A : LinalgScalar ,
25
38
S : Data < Elem = A >
26
39
{
27
40
let views: Vec < _ > = xs. iter ( )
@@ -33,6 +46,26 @@ pub fn vstack<A, S>(xs: &[ArrayBase<S, Ix1>]) -> Result<Array<A, Ix2>, ShapeErro
33
46
stack ( Axis ( 0 ) , & views)
34
47
}
35
48
49
+ pub enum NormalizeAxis {
50
+ Row = 0 ,
51
+ Column = 1 ,
52
+ }
53
+
54
+ /// normalize in L2 norm
55
+ pub fn normalize < A , S , T > ( mut m : ArrayBase < S , Ix2 > , axis : NormalizeAxis ) -> ( ArrayBase < S , Ix2 > , Vec < T > )
56
+ where A : LinalgScalar + NormedField < Output = T > + Div < T , Output = A > ,
57
+ S : DataMut < Elem = A > ,
58
+ T : Float + Sum
59
+ {
60
+ let mut ms = Vec :: new ( ) ;
61
+ for mut v in m. axis_iter_mut ( Axis ( axis as usize ) ) {
62
+ let n = v. norm ( ) ;
63
+ ms. push ( n) ;
64
+ v. map_inplace ( |x| * x = * x / n)
65
+ }
66
+ ( m, ms)
67
+ }
68
+
36
69
/// check two arrays are close in maximum norm
37
70
pub fn all_close_max < A , Tol , S1 , S2 , D > ( test : & ArrayBase < S1 , D > ,
38
71
truth : & ArrayBase < S2 , D > ,
0 commit comments