Numerical Differentiation using Finite Differences
71 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Akzeptierte Antwort
Torsten
am 4 Dez. 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
figure; fplot(df,[0,2*pi],'k--'); hold on
plot(x,df1,'b');
plot(x,df2,'g');
plot(x,df3,'r');
Weitere Antworten (2)
VBBV
am 4 Dez. 2023
Bearbeitet: VBBV
am 4 Dez. 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
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 Kommentare
VBBV
am 4 Dez. 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
figure; fplot(df,[0,2*pi],'k--');
hold on;
plot(X,df1,'b');
plot(X,df2,'g');
plot(X,df3,'r');
Dyuman Joshi
am 4 Dez. 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
figure; fplot(df,[0,2*pi],'k--'); hold on
plot(x0,df1,'b');
plot(x0,df2,'g');
plot(x0,df3,'r');
Siehe auch
Kategorien
Mehr zu Calculus finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!