Matrices

In this project, you'll write a number of functions. They all concern matrices.

What are matrices?  We'll discuss them in class, but also I need you to read this. It's a short introduction to matrices; it describes just those matrix operations you'll implement. I also suggest that you peruse the Wikipedia article. (I did say peruse. You won't read it start to finish. It's too much for that.) If you haven't taken a Linear Algebra course yet, you probably will at some point; and in that course, you'll study matrices in much greater depth.

So, I assume you've read my introduction and know what a matrix is.  Of course we'll need a way to get matrices into our code. What's the right data structure? I suggest that we use lists of lists. The outer list in each case will be the matrix; each inner list will be a row from the matrix. So for instance the list [[1, 2], [2, 3], [3, 4]] represents the 3 × 2 matrix whose rows are [1, 2], [2, 3] and [3, 4].

Write the six functions described below. Each takes a matrix or matrices; all but one returns a matrix. None of the functions are mutators. Note that some should raise value errors.  Recall the syntax:

if <boolean_expression>:

    raise ValueError(<string>)

Size

Note: the statement return m, n returns a tuple. Also note: the matrix with no elements, represented by us as [[]], has size (0, 0).

Addition

Scalar Multiplication

Subtraction

Multiplication

Transpose

Determinant (EC)


Test Cases:

>>> L = [[-8, 3, 0], [12, -10, -10], [-6, 10, -12], [12, 11, -9]]  # 4 by 3

>>> M = [[-10, 1, 1], [-12, -11, -7], [-5, -6, 3], [-8, 12, -4]]  # 4 by 3

>>> N = [[-1, 5, -9, 8], [-3, -4, 2, -4], [-10, 7, 8, 4], [3, 8, -8, 0]]  # 3 by 4

>>> r = -3

>>> mat_size(M)

(4, 3)

>>> mat_add(L, M)

[[-18, 4, 1], [0, -21, -17], [-11, 4, -9], [4, 23, -13]]

>>> mat_sub(L, M)

[[2, 2, -1], [24, 1, -3], [-1, 16, -15], [20, -1, -5]]

>>> scalar_mult(r, N)

[[3, -15, 27, -24], [9, 12, -6, 12], [30, -21, -24, -12], [-9, -24, 24, 0]]

>>> transpose(N)

[[-1, -3, -10, 3], [5, -4, 7, 8], [-9, 2, 8, -8], [8, -4, 4, 0]]

>>> mat_mult(N, L)

[[218, -55, -14], [-84, 7, 52], [164, 24, -202], [120, -151, 16]]