www.gusucode.com > matlab 案例源码 matlab代码程序 > matlab/ApproximateDerivativesWithDiffExample.m
%% Approximate Derivatives with diff % Use the |diff| function to approximate partial derivatives with the % syntax |Y = diff(f)/h|, where |f| is a vector of function values % evaluated over some domain, |X|, and |h| is an appropriate step size. %% % For example, the first derivative of |sin(x)| with respect to |x| is % |cos(x)|, and the second derivative with respect to |x| is |-sin(x)|. You % can use |diff| to approximate these derivatives. % Copyright 2015 The MathWorks, Inc. h = 0.001; % step size X = -pi:h:pi; % domain f = sin(X); % range Y = diff(f)/h; % first derivative Z = diff(Y)/h; % second derivative plot(X(:,1:length(Y)),Y,'r',X,f,'b', X(:,1:length(Z)),Z,'k') %% % In this plot the blue line corresponds to the original function, |sin|. % The red line corresponds to the calculated first derivative, |cos|, and % the black line corresponds to the calculated second derivative, |-sin|.