Skip to content

Instantly share code, notes, and snippets.

@sidonath
Created July 8, 2014 10:37
Show Gist options
  • Save sidonath/729ceef5730569da45a7 to your computer and use it in GitHub Desktop.
Save sidonath/729ceef5730569da45a7 to your computer and use it in GitHub Desktop.
#r "/Users/damir/packages/MathNet.Numerics.3.0.2/lib/net40/MathNet.Numerics.dll";;
#r "/Users/damir/packages/MathNet.Numerics.FSharp.3.0.2/lib/net40/MathNet.Numerics.FSharp.dll";;
open MathNet.Numerics.LinearAlgebra
let splitRows (matrix:string) =
matrix.Split([|'\n'|])
|> List.ofArray
let parseRow (row:string) =
row.Split([|' '|])
|> List.ofArray
|> List.map (fun x -> float x)
let stringToLists (m:string) =
m
|> splitRows
|> List.map parseRow
let stringToMatrix m =
m
|> stringToLists
|> matrix
let m1s = "2 4\n1 2"
let m2s = "3 2\n4 6"
// one liner:
// "3 4\n1 2".Split([|'\n'|]) |> List.ofArray |> List.map (fun row -> row.Split([|' '|]) |> List.ofArray |> List.map (fun x -> float x)) |> matrix
// one liner in Ruby (except there's no tranformation to matrix):
// "3 4\n1 2".split("\n").map { |row| row.split(' ').map(&:to_f) }
let m1 = stringToMatrix m1s
let m2 = stringToMatrix m2s
let r = m1 * m2
printfn "Result r1: %A" r
let sumProdPairs = List.fold (fun acc (x, y) -> acc + x * y) 0.
let dotProduct x y = List.zip x y |> sumProdPairs
let rec transpose = function
| (_::_)::_ as M -> List.map List.head M :: transpose ( List.map List.tail M)
| _ -> []
let multip m1 m2 =
m1
|> List.map (fun row -> (m2 |> transpose |> List.map (fun col -> dotProduct row col)))
let m1l = stringToLists m1s
let m2l = stringToLists m2s
let r2 = multip m1l m2l
printfn "Result r2: %A" r2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment