42 views (last 30 days)

Show older comments

I have been trying to plot a graph with the above description. However i am only able to plot the 0'th order taylor series. When trying to plot a 1st-5th order i am prompted with these comments

''>> taylor

Error using diff

Difference order N must be a positive integer scalar.

Error in taylor (line 17)

yest = yest+((diff(y,x).*((x-a).^n))/factorial(n));

''

My code is as follow:

x=0:2000;

y=nthroot(x,3);

a=1728;

fig=figure();

set(fig,'color','white')

plot(x,y,'LineWidth',2);

grid on

xlabel('x')

ylabel('y')

N=1;

yest=y;

for n=1:N

yest = yest+((diff(y,x).*((x-a).^n))/factorial(n));

end

hold on

plot(x,yest,'r-','LineWidth',2)

legend('Actual Function','Taylor Series Expansion')

Fabio Freschi
on 11 Jun 2020

Edited: Fabio Freschi
on 11 Jun 2020

One option is to use the built-in taylor function in symbolic math toolbox.

If you want to use your strategy, there are some issues that need to be accounted for

- when you use diff for the evaluation of the derivative, the output vector is one element shorter than the input. For this reason, every time you evaluate the nth order derivative, you must rebuild the x vector. I update the vector xd in the loop, having as coordinates the midpoints of the vector at the precedent iteration.
- the evaluation of the derivative at the point a is not "exact" if you dont use analytical functions but only numerical vectors. So I used an approximate evaluation looking for the first xd coordinate larger than or equal to a

clear all, close all

x = 0:2000;

y = nthroot(x,3);

a = 1728;

N = 5;

fig=figure();

set(fig,'color','white')

plot(x,y,'LineWidth',2);

grid on

xlabel('x')

ylabel('y')

% derivate function

dy = y;

% x vector

xd = x;

% preallocation

yEst = zeros(size(x));

for n = 0:N

% find the first element in xd such that xd >= a

idx = find(xd >= a,1,'first');

yEst = yEst+dy(idx)*(x-a).^n/factorial(n);

% update the array with numeric derivative

dy = diff(dy)./diff(xd);

% update the xd vector using midpoints (each derivative it has one

% point less than the original vector)

xd = (xd(2:end)+xd(1:end-1))/2;

end

figure(fig), hold on

plot(x,yEst,'r-','LineWidth',2)

legend('Actual Function','Taylor Series Expansion')

set(gca,'yLim',[min(y) max(y)]);

Fabio Freschi
on 11 Jun 2020

Two reasons (I also updated the explanation of the code):

- I prefer to calculate a numerical derivative by setting explicitly the x increment that in the genearl case may not be equal to 1
- I need to evaluate the the function at x = a, but this value may not be available in the vector x, so I use the approximate evaluation finding the first value larger than or equal to a

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!