Search code examples
pythonmatlabnumpypolynomials

Python equivalent of MATLAB's Legendre function


Currently, I am trying to analyze time series data with Python. As a guideline for doing so, I oriented myself on a MATLAB script that does pretty much everything I'd like to do. So far it worked fine, but now I bumped into this Legendre polynomial that was used in that script.

I tried the NumPy implementation of it, but I couldn't find a way that (more or less) yielded the same results as the MATLAB function.

Basically, this is what I'd like to know. How can I make my Python code give the same results as the MATLAB code?

As a small demonstration,

    k= [0 1 1;1 1 0 ;0 0 1]
    legendre(2,k)

gives:

ans(:,:,1) =

-0.5000    1.0000   -0.5000
0         0         0
3.0000         0    3.0000


ans(:,:,2) =

1.0000    1.0000   -0.5000
     0         0         0
     0         0    3.0000


ans(:,:,3) =

1.0000   -0.5000    1.0000
     0         0         0
     0    3.0000         0

Whereas my Python version of it goes like this: the way I tried it goes like so:

    legendre = np.polynomial.legendre.Legendre([0,1,2])
    legendre(k)

And yields:

   array([[-1.,  3.,  3.],
   [ 3.,  3., -1.],
   [-1., -1.,  3.]])

I see a few things that are a bit weird, but unfortunately I have no clue about how to test for them, because this is the first time I heard of such a thing like Legendre polynomial and neither NumPy's documentation nor Wikipedia are a big help understanding it.


Solution

  • I had the same problem and was successful with building the following:

    from scipy import special
    
    def legendre(n,X) :
    res = []
    for m in range(n+1):
        res.append(special.lpmv(m,n,X))
    return res
    

    For my applications this works very well - maybe some of you can use this too.