I’ll try to explain it a little bit easier than in the Scilab’s Help.
Suppose, you have a function of one variable, e.g.
y = x2
function y=f(x) y=x^2 endfunction
To take its derivative, write another function
function y=df(x) y=numderivative(f,x) endfunction
Now, if you want to plot this derivative, you need to compute its values at a number of points, that are usually equally spaced.
You can do it like this:
x=linspace(0,10,20)'; y=feval(x,df); plot(x,y,'x')
If your function depends on other parameters, say,
y = p1 sin (p2x)
then the code for calculating and plotting its derivative is:
function y=f(x, p1,p2) y = p1*sin(x*p2) endfunction function y=df(x) y=numderivative(list(f, p1,p2), x) endfunction p1 = 2; p2 = 3; x=linspace(0,2*%pi,200)'; y=feval(x,df); plot(x,y,'x')
Higher order derivatives can be obtained by applying
function y=f(x) y=sin(x) endfunction function y=df(x) y=numderivative(f,x) endfunction function y=d2f(x) y=numderivative(df,x) endfunction x=linspace(0,2*%pi,200)'; y=feval(x,d2f); plot(x,y,'x')
It’s possible to use a
for loop to get the n-th derivative of a function f for an arbitrary n
old = 'f'; for i=1:n new = 'd'+string(i)+'f'; deff('y='+new+'(x)','y=numderivative('+old+',x)'); old=new; end x=linspace(0,2*%pi,200)'; execstr('y=feval(x,'+new+');');
But be careful! Numerical errors increase with the number of iterations.
This is what happens, for example, to the derivatives of the function y=x4
This is common: while integrals are easier calculated numerically than analytically, the situation with derivatives is opposite. They are easier treated analytically than numerically.