【发布时间】:2019-08-03 02:41:58
【问题描述】:
问候我有一个文件 matrix.txt,具有以下矩阵 3x3 dtype float32...
-----------------matrix.txt------------
[[ 2.94795074e+00 3.15288849e-02 -8.67170450e+02]
[-2.21123258e-17 2.94877180e+00 -5.95651904e+02]
[ 1.49601560e-04 1.52843706e-04 1.00000000e+00]]
p_homo = np.array([[1], [1], [1]])
file = open('matrix.txt', 'r')
matrix_file_l =list()
matrix_file_l = file.read()
matrix_file = np.array(matrix_file_l, dtype="float32")
def mult_matrix(matrix1, matrix2):
matrixx = np.empty([len(matrix1), len(matrix2[0])])
for i in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
matrixx[i][j] += matrix1[i][k] * matrix2[k][j]
return matrixx
matrix = mult_matrix(matrix_file, p_homo)
matrix_file 是一个字符串,我无法转换为 float32 我尝试通过多种方式进行转换
matrix_file = np.array(matrix_file_l, dtype="float32")
ValueError: could not convert string to float: '[[-5.62093010e+01...
【问题讨论】:
-
如果该文件不包含方括号,它会更容易阅读。只是数字,每行的列数相等,并带有一些明确定义的分隔符(空格或逗号)。所谓的
csv格式。 -
是的,这是真的,但我需要括号以便稍后将矩阵相乘 @hpaulj.. 谢谢
-
文本文件中不需要括号。从技术上讲,括号也不是数组的一部分——它们只是数组漂亮显示格式的一部分。
csvnp.genfromtxt等读者从 csv 文件创建一个数组。 -
如果出于某种原因我想不出文本文件已经带有括号,请尝试使用
eval:matrix_file = np.array(eval(matrix_file_l))。仅供参考,numpy 还具有矩阵乘法的功能(np.matmul,np.dot) -
@Mstaino 我尝试使用
eval:但同样的错误..matrix_file = np.array(matrix_file_l, dtype="float32") ValueError: could not convert string to float: '[[ 1.82278459e+00 1.91872062e-02 -8.78831607e+02]\n'
标签: python-3.x string file numpy matrix-multiplication