@@ -1,13 +1,20 @@
11module LinearAlgebra.Matrix
22 ( Matrix
3+ -- * Constructors
34 , fromArray
45 , replicate
56 , zeros
7+ -- * Access data
8+ , column
9+ , element
10+ , row
611 ) where
712
813import Prelude
914import Data.Array as A
1015import Data.Maybe (Maybe(..))
16+import Data.Tuple (Tuple, fst, snd)
17+import LinearAlgebra.Vector (Vector)
1118
1219
1320-- | Dense Matrix implementation
@@ -32,4 +39,33 @@ zeros r c = replicate r c 0.0
3239-- | Create Matrix from Array
3340fromArray :: ∀ a. Int -> Int -> Array a -> Maybe (Matrix a)
3441fromArray r c vs | r > 0 && c > 0 && r*c == A.length vs = Just {nrows: r, ncols: c, values: vs}
35− | otherwise = Nothing
42+ | otherwise = Nothing
43+
44+
45+-- | Get specific column as a vector. Index is 0 based
46+-- | If the index is out of range then return empty vector
47+column :: ∀ a. Int -> Matrix a -> Vector a
48+column c mat = snd <<< A.unzip $ A.filter isInColumn ivalues
49+ where
50+ ivalues :: Array (Tuple Int a)
51+ ivalues = A.zip (A.range 0 (A.length mat.values - 1)) mat.values
52+
53+ isInColumn :: forall b. Tuple Int b -> Boolean
54+ isInColumn v = (fst v) `mod` mat.ncols == c
55+
56+
57+
58+-- | Get specific row as a vector. Index is 0 based
59+-- | If the index is out of range then return empty vector
60+row :: ∀ a. Int -> Matrix a -> Vector a
61+row r mat = A.slice i j mat.values
62+ where
63+ i = if r >=0 && r < mat.nrows then r*mat.ncols else 0
64+ j = if r >=0 && r < mat.nrows then i+mat.ncols else 0
65+
66+
67+-- | Get specific element. Index is 0 based
68+element :: ∀ a. Int -> Int -> Matrix a -> Maybe a
69+element r c mat = A.index mat.values ((r*mat.ncols) + c)
70+
71+