Matlab simple loop for different function variables (Finite Difference)
Show older comments
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);
Accepted Answer
More Answers (0)
Categories
Find more on MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!