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

26,227

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  
...  
Share:
26,227
whatin1992
Author by

whatin1992

Updated on March 04, 2021

Comments

  • whatin1992
    whatin1992 about 3 years

    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
    
  • vitoriodachef
    vitoriodachef about 4 years
    how would I evaluate the derivative for a specific value after I found it?