How do I find the derivative of a function in Octave?

whatin1992 picture whatin1992 · Mar 27, 2016 · Viewed 20.9k times · Source

Inputs:

Xf = and array that holds the x-values of the points

Yf = an array that holds the y-values of the points method = 2-point forward difference, 2-point backward difference, 3-point central difference, 5-point central difference

Outputs:

X = the array that contains the valid x-values where the method chosen can actually be used (for example, you cannot use the forward difference method at the upper bound of the Xf array because there is no value after it)

DF = the derivatives at those points

I need to give a script a set of points and then calculate the derivatives at those points using 4 different methods without using a built-in derivative function like diff. I'd like some assistance in coding one of them and then I think I should be able to figure out how to do the rest.

2-point forward difference

My attempt:

[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

Answer

guest picture guest · Nov 25, 2017

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  
...