MATLAB: Matlab simple loop for different function variables (Finite Difference)

backward difference approximationcentral difference approximationfinite differenceforwad difference approximationloop

So, i wrote a simple matlab script to evaluate forward, backward and central difference approximations of first and second derivatives for a spesific function (y = x^3-5x) at two different x values (x=0.5 and x = 1.5) and for 7 different step sizes (h) and compare the relative errors of the approximations to the analytical derivatives.
However, i need to enter x and h values manually every time. Question is, how do i create a loop for 7 different h values and 2 different x values and get all the results as a matrix?
Script:
clc
clear all
close all
h = 0.00001; %step size
x1 = 0.5; %x value
y = @(x) x.^3 - 5*x; %main function
dy = @(x) 3*x.^2 - 5; %first derivative
ddy = @(x) 6*x; %second derivative
d1 = dy(x1);
d2 = ddy(x1);
%Forward Differencing
f1 = (y(x1+h) - y(x1))/h;
f2 = (y(x1+2*h) - 2*y(x1+h) + y(x1))/(h.^2);
%Central Differencing
c1 = (y(x1+h)-y(x1-h))/(2*h);
c2 = (y(x1+h)-2*y(x1)+y(x1-h))/(h.^2);
% Backward Differencing
b1 = (y(x1) - y(x1-h))/h;
b2 = (y(x1)-2*y(x1-h)+y(x1-2*h))/(h.^2);
% Relative Errors
ForwardError1 = (f1 - dy(x1))/dy(x1);
ForwardError2 = (f2 - ddy(x1))/ddy(x1);
CentralError1 = (c1 - dy(x1))/dy(x1);
CentralError2 = (c2 - ddy(x1))/ddy(x1);
BackwardError1 = (b1 - dy(x1))/dy(x1);
BackwardError2 = (b2 - ddy(x1))/ddy(x1);

Best Answer

Something like this? Or did you want all the error terms in one 3D matrix?
clc
clearvars
close all
hVec = [0.00001 0.00005 0.0001 0.0005 0.001 0.005 0.01]; %step size
x1Vec = [0.5 1.5]; %x value
y = @(x) x.^3 - 5*x; %main function
dy = @(x) 3*x.^2 - 5; %first derivative
ddy = @(x) 6*x; %second derivative
for i = 1:2
for j=1:7
x1 = x1Vec(i);
h = hVec(j);
d1 = dy(x1);
d2 = ddy(x1);
%Forward Differencing
f1 = (y(x1+h) - y(x1))/h;
f2 = (y(x1+2*h) - 2*y(x1+h) + y(x1))/(h.^2);
%Central Differencing
c1 = (y(x1+h)-y(x1-h))/(2*h);
c2 = (y(x1+h)-2*y(x1)+y(x1-h))/(h.^2);
% Backward Differencing
b1 = (y(x1) - y(x1-h))/h;
b2 = (y(x1)-2*y(x1-h)+y(x1-2*h))/(h.^2);
% Relative Errors
ForwardError1(i,j) = (f1 - dy(x1))/dy(x1);
ForwardError2(i,j) = (f2 - ddy(x1))/ddy(x1);
CentralError1(i,j) = (c1 - dy(x1))/dy(x1);
CentralError2(i,j) = (c2 - ddy(x1))/ddy(x1);
BackwardError1(i,j) = (b1 - dy(x1))/dy(x1);
BackwardError2(i,j) = (b2 - ddy(x1))/ddy(x1);
end
end
Related Question