How to define a symbolic function that is only evaluated for numeric inputs?
1 次查看(过去 30 天)
显示 更早的评论
If I define a symbolic function that calls the legendreP function (or others like dirac) with symbolic inputs:
Z(n,x)=n+x+legendreP(n,x)
Matlab doesn't try to expand the legendreP function, and outputs:
Z(n, x) = n+x+legendreP(n, x)
And I can then use Z with numeric or symbolic outputs, and it expands as you'd expect. E.g. Z(3,x) gives ans=(5*x^3)/2 - x/2 + 3
How can I write a function that works like legendreP?
If I write a function:
function result = func(n,x)
if (n > 1)
result = x * func(n-1,x);
else
result = x;
end
end
Then define a symbolic function to use it:
Y(n,x)=n+x+func(n,x)
I get an error: Conversion to logical from sym is not possible. Due to the if statement.
I tried then checking the argument class:
function result = func(n,x)
if (isa(n,'double'))
if (n > 1)
result = x * func(n-1,x);
else
result = x;
end
else
result = what goes here?
end
end
But what should be returned when n is a 'sym'? If I return the function itself, (E.g. result=func(n,x)), then it appears to go in to a recurisive loop, trying to evaulate it. If I return an undefined symbolic function, then Matlab will just output that name, but then Y(n,x) can't be evaluated, because it uses the name of the undefined function.
Thanks.
0 个评论
回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Assumptions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!