% =======================================================================================
% =====   Discritized Approximation of Differentiated Hyperbolic Secant Function    =====
% ===== u=sech(x), The Exact Solution of The Derivative is: du/dx = -sech(x)tanh(x) =====
% =======================================================================================

clc
clear

SamplingRate=10;
dx=1/10;
X=-10:dx:10;

% ===== The Exact Solution =====
u=sech(X);
ExactSolutionSech=-sech(X).*tanh(X);

figure(1);
plot(X,u,X,ExactSolutionSech), axis([-10 10 -0.6 1.1]);
title('(Blue) The Sech(X) Function, (Green) Exact Solution of The First Derivative of The Sech(X)');
xlabel('X');
ylabel('Y');
grid on

% =======================================================================
% ===== Second-order Accurate Approximation of The First Derivative =====
% =======================================================================

% ===== The Forward-difference Method For Calculating The First Point =====
SecondOrderAccurate(1)=(-3*u(1)+4*u(2)-u(3))/(2*dx);

% ===== The Centre-difference Method For Calculating The Middle Points =====
for i=2:length(X)-1
   
   SecondOrderAccurate(i)=(u(i+1)-u(i-1))/(2*dx);
   
end

% ===== The Backward-difference Method For Calculating The Last Point =====
SecondOrderAccurate(length(X))=(3*u(length(X))-4*u(length(X)-1)+u(length(X)-2))/(2*dx);

figure(2);
plot(X,u,X,SecondOrderAccurate,'r'), axis([-10 10 -0.6 1.1]);
title('(Blue) The Sech(X) Function, (Red) Second-order Accurate Solution of The First Derivative of The Sech(X)');
xlabel('X');
ylabel('Y');
grid on

% =======================================================================
% ===== Fourth-order Accurate Approximation of The First Derivative =====
% =======================================================================

% ===== The Second-order Accurate Method For Calculating The First and Second Points=====
FourthOrderAccurate(1)=(-3*u(1)+4*u(2)-u(3))/(2*dx);
FourthOrderAccurate(2)=(-3*u(2)+4*u(3)-u(4))/(2*dx);

% ===== The Fourth-order Accurate Method For Calculating The Middle Points =====
for i=3:length(X)-2
   
   FourthOrderAccurate(i)=(-u(i+2)+8*u(i+1)-8*u(i-1)+u(i-2))/(12*dx);
   
end

% ===== The Second-order Accurate Method For Calculating The before The Last and The Last Points =====
FourthOrderAccurate(length(X)-1)=(3*u(length(X)-1)-4*u(length(X)-2)+u(length(X)-3))/(2*dx);
FourthOrderAccurate(length(X))=(3*u(length(X))-4*u(length(X)-1)+u(length(X)-2))/(2*dx);

figure(3);
plot(X,u,X,SecondOrderAccurate,'m'), axis([-10 10 -0.6 1.1]);
title('(Blue) The Sech(X) Function, (Mangenta) Fourth-order Accurate Solution of The First Derivative of The Sech(X)');
xlabel('X');
ylabel('Y');
grid on