Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/base/matrix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -994,6 +994,25 @@ impl<T, R: Dim, C: Dim, S: RawStorage<T, R, C>> Matrix<T, R, C, S> {
}
}

/// Applies a closure `f` to modify each component of `self`. Unlike `apply`,
/// `f` also gets passed the row and column index, i.e. `f(row, col, value)`.
#[inline]
pub fn apply_with_location<F: FnMut(usize, usize, &mut T)>(&mut self, mut f: F)
where
S: RawStorageMut<T, R, C>,
{
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);
f(i, j, e)
}
}
}
}

/// Replaces each component of `self` by the result of a closure `f` applied on its components
/// joined with the components from `rhs`.
#[inline]
Expand Down
11 changes: 11 additions & 0 deletions tests/core/matrix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,17 @@ fn apply() {
assert_eq!(a, expected);
}

#[test]
fn apply_with_location() {
let mut a = Matrix3::new(1.1f32, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9);

let expected = Matrix3::new(1.1, 3.2, 5.3, 5.4, 7.5, 9.6, 9.7, 11.8, 13.9);

a.apply_with_location(|i, j, e| *e += i as f32 + j as f32);

assert_eq!(a, expected);
}

#[test]
fn map() {
let a = Matrix4::new(
Expand Down