How can I solve this problem?

The following function is given f(x) = 2^x , Plot the function f(x) and its 3rd order Taylor series expansion at x0 = 1 in Matlab. Pay attention to the style (line thickness, symbols for data points) and format (legends, labeling) of the plot.
----------------------------------
%% f(x) and its derivatives are declared as anonymous functions
f = @(x) 2^x;
f_prime1 = @(x) 2.^x;
f_prime2 = @(x) 2.^x;
f_prime3 = @(x) 2.^x;
% Taylor series (polynomials) are declared as anonymous functions
% x0 : expansion point
% x : the point at which I would like to evaluate the Taylor series
%% 0th order Taylor series
T0 = @(x0,x) f(x0);
% 1st order Taylor series
T1 = @(x0,x) f(x0) + f_prime1(x0)*(x-x0);
% 2nd order Taylor series
T2 = @(x0,x) f(x0) + f_prime1(x0)*(x-x0) + f_prime2(x0)*(x-x0).^2/2;
% 3rd order Taylor series
T3 = @(x0,x) f(x0) + f_prime1(x0)*(x-x0) + f_prime2(x0)*(x-x0).^2/2 + f_prime3(x0)*(x-x0).^3/6;
%%
x0 = 1;
% Plot the Taylor series T0, T1, T2, T3 between -10 <= x <= +10 using expansion point x0 = 1;
x = linspace(-10,10,21);
y0 = T0(x0,x);
y1 = T1(x0,x);
y2 = T2(x0,x);
y3 = T3(x0,x);
yTrue = f(x);
%%
figure
plot(x,y0,'-ob','LineWidth',2)
hold on
plot(x,y1,'-ok','LineWidth',2)
hold on
plot(x,y2,'-or','LineWidth',2)
hold on
plot(x,y3,'-og','LineWidth',2)
hold on
plot(x,yTrue,'-oc','LineWidth',2)
xlabel('x')
ylabel('y')
legend('T0','T1','T2','T3','f(x) = 2^x')
set(gca, 'FontSize',18)
grid on
------------------------------------
Error using ^ (line 51)
Incorrect dimensions for raising a matrix to a power. Check that the matrix is square and the power
is a scalar. To perform elementwise matrix powers, use '.^'.
Error in hw>@(x)2^x (line 2)
f = @(x) 2^x;
Error in hw (line 28)
yTrue = f(x);

 Accepted Answer

f = @(x) 2.^x;
Note:
f_prime1 = @(x) 2.^x;
That is not the derivative of 2^x
syms x
diff(2^x, x)
ans = 
diff(ans, x)
ans = 

3 Comments

thank you for your answer but ı do not understand which part to fix. This is my first time using matlab and the first time I was able to type this much.
f = @(x) 2.^x .* log(2).^0;
f_prime1 = @(x) 2.^x .* log(2).^1;
f_prime2 = @(x) 2.^x .* log(2).^2;
f_prime3 = @(x) 2.^x .* log(2).^3;
Thank you very much

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!