Search code examples
f#plotlyf#-interactive

Typcasting Matrix<float> to seq<'a * 'b> in F with Plotly and F# .Net Interactive


#r "nuget: MathNet.Numerics"
#r "nuget: MathNet.Numerics.FSharp"
#r "nuget: Plotly.NET, 2.0.0"
#r "nuget: Plotly.NET.Interactive, 2.0.0"

open Plotly.NET 
open MathNet.Numerics
open MathNet.Numerics.LinearAlgebra

let matrix1 =   matrix [[1.0; 2.0]; [5.0; 6.0]]
let matrix2 =  matrix [[3.0; 3.0]; [7.0; 8.0]]
let matrix12 = matrix1 * matrix2

let myFirstChart = Chart.Point(matrix12) //TYPE CAST ERROR
let myFirstStyledChart =
    Chart.Point(xData,yData)
    |> Chart.withTitle "Hello world!"
    |> Chart.withXAxisStyle ("xAxis")
    |> Chart.withYAxisStyle ("yAxis")
    |> Chart.show

I get the error

Error: input.fsx (9,32)-(9,40) typecheck error The type 'Matrix<float>' is not compatible with the type 'seq<'a * 'b>'
input.fsx (9,32)-(9,40) typecheck error Type constraint mismatch. The type 
    'Matrix<float>'    
is not compatible with type
    'seq<'a * 'b>'  

Is there som compact way to make typecase from Matrix to seq<> in F# without needing make big convert function. I'm just look for fast way to display vectors and matrixes in plotly.


Solution

  • It doesn't need to be a complicated function but you need some way to convert the matrix into what the x and y data will be on your plot. e.g.:

    let x = matrix12.ToArray()
    
    let plottable = 
        seq {
            for i in 0..(Array2D.length1 x - 1) do
                for j in 0..(Array2D.length2 x - 1) do
                    yield (i * j), x.[i, j]
    
        }
    let myFirstChart = Chart.Point(plottable)