61.6k views
0 votes
Write a function readMatrix (filename) that takes a string as an argument, reads a matrix of numbers from that file, and returns a 2D numpy array (i.e. a matrix). The function should ignore blank lines and lines beginning with a #, even if the # is preceded by whitespace characters. Put your test(s) inside an if __name_ = "__main__:" so your submitted .py file can be imported as a module.

User Mark Kelly
by
9.2k points

1 Answer

5 votes

Final answer:

To write the readMatrix function in Python, we can make use of the numpy library, which provides functions for working with arrays. The function reads a file line by line, ignoring blank lines and lines beginning with a #, and returns the matrix as a 2D numpy array.

Step-by-step explanation:

To write the readMatrix function in Python, we can make use of the numpy library, which provides functions for working with arrays. Here is an example of how the function can be implemented:

import numpy as np

def readMatrix(filename):
matrix = []
with open(filename, 'r') as file:
for line in file:
line = line.strip()
if line and not line.startswith('#'):
matrix.append([float(num) for num in line.split()])
return np.array(matrix)


if __name__ == '__main__':
matrix = readMatrix('example.txt')
print(matrix)

In this implementation, the function reads the file line by line, strips any leading or trailing whitespace, and checks if the line is not empty and not a comment. It then splits the line by whitespace and converts each number to a float. The resulting matrix is returned as a 2D numpy array.

User Baksteen
by
7.9k points