Chechy Levas
Chechy Levas

Reputation: 2312

How to compare Matrix elements in Math.Net numerics in F#

In this question, I asked how to perform a similar operation using PowerPack. I have decided to use MathNet instead as it is designed for .Net in general, not just F#.

I need a function that takes 2 matrices and outputs the percentage of agreement. The values in the matrices are all either 1.0 or -1.0. Apparently matrices of type Matrix(int) are not supported.

I have come up with a function that accomplishes this but I suspect there is a more direct route to do this, preferably using functionality of the Matrix class.

This is what I've got:

let percentageTheSame (a:Matrix<float>) (b:Matrix<float>) =
  let seqA = a |> Matrix.toSeq
  let seqB = b |> Matrix.toSeq
  let sames = Seq.map2 (fun a b -> (a,b)) seqA seqB |> Seq.filter (fun (a, b) -> a = b)
  float(sames.Count())/float(seqA.Count())

Upvotes: 0

Views: 483

Answers (1)

Gus
Gus

Reputation: 26194

Here's a solution similar to the one using PowerPack:

let percentageTheSame (a:Matrix<float>) (b:Matrix<float>) =
  let z,t = Matrix.fold (fun (z,t) e -> (if e = 0. then z+1 else z), t+1) (0,0) (a-b)
  float z / float t

Or using foldi, instead of subtracting matrices, might be more efficient for big matrices since it doesn't need to allocate an intermediate matrix:

let percentageTheSame (a:Matrix<float>) (b:Matrix<float>) =
  let z,t = 
    Matrix.foldi (fun i j (z,t) e -> (if e = b.[i,j] then z+1 else z), t+1) (0,0) a
  float z / float t

Upvotes: 2

Related Questions