From 62ce6a140e491a8e91733e278d8653861e38466a Mon Sep 17 00:00:00 2001 From: =?utf8?q?Alexis=20Laferri=C3=A8re?= Date: Tue, 15 Sep 2015 13:17:17 -0400 Subject: [PATCH] lib/matrix: intro `Matrix::to_a & transposed` MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Alexis Laferrière --- lib/matrix/matrix.nit | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/lib/matrix/matrix.nit b/lib/matrix/matrix.nit index ab5755d..73131ca 100644 --- a/lib/matrix/matrix.nit +++ b/lib/matrix/matrix.nit @@ -61,6 +61,27 @@ class Matrix end end + # Get each row of this matrix in nested arrays + # + # ~~~ + # var items = [[1.0, 2.0], + # [3.0, 4.0]] + # var matrix = new Matrix.from(items) + # assert matrix.to_a == items + # ~~~ + fun to_a: Array[Array[Float]] + do + var a = new Array[Array[Float]] + for j in height.times do + var row = new Array[Float] + for i in width.times do + row.add self[j, i] + end + a.add row + end + return a + end + # Create a matrix from an `Array[Float]` composed of rows after rows # # Require: `width > 0 and height > 0` @@ -199,6 +220,25 @@ class Matrix return out end + # Get the transpose of this matrix + # + # ~~~ + # var matrix = new Matrix.from([[1.0, 2.0, 3.0], + # [4.0, 5.0, 6.0]]) + # assert matrix.transposed.to_a == [[1.0, 4.0], + # [2.0, 5.0], + # [3.0, 6.0]] + # + # var i = new Matrix.identity(3) + # assert i.transposed == i + # ~~~ + fun transposed: Matrix + do + var out = new Matrix(height, width) + for k, v in self do out[k.x, k.y] = v + return out + end + # Iterate over the values in this matrix fun iterator: MapIterator[MatrixCoordinate, Float] do return new MatrixIndexIterator(self) -- 1.7.9.5