% Used to produce the plots for the function approximation example % Example 4.5 function [] = optfcnap() p = 20; % number of basis functions % Define the basis functions for plotting purposes x = 0:0.01:2*pi; x=x(:); n = length(x); zeta = zeros(n, p); for i=1:n zeta(i,:) = makezeta(x(i), p)'; end %% plot the basis functions figure(1) plot(x, zeta); hold on; % define random sample points rand('seed', 100); % make sure we can repeat the results samp = rand(50,1)*2*pi; plot(samp, 0.6*ones(length(samp), 1), 'o'); xlabel('x'); axis([0 2*pi, 0 0.8]); hold off %%%% for the sin fcn yi = sin(samp); % define the function outputs at the sample points ysin = sin(x); % Initialize the estimate A0 = zeros(p, 1); % Solve the ODE for the estimates [t, A] = ode45('optAderiv', [0 1], A0, [], yi, samp, p); nt = length(t); Afin = A(nt,:); zsin = Afin*zeta'; figure(2); plot(x,ysin); hold on plot(x,zsin, '--'); hold off xlabel('x'); axis([0 2*pi, -1.1 1.1]); %%%% for the cos^2 fcn yi = cos(samp).^2; % define the function outputs at the sample points ycos = cos(x).^2; % Re-initialize the estimate A0 = zeros(p, 1); % Solve the ODE for the estimates [t, A] = ode45('optAderiv', [0 1], A0, [], yi, samp, p); nt = length(t); Afin = A(nt,:); zcos = Afin*zeta'; figure(3); plot(x,ycos); hold on plot(x,zcos, '--'); hold off xlabel('x'); axis([0 2*pi, 0 1.2]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Define the basis functions function [zeta] = makezeta(x, p) sigma = 2; cmax = 2*pi; c = 1:p; c = (c(:) - 1)*cmax/(p-1); % Gaussian centers zeta = zeros(p,1); for i=1:p zeta(i) = exp(-sigma^2*(x-c(i))^2); end sz = sum(zeta); zeta = zeta / sz;