필터 지우기
필터 지우기

Numerical Differentiation using Finite Differences

조회 수: 19 (최근 30일)
Matlab1
Matlab1 2023년 12월 4일
편집: VBBV 2023년 12월 4일
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
Matlab1
Matlab1 2023년 12월 4일
thank you!
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