export matrix to ascii file in python

To export a matrix to an ASCII file in Python, you can use the numpy.savetxt() function. Here's an example:

main.py
import numpy as np

# Create a matrix
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Export matrix to ASCII file
np.savetxt('matrix.txt', matrix)
155 chars
8 lines

In this example, we import the numpy library and create a matrix using the np.array() function. Then, we use the np.savetxt() function to save the matrix to the file 'matrix.txt'. The default delimiter is a space, but you can specify a different delimiter using the delimiter parameter. For example, to use a comma as the delimiter, you can modify the np.savetxt() line like this:

main.py
np.savetxt('matrix.txt', matrix, delimiter=',')
48 chars
2 lines

This will save the matrix with commas separating the values in the file.

Remember to have numpy installed in order to use the np module and the savetxt() function.

related categories

gistlibby LogSnag