Strange graph artifact when performing diff() of a high order
Show older comments
I think it has something to do with values going below eps within the code but I'm not sure. Is there a simple fix or do I have to rework the code entirely?
clearvars;
x1 = 0; %Start
x2 = 4*pi; %End
I = 1000; %Steps
h = (x2-x1)/I; %Step size
N = 5; %Number of derivatives
x = linspace(x1,x2,I);
y = exp(1/2*x); %Base function
dydx = zeros(N, I-N); %Preallocation
for n = 1:N
diffVector = diff(y,n)/h^n; %Calculates the nth derivative
dydx(n,:) = diffVector(1:I-N); %Stores it in the derivative array
end
plot(x(:,1:I-N),dydx,x,y) %Plots all derivatives
The code is just an exercise to find the nth derivative of a function (in this case exp(1/2x))
When N = 5 it seems to work fine. But if I change it to N = 7 I get some freaky graph output. This may also occur if I change I by a certain amount. Here are the graphs of each:

<<

>>
Accepted Answer
More Answers (1)
Roger Stafford
on 30 Jul 2014
1 vote
For the higher derivatives you need to increase the size of h which means decrease the number of points, I. There has to be a balance here between the error due to inaccuracies of the higher order differences on the one hand and the variation of the function throughout the range of n*h on the other hand. The higher the derivative, the larger the range of n+1 points has to be.
Categories
Find more on Particle & Nuclear Physics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!