how to cast obj to float for matrix

how to cast obj to float for matrix

three methods got compile error

   let mutable Q2 = Matrix.init A.NumCols A.NumCols (fun x y -> Q.GetValue(x,y) :> double)
    let mutable R2 = Matrix.init A.NumCols A.NumCols (fun x y -> R.GetValue(x,y) :> double)

    let mutable Q2 = Matrix.init A.NumCols A.NumCols (fun x y -> Convert.ToDouble(Q.GetValue(x,y)))
    let mutable R2 = Matrix.init A.NumCols A.NumCols (fun x y -> Convert.ToDouble(R.GetValue(x,y)))

    let mutable Q2 = Matrix.init A.NumCols A.NumCols (fun x y -> double Q.GetValue(x,y))
    let mutable R2 = Matrix.init A.NumCols A.NumCols (fun x y -> double R.GetValue(x,y))


let mutable tau: float[] = null
    let mutable Q: float[,] = null
    let mutable R: float[,] = null
    let mutable B: float[,] = Array2D.zeroCreate A.NumRows A.NumCols
    for i=0 to A.NumRows-1 do
        for j=0 to A.NumCols-1 do
            B.[i,j] <- A.[i,j]
  
    //let alglib.rmatrixschur s x = ()
    alglib.rmatrixqr(ref B, A.NumRows, A.NumCols, &tau);
    alglib.rmatrixqrunpackq(B, A.NumRows, A.NumCols, tau, A.NumRows, &Q)
    alglib.rmatrixqrunpackr(B, A.NumRows, A.NumCols, &R)
    let mutable Q2 = Matrix.init A.NumCols A.NumCols (fun x y -> Q.GetValue(x,y) :> double)
    let mutable R2 = Matrix.init A.NumCols A.NumCols (fun x y -> R.GetValue(x,y) :> double)

    let mutable Q2 = Matrix.init A.NumCols A.NumCols (fun x y -> Convert.ToDouble(Q.GetValue(x,y)))
    let mutable R2 = Matrix.init A.NumCols A.NumCols (fun x y -> Convert.ToDouble(R.GetValue(x,y)))

    let mutable Q2 = Matrix.init A.NumCols A.NumCols (fun x y -> double Q.GetValue(x,y))
    let mutable R2 = Matrix.init A.NumCols A.NumCols (fun x y -> double R.GetValue(x,y))

You may rewrite the function body using mutable references, this snippet on Stack Overflow shows how to. However a more idiomatic way would be refactoring your code using standard combinators, array slicing expressions and library functions from Matrix module of F# PowerPack, in particular, Matrix.ofArray2D and Matrix.toArray2D:

let QR2(A : matrix) =
    let mutable tau: float[] = null
    let mutable Q: float[,] = null
    let mutable R: float[,] = null
    let mutable B = Matrix.toArray2D A
    alglib.rmatrixqr(ref B, A.NumRows, A.NumCols, &tau);
    alglib.rmatrixqrunpackq(B, A.NumRows, A.NumCols, tau, A.NumRows, &Q)
    alglib.rmatrixqrunpackr(B, A.NumRows, A.NumCols, &R)
    [Q.[..A.NumCols-1, ..A.NumCols-1];R.[..A.NumCols-1, ..A.NumCols-1]]
    |> List.map Matrix.ofArray2D


This refactored implementation is succinct and runs OK. You may want to explore source code of F# PowerPack Matrix module for further details.

Copyright © 2007-2012 www.chuibin.com Chuibin Copyright