From 1338e0c35867b9604718b73f3c6f591d5cca2568 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Crozet?= Date: Sun, 10 Jan 2016 14:50:08 +0100 Subject: [PATCH] DMat: implement `from_row_iter` and `from_col_iter`. Those create a DMat by moving its argument into an interator and collecting it. Fix #167. --- src/structs/dmat.rs | 45 +++++++++++++++++++++++++++++++++++---------- 1 file changed, 35 insertions(+), 10 deletions(-) diff --git a/src/structs/dmat.rs b/src/structs/dmat.rs index 090c7789..efc359df 100644 --- a/src/structs/dmat.rs +++ b/src/structs/dmat.rs @@ -55,15 +55,10 @@ impl DMat { /// Note that `from_col_vec` is much faster than `from_row_vec` since a `DMat` stores its data /// in column-major order. /// - /// The vector must have at least `nrows * ncols` elements. + /// The vector must have exactly `nrows * ncols` elements. #[inline] pub fn from_row_vec(nrows: usize, ncols: usize, vec: &[N]) -> DMat { - let mut res = DMat::from_col_vec(ncols, nrows, vec); - - // we transpose because the buffer is row_major - res.transpose_mut(); - - res + DMat::from_row_iter(nrows, ncols, vec.to_vec()) } /// Builds a matrix filled with the components provided by a vector. @@ -71,15 +66,45 @@ impl DMat { /// Note that `from_col_vec` is much faster than `from_row_vec` since a `DMat` stores its data /// in column-major order. /// - /// The vector must have at least `nrows * ncols` elements. + /// The vector must have exactly `nrows * ncols` elements. #[inline] pub fn from_col_vec(nrows: usize, ncols: usize, vec: &[N]) -> DMat { - assert!(nrows * ncols == vec.len()); + DMat::from_col_iter(nrows, ncols, vec.to_vec()) + } + + /// Builds a matrix filled with the components provided by a source that may be moved into an iterator. + /// The source contains the matrix data in row-major order. + /// Note that `from_col_iter` is much faster than `from_row_iter` since a `DMat` stores its data + /// in column-major order. + /// + /// The source must have exactly `nrows * ncols` elements. + #[inline] + pub fn from_row_iter>(nrows: usize, ncols: usize, param: I) -> DMat { + let mut res = DMat::from_col_iter(ncols, nrows, param); + + // we transpose because the buffer is row_major + res.transpose_mut(); + + res + } + + + /// Builds a matrix filled with the components provided by a source that may be moved into an iterator. + /// The source contains the matrix data in column-major order. + /// Note that `from_col_iter` is much faster than `from_row_iter` since a `DMat` stores its data + /// in column-major order. + /// + /// The source must have exactly `nrows * ncols` elements. + #[inline] + pub fn from_col_iter>(nrows: usize, ncols: usize, param: I) -> DMat { + let mij: Vec = param.into_iter().collect(); + + assert!(nrows * ncols == mij.len(), "The ammount of data provided does not matches the matrix size."); DMat { nrows: nrows, ncols: ncols, - mij: vec.to_vec() + mij: mij } } }