From 3055c289c06ea3d42ffbd0b7131d8549b62e89ce Mon Sep 17 00:00:00 2001 From: shivshank Date: Wed, 9 Jan 2019 21:38:58 -0500 Subject: [PATCH 1/2] Add `push` method to Vector --- src/base/matrix.rs | 16 ++++++++++++++++ tests/core/matrix.rs | 12 ++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/base/matrix.rs b/src/base/matrix.rs index 7a29fe2a..172e293f 100644 --- a/src/base/matrix.rs +++ b/src/base/matrix.rs @@ -859,6 +859,22 @@ impl, S: Storage> Vector { } } +impl, S: Storage> Vector { + /// Constructs a new vector of higher dimension by appending `element` to the end of `self`. + #[inline] + pub fn push(&self, element: N) -> VectorN> + where DefaultAllocator: Allocator> { + let len = self.len(); + let hnrows = DimSum::::from_usize(len + 1); + let mut res = unsafe { VectorN::::new_uninitialized_generic(hnrows, U1) }; + res.generic_slice_mut((0, 0), self.data.shape()) + .copy_from(self); + res[(len, 0)] = element; + + res + } +} + impl AbsDiffEq for Matrix where N: Scalar + AbsDiffEq, diff --git a/tests/core/matrix.rs b/tests/core/matrix.rs index 2569ea7a..e3fa2bdb 100644 --- a/tests/core/matrix.rs +++ b/tests/core/matrix.rs @@ -287,6 +287,18 @@ fn to_homogeneous() { assert_eq!(d.to_homogeneous(), expected_d); } +#[test] +fn push() { + let a = Vector3::new(1.0, 2.0, 3.0); + let expected_a = Vector4::new(1.0, 2.0, 3.0, 4.0); + + let b = DVector::from_row_slice(3, &[1.0, 2.0, 3.0]); + let expected_b = DVector::from_row_slice(4, &[1.0, 2.0, 3.0, 4.0]); + + assert_eq!(a.push(4.0), expected_a); + assert_eq!(b.push(4.0), expected_b); +} + #[test] fn simple_add() { let a = Matrix2x3::new(1.0, 2.0, 3.0, 4.0, 5.0, 6.0); From 85a943b7ef8003328325c8f327a2d3d5f8cd2116 Mon Sep 17 00:00:00 2001 From: shivshank Date: Wed, 9 Jan 2019 21:48:03 -0500 Subject: [PATCH 2/2] Rewrite to_homogenous for vectors to use push --- src/base/matrix.rs | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/base/matrix.rs b/src/base/matrix.rs index 172e293f..38f7241f 100644 --- a/src/base/matrix.rs +++ b/src/base/matrix.rs @@ -832,14 +832,7 @@ impl, S: Storage> Vector { #[inline] pub fn to_homogeneous(&self) -> VectorN> where DefaultAllocator: Allocator> { - let len = self.len(); - let hnrows = DimSum::::from_usize(len + 1); - let mut res = unsafe { VectorN::::new_uninitialized_generic(hnrows, U1) }; - res.generic_slice_mut((0, 0), self.data.shape()) - .copy_from(self); - res[(len, 0)] = N::zero(); - - res + self.push(N::zero()) } /// Constructs a vector from coordinates in projective space, i.e., removes a `0` at the end of