Skip to content

Commit

Permalink
Implements Extend for Matrix<N, Dim, Dynamic>.
Browse files Browse the repository at this point in the history
Extends a matrix with new columns populated from an iterator.
  • Loading branch information
jswrenn committed Nov 10, 2018
1 parent 41a1e91 commit 9965163
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
48 changes: 48 additions & 0 deletions src/base/edition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
18 changes: 18 additions & 0 deletions src/base/matrix_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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>
{}

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.");
}
}

0 comments on commit 9965163

Please sign in to comment.