Develop a Matlab code to calculate the numerical differentia
Solution
Numbering equations according to order they are defined in.
Following is the required matlab code :
x = [0,1,2,3,4,5,6,7,8];
fx =[0.5, 4, 5.1, 9.8, 10.3, 9.4, 8.7, 6.6, 5.4 ];
%Equation numbered according to the given order in question
%Equation 1
dfx = zeros(8,1);
for i=1:8
dfx(i,1) = fx(i+1) - fx(i);
end
figure;
plot( [0,1,2,3,4,5,6,7,8 ], fx, \'r\', [0,1,2,3,4,5,6,7 ], dfx , \'black\' );
ylabel( \'Amplitude\' );
xlabel( \'x\' );
legend(\'f(x)\',\'df(x)\');
title(\'Equation 1\');
%Equation 2
dfx = zeros(7,1);
for i=1:7
dfx(i,1) = (-fx(i+2) + 4*fx(i+1) - 3*fx(i) )/2.0;
end
figure;
plot( [0,1,2,3,4,5,6,7,8 ], fx, \'r\', [0,1,2,3,4,5,6 ], dfx , \'black\' );
ylabel( \'Amplitude\' );
xlabel( \'x\' );
legend(\'f(x)\',\'df(x)\');
title(\'Equation 2\');
%Backward Difference
%Equation 3
dfx = zeros(8,1);
for i=2:9
dfx(i-1,1) = fx(i) - fx(i-1);
end
figure;
plot( [0,1,2,3,4,5,6,7,8 ], fx, \'r\', [ 1,2,3,4,5,6,7,8 ], dfx , \'black\' );
ylabel( \'Amplitude\' );
xlabel( \'x\' );
legend(\'f(x)\',\'df(x)\');
title(\'Equation 3\');
%Equation 4
dfx = zeros(7,1);
for i=3:9
dfx(i-2,1) = ( fx(i-2) - 4*fx(i-1) + 3*fx(i) )/2.0;
end
figure;
plot( [ 0,1,2,3,4,5,6,7,8 ], fx, \'r\', [ 2,3,4,5,6,7,8 ], dfx , \'black\' );
ylabel( \'Amplitude\' );
xlabel( \'x\' );
legend(\'f(x)\',\'df(x)\');
title(\'Equation 4\');
%Centerd Difference
%Equation 5
dfx = zeros(7,1);
for i=2:8
dfx(i-1,1) = (fx(i+1) - fx(i-1))/2;
end
figure;
plot( [0,1,2,3,4,5,6,7,8 ], fx, \'r\', [ 1,2,3,4,5,6,7 ], dfx , \'black\' );
ylabel( \'Amplitude\' );
xlabel( \'x\' );
legend(\'f(x)\',\'df(x)\');
title(\'Equation 5\');
%Equation 6
dfx = zeros(5,1);
for i=3:7
dfx(i-2,1) = ( -fx(i+2) + 8*fx(i+1) - 8*fx(i-1) + fx(i-2) )/12.0;
end
figure;
plot( [ 0,1,2,3,4,5,6,7,8 ], fx, \'r\', [ 2,3,4,5,6 ], dfx , \'black\' );
ylabel( \'Amplitude\' );
xlabel( \'x\' );
legend(\'f(x)\',\'df(x)\');
title(\'Equation 6\');

