Skip to content

Instantly share code, notes, and snippets.

@siedentop
Created November 26, 2010 09:49
Show Gist options
  • Save siedentop/716477 to your computer and use it in GitHub Desktop.
Save siedentop/716477 to your computer and use it in GitHub Desktop.
hermite.m % Using a better approach to recursion
classdef hermite
% Hermite class for hermite functions
properties
x
polynomes
hermites
end
methods
function self = hermite(x, n)
self.x = x;
self.polynomes = {};
self.hermites = {};
for i = 0:n
self.calc_polynomes(i);
end
end
function calc_polynomes(self, n) %, (SetAccess = private)
% calculates the Hermite polynomial, as given by the notes on page 24.
% Relies on n-1 already having been calculated!
if n == 0
h_poly = [1];
elseif n == 1
h_poly = [2 0];
else
% Split in two, so that h(n-2) can be evaluated first!
part2 = -2 * (n-1) * self.h(n-2);
part1 = 2 .* [self.h(n-1) 0]; % 2 * H_n-1 * x
h_poly = polyadd(part1, part2); % Recursive definition
end
self.set(polynomes{n+1}, h_poly);
end
function h_poly = h(self, n)
% Returns the n-th hermite polynomial
h_poly = self.polynomes{n+1};
end
function h = get(self, n)
% Returns the nth Hermite function
try self.hermites(n+1)
catch
% Use given formula for hermite function. Notes p. 24.
val = 1/sqrt(factorial(n)*2^n*sqrt(pi)) * exp(-self.x.^2/2) .* polyval(self.h(n), self.x);
self.hermites{n+1} = val;
end
h = self.hermites{n+1};
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment