How calculate the second and third numerical derivative of one variable f(x)

조회 수: 224 (최근 30일)
NoorKh
NoorKh 2019년 12월 13일
댓글: Jim Riggs 2019년 12월 14일
How can write a MATLAB to calculate the second and third numerical derivative of one variable f(x) ??

답변 (2개)

Jim Riggs
Jim Riggs 2019년 12월 13일
편집: Jim Riggs 2019년 12월 14일
The Matlab "diff" function is basically the Backward difference formula. There are much more accurate ways to compute numerical derivatives.
If you like, you can program your own function(s). The central difference calculation is much better than either forward or backward method. Use Forward difference to calculate the derivative at the first point, and backward difference to calculate the derivative at the last point. Everywhere in between, use the central difference formula. This allows you to compute a derivative at every point in your vector, and will provide better results than using recursive applications of "diff".
If you are interested in this method, I can provide equations for even better accuracy than these.
[EDIT] Here is a slightly more accurate version for the Forward/Backward difference:
Your Matlab function would look somethng like this:
function dy = Nderiv2(y,h)
% Compute the second derivative of input vector y, with spacing h
n = length(y);
for i=1:n
switch i
case 1
% use Forward difference equation for y''
dy(i) = ...
case n
% use backward difference equation for y''
dy(i) = ...
otherwise
% use central difference equation for y''
dy(i) = ...
end
end
end
The third derivative function is similar, except that the central difference formula uses a range on y of y(i-2), y(i-1) y(i+1) y(i+2), so you need two points on either side of y(i) to perform this calculation.
function dy = Nderive3(y,h)
% compute the third derivative of input vector y with spacing h
n = length(y);
for i=1:n;
switch i
case {1, 2}
% use forward difference equation for y'''
dy(i) = ...
case {n-1, n}
% use backward difference equation for y'''
dy(i) = ...
otherwise
% use central difference equation for y'''
dy(i) = ...
end
end
end
  댓글 수: 4
Guillaume
Guillaume 2019년 12월 14일
"however, gradient() only computes the first derivative."
gradient(gradient(gradient(somevector))) %3rd derivative
Given the lack of details in the question, I don't see why you'd need anything else more complicated.
Jim Riggs
Jim Riggs 2019년 12월 14일
You make a good point. (But I personally woud never consider calculating a third derivative this way.)

댓글을 달려면 로그인하십시오.


Matt J
Matt J 2019년 12월 13일
Matlab's diff command will do this directly,

카테고리

Help CenterFile Exchange에서 Signal Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by