Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy and matlab polyfit results differences

I'm getting different results when calling numpy.polyfit and matlab polyfit functions on exemplary set of data:

Python3.2:

(Pdb) a_array = [1, 2, 4, 6, 8,7, 9]
(Pdb) numpy.polyfit( range (len (a_array)), a_array, 1)
array([ 1.35714286,  1.21428571])

Matlab:

a_array = [1, 2, 4, 6, 8,7, 9]
polyfit(1:1:length(a_array), a_array, 1)

ans =
    1.3571   -0.1429

This is obviously not a numerical error.

I assume that the default value of some special option (like ddof in std function) differs between Python and matlab but I can't find it. Or maybe I should use another version of Python's polyfit?

How can I get the same polyfit results in both, Python Numpy and Matlab?

like image 980
Sebastian Kramer Avatar asked Feb 16 '14 01:02

Sebastian Kramer


People also ask

What is Numpy Polyfit return?

The np. polyfit() method takes a few parameters and returns a vector of coefficients p that minimizes the squared error in the order deg, deg-1, … 0. It least squares the polynomial fit.

How does Polyfit work Numpy?

The function NumPy. polyfit() helps us by finding the least square polynomial fit. This means finding the best fitting curve to a given set of points by minimizing the sum of squares. It takes 3 different inputs from the user, namely X, Y, and the polynomial degree.

Is Numpy faster than Matlab?

The time matlab takes to complete the task is 0.252454 seconds while numpy 0.973672151566, that is almost four times more.

What is Polyfit function in Python?

In python, Numpy polyfit() is a method that fits the data within a polynomial function. That is, it least squares the function polynomial fit. For example, a polynomial p(X) of deg degree fits the coordinate points (X, Y). This function returns a coefficient vector p that lessens the squared error in the deg, deg-1,…


1 Answers

This gives the same result.

In [10]: np.polyfit(range(1, len(a_array)+1), a_array, 1)
Out[10]: array([ 1.35714286, -0.14285714])

range(...) starts from zero if you don't give it a start argument, and the end point is not included.

1:1:length(a_array) this in Matlab should give you 1 to the length of a_array with both ends included. If I remember Matlab correctly)

The difference in the constant of the interpolated line was simply because of difference in the start value in the x-axis.

like image 114
M4rtini Avatar answered Oct 02 '22 00:10

M4rtini