HORIZON HASKELLDocslts/ghc-9.10.x248f8f02026-10-05Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · 248f8f0 · 2026-10-05

Modulematrix-0.3.6.3Haskell2010

Data.Matrix

Matrix datatype and operations.

Every provided example has been tested. Run cabal test for further tests.

  • 1 type
  • 64 values
  • Packagematrix-0.3.6.3
  • Exports65
  • LanguageHaskell2010
  • LicenceMIT
  • SourceMatrix.hs

Matrix type

5 declarations
datadata Matrix a
#

Type of matrices.

Elements can be of any type. Rows and columns are indexed starting by 1. This means that, if m :: Matrix a and i,j :: Int, then m ! (i,j) is the element in the i-th row and j-th column of m.

Instances12Functor, Applicative, Foldable, Traversable, Eq, Num, …

Builders

3 declarations
valuematrix
  1. :: Int

    Rows

  2. -> Int

    Columns

  3. -> ((Int, Int) -> a)

    Generator function

  4. -> Matrix a
#

O(rows*cols). Generate a matrix from a generator function. Example of usage:

                                 (  1  0 -1 -2 )
                                 (  3  2  1  0 )
                                 (  5  4  3  2 )
matrix 4 4 $ \(i,j) -> 2*i - j = (  7  6  5  4 )

Special matrices

valuezero
  1. :: Num a
  2. => Int

    Rows

  3. -> Int

    Columns

  4. -> Matrix a
#

O(rows*cols). The zero matrix of the given size.

zero n m =
                m
  1 ( 0 0 ... 0 0 )
  2 ( 0 0 ... 0 0 )
    (     ...     )
    ( 0 0 ... 0 0 )
  n ( 0 0 ... 0 0 )
valueidentity :: Num a => Int -> Matrix a
#

O(rows*cols). Identity matrix of the given order.

identity n =
                n
  1 ( 1 0 ... 0 0 )
  2 ( 0 1 ... 0 0 )
    (     ...     )
    ( 0 0 ... 1 0 )
  n ( 0 0 ... 0 1 )
valuediagonalList :: Int -> a -> [a] -> Matrix a
#

Diagonal matrix from a non-empty list given the desired size. Non-diagonal elements will be filled with the given default element. The list must have at least order elements.

diagonalList n 0 [1..] =
                  n
  1 ( 1 0 ... 0   0 )
  2 ( 0 2 ... 0   0 )
    (     ...       )
    ( 0 0 ... n-1 0 )
  n ( 0 0 ... 0   n )
valuepermMatrix
  1. :: Num a
  2. => Int

    Size of the matrix.

  3. -> Int

    Permuted row 1.

  4. -> Int

    Permuted row 2.

  5. -> Matrix a

    Permutation matrix.

#

O(rows*cols). Permutation matrix.

permMatrix n i j =
              i     j       n
  1 ( 1 0 ... 0 ... 0 ... 0 0 )
  2 ( 0 1 ... 0 ... 0 ... 0 0 )
    (     ...   ...   ...     )
  i ( 0 0 ... 0 ... 1 ... 0 0 )
    (     ...   ...   ...     )
  j ( 0 0 ... 1 ... 0 ... 0 0 )
    (     ...   ...   ...     )
    ( 0 0 ... 0 ... 0 ... 1 0 )
  n ( 0 0 ... 0 ... 0 ... 0 1 )

When i == j it reduces to identity n.

List conversions

4 declarations
valuefromList
  1. :: Int

    Rows

  2. -> Int

    Columns

  3. -> [a]

    List of elements

  4. -> Matrix a
#

Create a matrix from a non-empty list given the desired size. The list must have at least rows*cols elements. An example:

                      ( 1 2 3 )
                      ( 4 5 6 )
fromList 3 3 [1..] =  ( 7 8 9 )
valuefromLists :: [[a]] -> Matrix a
#

Create a matrix from a non-empty list of non-empty lists. Each list must have at least as many elements as the first list. Examples:

fromLists [ [1,2,3]      ( 1 2 3 )
          , [4,5,6]      ( 4 5 6 )
          , [7,8,9] ] =  ( 7 8 9 )
fromLists [ [1,2,3  ]     ( 1 2 3 )
          , [4,5,6,7]     ( 4 5 6 )
          , [8,9,0  ] ] = ( 8 9 0 )
valuetoList :: Matrix a -> [a]
#

Get the elements of a matrix stored in a list.

       ( 1 2 3 )
       ( 4 5 6 )
toList ( 7 8 9 ) = [1,2,3,4,5,6,7,8,9]
valuetoLists :: Matrix a -> [[a]]
#

Get the elements of a matrix stored in a list of lists, where each list contains the elements of a single row.

        ( 1 2 3 )   [ [1,2,3]
        ( 4 5 6 )   , [4,5,6]
toLists ( 7 8 9 ) = , [7,8,9] ]

Accessing

11 declarations
valuegetElem
  1. :: Int

    Row

  2. -> Int

    Column

  3. -> Matrix a

    Matrix

  4. -> a
#

O(1). Get an element of a matrix. Indices range from (1,1) to (n,m). It returns an error if the requested element is outside of range.

valuegetDiag :: Matrix a -> Vector a
#

O(min rows cols). Diagonal of a not necessarily square matrix.

Manipulating matrices

10 declarations
valuesetElem
  1. :: a

    New value.

  2. -> (Int, Int)

    Position to replace.

  3. -> Matrix a

    Original matrix.

  4. -> Matrix a

    Matrix with the given position replaced with the given value.

#

Replace the value of a cell in a matrix.

valueunsafeSet
  1. :: a

    New value.

  2. -> (Int, Int)

    Position to replace.

  3. -> Matrix a

    Original matrix.

  4. -> Matrix a

    Matrix with the given position replaced with the given value.

#

Unsafe variant of setElem, without bounds checking.

valuetranspose :: Matrix a -> Matrix a
#

O(rows*cols). The transpose of a matrix. Example:

          ( 1 2 3 )   ( 1 4 7 )
          ( 4 5 6 )   ( 2 5 8 )
transpose ( 7 8 9 ) = ( 3 6 9 )
valuesetSize
  1. :: a

    Default element.

  2. -> Int

    Number of rows.

  3. -> Int

    Number of columns.

  4. -> Matrix a
  5. -> Matrix a
#

Set the size of a matrix to given parameters. Use a default element for undefined entries if the matrix has been extended.

valueextendTo
  1. :: a

    Element to add when extending.

  2. -> Int

    Minimal number of rows.

  3. -> Int

    Minimal number of columns.

  4. -> Matrix a
  5. -> Matrix a
#

Extend a matrix to a given size adding a default element. If the matrix already has the required size, nothing happens. The matrix is never reduced in size. Example:

                           ( 1 2 3 0 0 )
               ( 1 2 3 )   ( 4 5 6 0 0 )
               ( 4 5 6 )   ( 7 8 9 0 0 )
extendTo 0 4 5 ( 7 8 9 ) = ( 0 0 0 0 0 )

The definition of extendTo is based on setSize:

extendTo e n m a = setSize e (max n $ nrows a) (max m $ ncols a) a
valuerref :: (Fractional a, Eq a) => Matrix a -> Either String (Matrix a)
#

Converts a matrix to reduced row echelon form, thus solving a linear system of equations. This requires that (cols > rows) if cols < rows, then there are fewer variables than equations and the problem cannot be solved consistently. If rows = cols, then it is basically a homogenous system of equations, so it will be reduced to identity or an error depending on whether the marix is invertible (this case is allowed for robustness). This implementation is taken from rosettacode https://rosettacode.org/wiki/Reduced_row_echelon_form#Haskell

valuemapRow
  1. :: (Int -> a -> a)

    Function takes the current column as additional argument.

  2. -> Int

    Row to map.

  3. -> Matrix a
  4. -> Matrix a
#

O(rows*cols). Map a function over a row. Example:

                         ( 1 2 3 )   ( 1 2 3 )
                         ( 4 5 6 )   ( 5 6 7 )
mapRow (\_ x -> x + 1) 2 ( 7 8 9 ) = ( 7 8 9 )
valuemapCol
  1. :: (Int -> a -> a)

    Function takes the current row as additional argument.

  2. -> Int

    Column to map.

  3. -> Matrix a
  4. -> Matrix a
#

O(rows*cols). Map a function over a column. Example:

                         ( 1 2 3 )   ( 1 3 3 )
                         ( 4 5 6 )   ( 4 6 6 )
mapCol (\_ x -> x + 1) 2 ( 7 8 9 ) = ( 7 9 9 )
valuemapPos
  1. :: ((Int, Int) -> a -> b)

    Function takes the current Position as additional argument.

  2. -> Matrix a
  3. -> Matrix b
#

O(rows*cols). Map a function over elements. Example:

                           ( 1 2 3 )   ( 0 -1 -2 )
                           ( 4 5 6 )   ( 1  0 -1 )
mapPos (\(r,c) a -> r - c) ( 7 8 9 ) = ( 2  1  0 )

Submatrices

0 declarations

Splitting blocks

valuesubmatrix
  1. :: Int

    Starting row

  2. -> Int

    Ending row

  3. -> Int

    Starting column

  4. -> Int

    Ending column

  5. -> Matrix a
  6. -> Matrix a
#

O(1). Extract a submatrix given row and column limits. Example:

                  ( 1 2 3 )
                  ( 4 5 6 )   ( 2 3 )
submatrix 1 2 2 3 ( 7 8 9 ) = ( 5 6 )
valueminorMatrix
  1. :: Int

    Row r to remove.

  2. -> Int

    Column c to remove.

  3. -> Matrix a

    Original matrix.

  4. -> Matrix a

    Matrix with row r and column c removed.

#

O(rows*cols). Remove a row and a column from a matrix. Example:

                ( 1 2 3 )
                ( 4 5 6 )   ( 1 3 )
minorMatrix 2 2 ( 7 8 9 ) = ( 7 9 )
valuesplitBlocks
  1. :: Int

    Row of the splitting element.

  2. -> Int

    Column of the splitting element.

  3. -> Matrix a

    Matrix to split.

  4. -> (Matrix a, Matrix a, Matrix a, Matrix a)

    (TL,TR,BL,BR)

#

O(1). Make a block-partition of a matrix using a given element as reference. The element will stay in the bottom-right corner of the top-left corner matrix.

                (             )   (      |      )
                (             )   ( ...  | ...  )
                (    x        )   (    x |      )
splitBlocks i j (             ) = (-------------) , where x = a_{i,j}
                (             )   (      |      )
                (             )   ( ...  | ...  )
                (             )   (      |      )

Note that some blocks can end up empty. We use the following notation for these blocks:

( TL | TR )
(---------)
( BL | BR )

Where T = Top, B = Bottom, L = Left, R = Right.

Joining blocks

value(<|>) :: Matrix a -> Matrix a -> Matrix a
#

Horizontally join two matrices. Visually:

( A ) <|> ( B ) = ( A | B )

Where both matrices A and B have the same number of rows. This condition is not checked.

value(<->) :: Matrix a -> Matrix a -> Matrix a
#

Vertically join two matrices. Visually:

                  ( A )
( A ) <-> ( B ) = ( - )
                  ( B )

Where both matrices A and B have the same number of columns. This condition is not checked.

Matrix operations

2 declarations
valueelementwise :: (a -> b -> c) -> Matrix a -> Matrix b -> Matrix c
#

Perform an operation element-wise. The second matrix must have at least as many rows and columns as the first matrix. If it's bigger, the leftover items will be ignored. If it's smaller, it will cause a run-time error. You may want to use elementwiseUnsafe if you are definitely sure that a run-time error won't arise.

Matrix multiplication

0 declarations

About matrix multiplication

Four methods are provided for matrix multiplication.

  • multStd: Matrix multiplication following directly the definition. This is the best choice when you know for sure that your matrices are small.

  • multStd2: Matrix multiplication following directly the definition. However, using a different definition from multStd. According to our benchmarks with this version, multStd2 is around 3 times faster than multStd.

  • multStrassen: Matrix multiplication following the Strassen's algorithm. Complexity grows slower but also some work is added partitioning the matrix. Also, it only works on square matrices of order 2^n, so if this condition is not met, it is zero-padded until this is accomplished. Therefore, its use is not recommended.

  • multStrassenMixed: This function mixes the previous methods. It provides a better performance in general. Method (*) of the Num class uses this function because it gives the best average performance. However, if you know for sure that your matrices are small (size less than 500x500), you should use multStd or multStd2 instead, since multStrassenMixed is going to switch to those functions anyway.

We keep researching how to get better performance for matrix multiplication. If you want to be on the safe side, use (*).

Functions

Linear transformations

5 declarations
valuescaleMatrix :: Num a => a -> Matrix a -> Matrix a
#

Scale a matrix by a given factor. Example:

              ( 1 2 3 )   (  2  4  6 )
              ( 4 5 6 )   (  8 10 12 )
scaleMatrix 2 ( 7 8 9 ) = ( 14 16 18 )
valuescaleRow :: Num a => a -> Int -> Matrix a -> Matrix a
#

Scale a row by a given factor. Example:

             ( 1 2 3 )   (  1  2  3 )
             ( 4 5 6 )   (  8 10 12 )
scaleRow 2 2 ( 7 8 9 ) = (  7  8  9 )
valuecombineRows :: Num a => Int -> a -> Int -> Matrix a -> Matrix a
#

Add to one row a scalar multiple of another row. Example:

                  ( 1 2 3 )   (  1  2  3 )
                  ( 4 5 6 )   (  6  9 12 )
combineRows 2 2 1 ( 7 8 9 ) = (  7  8  9 )
valueswitchRows
  1. :: Int

    Row 1.

  2. -> Int

    Row 2.

  3. -> Matrix a

    Original matrix.

  4. -> Matrix a

    Matrix with rows 1 and 2 switched.

#

Switch two rows of a matrix. Example:

               ( 1 2 3 )   ( 4 5 6 )
               ( 4 5 6 )   ( 1 2 3 )
switchRows 1 2 ( 7 8 9 ) = ( 7 8 9 )
valueswitchCols
  1. :: Int

    Col 1.

  2. -> Int

    Col 2.

  3. -> Matrix a

    Original matrix.

  4. -> Matrix a

    Matrix with cols 1 and 2 switched.

#

Switch two coumns of a matrix. Example:

               ( 1 2 3 )   ( 2 1 3 )
               ( 4 5 6 )   ( 5 4 6 )
switchCols 1 2 ( 7 8 9 ) = ( 8 7 9 )

Decompositions

5 declarations
valueluDecomp
  1. :: (Ord a, Fractional a)
  2. => Matrix a
  3. -> Maybe (Matrix a, Matrix a, Matrix a, a)
#

Matrix LU decomposition with partial pivoting. The result for a matrix M is given in the format (U,L,P,d) where:

  • U is an upper triangular matrix.

  • L is an unit lower triangular matrix.

  • P is a permutation matrix.

  • d is the determinant of P.

  • PM = LU.

These properties are only guaranteed when the input matrix is invertible. An additional property matches thanks to the strategy followed for pivoting:

  • L_(i,j) <= 1, for all i,j.

This follows from the maximal property of the selected pivots, which also leads to a better numerical stability of the algorithm.

Example:

         ( 1 2 0 )     ( 2 0  2 )   (   1 0 0 )   ( 0 0 1 )
         ( 0 2 1 )     ( 0 2 -1 )   ( 1/2 1 0 )   ( 1 0 0 )
luDecomp ( 2 0 2 ) = ( ( 0 0  2 ) , (   0 1 1 ) , ( 0 1 0 ) , 1 )

Nothing is returned if no LU decomposition exists.

valueluDecomp'
  1. :: (Ord a, Fractional a)
  2. => Matrix a
  3. -> Maybe (Matrix a, Matrix a, Matrix a, Matrix a, a, a)
#

Matrix LU decomposition with complete pivoting. The result for a matrix M is given in the format (U,L,P,Q,d,e) where:

  • U is an upper triangular matrix.

  • L is an unit lower triangular matrix.

  • P,Q are permutation matrices.

  • d,e are the determinants of P and Q respectively.

  • PMQ = LU.

These properties are only guaranteed when the input matrix is invertible. An additional property matches thanks to the strategy followed for pivoting:

  • L_(i,j) <= 1, for all i,j.

This follows from the maximal property of the selected pivots, which also leads to a better numerical stability of the algorithm.

Example:

          ( 1 0 )     ( 2 1 )   (   1    0 0 )   ( 0 0 1 )
          ( 0 2 )     ( 0 2 )   (   0    1 0 )   ( 0 1 0 )   ( 1 0 )
luDecomp' ( 2 1 ) = ( ( 0 0 ) , ( 1/2 -1/4 1 ) , ( 1 0 0 ) , ( 0 1 ) , -1 , 1 )

Nothing is returned if no LU decomposition exists.

valuecholDecomp :: Floating a => Matrix a -> Matrix a
#

Simple Cholesky decomposition of a symmetric, positive definite matrix. The result for a matrix M is a lower triangular matrix L such that:

  • M = LL^T.

Example:

           (  2 -1  0 )   (  1.41  0     0    )
           ( -1  2 -1 )   ( -0.70  1.22  0    )
cholDecomp (  0 -1  2 ) = (  0.00 -0.81  1.15 )

Properties

2 declarations
valuetrace :: Num a => Matrix a -> a
#

Sum of the elements in the diagonal. See also getDiag. Example:

      ( 1 2 3 )
      ( 4 5 6 )
trace ( 7 8 9 ) = 15
valuediagProd :: Num a => Matrix a -> a
#

Product of the elements in the diagonal. See also getDiag. Example:

         ( 1 2 3 )
         ( 4 5 6 )
diagProd ( 7 8 9 ) = 45

Determinants

valuedetLU :: (Ord a, Fractional a) => Matrix a -> a
#

Matrix determinant using LU decomposition. It works even when the input matrix is singular.

valueflatten :: Matrix (Matrix a) -> Matrix a
#

Flatten a matrix of matrices. All sub matrices must have same dimensions This criteria is not checked.