我想知道将一个640x640元素的大矩阵保存到.txt文件中最简单的方法是什么,以便更容易地进行概述。我一直试图将每个元素转换为字符串后再保存,但我从未成功过得到一个正确的、类似于矩阵的组织的.txt文件。因此,我想要按照完全相同的顺序保存所有元素,也许我会添加一行和一列来枚举行(从-320到+320)和列。我猜这对你们中的一些人来说是很常见的事情,所以我想知道是否有人愿意分享他的知识,并可能展示一个随机矩阵的示例...Luka
def write_matrix_to_textfile(a_matrix, file_to_write):
def compile_row_string(a_row):
return str(a_row).strip(']').strip('[').replace(' ','')
with open(file_to_write, 'w') as f:
for row in a_matrix:
f.write(compile_row_string(row)+'\n')
return True
这应该能满足你的需求。我没有实际运行这个代码,因为我没有矩阵可以运行它。如果它对你有用,请告诉我。
例子:
a = [[1,2],[3,4],[5,6]] # nested list
b = np.array(a) # 2-d array
array([[1, 2],
[3, 4],
[5, 6]])
c = np.array2string(b) # '[[1 2]\n [3 4]\n [5 6]]'. You can save this. Or
np.savetxt('foo', b) # It saves to foo file while preserving the 2d array shape
尝试使用numpy.savetxt()
和numpy.loadtxt()
将矩阵写入文件并从文件中读取矩阵。
#write matrix to file
import numpy
my_matrix = numpy.matrix('1 2; 3 4')
numpy.savetxt('matrix.txt', my_matrix, delimiter = ',')
#read file into a matrix
import numpy
my_matrix = numpy.loadtxt(open("matrix.txt","rb"),delimiter=",",skiprows=0)
matrix.txt
的样子如下:
1.000000000000000000e+00,2.000000000000000000e+00
3.000000000000000000e+00,4.000000000000000000e+00