Implements `Extend` for `Matrix<N, Dim, Dynamic>`.

Extends a matrix with new columns populated from an iterator.
This commit is contained in:
Jack Wrenn 2018-11-10 18:02:52 -05:00 committed by Sébastien Crozet
parent 41a1e91ac9
commit c3dd709c0a
2 changed files with 66 additions and 0 deletions

View File

@ -703,3 +703,51 @@ unsafe fn extend_rows<N: Scalar>(
); );
} }
} }
/// Extend the number of columns of the `Matrix` with elements from
/// a given iterator.
impl<N, R, S> Extend<N> for Matrix<N, R, Dynamic, S>
where
N: Scalar,
R: Dim,
S: Extend<N>,
{
/// Extend the number of columns of the `Matrix` with elements
/// from the given iterator.
///
/// # Example
/// ```
/// use nalgebra::{Dynamic, Matrix, MatrixMN, Matrix3};
///
/// let data = vec![0, 1, 2, // column 1
/// 3, 4, 5]; // column 2
///
/// let mut matrix : MatrixMN<_, Dynamic, Dynamic> =
/// Matrix::from_vec_generic(Dynamic::new(3), Dynamic::new(2), data);
///
/// matrix.extend(vec![6, 7, 8]); // column 3
///
/// assert!(matrix.eq(&Matrix3::new(0, 3, 6,
/// 1, 4, 7,
/// 2, 5, 8)));
/// ```
///
/// # Panics
/// This function panics if the number of elements yielded by the
/// given iterator is not a multiple of the number of rows of the
/// `Matrix`.
///
/// ```should_panic
/// # use nalgebra::{Dynamic, Matrix, MatrixMN, Matrix3, U3};
/// let data = vec![0, 1, 2, // column 1
/// 3, 4, 5]; // column 2
///
/// let mut matrix : MatrixMN<_, U3, Dynamic> =
/// Matrix::from_vec_generic(U3, Dynamic::new(2), data);
///
/// matrix.extend(vec![6, 7, 8, 9]); // column 3
/// ```
fn extend<I: IntoIterator<Item=N>>(&mut self, iter: I) {
self.data.extend(iter);
}
}

View File

@ -240,3 +240,21 @@ unsafe impl<N: Scalar, R: DimName> ContiguousStorage<N, R, Dynamic> for MatrixVe
unsafe impl<N: Scalar, R: DimName> ContiguousStorageMut<N, R, Dynamic> for MatrixVec<N, R, Dynamic> where DefaultAllocator: Allocator<N, R, Dynamic, Buffer = Self> unsafe impl<N: Scalar, R: DimName> ContiguousStorageMut<N, R, Dynamic> for MatrixVec<N, R, Dynamic> where DefaultAllocator: Allocator<N, R, Dynamic, Buffer = Self>
{} {}
impl<N, R: Dim> Extend<N> for MatrixVec<N, R, Dynamic>
{
/// Extends the number of columns of the `MatrixVec` with elements
/// from the given iterator.
///
/// # Panics
/// This function panics if the number of elements yielded by the
/// given iterator is not a multiple of the number of rows of the
/// `MatrixVec`.
fn extend<I: IntoIterator<Item=N>>(&mut self, iter: I)
{
self.data.extend(iter);
self.ncols = Dynamic::new(self.data.len() / self.nrows.value());
assert!(self.data.len() % self.nrows.value() == 0,
"The number of elements produced by the given iterator was not a multiple of the number of rows.");
}
}