I cannot seem to get a second line for the forward finite difference
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
Walter Roberson
el 25 de Sept. de 2019
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.
Respuestas (1)
Image Analyst
el 25 de Sept. de 2019
Looks like d2 is a scalar, not a vector (a list of values for each x value).
0 comentarios
Ver también
Categorías
Más información sobre Signal Generation and Preprocessing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!