= Solution
Construct a fresh <sparse matrix>, transform each stored value, and omit products that become zero.
``
def scale(s: Double): SparseMatrix = {
val out = new SparseMatrix(N)
for (i <- 0 until N) {
out.rows(i) = rows(i).map { case (j, x) => (j, s * x) }
.filter(e => e._2 != 0.0)
}
out
}
``
Filtering preserves column order. It handles `s == 0.0` and any <floating point> underflow producing zero. Sharing immutable <list> structure elsewhere would be safe; this code constructs new transformed rows. Within the class, Scala's ordinary `private` permits access to `out.rows`. The result is
$$
\boxed{\mathrm{out}_{ij}=sA_{ij}.}
$$
The <time complexity> is $O(N+M)$ for $M$ stored entries. As usual for the supplied `Double` model, arithmetic means machine arithmetic; for a finite-real interpretation assume finite operands and products, excluding infinities and NaNs.
Back to article page