Forward, Reverse finite difference question

18 views (last 30 days)
kjw
kjw on 15 Dec 2024 at 13:57
Moved: Torsten on 15 Dec 2024 at 14:21
%forward
function df1_forward = forward_first(f,x,h)
df1_forward = (f(x(2:end))-f(x(1:end-1)))/h;
end
function df2_forward = forward_second(f,x,h)
df2_forward = (f(x(3:end))-2*f(x(2:end-1))+f(x(1:end-2)))/h^2;
end
function df3_forward = forward_third(f,x,h)
df3_forward = (f(x(4:end))-3*f(x(3:end-1))+3*f(x(2:end-2))-f(x(1:end-3)))/h^3;
end
function df4_forward = forward_fourth(f,x,h)
df4_forward = (f(x(5:end))-4*f(x(4:end-1))+6*f(x(3:end-2))-4*f(x(2:end-3))+f(x(1:end-4)))/h^4;
end
%reverse
function df1_reverse = reverse_first(f,x,h)
df1_reverse = (f(x(2:end))-f(x(1:end-1)))/h;
end
function df2_reverse = reverse_second(f,x,h)
df2_reverse = (f(x(3:end))-2*f(x(2:end-1))+f(x(1:end-2)))/h^2;
end
function df3_reverse = reverse_third(f,x,h)
df3_reverse = (f(x(4:end))-3*f(x(3:end-1))+3*f(x(2:end-2))-f(x(1:end-3)))/h^3;
end
function df4_reverse = reverse_fourth(f,x,h)
df4_reverse = (f(x(5:end))-4*f(x(4:end-1))+6*f(x(3:end-2))-4*f(x(2:end-3))+f(x(1:end-4)))/h^4;
end
I made a forward and backward finite difference code, and the forward and backward codes come out the same. Is this correct?

Accepted Answer

Torsten
Torsten on 15 Dec 2024 at 14:20
Moved: Torsten on 15 Dec 2024 at 14:21
x = 0:0.1:1;
f = @(x)x.^2;
derf = (f(x(2:end))-f(x(1:end-1)))/0.1;
hold on
plot(x(2:end),derf); % backward
plot(x(1:end-1),derf); % forward
plot(x,2*x) % analytical
grid on
hold off

More Answers (1)

KALYAN ACHARJYA
KALYAN ACHARJYA on 15 Dec 2024 at 14:08
In your code, you have written both forward and reverse functions identically, please check it again and make the reverse code.

Categories

Find more on Image Processing Toolbox in Help Center and File Exchange

Products


Release

R2024b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!