function approx = taylor_approx(a,b,srate,degree,func) %% Construct taylor approximation %% example: approx=taylor_approx(-6,6,100,5,'exp'); %% constructs a Taylor approximation of degree 4 of exp(x) with 100 samples per unit %% time on the interval [-6,6] syms x; % symbolic variable if strcmp(func,'sin'), f=sin(x); elseif strcmp(func,'cos'), f=cos(x); elseif strcmp(func,'exp'), f=exp(x); elseif strcmp(func,'log'), f=log(1+x); else disp('WARNING: function must be one of sin, cos, log, or exp'); end approx=diff(f); coeffs=fliplr(sym2poly(taylor(f,degree))); t=a:1/srate:b-1/srate; y=zeros(size(t)); for i=0:degree-2 y=y+coeffs(i+1)*t.^i; end approx=y; plot(t,approx); hold on if strcmp(func,'sin'), plot(t,sin(t),'r'); elseif strcmp(func,'cos'), plot(t,cos(t),'r'); elseif strcmp(func,'exp'), plot(t,exp(t),'r'); elseif strcmp(func,'log'), plot(t,log(1+t),'r'); else disp('WARNING: function must be one of sin, cos, log, or exp'); end title('Original f (red) and approximation'); %for i=1:degree