Skip to content

Commit bd851f3

Browse files
committed
add functions for appending vector to matrix in columns and rows
1 parent b213be3 commit bd851f3

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

src/main/scala/matrix.scala

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,10 @@ object Matrix:
9494

9595
def size(a: Mat): (Int, Int) = (a.length, a(0).length)
9696

97+
def appendColumnVec(a: Mat, b: Vec): Mat = a :+ b
98+
99+
def appendRowVec(a: Mat, b: Vec): Mat = (a.transpose :+ b).transpose
100+
97101
def euclideanDistance(a: Vec, b: Vec): Double =
98102
math.sqrt(a.zip(b).map((x, y) => (x - y) * (x - y)).sum)
99103

src/test/scala/testmatrix.scala

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,4 +217,18 @@ class TestMatrix extends munit.FunSuite {
217217
val expected = Array(1.0 + 2.0 + 3.0 + 4.0, 4.0 + 5.0 + 6.0 + 7.0, 7.0 + 8.0 + 9.0 + 10.0)
218218
A.assert(Matrix.elementwise_equal(result, expected))
219219
}
220+
test("Append a Column Vector to Matrix"){
221+
val mat = Array(Array(1.0, 2.0, 3.0), Array(4.0, 5.0, 6.0), Array(7.0, 8.0, 9.0))
222+
val col = Array(10.0, 11.0, 12.0)
223+
val newmat = Matrix.appendcol(mat, col)
224+
val expected = Array(Array(1.0, 2.0, 3.0, 10.0), Array(4.0, 5.0, 6.0, 11.0), Array(7.0, 8.0, 9.0, 12.0))
225+
A.assert(Matrix.elementwise_equal(newmat, expected, 1e-6))
226+
}
227+
test("Append a Row Vector to Matrix"){
228+
val mat = Array(Array(1.0, 2.0, 3.0), Array(4.0, 5.0, 6.0))
229+
val row = Array(7.0, 8.0, 9.0)
230+
val newmat = Matrix.appendrow(mat, row)
231+
val expected = Array(Array(1.0, 2.0, 3.0), Array(4.0, 5.0, 6.0), Array(7.0, 8.0, 9.0))
232+
A.assert(Matrix.elementwise_equal(newmat, expected, 1e-6))
233+
}
220234
}

0 commit comments

Comments
 (0)