WHY DOES the 2nd Approx does not show
6 views (last 30 days)
Show older comments
%DEFINING FUNCTION x(e^x)
x = 1.8:0.1:2.2;
y = x.*(exp(x));
%EXACT DIFFERENTIATION of f(x)
exact_dy = x.*exp(x) + exp(x);
exact_ddy = x.*exp(x) + 2.*exp(x);
%SOLVING NUMERICALLY
%FIRST DERIVATIVE
dx = diff(x);
dy = diff(y);
num_dy = dy./dx;
%SECOND DERIVATIVE
num_ddy = diff(num_dy)./diff(x(1:end-1));
%TRUNCATION ERROR
ERROR1 = exact_dy(1:end-1) - num_dy;
ERROR2 = exact_ddy(1:end-2) - num_ddy;
%FOR PLOTTING
figure;
subplot(1,2,1);
plot(x,y);
hold on;
plot(x(1:end-1), num_dy,'--d');
plot(x(1:end-2),num_ddy,'-.');
plot(x, exact_dy, '--mo');
plot(x, exact_ddy, '--s');
xlabel('x');
ylabel('y');
legend('Function x(e^x)','First numerical differentiation', 'Second numerical differentiation', 'First exact differentiation','Second exact differential');
grid on;
subplot(1, 2, 2);
plot(x(1:end-1), ERROR1, 'g');
plot(x(1:end-2), ERROR2, 'r');
grid on;
xlabel('x');
ylabel('ERROR');
legend('first approx.', '2nd approx.')

0 Comments
Answers (1)
KSSV
on 2 Jun 2021
You forgot to use hold on.
plot(x(1:end-1), ERROR1, 'g');
hold on
plot(x(1:end-2), ERROR2, 'r');
2 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!