]> gitweb.michael.orlitzky.com - numerical-analysis.git/blobdiff - src/Linear/Matrix.hs
Add 'diagonal' function.
[numerical-analysis.git] / src / Linear / Matrix.hs
index b17d0eb391484767cfed99d70f9b6ee7268a2394..20769b4708950d103bd0ec1fd18737d9616cb0ca 100644 (file)
@@ -417,9 +417,8 @@ instance (Ring.C a, Arity m, Arity n) => Module.C a (Mat m n a) where
 
 instance (Algebraic.C a,
           ToRational.C a,
-          Arity m,
-          Arity n)
-         => Normed (Mat (S m) (S n) a) where
+          Arity m)
+         => Normed (Mat (S m) N1 a) where
   -- | Generic p-norms. The usual norm in R^n is (norm_p 2). We treat
   --   all matrices as big vectors.
   --
@@ -521,3 +520,23 @@ angle v1 v2 =
   where
    theta = (recip norms) NP.* (v1 `dot` v2)
    norms = (norm v1) NP.* (norm v2)
+
+
+
+-- | Given a square @matrix@, return a new matrix of the same size
+--   containing only the on-diagonal entries of @matrix@. The
+--   off-diagonal entries are set to zero.
+--
+--   Examples:
+--
+--   >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
+--   >>> diagonal m
+--   ((1,0,0),(0,5,0),(0,0,9))
+--
+diagonal :: (Arity m, Ring.C a)
+         => Mat m m a
+         -> Mat m m a
+diagonal matrix =
+  construct lambda
+  where
+    lambda i j = if i == j then matrix !!! (i,j) else 0