In: Advanced Math
Given x = [0, 0.05, 0.1, 0.15, 0.20, ... , 0.95, 1] and f(x) = [1, 1.0053, 1.0212, 1.0475, 1.0841, 1.1308, 1.1873, 1.2532, 1.3282, 1.4117, 1.5033, 1.6023, 1.7083, 1.8205, 1.9382, 2.0607, 2.1873, 2.3172, 2.4495, 2.5835, 2.7183], write a Matlab script that computes the 1st and 2nd derivatives of O(h^2).
MATLAB Code:
close all
clear
clc
% O(h^2) first derivative:
% f'(x) = (f(x + h) - f(x - h)) / (2h)
%
% O(h^2) second derivative:
% f''(x) = (f(x + h) - 2*f(x) + f(x - h)) / (h^2)
% Given x and f(x)
x = 0:0.05:1;
f = [1, 1.0053, 1.0212, 1.0475, 1.0841, 1.1308, 1.1873, 1.2532,
1.3282, 1.4117, 1.5033, 1.6023, 1.7083, 1.8205, 1.9382, 2.0607,
2.1873, 2.3172, 2.4495, 2.5835, 2.7183];
h = 0.05; % Step in x
f_ = (f(3:end) - f(1:end-2)) / (2*h); % f'(x)
f__ = (f(3:end) - 2*f(2:end-1) + f(1:end-2)) / (h^2); % f''(x)
% Dumping the results in a table
fprintf('x\t\t\tf''(x)\t\tf''''(x)\n')
for i = 2:length(x)-1
fprintf('%.2f\t\t%.4f\t\t%.4f\n', x(i), f_(i-1), f__(i-1))
end
Output: