Numerical Differentiation using Finite Differences
23 次查看(过去 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.
0 个评论
采纳的回答
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
figure; fplot(df,[0,2*pi],'k--'); hold on
plot(x,df1,'b');
plot(x,df2,'g');
plot(x,df3,'r');
更多回答(2 个)
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
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
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
figure; fplot(df,[0,2*pi],'k--');
hold on;
plot(X,df1,'b');
plot(X,df2,'g');
plot(X,df3,'r');
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
figure; fplot(df,[0,2*pi],'k--'); hold on
plot(x0,df1,'b');
plot(x0,df2,'g');
plot(x0,df3,'r');
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Calculus 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!