1

I am working with an equation from a book and it works when I used Mathematica to solve it. It essentially contains the integral of certain orders of Legendre polynomials. E.g. P_1(x), P_2(x), P_3(x).

When I use Mathematica for a particular case e.g.

LegendreP[3, 0.5]

I get

-0.4375

which allows me to continue with my evaluation. But in MATLAB I get:

>> legendre(3,0.5)
ans =
-0.4375
-0.3248
5.6250
-9.7428

The first returned value is always correct but then it spits out... I think the other coefficients? So what I would like to do is tell MATLAB just to return the first value. Is there a way to do this without assigning it to its own variable afterwards? Eg. something like

legendre(3,0.5)(1)   

Obviously wont work because it doesn't exist in memory yet. Am I even going about this the right way?

Thanks

Steve Hatcher
  • 715
  • 11
  • 27
  • 1
    Similar question [here](http://stackoverflow.com/questions/3627107/how-can-i-index-a-matlab-array-returned-by-a-function-without-first-assigning-it) – Ray Dec 12 '13 at 08:55
  • Very nice, Thanks. well that answers that bit. Now I wonder if its okay to use that in big loops or should I write my own legendre function to just return the first order...? – Steve Hatcher Dec 12 '13 at 08:59
  • It is always better to stick to the library because the official function is optimized. Since in this case it is not that bothering to call the libarary, I would suggest using it directly. – Ray Dec 12 '13 at 09:02

1 Answers1

3

If it bothers you, just put legendre into a new function legendre1, so you're using the library function, but with your desired functionality.

function [ P ] = legendre1( n,X )
P = legendre(n,X);
P = P(1);
end

or implement a custom range:

function [ P ] = legendre1( n,X,range )
P = legendre(n,X);
P = P(range);
end

so legendre1( 3,0.5,1 ) will return:

P =

   -0.4375

and legendre1( 3,0.5,1:2 )

P =

   -0.4375
   -0.3248
Robert Seifert
  • 25,078
  • 11
  • 68
  • 113
  • Dude, great idea! I will use that. Thanks both of you guys! – Steve Hatcher Dec 12 '13 at 09:38
  • Just a minor improvement. Replace `P(1)` by `P(1,:)` since `X` can also be a vector, which would mean, that `legendre(N,X)` would return a matrix. The same for `P(range)`. – Thomas Mar 11 '16 at 13:33