MATLAB: Writing the Sum when Plotting Taylor Series

plotseriessumtaylor

We want to plot f(x) and Taylor polynomials P0(x), P1(x),P2(x), P3(x) of f(x)=cot(x) ; about base point x=a=5*pi/8. step size is 0.01
The problem is we can't make our Taylor Series sum( T1) work. It gives this error:
Error using diff
Difference order N must be a positive integer scalar.
Error in matlab_hw1_q3 (line 11)
T1=sum( (diff(f(a),n(1,i))) ./ factorial(n(1,i)) .* ((x-a).^n(1,i)) , n(1,i))
Our code:
clc
clear all
close all
f=@(x) cot(x)
x= pi/8:0.01:7*pi/8 ;
a=5*pi/8 ;
n=[0 1 2 3]
for i=1:1:4
T1=sum( (diff(f(a),n(1,i))) ./ factorial(n(1,i)) .* ((x-a).^n(1,i)) , n(1,i))
end

Best Answer

There are two functions named diff that are quite different in what they do.
When you apply diff() to a symbolic function or symbolic expression, then diff() does calculus differentiation.
When you apply diff() to a numeric variable then the operation calculates successive differences, such as diff([3 7 -2]) would give [7-3, -2-7] = [4, -9]. In its simplest form, diff(v) where v is a vector, is equivalent to v(2:end)-v(1:end-1) . When diff() is applied to a numeric scalar, then because there are not at least two values to subtract, the result is empty.
When used with a second parameter, the parameter must be positive integer, and numeric diff() repeats the basic diff() operation that many times -- so diff([3 7 -2],2) would be diff(diff([3 7 -2])) which would be diff([4,-9]) which would be -13.
Now, you define the function handle f=@(x) cot(x) and you assign a=5*pi/8 so a is a numeric scalar. f(a) is going to calculate cot(5*pi/8) which is about -0.41 . Then you try diff(-0.41, n(1,1)) which is diff(-0.41, 0) which is an error because the order number is not a positive integer. If you had happened to start with n(1,1) being 1, then you would have had diff(-0.41, 1) which would have returned empty because there were not at least two numeric values to subtract.
If you are trying to take the 0'th derivative of cot(x), then the 1'st derivative, then 2'nd derivative, then you should not be working with function handles applied to numeric values: you should be working with symbolic expressions. Like
syms X
f = cot(X);
diff(f, X, n(1,i))
Once you have that abstract derivative in terms of the variable X, then you need to evaluate it at a :
subs( diff(f, X, n(1,i)), X, a )