This is the place for queries that don't fit in any of the other categories.


Postby Cereal » Mon Apr 21, 2014 9:29 am

I am using polyfit, and I can't make it work. I think that it doesn't like that I put in a matrix. What could I change to make it work?

Code: Select all
x = array([0.0,0.5,1.0,1.5,2.0,2.5])
N = (len(x)-1)
m1 = ([x**N])
m2 = ([x**(N-1)])
m3 = ([x**(N-2)])
m4 = ([x**(N-3)])
m5 = ([x**(N-4)])
m6 = ([x**(N-5)])

def M(x1,x2,x3,x4,x5,x6):
    return column_stack(([x1],[x2],[x3],[x4],[x5],[x6]))
print M(m1,m2,m3,m4,m5,m6)
Matris = M(m1,m2,m3,m4,m5,m6)

y = array([[-2],[0.5],[-2],[1],[-0.5],[1]])

print y

def polyfit(a,b):
    return linalg.solve(a,b)
    c = polyfit(a,b)

print polyfit(Matris,y)

It says this:

Code: Select all
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 523, in runfile
    execfile(filename, namespace)
  File "C:\Users\mat11CJo\Downloads\H1 4-9.py", line 34, in <module>
    print polyfit(Matris,y)#dimension? Third variable?
  File "C:\Users\mat11CJo\Downloads\H1 4-9.py", line 31, in polyfit
    return linalg.solve(a,b)
  File "C:\Python27\lib\site-packages\numpy\linalg\linalg.py", line 311, in solve
    _assertRank2(a, b)
  File "C:\Python27\lib\site-packages\numpy\linalg\linalg.py", line 155, in _assertRank2
    'two-dimensional' % len(a.shape))
numpy.linalg.linalg.LinAlgError: 3-dimensional array given. Array must be two-dimensional

Posts: 15
Joined: Tue Apr 15, 2014 7:42 am

Re: Polyfit

Postby tnknepp » Wed Apr 23, 2014 5:16 pm

It has nothing to do with being a matrix, rather you are trying to fit a three-dimensional matrix with a two-dimensional matrix, which fundamentally does not make sense. Further, linalg.solve deals only with two-dimensional matrices/arrays. You could use numpy.polyfit as well, which may be better. Something like the example below does work.

Code: Select all
import numpy as np
lobf = np.polyfit(Matris[0,:,0],y)
Python: 2.7 via Anaconda
Numpy: 1.7
Pandas: 0.11
OS: Windows 7
IDE: Spyder/IPython
User avatar
Posts: 119
Joined: Mon Mar 11, 2013 7:41 pm

Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 2 guests