matlab - How to recursively fill an array with functions? -
so i'm trying write function generate hermite polynomials , it's doing super crazy ... why generate different elements h
when start different n
? inputting hpoly(2,1)
gives
h = [ 1, 2*y, 4*y^2 - 2]
while hpoly(3,1)
,
h = [ 1, 2*y, 4*y^2 - 4, 2*y*(4*y^2 - 4) - 8*y]
( (4y^2 - 2) vs (4y^2 - 4) third element here )
also, can't figure out how evaluate expression. tried out = subs(h(np1),y,x)
did nothing.
code:
function out = hpoly(n, x) clc; syms y np1 = n + 1; h = [1, 2*y]; f(np1) function f(np1) if numel(h) < np1 f(np1 - 1) h(np1) = 2*y*h(np1-1) - 2*(n-1)*h(np1-2); end end h y = x; out = h(np1); end
-------------------------- edit ----------------------------
so got around using while
loop instead. wonder why other way didn't work ... (and still can't figure out how evaluate expression other plug in x beginning ... suppose that's not important, still nice know...)
sadly, code isn't fast hermiteh
:( wonder why.
function out = hpoly(n, x) h = [1, 2*x]; np1 = n + 1; while np1 > length(h) h(end+1) = 2*x*h(end) - 2*(length(h)-1)*h(end-1); end out = h(end) end
why code slower? recursion not of matlab's fortes may have improved using recurrence relation. however, hermiteh
written in c , loop won't fast because you're using while
instead of for
, needlessly reallocating memory instead of preallocating it. hermiteh
may use lookup table first coefficients or might benefit vectorization using explicit expression. might rewrite function this:
function h = hpoly(n,x) % n - increasing sequence of integers starting @ 0 % x - point @ evaluate polynomial, numeric or symbolic value mx = max(n); h = cast(zeros(1,mx),class(x)); % use zeros(1,mx,'like',x) in newer versions of matlab h(1) = 1; if mx > 0 h(2) = 2*x; end = 2:length(n)-1 h(i+1) = 2*x*h(i)-2*(i-1)*h(i-1); end
you can call with
syms x; deg = 3; h = hpoly(0:deg,x)
which returns [ 1, 2*x, 4*x^2 - 2, 2*x*(4*x^2 - 2) - 8*x]
(use expand
on output if want). unfortunately, won't faster if x
symbolic.
if you're interested in numeric results of the polynomial evaluated @ particular values, it's best avoid symbolic math altogether. function above valued double precision x
3 4 orders of magnitude faster symbolic x
. example:
x = pi; deg = 3; h = hpoly(0:deg,x)
yields
h = 1.0e+02 * 0.010000000000000 0.062831853071796 0.374784176043574 2.103511015993210
note:
the hermiteh
function r2015a+, assuming still have access symbolic math toolbox , matlab version
r2012b+, can try calling mupad's orthpoly::hermite
. hermiteh
used function under hood. see here details on how call mupad functions matlab. function bit simpler in returns single term. using for
loop:
syms x; deg = 2; h = sym(zeros(1,deg+1)); = 1:deg+1 h(i) = feval(symengine,'orthpoly::hermite',i-1,x); end
alternatively, can use map
vectorize above:
deg = 2; h = feval(symengine,'map',0:deg,'n->orthpoly::hermite(n,x)');
both return [ 1, 2*x, 4*x^2 - 2]
.
Comments
Post a Comment