2function y = chebEval(x,wts,chebApproxInfo)
3% CHEBEval retruns the approximation of a function at x
4%
5% y = chebApprox(x,ax,h,wts,ninters,nord) approximates a function f
6% (included in the wts argument) using chebyshev polynomial expansion on
7% subintervals of a domain that starts at ax
8%
9% INPUTS:
10% x: value in the domain where f is to be approximated
11% wts: chebyshev weights multiplied by function values in all
12% subintervals, wts(nord,ninters)
13% chebApproxInfo.domain: domain [ax,bx] overwhich wts are computed.
14% chebApproxInfo.ninters: number of subintervals
15% chebApproxInfo.nord: order of polynomial interpolation; number of cheb
16% nodes
17% NOTE: code adjusted from code provided by Leslie Greengard.
19if nargin == 0, test_chebEval; return; end
21domain = chebApproxInfo.domain; ax = domain(1); bx = domain(2);
22ninters = chebApproxInfo.ninters;
23nord = chebApproxInfo.nord;
25Nx = length(x);
26y = zeros(Nx,1);
28h = (bx-ax)/ninters;
30for ix = 1:Nx
31 % get index of left node in current interval
32 iint = min((floor((x(ix)-ax)/h) + 1),ninters);
34 % get interval endpoints [a,b]
35 a = ax + (iint-1)*h; b = ax + iint*h;
37 % transform to u in [-1,1]
38 u = (2*x(ix) - a - b)/(b-a);
40 % Evaluate the cheb polynomial
41 y(ix) = wts(1,iint);
42 for J = 2:nord
43 TJ = cos((J - 1) * acos(u)); % Chebyshev polynomial T_J(X)
44 y(ix) = y(ix) + TJ * wts(J,iint); % Accumulate the value
45 end
46end
47end
49function test_chebEval
50ninters = 12; % number of subintervals
51nord = 4; % number of cheb nodes in each interval
53% define the function that we wish to approximate
54fun = @(x) log(x + 3).*exp(-2*x).*(x.^2).*cos(20*x);
56% define the domain over which f is defined
57ax = -2; bx = -1;
58chebApproxInfo.domain = [ax,bx];
59chebApproxInfo.ninters = ninters;
60chebApproxInfo.nord = nord;
62% table of cheb weights times function values
63wts = mktab_wts(fun, chebApproxInfo);
65Nx = 120;
66x = linspace(ax,bx,Nx)';
67y = chebEval(x,wts,chebApproxInfo);
69plot(x,fun(x),'xb',x,y,'or','LineWidth',2);
70xlabel x; ylabel y; legend('true','approx');
71title(sprintf('Approximation of f(x) = x^2e^{-2x}cos(20x)log(x + 3) via\n order %d Chebyshev polynomials\n on %d subintervals',nord,ninters))
72set(gca,'fontsize',15);
73end