← back

Scalar Multiplication of a Matrix

#5 · Linear Algebra · Easy

⊣ Solve on deep-ml.com

Problem

Multiply every element of a matrix by a given scalar value and return the resulting matrix.

Solution

1
2
def scalar_multiply(matrix: list[list[int|float]], scalar: int|float) -> list[list[int|float]]:
    return [[element * scalar for element in row] for row in matrix]

Explanation

  1. Iterate over each row in the matrix.
  2. For each element in the row, multiply it by the scalar.
  3. Return the new matrix with scaled values.

Complexity

  • Time: O(m * n)
  • Space: O(m * n) for the result matrix