简体   繁体   中英

Converting System.Double[,] to DenseMatrix

The hessian function in Diffsharp returns something called System.Double[,]. Or if you hover on the variable it shows as a float[,]. This object seems a bit difficult to parse, I'm not sure why. This question is related but the answer doesn't seem general enough as it only deals with a specific size of matrix.

I'm wondering if anyone has any cleaner way than the following to massage this object into a DenseMatrix. The matrices returned will always be square.

I want to change this:

System.Double[,]
[[-1.008660933; 9.992007222e-06]
 [9.992007222e-06; 0.4999911596]]

to this but cleanly:

MathNet.Numerics.LinearAlgebra.Double.DenseMatrix
DenseMatrix 2x2-Double
   -1.00866  9.99201E-06
9.99201E-06     0.499991

Here is my code. This just looks a bit awkward amid the rest of the F# code.

let hessianToMatrix (h: float[,]) = 
    let v = h |> Seq.cast<float> |> Seq.toArray |> DenseVector
    let dim = float v.Count |> sqrt |> int    
    let m = DenseMatrix.init dim dim (fun i j -> 0.)
    for r in 0 .. dim-1 do
        for c in 0 .. dim-1 do
            m.[r, c] <- v.[r*dim + c]
    m

let hess = hessian llNormal [|5.; 1.|] |> hessianToMatrix
hess.GetType() |> printfn "\n\n\n%A"
hess |> printfn "%A"

float in F# is a synonym for double in .Net. And float [,] is a 2d Array. You can convert it to Densematrix:

let rnd = System.Random()
let x2d = Array2D.init 2 2 (fun i j -> rnd.NextDouble()) 
x2d |> DenseMatrix.ofArray2

I get:

val it : Matrix<float> =
  DenseMatrix 2x2-Double
0.438629  0.462749
0.386625  0.740308

{ColumnCount = 2;
 Item = ?;
 RowCount = 2;
 Storage = MathNet.Numerics.LinearAlgebra.Storage.DenseColumnMajorMatrixStorage`1[System.Double];
 Values = [|0.4386289918; 0.3866254107; 0.4627486283; 0.7403077645|];}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM