Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 996
userE Avatar asked Sep 11 '26 13:09

userE


2 Answers

I just ran into this problem as well. Used this question as a starting point and came up with the following. Please note: I'm using the MATLAB function like so:

legendre(10,linspace(-1,1,10))

And I needed to generate the equivalent in Python. Here's the code:

import numpy as np
from scipy import special as sp

def legendre(N,X) :
    matrixReturn = np.zeros((N+1,X.shape[0]))
    for i in enumerate(X) :
        currValues = sp.lpmn(N,N,i[1])
        matrixReturn[:,i[0]] = np.array([j[N] for j in currValues[0]])
    return matrixReturn

I'm very new to Python, so I'm sure the above could be improved.

like image 92
J Pierret Avatar answered Sep 14 '26 01:09

J Pierret


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.

like image 32
maxm59 Avatar answered Sep 14 '26 01:09

maxm59