""" This module provides functions for performing some standard matrix operations. Matrices are represented as nested lists, i.e. lists of lists of numbers (float or int.) Functions that take two matrix arguments may produce arbitrary output if the matrices are not compatible, i.e. of similar dimension. """ #------------------------------------------------------------------------------ # Matrix.py #------------------------------------------------------------------------------ import random def add(A, B): """ Return a matrix that is the sum A+B of matrices A and B. """ C = [] for i in range(len(A)): R = [] for j in range(len(A[i])): R.append(A[i][j]+B[i][j]) # end inner for C.append(R) # end outer for return C # end add() def negate(A): """ Return the negative -A of matrix A. """ negativeA = [] for row in A: negativeRow = [] for x in row: negativeRow.append(-x) # end inner for negativeA.append(negativeRow) #end outer for return negativeA # end negate() def sub(A, B): """ Return a matrix that is the difference A-B of matrices A and B. """ return add(A, negate(B)) # end sub() def scalarMult(c, A): """ Return a matrix that is the scalar multiple of matrix A by the number c. """ M = [] for row in A: newRow = [] for x in row: newRow.append(c*x) # end M.append(newRow) # end return M # end scalarMult() def randomMatrix(n, a, b): """ Return square matrix of size n by n whose entries are random floats in the range [a, b). """ M = [] for i in range(n): newRow = [] for j in range(n): newRow.append(a+(b-a)*random.random()) # same as random.uniform(a, b) M.append(newRow) return M # end randomMatrix() def printMatrix(M): """ Print in nice format. """ print('[') for row in M: print(' ',row) print(']') # end printMatrix()