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

조회 수: 1 (최근 30일)
Michael Corbett
Michael Corbett 2019년 9월 24일
댓글: Walter Roberson 2019년 9월 25일
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