]> gitweb.michael.orlitzky.com - numerical-analysis.git/blob - src/Linear/Matrix.hs
Drop the 'column' function that returned a vector instead of a matrix.
[numerical-analysis.git] / src / Linear / Matrix.hs
1 {-# LANGUAGE ExistentialQuantification #-}
2 {-# LANGUAGE FlexibleContexts #-}
3 {-# LANGUAGE FlexibleInstances #-}
4 {-# LANGUAGE MultiParamTypeClasses #-}
5 {-# LANGUAGE NoMonomorphismRestriction #-}
6 {-# LANGUAGE ScopedTypeVariables #-}
7 {-# LANGUAGE TypeFamilies #-}
8 {-# LANGUAGE RebindableSyntax #-}
9
10 -- | Boxed matrices; that is, boxed m-vectors of boxed n-vectors. We
11 -- assume that the underlying representation is
12 -- Data.Vector.Fixed.Boxed.Vec for simplicity. It was tried in
13 -- generality and failed.
14 --
15 module Linear.Matrix
16 where
17
18 import Data.List (intercalate)
19
20 import Data.Vector.Fixed (
21 (!),
22 N1,
23 N2,
24 N3,
25 N4,
26 N5,
27 S,
28 Z,
29 generate,
30 mk1,
31 mk2,
32 mk3,
33 mk4,
34 mk5
35 )
36 import qualified Data.Vector.Fixed as V (
37 and,
38 fromList,
39 head,
40 ifoldl,
41 length,
42 map,
43 maximum,
44 replicate,
45 toList,
46 zipWith )
47 import Data.Vector.Fixed.Cont ( Arity, arity )
48 import Linear.Vector ( Vec, delete, element_sum )
49 import Normed ( Normed(..) )
50
51 import NumericPrelude hiding ( (*), abs )
52 import qualified NumericPrelude as NP ( (*) )
53 import qualified Algebra.Absolute as Absolute ( C )
54 import Algebra.Absolute ( abs )
55 import qualified Algebra.Additive as Additive ( C )
56 import qualified Algebra.Algebraic as Algebraic ( C )
57 import Algebra.Algebraic ( root )
58 import qualified Algebra.Ring as Ring ( C )
59 import qualified Algebra.Module as Module ( C )
60 import qualified Algebra.RealRing as RealRing ( C )
61 import qualified Algebra.ToRational as ToRational ( C )
62 import qualified Algebra.Transcendental as Transcendental ( C )
63 import qualified Prelude as P ( map )
64
65 -- | Our main matrix type.
66 data Mat m n a = (Arity m, Arity n) => Mat (Vec m (Vec n a))
67
68 -- Type synonyms for n-by-n matrices.
69 type Mat1 a = Mat N1 N1 a
70 type Mat2 a = Mat N2 N2 a
71 type Mat3 a = Mat N3 N3 a
72 type Mat4 a = Mat N4 N4 a
73 type Mat5 a = Mat N5 N5 a
74
75 -- | Type synonym for row vectors expressed as 1-by-n matrices.
76 type Row n a = Mat N1 n a
77
78 -- Type synonyms for 1-by-n row "vectors".
79 type Row1 a = Row N1 a
80 type Row2 a = Row N2 a
81 type Row3 a = Row N3 a
82 type Row4 a = Row N4 a
83 type Row5 a = Row N5 a
84
85 -- | Type synonym for column vectors expressed as n-by-1 matrices.
86 type Col n a = Mat n N1 a
87
88 -- Type synonyms for n-by-1 column "vectors".
89 type Col1 a = Col N1 a
90 type Col2 a = Col N2 a
91 type Col3 a = Col N3 a
92 type Col4 a = Col N4 a
93 type Col5 a = Col N5 a
94
95 -- We need a big column for Gaussian quadrature.
96 type N10 = S (S (S (S (S N5))))
97 type Col10 a = Col N10 a
98
99
100 instance (Eq a) => Eq (Mat m n a) where
101 -- | Compare a row at a time.
102 --
103 -- Examples:
104 --
105 -- >>> let m1 = fromList [[1,2],[3,4]] :: Mat2 Int
106 -- >>> let m2 = fromList [[1,2],[3,4]] :: Mat2 Int
107 -- >>> let m3 = fromList [[5,6],[7,8]] :: Mat2 Int
108 -- >>> m1 == m2
109 -- True
110 -- >>> m1 == m3
111 -- False
112 --
113 (Mat rows1) == (Mat rows2) =
114 V.and $ V.zipWith comp rows1 rows2
115 where
116 -- Compare a row, one column at a time.
117 comp row1 row2 = V.and (V.zipWith (==) row1 row2)
118
119
120 instance (Show a) => Show (Mat m n a) where
121 -- | Display matrices and vectors as ordinary tuples. This is poor
122 -- practice, but these results are primarily displayed
123 -- interactively and convenience trumps correctness (said the guy
124 -- who insists his vector lengths be statically checked at
125 -- compile-time).
126 --
127 -- Examples:
128 --
129 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
130 -- >>> show m
131 -- ((1,2),(3,4))
132 --
133 show (Mat rows) =
134 "(" ++ (intercalate "," (V.toList row_strings)) ++ ")"
135 where
136 row_strings = V.map show_vector rows
137 show_vector v1 =
138 "(" ++ (intercalate "," element_strings) ++ ")"
139 where
140 v1l = V.toList v1
141 element_strings = P.map show v1l
142
143
144 -- | Convert a matrix to a nested list.
145 toList :: Mat m n a -> [[a]]
146 toList (Mat rows) = map V.toList (V.toList rows)
147
148 -- | Create a matrix from a nested list.
149 fromList :: (Arity m, Arity n) => [[a]] -> Mat m n a
150 fromList vs = Mat (V.fromList $ map V.fromList vs)
151
152
153 -- | Unsafe indexing.
154 (!!!) :: (Arity m, Arity n) => Mat m n a -> (Int, Int) -> a
155 (!!!) m (i, j) = (row m i) ! j
156
157 -- | Safe indexing.
158 (!!?) :: Mat m n a -> (Int, Int) -> Maybe a
159 (!!?) m@(Mat rows) (i, j)
160 | i < 0 || j < 0 = Nothing
161 | i > V.length rows = Nothing
162 | otherwise = if j > V.length (row m j)
163 then Nothing
164 else Just $ (row m j) ! j
165
166
167 -- | The number of rows in the matrix.
168 nrows :: forall m n a. (Arity m) => Mat m n a -> Int
169 nrows _ = arity (undefined :: m)
170
171 -- | The number of columns in the first row of the
172 -- matrix. Implementation stolen from Data.Vector.Fixed.length.
173 ncols :: forall m n a. (Arity n) => Mat m n a -> Int
174 ncols _ = arity (undefined :: n)
175
176
177 -- | Return the @i@th row of @m@. Unsafe.
178 row :: Mat m n a -> Int -> (Vec n a)
179 row (Mat rows) i = rows ! i
180
181
182 -- | Return the @i@th row of @m@ as a matrix. Unsafe.
183 row' :: (Arity m, Arity n) => Mat m n a -> Int -> Row n a
184 row' m i =
185 construct lambda
186 where
187 lambda _ j = m !!! (i, j)
188
189
190 -- | Return the @j@th column of @m@. Unsafe.
191 --column :: Mat m n a -> Int -> (Vec m a)
192 --column (Mat rows) j =
193 -- V.map (element j) rows
194 -- where
195 -- element = flip (!)
196
197
198 -- | Return the @j@th column of @m@ as a matrix. Unsafe.
199 column :: (Arity m, Arity n) => Mat m n a -> Int -> Col m a
200 column m j =
201 construct lambda
202 where
203 lambda i _ = m !!! (i, j)
204
205
206 -- | Transpose @m@; switch it's columns and its rows. This is a dirty
207 -- implementation, but I don't see a better way.
208 --
209 -- TODO: Don't cheat with fromList.
210 --
211 -- Examples:
212 --
213 -- >>> let m = fromList [[1,2], [3,4]] :: Mat2 Int
214 -- >>> transpose m
215 -- ((1,3),(2,4))
216 --
217 transpose :: (Arity m, Arity n) => Mat m n a -> Mat n m a
218 transpose matrix =
219 construct lambda
220 where
221 lambda i j = matrix !!! (j,i)
222
223
224 -- | Is @m@ symmetric?
225 --
226 -- Examples:
227 --
228 -- >>> let m1 = fromList [[1,2], [2,1]] :: Mat2 Int
229 -- >>> symmetric m1
230 -- True
231 --
232 -- >>> let m2 = fromList [[1,2], [3,1]] :: Mat2 Int
233 -- >>> symmetric m2
234 -- False
235 --
236 symmetric :: (Eq a, Arity m) => Mat m m a -> Bool
237 symmetric m =
238 m == (transpose m)
239
240
241 -- | Construct a new matrix from a function @lambda@. The function
242 -- @lambda@ should take two parameters i,j corresponding to the
243 -- entries in the matrix. The i,j entry of the resulting matrix will
244 -- have the value returned by lambda i j.
245 --
246 -- Examples:
247 --
248 -- >>> let lambda i j = i + j
249 -- >>> construct lambda :: Mat3 Int
250 -- ((0,1,2),(1,2,3),(2,3,4))
251 --
252 construct :: forall m n a. (Arity m, Arity n)
253 => (Int -> Int -> a) -> Mat m n a
254 construct lambda = Mat $ generate make_row
255 where
256 make_row :: Int -> Vec n a
257 make_row i = generate (lambda i)
258
259
260 -- | Create an identity matrix with the right dimensions.
261 --
262 -- Examples:
263 --
264 -- >>> identity_matrix :: Mat3 Int
265 -- ((1,0,0),(0,1,0),(0,0,1))
266 -- >>> identity_matrix :: Mat3 Double
267 -- ((1.0,0.0,0.0),(0.0,1.0,0.0),(0.0,0.0,1.0))
268 --
269 identity_matrix :: (Arity m, Ring.C a) => Mat m m a
270 identity_matrix =
271 construct (\i j -> if i == j then (fromInteger 1) else (fromInteger 0))
272
273 -- | Given a positive-definite matrix @m@, computes the
274 -- upper-triangular matrix @r@ with (transpose r)*r == m and all
275 -- values on the diagonal of @r@ positive.
276 --
277 -- Examples:
278 --
279 -- >>> let m1 = fromList [[20,-1], [-1,20]] :: Mat2 Double
280 -- >>> cholesky m1
281 -- ((4.47213595499958,-0.22360679774997896),(0.0,4.466542286825459))
282 -- >>> (transpose (cholesky m1)) * (cholesky m1)
283 -- ((20.000000000000004,-1.0),(-1.0,20.0))
284 --
285 cholesky :: forall m n a. (Algebraic.C a, Arity m, Arity n)
286 => (Mat m n a) -> (Mat m n a)
287 cholesky m = construct r
288 where
289 r :: Int -> Int -> a
290 r i j | i == j = sqrt(m !!! (i,j) - sum [(r k i)^2 | k <- [0..i-1]])
291 | i < j =
292 (((m !!! (i,j)) - sum [(r k i) NP.* (r k j) | k <- [0..i-1]]))/(r i i)
293 | otherwise = 0
294
295
296 -- | Returns True if the given matrix is upper-triangular, and False
297 -- otherwise. The parameter @epsilon@ lets the caller choose a
298 -- tolerance.
299 --
300 -- Examples:
301 --
302 -- >>> let m = fromList [[1,1],[1e-12,1]] :: Mat2 Double
303 -- >>> is_upper_triangular m
304 -- False
305 -- >>> is_upper_triangular' 1e-10 m
306 -- True
307 --
308 -- TODO:
309 --
310 -- 1. Don't cheat with lists.
311 --
312 is_upper_triangular' :: (Ord a, Ring.C a, Absolute.C a, Arity m, Arity n)
313 => a -- ^ The tolerance @epsilon@.
314 -> Mat m n a
315 -> Bool
316 is_upper_triangular' epsilon m =
317 and $ concat results
318 where
319 results = [[ test i j | i <- [0..(nrows m)-1]] | j <- [0..(ncols m)-1] ]
320
321 test :: Int -> Int -> Bool
322 test i j
323 | i <= j = True
324 -- use "less than or equal to" so zero is a valid epsilon
325 | otherwise = abs (m !!! (i,j)) <= epsilon
326
327
328 -- | Returns True if the given matrix is upper-triangular, and False
329 -- otherwise. A specialized version of 'is_upper_triangular\'' with
330 -- @epsilon = 0@.
331 --
332 -- Examples:
333 --
334 -- >>> let m = fromList [[1,0],[1,1]] :: Mat2 Int
335 -- >>> is_upper_triangular m
336 -- False
337 --
338 -- >>> let m = fromList [[1,2],[0,3]] :: Mat2 Int
339 -- >>> is_upper_triangular m
340 -- True
341 --
342 -- TODO:
343 --
344 -- 1. The Ord constraint is too strong here, Eq would suffice.
345 --
346 is_upper_triangular :: (Ord a, Ring.C a, Absolute.C a, Arity m, Arity n)
347 => Mat m n a -> Bool
348 is_upper_triangular = is_upper_triangular' 0
349
350
351 -- | Returns True if the given matrix is lower-triangular, and False
352 -- otherwise. This is a specialized version of 'is_lower_triangular\''
353 -- with @epsilon = 0@.
354 --
355 -- Examples:
356 --
357 -- >>> let m = fromList [[1,0],[1,1]] :: Mat2 Int
358 -- >>> is_lower_triangular m
359 -- True
360 --
361 -- >>> let m = fromList [[1,2],[0,3]] :: Mat2 Int
362 -- >>> is_lower_triangular m
363 -- False
364 --
365 is_lower_triangular :: (Ord a,
366 Ring.C a,
367 Absolute.C a,
368 Arity m,
369 Arity n)
370 => Mat m n a
371 -> Bool
372 is_lower_triangular = is_upper_triangular . transpose
373
374
375 -- | Returns True if the given matrix is lower-triangular, and False
376 -- otherwise. The parameter @epsilon@ lets the caller choose a
377 -- tolerance.
378 --
379 -- Examples:
380 --
381 -- >>> let m = fromList [[1,1e-12],[1,1]] :: Mat2 Double
382 -- >>> is_lower_triangular m
383 -- False
384 -- >>> is_lower_triangular' 1e-12 m
385 -- True
386 --
387 is_lower_triangular' :: (Ord a,
388 Ring.C a,
389 Absolute.C a,
390 Arity m,
391 Arity n)
392 => a -- ^ The tolerance @epsilon@.
393 -> Mat m n a
394 -> Bool
395 is_lower_triangular' epsilon = (is_upper_triangular' epsilon) . transpose
396
397
398 -- | Returns True if the given matrix is triangular, and False
399 -- otherwise.
400 --
401 -- Examples:
402 --
403 -- >>> let m = fromList [[1,0],[1,1]] :: Mat2 Int
404 -- >>> is_triangular m
405 -- True
406 --
407 -- >>> let m = fromList [[1,2],[0,3]] :: Mat2 Int
408 -- >>> is_triangular m
409 -- True
410 --
411 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
412 -- >>> is_triangular m
413 -- False
414 --
415 is_triangular :: (Ord a,
416 Ring.C a,
417 Absolute.C a,
418 Arity m,
419 Arity n)
420 => Mat m n a
421 -> Bool
422 is_triangular m = is_upper_triangular m || is_lower_triangular m
423
424
425 -- | Return the (i,j)th minor of m.
426 --
427 -- Examples:
428 --
429 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
430 -- >>> minor m 0 0 :: Mat2 Int
431 -- ((5,6),(8,9))
432 -- >>> minor m 1 1 :: Mat2 Int
433 -- ((1,3),(7,9))
434 --
435 minor :: (m ~ S r,
436 n ~ S t,
437 Arity r,
438 Arity t)
439 => Mat m n a
440 -> Int
441 -> Int
442 -> Mat r t a
443 minor (Mat rows) i j = m
444 where
445 rows' = delete rows i
446 m = Mat $ V.map ((flip delete) j) rows'
447
448
449 class (Eq a, Ring.C a) => Determined p a where
450 determinant :: (p a) -> a
451
452 instance (Eq a, Ring.C a) => Determined (Mat (S Z) (S Z)) a where
453 determinant (Mat rows) = (V.head . V.head) rows
454
455 instance (Ord a,
456 Ring.C a,
457 Absolute.C a,
458 Arity n,
459 Determined (Mat (S n) (S n)) a)
460 => Determined (Mat (S (S n)) (S (S n))) a where
461 -- | The recursive definition with a special-case for triangular matrices.
462 --
463 -- Examples:
464 --
465 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
466 -- >>> determinant m
467 -- -1
468 --
469 determinant m
470 | is_triangular m = product [ m !!! (i,i) | i <- [0..(nrows m)-1] ]
471 | otherwise = determinant_recursive
472 where
473 m' i j = m !!! (i,j)
474
475 det_minor i j = determinant (minor m i j)
476
477 determinant_recursive =
478 sum [ (-1)^(toInteger j) NP.* (m' 0 j) NP.* (det_minor 0 j)
479 | j <- [0..(ncols m)-1] ]
480
481
482
483 -- | Matrix multiplication.
484 --
485 -- Examples:
486 --
487 -- >>> let m1 = fromList [[1,2,3], [4,5,6]] :: Mat N2 N3 Int
488 -- >>> let m2 = fromList [[1,2],[3,4],[5,6]] :: Mat N3 N2 Int
489 -- >>> m1 * m2
490 -- ((22,28),(49,64))
491 --
492 infixl 7 *
493 (*) :: (Ring.C a, Arity m, Arity n, Arity p)
494 => Mat m n a
495 -> Mat n p a
496 -> Mat m p a
497 (*) m1 m2 = construct lambda
498 where
499 lambda i j =
500 sum [(m1 !!! (i,k)) NP.* (m2 !!! (k,j)) | k <- [0..(ncols m1)-1] ]
501
502
503
504 instance (Ring.C a, Arity m, Arity n) => Additive.C (Mat m n a) where
505
506 (Mat rows1) + (Mat rows2) =
507 Mat $ V.zipWith (V.zipWith (+)) rows1 rows2
508
509 (Mat rows1) - (Mat rows2) =
510 Mat $ V.zipWith (V.zipWith (-)) rows1 rows2
511
512 zero = Mat (V.replicate $ V.replicate (fromInteger 0))
513
514
515 instance (Ring.C a, Arity m, Arity n, m ~ n) => Ring.C (Mat m n a) where
516 -- The first * is ring multiplication, the second is matrix
517 -- multiplication.
518 m1 * m2 = m1 * m2
519
520
521 instance (Ring.C a, Arity m, Arity n) => Module.C a (Mat m n a) where
522 -- We can multiply a matrix by a scalar of the same type as its
523 -- elements.
524 x *> (Mat rows) = Mat $ V.map (V.map (NP.* x)) rows
525
526
527 instance (Algebraic.C a,
528 ToRational.C a,
529 Arity m)
530 => Normed (Mat (S m) N1 a) where
531 -- | Generic p-norms for vectors in R^n that are represented as nx1
532 -- matrices.
533 --
534 -- Examples:
535 --
536 -- >>> let v1 = vec2d (3,4)
537 -- >>> norm_p 1 v1
538 -- 7.0
539 -- >>> norm_p 2 v1
540 -- 5.0
541 --
542 norm_p p (Mat rows) =
543 (root p') $ sum [fromRational' (toRational x)^p' | x <- xs]
544 where
545 p' = toInteger p
546 xs = concat $ V.toList $ V.map V.toList rows
547
548 -- | The infinity norm.
549 --
550 -- Examples:
551 --
552 -- >>> let v1 = vec3d (1,5,2)
553 -- >>> norm_infty v1
554 -- 5
555 --
556 norm_infty (Mat rows) =
557 fromRational' $ toRational $ V.maximum $ V.map V.maximum rows
558
559
560 -- | Compute the Frobenius norm of a matrix. This essentially treats
561 -- the matrix as one long vector containing all of its entries (in
562 -- any order, it doesn't matter).
563 --
564 -- Examples:
565 --
566 -- >>> let m = fromList [[1, 2, 3],[4,5,6],[7,8,9]] :: Mat3 Double
567 -- >>> frobenius_norm m == sqrt 285
568 -- True
569 --
570 -- >>> let m = fromList [[1, -1, 1],[-1,1,-1],[1,-1,1]] :: Mat3 Double
571 -- >>> frobenius_norm m == 3
572 -- True
573 --
574 frobenius_norm :: (Algebraic.C a, Ring.C a) => Mat m n a -> a
575 frobenius_norm (Mat rows) =
576 sqrt $ element_sum $ V.map row_sum rows
577 where
578 -- | Square and add up the entries of a row.
579 row_sum = element_sum . V.map (^2)
580
581
582 -- Vector helpers. We want it to be easy to create low-dimension
583 -- column vectors, which are nx1 matrices.
584
585 -- | Convenient constructor for 2D vectors.
586 --
587 -- Examples:
588 --
589 -- >>> import Roots.Simple
590 -- >>> let fst m = m !!! (0,0)
591 -- >>> let snd m = m !!! (1,0)
592 -- >>> let h = 0.5 :: Double
593 -- >>> let g1 m = 1.0 + h NP.* exp(-((fst m)^2))/(1.0 + (snd m)^2)
594 -- >>> let g2 m = 0.5 + h NP.* atan((fst m)^2 + (snd m)^2)
595 -- >>> let g u = vec2d ((g1 u), (g2 u))
596 -- >>> let u0 = vec2d (1.0, 1.0)
597 -- >>> let eps = 1/(10^9)
598 -- >>> fixed_point g eps u0
599 -- ((1.0728549599342185),(1.0820591495686167))
600 --
601 vec1d :: (a) -> Col1 a
602 vec1d (x) = Mat (mk1 (mk1 x))
603
604 vec2d :: (a,a) -> Col2 a
605 vec2d (x,y) = Mat (mk2 (mk1 x) (mk1 y))
606
607 vec3d :: (a,a,a) -> Col3 a
608 vec3d (x,y,z) = Mat (mk3 (mk1 x) (mk1 y) (mk1 z))
609
610 vec4d :: (a,a,a,a) -> Col4 a
611 vec4d (w,x,y,z) = Mat (mk4 (mk1 w) (mk1 x) (mk1 y) (mk1 z))
612
613 vec5d :: (a,a,a,a,a) -> Col5 a
614 vec5d (v,w,x,y,z) = Mat (mk5 (mk1 v) (mk1 w) (mk1 x) (mk1 y) (mk1 z))
615
616 -- Since we commandeered multiplication, we need to create 1x1
617 -- matrices in order to multiply things.
618 scalar :: a -> Mat1 a
619 scalar x = Mat (mk1 (mk1 x))
620
621 dot :: (RealRing.C a, n ~ N1, m ~ S t, Arity t)
622 => Mat m n a
623 -> Mat m n a
624 -> a
625 v1 `dot` v2 = ((transpose v1) * v2) !!! (0, 0)
626
627
628 -- | The angle between @v1@ and @v2@ in Euclidean space.
629 --
630 -- Examples:
631 --
632 -- >>> let v1 = vec2d (1.0, 0.0)
633 -- >>> let v2 = vec2d (0.0, 1.0)
634 -- >>> angle v1 v2 == pi/2.0
635 -- True
636 --
637 angle :: (Transcendental.C a,
638 RealRing.C a,
639 n ~ N1,
640 m ~ S t,
641 Arity t,
642 ToRational.C a)
643 => Mat m n a
644 -> Mat m n a
645 -> a
646 angle v1 v2 =
647 acos theta
648 where
649 theta = (recip norms) NP.* (v1 `dot` v2)
650 norms = (norm v1) NP.* (norm v2)
651
652
653 -- | Retrieve the diagonal elements of the given matrix as a \"column
654 -- vector,\" i.e. a m-by-1 matrix. We require the matrix to be
655 -- square to avoid ambiguity in the return type which would ideally
656 -- have dimension min(m,n) supposing an m-by-n matrix.
657 --
658 -- Examples:
659 --
660 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
661 -- >>> diagonal m
662 -- ((1),(5),(9))
663 --
664 diagonal :: (Arity m) => Mat m m a -> Col m a
665 diagonal matrix =
666 construct lambda
667 where
668 lambda i _ = matrix !!! (i,i)
669
670
671 -- | Given a square @matrix@, return a new matrix of the same size
672 -- containing only the on-diagonal entries of @matrix@. The
673 -- off-diagonal entries are set to zero.
674 --
675 -- Examples:
676 --
677 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
678 -- >>> diagonal_part m
679 -- ((1,0,0),(0,5,0),(0,0,9))
680 --
681 diagonal_part :: (Arity m, Ring.C a)
682 => Mat m m a
683 -> Mat m m a
684 diagonal_part matrix =
685 construct lambda
686 where
687 lambda i j = if i == j then matrix !!! (i,j) else 0
688
689
690 -- | Given a square @matrix@, return a new matrix of the same size
691 -- containing only the on-diagonal and below-diagonal entries of
692 -- @matrix@. The above-diagonal entries are set to zero.
693 --
694 -- Examples:
695 --
696 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
697 -- >>> lt_part m
698 -- ((1,0,0),(4,5,0),(7,8,9))
699 --
700 lt_part :: (Arity m, Ring.C a)
701 => Mat m m a
702 -> Mat m m a
703 lt_part matrix =
704 construct lambda
705 where
706 lambda i j = if i >= j then matrix !!! (i,j) else 0
707
708
709 -- | Given a square @matrix@, return a new matrix of the same size
710 -- containing only the below-diagonal entries of @matrix@. The on-
711 -- and above-diagonal entries are set to zero.
712 --
713 -- Examples:
714 --
715 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
716 -- >>> lt_part_strict m
717 -- ((0,0,0),(4,0,0),(7,8,0))
718 --
719 lt_part_strict :: (Arity m, Ring.C a)
720 => Mat m m a
721 -> Mat m m a
722 lt_part_strict matrix =
723 construct lambda
724 where
725 lambda i j = if i > j then matrix !!! (i,j) else 0
726
727
728 -- | Given a square @matrix@, return a new matrix of the same size
729 -- containing only the on-diagonal and above-diagonal entries of
730 -- @matrix@. The below-diagonal entries are set to zero.
731 --
732 -- Examples:
733 --
734 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
735 -- >>> ut_part m
736 -- ((1,2,3),(0,5,6),(0,0,9))
737 --
738 ut_part :: (Arity m, Ring.C a)
739 => Mat m m a
740 -> Mat m m a
741 ut_part = transpose . lt_part . transpose
742
743
744 -- | Given a square @matrix@, return a new matrix of the same size
745 -- containing only the above-diagonal entries of @matrix@. The on-
746 -- and below-diagonal entries are set to zero.
747 --
748 -- Examples:
749 --
750 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
751 -- >>> ut_part_strict m
752 -- ((0,2,3),(0,0,6),(0,0,0))
753 --
754 ut_part_strict :: (Arity m, Ring.C a)
755 => Mat m m a
756 -> Mat m m a
757 ut_part_strict = transpose . lt_part_strict . transpose
758
759
760 -- | Compute the trace of a square matrix, the sum of the elements
761 -- which lie on its diagonal. We require the matrix to be
762 -- square to avoid ambiguity in the return type which would ideally
763 -- have dimension min(m,n) supposing an m-by-n matrix.
764 --
765 -- Examples:
766 --
767 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
768 -- >>> trace m
769 -- 15
770 --
771 trace :: (Arity m, Ring.C a) => Mat m m a -> a
772 trace matrix =
773 let (Mat rows) = diagonal matrix
774 in
775 element_sum $ V.map V.head rows
776
777
778 -- | Zip together two column matrices.
779 --
780 -- Examples:
781 --
782 -- >>> let m1 = fromList [[1],[1],[1]] :: Col3 Int
783 -- >>> let m2 = fromList [[1],[2],[3]] :: Col3 Int
784 -- >>> colzip m1 m2
785 -- (((1,1)),((1,2)),((1,3)))
786 --
787 colzip :: Arity m => Col m a -> Col m a -> Col m (a,a)
788 colzip c1 c2 =
789 construct lambda
790 where
791 lambda i j = (c1 !!! (i,j), c2 !!! (i,j))
792
793
794 -- | Zip together two column matrices using the supplied function.
795 --
796 -- Examples:
797 --
798 -- >>> let c1 = fromList [[1],[2],[3]] :: Col3 Integer
799 -- >>> let c2 = fromList [[4],[5],[6]] :: Col3 Integer
800 -- >>> colzipwith (^) c1 c2
801 -- ((1),(32),(729))
802 --
803 colzipwith :: Arity m
804 => (a -> a -> b)
805 -> Col m a
806 -> Col m a
807 -> Col m b
808 colzipwith f c1 c2 =
809 construct lambda
810 where
811 lambda i j = f (c1 !!! (i,j)) (c2 !!! (i,j))
812
813
814 -- | Map a function over a matrix of any dimensions.
815 --
816 -- Examples:
817 --
818 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
819 -- >>> map2 (^2) m
820 -- ((1,4),(9,16))
821 --
822 map2 :: (a -> b) -> Mat m n a -> Mat m n b
823 map2 f (Mat rows) =
824 Mat $ V.map g rows
825 where
826 g = V.map f
827
828
829 -- | Fold over the entire matrix passing the coordinates @i@ and @j@
830 -- (of the row/column) to the accumulation function.
831 --
832 -- Examples:
833 --
834 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
835 -- >>> ifoldl2 (\i j cur _ -> cur + i + j) 0 m
836 -- 18
837 --
838 ifoldl2 :: forall a b m n.
839 (Int -> Int -> b -> a -> b)
840 -> b
841 -> Mat m n a
842 -> b
843 ifoldl2 f initial (Mat rows) =
844 V.ifoldl row_function initial rows
845 where
846 -- | The order that we need this in (so that @g idx@ makes sense)
847 -- is a little funny. So that we don't need to pass weird
848 -- functions into ifoldl2, we swap the second and third
849 -- arguments of @f@ calling the result @g@.
850 g :: Int -> b -> Int -> a -> b
851 g w x y = f w y x
852
853 row_function :: b -> Int -> Vec n a -> b
854 row_function rowinit idx r = V.ifoldl (g idx) rowinit r
855
856