Add a copy_from_slice method.

Fix #381.
This commit is contained in:
sebcrozet 2018-09-13 05:38:57 +02:00 committed by Sébastien Crozet
parent 1706f9c15f
commit 99b54465c7
3 changed files with 41 additions and 0 deletions

View File

@ -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.

View File

@ -475,6 +475,27 @@ impl<N: Scalar, R: Dim, C: Dim, S: StorageMut<N, R, C>> Matrix<N, R, C, S> {
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<R2, C2, SB>(&mut self, other: &Matrix<N, R2, C2, SB>)

View File

@ -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);