I am using a generating function of Legendre polynomials (no matter what math entity it is) and for that I need to use "syms" type and then take the derivative by "diff" function.
function p=Plm(l,m)
syms x
p = diff((x^2-1)^l,m);
end
Then the output of this function, "p", should be used to take a definite integral as
fun = @(x) Plm(l,m).*cos(x).^2
integral(fun,-1,1)
where "l" and "m" could be replaced by any positive integer. Matlab gives the error that it cannot integrate over symbolic x that comes from "p". What is the way to get around this?
The problem is your definition of fun
, as it doesn't return a numerical output. then you have a symbolic variable x
and a numeric substitution of x
(not the same) in the anonymous function. This makes things complicated, as the symbolic output of Plm
returns a function that depends on a symbol that is not defined anymore, as it was created in the function workspace. This is a very bad programming practice, as in general, you wont be able to mix it with more symbolic x
outside the function declaration
My suggestions would be either
cos
inside Plm
Plm
to accept a symbol defined outside the function scope, function p=Plm(l,m,x)
being x
the said symbol.Else the following will work. The anonymous function must return a numerical value, so you should add the function subs
and double
to it as:
fun = @(xin)double(subs(Plm(l,m).*cos(x).^2,'x',xin))
The problem here is that the x
in cos(x)
is not a symbol, and if you substitute it by xin
it will behave weirdly due to the behaviour of subs
. However, we could hack the thing a bit, making a symbolic cos()
using the variable that Plm
depends on, by using symbar
. This will force the anonymous function to evaluate Plm
twice (which is not good).
In short, this works :
fun = @(xin)double(subs(Plm(l,m).*cos(symvar(Plm(l,m))).^2,xin));
integral(fun,-1,1);