-
Notifications
You must be signed in to change notification settings - Fork 32
/
matlab_macro.rs
111 lines (105 loc) · 2.14 KB
/
matlab_macro.rs
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
105
106
107
108
109
110
111
extern crate rand;
pub use self::rand::prelude::*;
/// MATLAB like zeros - zero matrix
///
/// # Examples
/// ```
/// #[macro_use]
/// extern crate peroxide;
/// use peroxide::fuga::*;
///
/// fn main() {
/// let a = zeros!(4);
/// assert_eq!(a, c!(0,0,0,0));
///
/// let b = zeros!(3, 2);
/// assert_eq!(b, matrix(c!(0,0,0,0,0,0), 3, 2, Row));
/// }
/// ```
#[macro_export]
macro_rules! zeros {
( $n:expr ) => {
vec![0f64; $n]
};
( $r:expr, $c:expr ) => {{
let (r, c) = ($r, $c);
matrix(vec![0f64; r * c], r, c, Row)
}};
}
/// MATLAB like rand - random matrix
///
/// # Examples
/// ```
/// #[macro_use]
/// extern crate peroxide;
/// use peroxide::fuga::*;
///
/// fn main() {
/// let a = rand!(2, 2);
/// println!("{}", a); // 2 x 2 random matrix (0 ~ 1)
/// }
/// ```
#[macro_export]
macro_rules! rand {
() => {{
let mut rng = thread_rng();
rng.gen_range(0f64..=1f64)
}};
( $m:expr, $n:expr ) => {{
let r = $m;
let c = $n;
let mut rng = thread_rng();
let mut m = matrix(vec![0f64; r * c], r, c, Row);
for i in 0..r {
for j in 0..c {
m[(i, j)] = rng.gen_range(0f64..=1f64);
}
}
m
}};
}
/// MATLAB like eye - identity matrix
///
/// # Examples
///
/// ```
/// #[macro_use]
/// extern crate peroxide;
/// use peroxide::fuga::*;
///
/// fn main() {
/// let i = eye!(2);
/// assert_eq!(i, matrix(c!(1,0,0,1), 2, 2, Row));
/// }
/// ```
#[macro_export]
macro_rules! eye {
( $n:expr ) => {{
let n = $n;
let mut m = matrix(vec![0f64; n * n], n, n, Row);
for i in 0..n {
m[(i, i)] = 1f64;
}
m
}};
}
/// MATLAB like linspace
///
/// # Examples
/// ```
/// #[macro_use]
/// extern crate peroxide;
/// use peroxide::fuga::*;
///
/// fn main() {
/// let a = linspace!(1, 10, 10);
/// assert_eq!(a, seq!(1,10,1));
/// }
/// ```
#[macro_export]
macro_rules! linspace {
( $start:expr, $end:expr, $length: expr) => {{
let step = ($end - $start) as f64 / ($length as f64 - 1f64);
seq!($start, $end, step)
}};
}