diff --git a/src/core/matrix.rs b/src/core/matrix.rs index 809611bb..eef100e8 100644 --- a/src/core/matrix.rs +++ b/src/core/matrix.rs @@ -284,8 +284,8 @@ impl> Matrix { /// Returns a matrix containing the result of `f` applied to each of its entries. #[inline] - pub fn map N>(&self, mut f: F) -> MatrixMN - where DefaultAllocator: Allocator { + pub fn map N2>(&self, mut f: F) -> MatrixMN + where DefaultAllocator: Allocator { let (nrows, ncols) = self.data.shape(); let mut res = unsafe { MatrixMN::new_uninitialized_generic(nrows, ncols) }; @@ -440,6 +440,22 @@ impl> Matrix { ShapeConstraint: SameNumberOfRows { self.column_mut(i).copy_from(column); } + + /// Replaces each component of `self` by the result of a closure `f` applied on it. + #[inline] + pub fn apply N>(&mut self, mut f: F) + where DefaultAllocator: Allocator { + let (nrows, ncols) = self.shape(); + + for j in 0 .. ncols { + for i in 0 .. nrows { + unsafe { + let e = self.data.get_unchecked_mut(i, j); + *e = f(*e) + } + } + } + } } impl> Vector { diff --git a/tests/core/matrix.rs b/tests/core/matrix.rs index d60029a2..6ef8722a 100644 --- a/tests/core/matrix.rs +++ b/tests/core/matrix.rs @@ -1,4 +1,5 @@ use num::{Zero, One}; +use num::Float; use std::fmt::Display; use alga::linear::FiniteDimInnerSpace; @@ -395,6 +396,44 @@ fn simple_scalar_conversion() { assert_eq!(expected, a_u32); } +#[test] +fn apply() { + let mut a = Matrix4::new( + 1.1, 2.2, 3.3, 4.4, + 5.5, 6.6, 7.7, 8.8, + 9.9, 8.8, 7.7, 6.6, + 5.5, 4.4, 3.3, 2.2); + + let expected = Matrix4::new( + 1.0, 2.0, 3.0, 4.0, + 6.0, 7.0, 8.0, 9.0, + 10.0, 9.0, 8.0, 7.0, + 6.0, 4.0, 3.0, 2.0); + + a.apply(|e| e.round()); + + assert_eq!(a, expected); +} + +#[test] +fn map() { + let a = Matrix4::new( + 1.1f64, 2.2, 3.3, 4.4, + 5.5, 6.6, 7.7, 8.8, + 9.9, 8.8, 7.7, 6.6, + 5.5, 4.4, 3.3, 2.2); + + let expected = Matrix4::new( + 1, 2, 3, 4, + 6, 7, 8, 9, + 10, 9, 8, 7, + 6, 4, 3, 2); + + let computed = a.map(|e| e.round() as i64); + + assert_eq!(computed, expected); +} + #[test] #[should_panic] fn trace_panic() {