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
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
2019 年 9 月 25 日
Looks like d2 is a scalar, not a vector (a list of values for each x value).
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Signal Generation and Preprocessing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!