Question
Matlab
A Taylor series expansion is When f(x) is expanded at a local point x0=0, it is also called the Maclaurin series expansion. Write a MATLAB program to calculate cos(x) based on the Maclaurin series expansion when f(x) = cos(x). You MATLAB code submission to T-square should contain two files: cos_maclauriu.m This file is a general function so that, for example, a functional call of cos_maclaurin(pi/4, 6) should return the value of cos(pi/4) from the expansion m with a polynomial degree or order of 6. draw_cos_maclaurin.m This file is a script that draw four subplots, one is cos(x) by calling cos() directly in Matlab and the other three are approximated curves by calling the above function cos_maclaurin(), with which the degree or order of the polynomial is 6, 8, 10 respectively. The range of x in the four subplots should be [0, 4pi]. Compare the results between cos() and cos_maclaurin().
Explanation / Answer
#cos_maclaurin.m
function val = cos_maclaurin(x,deg)
val = 0;
sign =1;
i =0;
while i<=deg
val = val + (sign*( (x^i)/factorial(i)));
i=i+2;
sign = sign*-1;
end
end
#draw_cos_maclaurin.m
x= linspace(0,4*pi);
y1 = cos(x);
y2 = arrayfun(@cos_maclaurin, x, linspace(6,6));
y3 = arrayfun(@cos_maclaurin, x, linspace(8,8));
y4 = arrayfun(@cos_maclaurin, x, linspace(10,10));
subplot(2,2,1);
plot(x,y1);
title('Subplot 1: cos(x)');
subplot(2,2,2);
plot(x,y2);
title('Subplot 2: cos maclaurin(x,6)');
subplot(2,2,3)
plot(x,y3);
title('Subplot 3: cos maclaurin(x,8)');
subplot(2,2,4)
plot(x,y4);
title('Subplot 4: cos maclaurin(x,10)');