From 99b54465c7b6c67330593b77f81a765b74ecf66a Mon Sep 17 00:00:00 2001 From: sebcrozet Date: Thu, 13 Sep 2018 05:38:57 +0200 Subject: [PATCH] Add a copy_from_slice method. Fix #381. --- CHANGELOG.md | 5 +++++ src/base/matrix.rs | 21 +++++++++++++++++++++ tests/core/matrix.rs | 15 +++++++++++++++ 3 files changed, 41 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f3c09964..e03b90e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ documented here. This project adheres to [Semantic Versioning](http://semver.org/). +## [0.17.0] - WIP + +### Added + * Add `.copy_from_slice` to copy matrix components from a slice in column-major order. + ## [0.16.0] All dependencies have been updated to their latest versions. diff --git a/src/base/matrix.rs b/src/base/matrix.rs index fae56d70..2c7c673a 100644 --- a/src/base/matrix.rs +++ b/src/base/matrix.rs @@ -475,6 +475,27 @@ impl> Matrix { unsafe { self.swap_unchecked(row_cols1, row_cols2) } } + /// Fills this matrix with the content of a slice. Both must hold the same number of elements. + /// + /// The components of the slice are assumed to be ordered in column-major order. + #[inline] + pub fn copy_from_slice(&mut self, slice: &[N]) { + let (nrows, ncols) = self.shape(); + + assert!( + nrows * ncols == slice.len(), + "The slice must contain the same number of elements as the matrix." + ); + + for j in 0..ncols { + for i in 0..nrows { + unsafe { + *self.get_unchecked_mut(i, j) = *slice.get_unchecked(i + j * nrows); + } + } + } + } + /// Fills this matrix with the content of another one. Both must have the same shape. #[inline] pub fn copy_from(&mut self, other: &Matrix) diff --git a/tests/core/matrix.rs b/tests/core/matrix.rs index d515d0ac..1b08acca 100644 --- a/tests/core/matrix.rs +++ b/tests/core/matrix.rs @@ -239,6 +239,21 @@ fn from_rows_with_different_dimensions() { let _ = DMatrix::from_columns(columns); } +#[test] +fn copy_from_slice() { + let mut a = Matrix3::zeros(); + let data = [ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 ]; + let expected_a = Matrix3::new( + 1.0, 4.0, 7.0, + 2.0, 5.0, 8.0, + 3.0, 6.0, 9.0 + ); + + a.copy_from_slice(&data); + + assert_eq!(a, expected_a); +} + #[test] fn to_homogeneous() { let a = Vector3::new(1.0, 2.0, 3.0);