MATLAB: How do i graph a certain amount of elements in a taylor series.

homeworktaylor

Here is my question: For all of these on the same figure , plot:
• The Taylor Series expansion using the first 2 terms as a DASHED red line.
• The Taylor Series expansion using the first 4 terms as a DOTTED cyan line.
• The Taylor Series expansion using the first 6 terms as a DASHED blue line.
How do i do this?
This graph has the following limits:
xlim([-4*pi,4*pi])
ylim([-2,2])

Best Answer

As this is homework you may have to write your own taylor series expansion code but:
%from https://www.mathworks.com/help/symbolic/sym.taylor.html
%TS
syms x %use x as your independent variable
f = sin(x); %define f(x)
%use built in taylor function,define independent variable, define n order expansion
T2 = taylor(f, x, 'Order', 2);
T4 = taylor(f, x, 'Order', 4);
T6 = taylor(f, x, 'Order', 6);
%plotting
figure(1);
hold on;grid on;
%labeling the bottom
xticks([-4*pi,-3*pi,-2*pi,-pi,0,pi,2*pi,3*pi,4*pi])
xticklabels({'-4\pi','-3\pi','-2\pi','-\pi','0','\pi','2\pi','3\pi','4\pi'})
%setting limits
xlim([-4*pi,4*pi]);
ylim([-2,2]);
%assing plots to variable names for easy legend creation
%use fplot so we dont need an xaxis variable
p1 = fplot(T2,"r--");l1 = "two terms"; %red dashed
p2 = fplot(T4,"c:");l2 = "four terms"; %cyan dotted
p3 = fplot(T6,"b--");l3 = "six terms"; %blue dashed
legend([p1,p2,p3],[l1,l2,l3],'location','northwest');
hold off
[T2,T4,T6] being your taylor series representations.
"help plot" in the command window will give you more information on plotting styles.
hope this helped.