Calculate derivatives on the interval 0<x<2pi using forward, backward, centered, and fourth order accurate finite differences
Show older comments
f(x) = ax+bx^2+cx^3+dsin(mx)+gexp(hx)
a=-5
b=.5
c=-.15
d=.2
m=6
g=-2
h=-3
Calculate first derivatives using forward, backward, centered, and fourth order accurate finite differences.
calculate second derivative using 2nd order accurate central differences.
plot the finite difference solutions compared to the analytic solutions. 6 plots total (3 for the first derivatives and 3 for the second derivatives) with 5 lines per graph for the first derivatives and 2 lines per graph for the second derivatives.
for simplicity it is ok to plot the solutions starting at grid point 3, and ending at grid point N-2, or any alternate methods for calculating the derivatives near the boundaries may be used that is consistent with the interior scheme.
also calculate the RMS error for each finite difference derivative at each grid resolution and present the results in a table or graph showing N vs error for each scheme. Note that these should form nearly a straight line on a log-log scale with a slope of -1 for the first order accurate schemes and a slope of -2 for the second order accurate schemes and a slope of -4 for the fourth order accurate schemes.
This is what I've done so far...but I don't know where to go from here or what I'm doing wrong.
clear
hw4_input
L = 2*pi;
N=input('How many grid points would you like to use on the interval. Enter 20,200, or 2000');
if (N==20);
dx = L/(N-1);
x=0:dx:2*pi;
analytical
for i = 1:N
f(i) = a*x(i)+b*x(i)^2+c*x(i)^3+d*sin(m*x(i))+g*exp(h*x(i));
dfdx=zeros(1,N);
dfdx(i) = a+2*b*x(i)+3*c*x(i)^2+m*d*cos(m*x(i))+h*g*exp(h*x(i));
x(i)=x(i);
end
fw
for i = 1:N-1
f(i) = a*x(i)+b*x(i)^2+c*x(i)^3+d*sin(m*x(i))+g*exp(h*x(i));
dfdx1=zeros(1,N);
dfdx1(i) = (f(i+1)-f(i))/dx;
x1(i) = x(i);
end
bw
for i= 2:N
f(i) = a*x(i)+b*x(i)^2+c*x(i)^3+d*sin(m*x(i))+g*exp(h*x(i));
dfdx2=zeros(1,N);
dfdx2(i) = (f(i)-f(i-1))/dx;
x2(i) = x(i);
end
cd
for i = 2:N-1
f(i) = a*x(i)+b*x(i)^2+c*x(i)^3+d*sin(m*x(i))+g*exp(h*x(i));
dfdx3=zeros(1,N);
dfdx3(i)=(f(i+1)-f(i-1))/(2*dx);
x3(i)= x(i);
end
forth
for i = 1:N-3
f(i) = a*x(i)+b*x(i)^2+c*x(i)^3+d*sin(m*x(i))+g*exp(h*x(i));
dfdx4=zeros(N,1);
dfdx4(i)= (-f(i+2)+8*f(i+1)-8*f(i-1)+f(i-2))/(12*dx);
end
end
Accepted Answer
More Answers (1)
Matt Fig
on 15 Feb 2011
3 votes
It looks like you just pasted the HW assignment. But this is MATLAB Answers, implying that there are questions being answered. I don't see any questions in your paste.
Soooo, do you have a question?
Categories
Find more on Mathematics in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!