Skip to content

Commit 862bda5

Browse files
committed
fix matrix inversion to be immutable
1 parent 0ff0f49 commit 862bda5

File tree

2 files changed

+7
-4
lines changed

2 files changed

+7
-4
lines changed

src/main/scala/matrix.scala

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -100,16 +100,17 @@ object Matrix:
100100
val n = a.length
101101
val m = a(0).length
102102
val identity = Array.tabulate(n, m)((i, j) => if i == j then 1.0 else 0.0)
103+
var anew = a.map(_.clone)
103104
for i <- 0 until n do
104-
val pivot = a(i)(i)
105+
val pivot = anew(i)(i)
105106
for j <- 0 until m do
106-
a(i)(j) /= pivot
107+
anew(i)(j) /= pivot
107108
identity(i)(j) /= pivot
108109
for k <- 0 until n do
109110
if k != i then
110-
val factor = a(k)(i)
111+
val factor = anew(k)(i)
111112
for j <- 0 until m do
112-
a(k)(j) -= factor * a(i)(j)
113+
anew(k)(j) -= factor * anew(i)(j)
113114
identity(k)(j) -= factor * identity(i)(j)
114115
identity
115116

src/test/scala/testmatrix.scala

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,7 @@ class TestMatrix extends munit.FunSuite {
291291
Array(-0.119672, 0.00983607, 0.0114754)
292292
)
293293
A.assert(Matrix.elementwise_equal(inv, expected, 1e-6))
294+
A.assert(!Matrix.elementwise_equal(inv, mat, 1e-6))
294295
}
295296
test("Inverse of a matrix - 2") {
296297
val mat = Array(
@@ -305,6 +306,7 @@ class TestMatrix extends munit.FunSuite {
305306
)
306307
val inv = Matrix.inverse(mat)
307308
A.assert(Matrix.elementwise_equal(inv, expected, 1e-6))
309+
A.assert(!Matrix.elementwise_equal(inv, mat, 1e-6))
308310
}
309311
test("Column min max regarding to direction vector - 1") {
310312
val mat = Array(

0 commit comments

Comments
 (0)