From 787d638a1b4a65185b98484056fc087e57f25f23 Mon Sep 17 00:00:00 2001 From: Agathoklis Papadopoulos Date: Wed, 18 Oct 2023 10:22:11 +0400 Subject: [PATCH] Improvements on median_filter --- Cargo.toml | 2 +- README.md | 3 +++ src/mathematics/median_filter.rs | 22 +++++++++++----------- 3 files changed, 15 insertions(+), 12 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 1316d24..fc24bec 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "utils-box" -version = "0.1.4" +version = "0.1.5" edition = "2021" authors = ["Agathoklis Papadopoulos "] license = "MIT" diff --git a/README.md b/README.md index 93bef7d..9f8b47c 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,9 @@ A toolbox library that holds a useful collection of small unitilies written in R # Utilities provided: +## Mathematics +A collection of useful methematic methods used in various DSP and other applications + ## Archives Extract files from Tar, Gz and Zip Files diff --git a/src/mathematics/median_filter.rs b/src/mathematics/median_filter.rs index 9d0607b..4a582ca 100644 --- a/src/mathematics/median_filter.rs +++ b/src/mathematics/median_filter.rs @@ -13,12 +13,12 @@ pub enum MedianPaddingMode { /// Wrapper to call median_filter() with the most useful configuration /// ZeroPad and IncludeNaN are active pub fn medianfilter_default(x: &[f64], n: usize) -> Vec { - return moving_median_filter( + moving_median_filter( x, n, MedianPaddingMode::ZeroPad, MedianMissingMode::IncludeNaN, - ); + ) } /// An implementation of Moving Median Filtering @@ -32,7 +32,7 @@ pub fn moving_median_filter( ) -> Vec { let len = x.len(); let mut y = vec![0.0; len]; - for i in 0..len { + for (i, y_value) in y.iter_mut().enumerate() { let mut segment: Vec = vec![]; let mut segment_start: i64 = i as i64 - (n as i64 - 1) / 2; if n % 2 == 0 { @@ -41,10 +41,9 @@ pub fn moving_median_filter( for j in 0..n { let index = segment_start + j as i64; if index < 0 || index >= len as i64 { - if padding == MedianPaddingMode::ZeroPad { - segment.push(0.0); - } else if padding == MedianPaddingMode::Truncate { - continue; + match padding { + MedianPaddingMode::ZeroPad => segment.push(0.0), + MedianPaddingMode::Truncate => continue, } } else { segment.push(x[index as usize]); @@ -56,20 +55,21 @@ pub fn moving_median_filter( } if segment.iter().any(|x| x.is_nan()) { - y[i] = f64::NAN; + *y_value = f64::NAN; continue; } segment.sort_by(|a, b| a.partial_cmp(b).unwrap()); if segment.len() % 2 == 1 { - y[i] = segment[segment.len() / 2]; + *y_value = segment[segment.len() / 2]; } else { let middle = segment.len() / 2; - y[i] = (segment[middle - 1] + segment[middle]) / 2.0; + *y_value = (segment[middle - 1] + segment[middle]) / 2.0; } } - return y; + + y } fn remove_nan(segment: &[f64]) -> Vec {