%This code computes up to a third order
%taylor approximation of the function x^2
clear all
xbar=0; %point of approximation
h=-1:.001:1; %grid of values for h
%vectorize for every h below
tic %start the timer
fxtrue=[(xbar+h).^2]'; %true function
fxn1=[xbar^2+2*xbar.*h]'; %first-order approximation
fxn2=[xbar^2+2*xbar.*h+(2.*(h.^2))./2]'; %second-order approximation
fxn3=[xbar^2+2*xbar.*h+(2.*(h.^2))/2+0]'; %third-order approximation

tvec=toc %stop the timer for the for loop

tic %start the timer
for i=1:length(h)
    fxtrue(i,1)=(xbar+h(i))^2; %true function
    fxn1(i,1)=xbar^2+2*xbar*h(i); %first-order approximation
    fxn2(i,1)=xbar^2+2*xbar*h(i)+(2*(h(i)^2))/2; %second-order approximation
    fxn3(i,1)=xbar^2+2*xbar*h(i)+(2*(h(i)^2))/2+0; %third-order approximation
end
tloop=toc %stop the timer for the for loop
%plotting the true function and approximate functions below
plot(h,fxtrue,h,fxn1,h,fxn2,h,fxn3,'linewidth',2)
legend('x^2','f(0+h) n=1','f(0+h) n=2','f(0+h) n=3')
title('Taylor Approximation of x^2 About x=0')
xlabel('h')
ylabel('f(0+h)')
