From 7c2301797e35930298db9a6bff09eefdd4fbd577 Mon Sep 17 00:00:00 2001 From: Erik de Castro Lopo Date: Thu, 10 Dec 2009 10:35:35 +0000 Subject: Add functions buildVector and buildMatrix. Both take a size parameter(s) and a function that maps vector/matrix indices to the values at that position. --- lib/Data/Packed/Matrix.hs | 17 ++++++++++++++++- lib/Data/Packed/Vector.hs | 13 ++++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/lib/Data/Packed/Matrix.hs b/lib/Data/Packed/Matrix.hs index ad0776e..6a6942d 100644 --- a/lib/Data/Packed/Matrix.hs +++ b/lib/Data/Packed/Matrix.hs @@ -19,7 +19,7 @@ module Data.Packed.Matrix ( (><), trans, reshape, flatten, - fromLists, toLists, + fromLists, toLists, buildMatrix, (@@>), asRow, asColumn, fromRows, toRows, fromColumns, toColumns, @@ -176,6 +176,21 @@ asRow v = reshape (dim v) v asColumn :: Element a => Vector a -> Matrix a asColumn v = reshape 1 v + +{- | creates a Matrix of the specified size using the supplied function to + to map the row/column position to the value at that row/column position. + +@> buildMatrix 3 4 (\ (r,c) -> fromIntegral r * fromIntegral c) +(3><4) + [ 0.0, 0.0, 0.0, 0.0, 0.0 + , 0.0, 1.0, 2.0, 3.0, 4.0 + , 0.0, 2.0, 4.0, 6.0, 8.0]@ +-} +buildMatrix :: Element a => Int -> Int -> ((Int, Int) -> a) -> Matrix a +buildMatrix rc cc f = + fromLists $ map (\x -> map f x) + $ map (\ ri -> map (\ ci -> (ri, ci)) [0 .. (cc - 1)]) [0 .. (rc - 1)] + ----------------------------------------------------- fromArray2D :: (Element e) => Array (Int, Int) e -> Matrix e diff --git a/lib/Data/Packed/Vector.hs b/lib/Data/Packed/Vector.hs index 21f51e5..457da71 100644 --- a/lib/Data/Packed/Vector.hs +++ b/lib/Data/Packed/Vector.hs @@ -14,7 +14,7 @@ module Data.Packed.Vector ( Vector, - fromList, (|>), toList, + fromList, (|>), toList, buildVector, dim, (@>), subVector, join, constant, linspace, @@ -59,3 +59,14 @@ vectorMinIndex = round . toScalarR MinIdx constant :: Element a => a -> Int -> Vector a -- constant x n = runSTVector (newVector x n) constant = constantD -- about 2x faster + +{- | creates a Vector of the specified length using the supplied function to + to map the index to the value at that index. + +@> buildVector 4 fromIntegral +4 |> [0.0,1.0,2.0,3.0]@ + +-} +buildVector :: Element a => Int -> (Int -> a) -> Vector a +buildVector len f = + fromList $ map f [0 .. (len - 1)] -- cgit v1.2.3