% MEC E 390 Chapter 2
% Example 2.3
% Approximate the function cos(x) with a specified number of terms.
% This script calls the funciton approxcos.m and outputs the approximate
% relative error for values of i between 2 and 20 for x = 1.5 and x = 10.


clc  % clear the command window
close all % close all figures

min = 2;
max = 20;
n = max - min + 1;

a1 = 1.5;
a2 = 10;

output1 = zeros(n,3); % initialize output matrices
output1(:,1) = min:max;

output2 = zeros(n,3);
output2(:,1) = min:max;

for j = 1:n,
    output1(j,2) = (approxcos(a1,min+j-1) - approxcos(a1,min+j-2))/approxcos(a1,min+j-1);  % approx. relative error
    output2(j,2) = (approxcos(a2,min+j-1) - approxcos(a2,min+j-2))/approxcos(a2,min+j-1);  % approx. relative error
    
    output1(j,3) = approxcos(a1,min+j-1);
    output2(j,3) = approxcos(a2,min+j-1);
end

figure
hold on
p1=plot(0:max,zeros(max+1,1),'-k'); %Plots a line for the zero axis
p2=plot(output1(:,1),output1(:,2));
p3=plot(output2(:,1),output2(:,2));
xlim([0,20])
ylim([-10,10])
xlabel('Number of Terms (i)')
ylabel('Approximate Relative Error (er)')
legend([p2,p3],['Relative Error in Cos(',num2str(a1),')'],['Relative Error in Cos(',num2str(a2),')'])
hold off

figure
hold on
plot(output1(:,1),output1(:,3))
plot(output2(:,1),output2(:,3))
xlim([0,20])
ylim([-10,10])
xlabel('Number of Terms (i)')
ylabel('Cos(x) Approximation')
legend(['Cos(',num2str(a1),') Approximation'],['Cos(',num2str(a2),') Approximation'])
hold off
