BaRud
BaRud

Reputation: 3218

loadtxt a matrix in python3 error

in python, I am trying to load a 2 column matrix from file. I can manually enter this as:

xdata = np.array([0.1639534, 0.2411005, 0.3130353, 0.3788510,  0.4381247, 0.5373147, 0.6135673, 0.6716365, 0.7506711,  0.8000908, 0.9000000])
ydata =np.array ([7.1257999E-04,9.6610998E-04,1.1894000E-03,1.3777000E-03,1.5285000E-03,1.7297000E-03,1.8226000E-03,1.8422999E-03,1.7741000E-03,1.6574000E-03,1.1877000E-03])

But I want it to load from file:

$ cat fit
0.16395341   0.71258E-03
0.24110050   0.96611E-03
0.31303529   0.11894E-02
0.37885098   0.13777E-02
0.43812473   0.15285E-02
0.53731472   0.17297E-02
0.61356731   0.18226E-02
0.67163649   0.18423E-02
0.75067115   0.17741E-02
0.80009080   0.16574E-02
0.90000000   0.11877E-02

From this and this, I tried

xdata, ydata =np.loadtxt(fit,delimiter=' ')

only to know that:

$ python least.py 
Traceback (most recent call last):
  File "least.py", line 5, in <module>
    xdata, ydata =np.loadtxt(fit,delimiter=' ')
NameError: name 'fit' is not defined

Whats going wrong here? Any help please?

Upvotes: 0

Views: 369

Answers (1)

Eryk Sun
Eryk Sun

Reputation: 34270

You don't have a variable named fit. The filename is the string 'fit'. You'll also need the argument unpack=True to create the array transposed for unpacking:

>>> xdata, ydata = np.loadtxt('fit', unpack=True)

>>> xdata
array([ 0.16395341,  0.2411005 ,  0.31303529,  0.37885098,  0.43812473,
        0.53731472,  0.61356731,  0.67163649,  0.75067115,  0.8000908 ,
        0.9       ])

>>> ydata
array([ 0.00071258,  0.00096611,  0.0011894 ,  0.0013777 ,  0.0015285 ,
        0.0017297 ,  0.0018226 ,  0.0018423 ,  0.0017741 ,  0.0016574 ,
        0.0011877 ])

Upvotes: 1

Related Questions