In: Advanced Math
Develop a well-structured MATLAB function to compute the Maclaurin series expansion
for the cosine function and name the function cosMac. The function should have the following features:
Iterate until the relative error (variable name “relErr” ) falls below a stopping criterion OR exceeds a maximum number of iterations (variable name“maxIter”) for a given value of x.
Include a default value of relErr = 1e-6 if the user does not enter the value (use nargin function).
Include a default value for maxIter = 100 if the user does not enter the value (use nargin function).
Return the estimate of cos(x), the approximate relative error, the number of iterations, and the true relative error (that you can calculate based on the built- in cosine function).
%Matlab code for Maclaurin series
clear all
close all
%example of cosMac function
x=pi;
[val,tr_er,rel_err,iter]=cosMac(x);
fprintf('For x=%f, cos(x)=%f with relative error=%e and
iteration=%d\n',x,val,rel_err,iter)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%function for Maclaurin series for cos(x)
function [val,tr_er,rel_err,iter]=cosMac(x,maxIter,relErr)
if nargin < 3
relErr = 10^-6;
end
if nargin < 2
maxIter = 100;
end
err=1;k=1;vv(1)=1; val=1;
while err>=relErr
k=k+1;
if mod(k,2)==1
vv(k)=((x^(2*(k-1)))/(factorial(2*(k-1))));
else
vv(k)=-((x^(2*(k-1)))/(factorial(2*(k-1))));
end
val=val+vv(k);
err=abs(abs(vv(k-1))-abs(vv(k)));
if k>=maxIter
break
end
end
tr_er=(cos(x)-val);
rel_err=err;
iter=k;
end
%%%%%%%%%%%%%%%%%%%%% End of Code %%%%%%%%%%%%%%%%%%