]> gitweb.michael.orlitzky.com - numerical-analysis.git/blobdiff - src/Linear/Matrix.hs
Drop the 'column' function that returned a vector instead of a matrix.
[numerical-analysis.git] / src / Linear / Matrix.hs
index dd89a9ff3f091490c3d1587b2839c338ec495468..6d13a693b71e37631e8600f87652f6c9eb73b883 100644 (file)
@@ -37,6 +37,7 @@ import qualified Data.Vector.Fixed as V (
   and,
   fromList,
   head,
+  ifoldl,
   length,
   map,
   maximum,
@@ -187,24 +188,23 @@ row' m i =
 
 
 -- | Return the @j@th column of @m@. Unsafe.
-column :: Mat m n a -> Int -> (Vec m a)
-column (Mat rows) j =
-  V.map (element j) rows
-  where
-    element = flip (!)
+--column :: Mat m n a -> Int -> (Vec m a)
+--column (Mat rows) j =
+--  V.map (element j) rows
+--  where
+--    element = flip (!)
 
 
 -- | Return the @j@th column of @m@ as a matrix. Unsafe.
-column' :: (Arity m, Arity n) => Mat m n a -> Int -> Col m a
-column' m j =
+column :: (Arity m, Arity n) => Mat m n a -> Int -> Col m a
+column m j =
   construct lambda
   where
     lambda i _ = m !!! (i, j)
 
 
 -- | Transpose @m@; switch it's columns and its rows. This is a dirty
---   implementation.. it would be a little cleaner to use imap, but it
---   doesn't seem to work.
+--   implementation, but I don't see a better way.
 --
 --   TODO: Don't cheat with fromList.
 --
@@ -215,9 +215,10 @@ column' m j =
 --   ((1,3),(2,4))
 --
 transpose :: (Arity m, Arity n) => Mat m n a -> Mat n m a
-transpose m = Mat $ V.fromList column_list
+transpose matrix =
+  construct lambda
   where
-    column_list = [ column m i | i <- [0..(ncols m)-1] ]
+    lambda i j = matrix !!! (j,i)
 
 
 -- | Is @m@ symmetric?
@@ -815,11 +816,41 @@ colzipwith f c1 c2 =
 --   Examples:
 --
 --   >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
---   >>> matmap (^2) m
+--   >>> map2 (^2) m
 --   ((1,4),(9,16))
 --
-matmap :: (a -> b) -> Mat m n a -> Mat m n b
-matmap f (Mat rows) =
+map2 :: (a -> b) -> Mat m n a -> Mat m n b
+map2 f (Mat rows) =
   Mat $ V.map g rows
   where
     g = V.map f
+
+
+-- | Fold over the entire matrix passing the coordinates @i@ and @j@
+--   (of the row/column) to the accumulation function.
+--
+--   Examples:
+--
+--   >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
+--   >>>  ifoldl2 (\i j cur _ -> cur + i + j) 0 m
+--   18
+--
+ifoldl2 :: forall a b m n.
+           (Int -> Int -> b -> a -> b)
+        -> b
+        -> Mat m n a
+        -> b
+ifoldl2 f initial (Mat rows) =
+  V.ifoldl row_function initial rows
+  where
+    -- | The order that we need this in (so that @g idx@ makes sense)
+    --   is a little funny. So that we don't need to pass weird
+    --   functions into ifoldl2, we swap the second and third
+    --   arguments of @f@ calling the result @g@.
+    g :: Int -> b -> Int -> a -> b
+    g w x y = f w y x
+
+    row_function :: b -> Int -> Vec n a -> b
+    row_function rowinit idx r = V.ifoldl (g idx) rowinit r
+
+