#!/usr/bin/env python # # file: $ENGR_2011/lecture_08.py # # A simple Python program that demonstrates basic vectors and matrices # # import system modules # import os import sys import numpy as np from numpy.linalg import matrix_rank from scipy.linalg import solve # function: myloadtxt # # arguments: # fname: a filename containing a matrix # # return: a numpy float array # # Note: we use our own loader because numpy's loadtxt does not handle # single line matrices properly - it converts them to vectors # def myloadtxt(fname): # open the file # fp = open(fname) if fp is None: print("Error: error opening file (%s)" % (fname)) return None # read the lines into a list # lines = [] for l in fp: lines.append(l.rstrip('\n')) # create a numpy array # nrows = len(lines) ncols = len(lines[0].split()) A = np.zeros((nrows, ncols)) # loop over the list and parse the entries # for i in range(0, nrows): vals = lines[i].split() for j in range(0, ncols): A[i][j] = float(vals[j]) # exit gracefully # return(A) # end of function # # function: main # def main(argv): # read a matrix from a file specified at the command line # A = myloadtxt(argv[1]) # print the matrices # print("A:\n", A) # invert the matrix # B = np.linalg.inv(A) # display the result # print("B = A_inv\n", B) # verify the result # C = B @ A print("C = A_inv * A\n", C) # exit gracefully # return True # begin gracefully # if __name__ == '__main__': main(sys.argv[0:]) # # end of file