Last active
December 29, 2015 11:09
-
-
Save okapies/7661540 to your computer and use it in GitHub Desktop.
「プログラマの為の数学勉強会」の資料を ScalaNLP で写経してみたかった http://nineties.github.io/math-seminar/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import breeze.linalg._ | |
/* | |
* p.15 (http://nineties.github.io/math-seminar/7.html#/15) | |
* | |
* Note: Does breeze basically recommend side effects? | |
* Note: The compiler will complain 'could not find implicit value for parameter canMapValues' | |
* if you make the type parameter 'Int' as a generic type. | |
*/ | |
def matAdd(a: DenseMatrix[Int], b: DenseMatrix[Int]) = | |
if ((a.rows, a.cols) == (b.rows, b.cols)) { | |
a.mapPairs((ka, va) => va + b(ka)) | |
} else { | |
throw new IllegalArgumentException | |
} | |
def matScale(a: DenseMatrix[Int], k: Int) = a.map(_ * k) | |
def matMul(a: DenseMatrix[Int], b: DenseMatrix[Int]) = | |
if (a.cols == b.rows) { | |
val c = DenseMatrix.zeros[Int](a.rows, b.cols) | |
(0 until a.rows).foreach { i => | |
(0 until b.cols).foreach { j => | |
var v = 0 | |
(0 until a.cols).foreach { k => | |
v += a(i, k) * b(k, j) | |
} | |
c(i, j) = v | |
} | |
} | |
c | |
} else { | |
throw new IllegalArgumentException | |
} | |
val a = DenseMatrix((1, 2, 3), (4, 5, 6)) | |
val b = DenseMatrix((2, 1, 4), (5, 2, 1)) | |
matAdd(a, b) == a + b | |
matScale(a, 2) == a * 2 | |
val a = DenseMatrix((1, 2, 3), (4, 5, 6)) | |
val b = DenseMatrix((2, 1, 4), (5, 2, 1), (0, 1, 3)) | |
matMul(a, b) == a * b | |
/* | |
* p.43 (http://nineties.github.io/math-seminar/7.html#/43) | |
*/ | |
def fib(n: Int) = Iterator.fill(n)(DenseMatrix((1L, 1L), (1L, 0L))).reduceLeft(_ * _)(1, 0) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
git clone https://github.com/scalanlp/breeze-examples | |
sbt console |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment