如何在 Octave 中找到函数的导数?

wha*_*992 7 matlab for-loop octave derivative

输入:

Xf = 和保存点的 x 值的数组

Yf = 保存点方法的 y 值的数组 = 2 点前向差、2 点后向差、3 点中心差、5 点中心差

输出:

X= 包含有效 x 值的数组,其中选择的方法实际上可以使用(例如,您不能在Xf数组的上限使用前向差分方法,因为它后面没有值)

DF = 在这些点的导数

我需要为脚本提供一组点,然后使用 4 种不同的方法计算这些点的导数,而不使用像 diff. 我需要一些帮助来编写其中一个代码,然后我想我应该能够弄清楚如何完成其​​余的工作。

2分前差

我的尝试:

[a, minidx] = min(Xf);
[b, maxidx] = max(Xf);
n = 10;
h = (b-a)/n;
f = (x .^3) .* e.^(-x) .* cos(x);

If method = "forward" #Input by user

    X = [min(Xf), Xf(maxidx-1)];
    for k = min(Xf):n # not sure if this is the right iteration range...

        f(1) = f(x-2*h) + 8*f(x +h);
        f(2) = 8*f(x-h) + f(x+2*h);
        DF = (f1-f2)/(12*h);

    endfor
endif
Run Code Online (Sandbox Code Playgroud)

小智 9

https://wiki.octave.org/Symbolic_package

% this is just a formula to start with,  
% have fun and change it if you want to.  
f = @(x) x.^2 + 3*x - 1 + 5*x.*sin(x);  
% these next lines take the Anonymous function into a symbolic formula  
pkg load symbolic  
syms x;  
ff = f(x);  
% now calculate the derivative of the function  
ffd = diff(ff, x)  
% answer is ffd = (sym) 5*x*cos(x) + 2*x + 5*sin(x) + 3  
...  
Run Code Online (Sandbox Code Playgroud)


Jag*_*gte 0

以下是 Matlab 如何计算导数的一些文档:

diff Difference and approximate derivative.
     diff(X), for a vector X, is [X(2)-X(1)  X(3)-X(2) ... X(n)-X(n-1)].
     diff(X), for a matrix X, is the matrix of row differences,
           [X(2:n,:) - X(1:n-1,:)].
     diff(X), for an N-D array X, is the difference along the first
          non-singleton dimension of X.
     diff(X,N) is the N-th order difference along the first non-singleton 
          dimension (denote it by DIM). If N >= size(X,DIM), diff takes 
          successive differences along the next non-singleton dimension.
     diff(X,N,DIM) is the Nth difference function along dimension DIM. 
         If N >= size(X,DIM), diff returns an empty array.

Examples:
   h = .001; x = 0:h:pi;
   diff(sin(x.^2))/h is an approximation to 2*cos(x.^2).*x
   diff((1:10).^2) is 3:2:19

   If X = [3 7 5
           0 9 2]
   then diff(X,1,1) is [-3 2 -3], diff(X,1,2) is [4 -2
                                                  9 -7],
   diff(X,2,2) is the 2nd order difference along the dimension 2, and
   diff(X,3,2) is the empty matrix.
Run Code Online (Sandbox Code Playgroud)

这是另一个例子:

xp= diff(xf);
yp= diff(yf);

% derivative:
dydx=yp./xp;
% also try:
dydx1=gradient(yf)./gradient(xf)
Run Code Online (Sandbox Code Playgroud)