diff --git a/src/dmat.rs b/src/dmat.rs index 881d315c..41142f17 100644 --- a/src/dmat.rs +++ b/src/dmat.rs @@ -1,5 +1,5 @@ use std::num::{One, Zero}; -use std::vec::from_elem; +use std::vec; use std::cmp::ApproxEq; use std::util; use traits::inv::Inv; @@ -23,11 +23,7 @@ impl DMat { /// components. #[inline] pub fn new_zeros(nrows: uint, ncols: uint) -> DMat { - DMat { - nrows: nrows, - ncols: ncols, - mij: from_elem(nrows * ncols, Zero::zero()) - } + DMat::from_elem(nrows, ncols, Zero::zero()) } /// Tests if all components of the matrix are zeroes. @@ -37,6 +33,38 @@ impl DMat { } } +impl DMat { + /// Builds a matrix filled with a given constant. + #[inline] + pub fn new_ones(nrows: uint, ncols: uint) -> DMat { + DMat::from_elem(nrows, ncols, One::one()) + } +} + +impl DMat { + /// Builds a matrix filled with a given constant. + #[inline] + pub fn from_elem(nrows: uint, ncols: uint, val: N) -> DMat { + DMat { + nrows: nrows, + ncols: ncols, + mij: vec::from_elem(nrows * ncols, val) + } + } +} + +impl DMat { + /// Builds a matrix filled with a given constant. + #[inline(always)] + pub fn from_fn(nrows: uint, ncols: uint, f: &fn(uint, uint) -> N) -> DMat { + DMat { + nrows: nrows, + ncols: ncols, + mij: vec::from_fn(nrows * ncols, |i| { let m = i % ncols; f(m, m - i * ncols) }) + } + } +} + // FIXME: add a function to modify the dimension (to avoid useless allocations)? impl DMat { diff --git a/src/dvec.rs b/src/dvec.rs index d351556f..5caee856 100644 --- a/src/dvec.rs +++ b/src/dvec.rs @@ -1,6 +1,6 @@ use std::num::{Zero, One, Algebraic}; +use std::vec; use std::vec::{VecIterator, VecMutIterator}; -use std::vec::from_elem; use std::cmp::ApproxEq; use std::iterator::FromIterator; use traits::vector::{Vec, AlgebraicVec}; @@ -22,7 +22,7 @@ impl DVec { /// * `dim` - The dimension of the vector. #[inline] pub fn new_zeros(dim: uint) -> DVec { - DVec { at: from_elem(dim, Zero::zero()) } + DVec::from_elem(dim, Zero::zero()) } /// Tests if all components of the vector are zeroes. @@ -32,6 +32,33 @@ impl DVec { } } +impl DVec { + /// Builds a vector filled with ones. + /// + /// # Arguments + /// * `dim` - The dimension of the vector. + #[inline] + pub fn new_ones(dim: uint) -> DVec { + DVec::from_elem(dim, One::one()) + } +} + +impl DVec { + /// Builds a vector filled with a constant. + #[inline] + pub fn from_elem(dim: uint, elem: N) -> DVec { + DVec { at: vec::from_elem(dim, elem) } + } +} + +impl DVec { + /// Builds a vector filled with the result of a function. + #[inline(always)] + pub fn from_fn(dim: uint, f: &fn(uint) -> N) -> DVec { + DVec { at: vec::from_fn(dim, |i| f(i)) } + } +} + impl Iterable for DVec { fn iter<'l>(&'l self) -> VecIterator<'l, N> { self.at.iter()