Numerical Differentiation using Finite Differences

82 次查看(过去 30 天)
Hello,
I am trying to do finite differences to approximate the derivative of sin(x) in Matlab. Matlab shows an error in the way i used plot but im not sure how to fix it "plot(x,df1,'b');". Any advice is appreciated thank you.

采纳的回答

Torsten
Torsten 2023-12-4
h = 0.01;
x = 0:h:2*pi;
fx = sin(x);
%df1 = (sin(x+h) - sin(h))/h;
df1 = (sin(x+h) - sin(x))/h;
df2 = (sin(x) - sin(x-h))/h;
df3 = (sin(x+h) - sin(x-h))/(2*h);
% Symbolic (exact) solution
%syms x
%fx = sin(x);
syms xs
fx = sin(xs);
df = diff(fx);
df
df = 
figure; fplot(df,[0,2*pi],'k--'); hold on
plot(x,df1,'b');
plot(x,df2,'g');
plot(x,df3,'r');

更多回答(2 个)

VBBV
VBBV 2023-12-4
编辑:VBBV 2023-12-4
h = 0.01;
X = 0:h:2*pi;
fx = sin(X);
df1 = (sin(X+h) - sin(X))/h;
df2 = (sin(X) - sin(X-h))/h;
df3 = (sin(X+h) - sin(X-h))/(2*h);
% Symbolic (exact) solution
syms x
fx = sin(x);
df = diff(fx);
df
df = 
figure; fplot(df,[0,2*pi],'k--'); hold on;
plot(X,df1,'b');
plot(X,df2,'g');
plot(X,df3,'r');; legend('f(x)','Forward','Backward','Central')
  2 个评论
VBBV
VBBV 2023-12-4
h = 0.01;
X = 0:h:2*pi;
fx = sin(X);
df1 = (sin(X+h) - sin(X))/h;
df2 = (sin(X) - sin(X-h))/h;
df3 = (sin(X+h) - sin(X-h))/(2*h);
% Symbolic (exact) solution
syms x
fx = sin(x);
df = diff(fx);
df
df = 
figure; fplot(df,[0,2*pi],'k--');
hold on;
plot(X,df1,'b');
plot(X,df2,'g');
plot(X,df3,'r');

请先登录,再进行评论。


Dyuman Joshi
Dyuman Joshi 2023-12-4
It's because you over-write the variable x as a symbolic variable. Thus you get the aforementioned error.
To solve the issue, use different variable names.
Also, there's also a mistake in the forward difference. It should be x instead of h.
h = 0.01;
x0 = 0:h:2*pi;
fx = sin(x0);
% vv
df1 = (sin(x0+h) - sin(x0))/h;
df2 = (sin(x0) - sin(x0-h))/h;
df3 = (sin(x0+h) - sin(x0-h))/(2*h);
% Symbolic (exact) solution
syms x
fx = sin(x);
df = diff(fx);
df
df = 
figure; fplot(df,[0,2*pi],'k--'); hold on
plot(x0,df1,'b');
plot(x0,df2,'g');
plot(x0,df3,'r');

类别

Help CenterFile Exchange 中查找有关 Calculus 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by