Azzera filtri
Azzera filtri

Numerical Differentiation using Finite Differences

19 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Torsten
Torsten il 4 Dic 2023
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');

Più risposte (2)

VBBV
VBBV il 4 Dic 2023
Modificato: VBBV il 4 Dic 2023
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 Commenti
VBBV
VBBV il 4 Dic 2023
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');

Accedi per commentare.


Dyuman Joshi
Dyuman Joshi il 4 Dic 2023
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');

Community Treasure Hunt

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

Start Hunting!

Translated by