Skip to content

Instantly share code, notes, and snippets.

@sidharthkuruvila
Created November 3, 2011 16:13
Show Gist options
  • Select an option

  • Save sidharthkuruvila/1336915 to your computer and use it in GitHub Desktop.

Select an option

Save sidharthkuruvila/1336915 to your computer and use it in GitHub Desktop.
//https://www.ai-class.com/course/video/quizquestion/116
//Calculate the average and the covariance matrix.
val ls = List(3 -> 8, 4 -> 7, 5 -> 5, 6 -> 3, 7 -> 2)
val l = ls.map{case (a, b) => (a.toDouble, b.toDouble)}
def square(n:Double) = n*n
def mu(l:List[Double]):Double = l.sum/l.length
def sigmaSq(l:List[Double], mu:Double):Double = l.map(x=>square(x-mu)).sum/l.length
val mx = mu(l.map(r=>r._1))
val my = mu(l.map(r=>r._2))
val m = (mx, my)
val M = l.length
def sum2(t:(Double, Double)):Double = t._1 + t._2
val sigma = l.map{case (ax, ay) =>
val dx = ax - mx
val dy = ay - my
List(dx*dx, dy*dx,dx*dy,dy*dy)
}.reduce{(a, b)=>a zip b map sum2}.map(_/M)
println("mu = "+m)
println("Sigma = "+sigma)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment