Using the Pochhammer Symbol in Matlab

旧时模样 提交于 2019-12-22 11:06:31

问题


I've tried to use a script that evaluates the Pochhammer symbol (rising factorial) in Matlab, but it fails to evaluate pochhammer(x,n) whenever x is a negative number even though the expression is valid when x is negative (Wolfram Alpha and Mathematica give answers for Pochhammer(-3,2)).

Can anyone help me get pochhammer working in Matlab for negative arguments?


回答1:


I assume that you're referring to this Pochhammer function. Note that pochhammer (not capitalized) is part of MuPAD, which is a separate environment available with Matlab's Symbolic Math Toolbox. You can access MuPAD by typing mupad in the Matlab command window.

If, however, like a normal Matlab user, you wish to use the pochhammer function from Matlab itself and program with it, you cannot run it from the regular command window or Editor in the normal fashion, as you discovered. Instead, you must use

evalin(symengine,'pochhammer(-3,2)')

or the more flexible

feval(symengine,'pochhammer',-3,2)

See more here. These both return symbolic numbers as results and only work for scalar inputs. If you require double-precision output and have vector inputs (only works for the the second one, n) use

mfun('pochhammer',-3,-3:3)

This is equivalent to using MuPAD's map function, so you could also write:

feval(symengine,'map',sym(-3:3),'n->pochhammer(-3,n)')


However, if you're not working with symbolic math at all, there may be no reason to use this function instead of a fully double-precision solution. The Pochhammer symbol is defined simply as the ratio of two gamma functions and can be implemented efficiently as (x and n must be the same dimensions or scalar – additionally, neither x nor x-n can be an integer less than or equal to zero, where the gamma function is singular):

poch = @(x,n)gamma(x+n)./gamma(x);

If n and x are integers you should use round to ensure that the output is exactly integer. The only pitfall is that for sufficiently large values of x and/or n this naïve implementation will overflow to Inf (or NaN). In these cases you'll need to do something else such as use the symbolic version (which may or may not return Inf when cast back to double). For integer values of n (and scalar n>=0), something like the following can be used

poch = @(x,n)prod(bsxfun(@plus,x(:),0:n-1),2);

Note that even for integers this can be up 20 times slower than the gamma version.




回答2:


The numerical command pochhammer for Matlab (not MuPAD) was introduced in matlab version R2014b.



来源:https://stackoverflow.com/questions/18135186/using-the-pochhammer-symbol-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!