This project has moved. For the latest updates, please go here.

F# matrix initialization

Aug 17, 2012 at 8:54 AM


I need to Cholesky decompose a matrix in F#. I can use the SymmetricMatrix class to do this. However, I cannot figure out a way to initialize an immutable Meta Numerics matrix in F#.

Any help would be much appreciated.



Aug 20, 2012 at 9:08 AM

Here is example F# code that shows how to use Meta.Numerics to create a symmetric matrix, assign values to it, Cholesky decompose it, and then use the Cholesky decomposition to obtain its inverse.

// Simple routine to print a matrix
let PrintMatrix (M : AnyRectangularMatrix) =
  for r = 0 to M.RowCount-1 do
    for c = 0 to M.ColumnCount-1 do
      printf "%A " M.[r, c]
    printfn ""

// Create, fill, and print a new symmetric matrix
let A = new SymmetricMatrix(2)
A.[0,0] <- 2.0
A.[0,1] <- 1.0
A.[1,1] <- 3.0

// Use Cholesky decomposition to find the matrix
// inverse and print it
let CD = A.CholeskyDecomposition()
let AI = CD.Inverse()

Are you perhaps asking how to can do initialization using some sort of bracket notation to specify all the matrix entires at once? The RectangularMatrix class has a constructor that supports this, as shown in the following example...

let R = new RectangularMatrix(array2D [[1.0; 2.0; 3.0] ; [4.0; 5.0; 6.0]])

...but other matrix classes do not, because there is no way for us to know at compile time whether the supplied matrix of values actually fufills the requirements (e.g. squareness, symmetry) of the class. While these sorts of constructions are often helpful in writing compact code examples, they aren't all that useful in real life, where it is unlikely that your matrices will be small and fully specified at compile time.

Aug 20, 2012 at 4:20 PM

Thanks ichbin, that worked.