I cannot seem to get a second line for the forward finite difference

1 次查看(过去 30 天)
clc
clear
close all
h = [-2 -1.75 -1.5 -1.25 -1 -.75 -.5 -.25 0 .25 .5 .75 1 1.25 1.5 1.75 2];
x = [-2 -1.75 -1.5 -1.25 -1 -.75 -.5 -.25 0 .25 .5 .75 1 1.25 1.5 1.75 2];
y = @(x) x.^3 - 2*x + 4; %start function
yd = @(x) 3*x.^2 - 2; %first deriv
ydd = @(x) 6*x; %second deriv
for i = 1:2
for j = 1:17
xi = x(i);
hj = h(j);
d1 = yd(xi);
d2 = ydd(xi);
%forward diff
f1 = (y(xi+hj) - y(xi))/hj;
f2 = (y(xi+2*hj) - 2*y(xi+hj))/(hj.^2);
%backward diff
b1 = (y(xi) - y(xi-hj))/hj;
b2 = (y(xi)-2*y(xi-hj)+y(xi-2*hj))./(h.^2);
%centered diff
c1 = (y(xi+hj) - y(xi-hj))/(2*hj);
c2 = (y(xi+hj) - 2*y(xi)+y(xi-hj))/(hj.^2);
plot(x,yd(x));
hold on
plot(x,d2,'r');
hold off
legend('Analytic','Forward','Backward','Center')
end
end
This is the code I've gotten so far. For the second plot I have tried everything I can think of and it will not plot. Why is this?
  1 个评论
Walter Roberson
Walter Roberson 2019-9-25
You should not be plotting inside your for j loop. You should be recording the results into a vector and plotting after the loop.
plot(x,yd(x));
You current point is xi so yd(xi) what you should be concerned with recording for later.

请先登录,再进行评论。

回答(1 个)

Image Analyst
Image Analyst 2019-9-25
Looks like d2 is a scalar, not a vector (a list of values for each x value).

类别

Help CenterFile Exchange 中查找有关 Signal Generation and Preprocessing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by