#------------------------------------------------------------------------------ # MatrixAdd.py #------------------------------------------------------------------------------ def matrix_add(A, B): """ return a new matrix (i.e. nested list) that is the sum of matrices A and B. A and B must be compatible. """ 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 matrix_add() #-- main program -------------------------------------------------------------- M = [[1,2,3],[4,5,6],[7,8,9]] N = [[-1,-2,-3],[-4,-5,-6],[-7,-8,-9]] P = matrix_add(M, N) print(P) print(matrix_add(M,M)) R=[['one','two'],['three','four']] S=[['five','six'],['seven','eight']] print(matrix_add(R,S)) print(matrix_add([[1,3],[0,2]],[[2,5],[-3,0]]))