Search code examples
scilab

Scilab: How to use ´numderivative´ function


  • I am a new user of Scilab and I am not a mathematician.
  • As my end goal, I want to calculate (and plot) the derivative of a piece-wise defined function, see here.
  • I tried to start small and just use a simple (continuous) function: f(x) = 3*x.
  • My Google-Fu lead me to the numderivative function.
  • Problem: It seems that I do not understand how the argument x works since the result is not a 1D-array, instead, it is a matrix.
  • Update 1: Maybe I use the wrong function and diff is the way to go. But what is then the purpose of numderivative?

PS: Is this the right place to ask Scilab-related questions? It seems that there are several StackOverflow communities where Scilab-related questions are asked.


// Define limits
x0 = 0;
x1 = 2;
// Define array x for which the derivative will be calculated. 
n = 100;
x = linspace (x0, x1, n);

// Define  function f(x)
deff('y=f(x)','y=3*x');

// Calculate derivative of f(x) at the positions x
myDiff = numderivative(f,x)

enter image description here

(I expect the result 3 3 and not a matrix.)

https://help.scilab.org/docs/6.1.1/en_US/numderivative.html


Solution

  • numderivative(f,x) will give you the approximated derivative/Jacobian of f at the single vector x. For your example it yields 3 times the identity matrix, which is the expected result since f(x)=3*x. If you rather need the derivative of f considered as a function of a single scalar variable at x=1 and x=2, then numderivative is not convenient as you would have to make an explicit loop. Just code the formula yourself (here first order formula) :

    // Define limits
    x0 = 0;
    x1 = 2;
    // Define array x for which the derivative will be calculated. 
    n = 100;
    x = linspace (x0, x1, n);
    
    // Define  function f(x)
    deff('y=f(x)','y=3*x');x = [1 2];
    h = sqrt(%eps);
    d = (f(x+h)-f(x))/h;
    

    The formula can be improved (second order or complex step formula).