I'm doing exercise 11.8 from Scala for impatient, asking to write a matrix class:
Provide a class
Matrix
- you can choose whether you want to implement 2 x 2 matrices, square matrices of any size, or m x n matrices. Supply operations + and *. The latter should also work with scalars, for example mat * 2. A single element should be accessible asmat(row, col)
.
The code is working, but may be there can be improvements to make code more functional or more stable:
class Matrix(val n: Int, val m: Int, fun: (Int, Int) => Double) {
private val matrix = Array.tabulate[Double](n,m)(fun)
def +(another: Matrix) = {
if (n != another.n || m != another.m)
throw new IllegalArgumentException("Sizes of arrays don't match.")
else
new Matrix(n, m, (i, j) => this(i)(j) + another(i)(j))
}
def *(another: Matrix) = {
if (m != another.n)
throw new IllegalArgumentException("Sizes of arrays don't match.")
else
new Matrix(n, another.m, (i,j) => { var sum = 0.0;
for (k <- matrix(i).indices) sum += matrix(i)(k) * another(k)(j);
sum }
)
}
def *(k: Int) = new Matrix(n, m, k * matrix(_)(_) )
def apply(i: Int)(j: Int) = matrix(i)(j)
override def toString = {
var result = ""
for (row <- matrix) {
for (value <- row)
result += value + " "
result += "\n"
}
result
}
}
tabulate
is in there either, and I'm not sure if it's something the book said that you didn't mention, or something you came up with for reasons I don't understand. \$\endgroup\$