Skip to content

Instantly share code, notes, and snippets.

@hiraksarkar
Last active January 10, 2020 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hiraksarkar/715c18947fe6d57c79e08f22ec4030ad to your computer and use it in GitHub Desktop.
Save hiraksarkar/715c18947fe6d57c79e08f22ec4030ad to your computer and use it in GitHub Desktop.
use ndarray::prelude::*;
fn std1d(a: ArrayView1<'_, f64>) -> f64 {
let n = a.len() as f64;
if n == 0. {
return 0.;
}
let mean = a.sum() / n;
(a.fold(0., |acc, &x| acc + (x - mean).powi(2)) / n).sqrt()
}
fn std(a: &Array2<f64>, axis: Axis) -> Array1<f64> {
a.map_axis(axis, std1d)
}
fn main() {
// "recreating the following"
// counts -= np.mean(counts, axis=0)
// counts /= np.std(counts, axis=0)
let mut data = array![[-1., -2., -3.], [1., -3., 5.], [2., 2., 2.]];
println!("{:8.4}", data);
println!("{:8.4} (Mean axis=0)", data.mean_axis(Axis(0)).unwrap());
data -= &data.mean_axis(Axis(0)).unwrap();
println!("{:8.4}", data);
data /= &std(&data, Axis(0));
println!("{:8.4}", data);
}
#[macro_use]
extern crate ndarray;
fn main() {
let numbers = array![[0, 1, 0], [2, 0, 3]];
let nonzero: Vec<_> = numbers
.indexed_iter()
.filter_map(|(index, &item)| if item != 0 { Some(index) } else { None })
.collect();
assert_eq!(nonzero, vec![(0, 1), (1, 0), (1, 2)]);
let bools = array![[false, true, false], [true, false, true]];
let nonzero: Vec<_> = bools
.indexed_iter()
.filter_map(|(index, &item)| if item { Some(index) } else { None })
.collect();
assert_eq!(nonzero, vec![(0, 1), (1, 0), (1, 2)]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment