MATLAB How do I differentiate in MATLAB?

AI Thread Summary
The discussion centers on the challenges of differentiating functions in MATLAB without the symbolic toolbox. Users highlight that while the 'diff' command can be used for numerical differentiation, it requires careful selection of step size to yield accurate results. An example is provided where the sine function is differentiated numerically using 'diff' with a small step size, demonstrating that the output approximates the cosine function. It is noted that 'diff' returns a vector with one less element than the input. An alternative method mentioned is the 'gradient' function, which maintains the same vector size and can handle higher-dimensional problems. Overall, these methods offer practical solutions for numerical differentiation in MATLAB.
Urmi Roy
Messages
743
Reaction score
1
I find that I don't have the symbolic toolbox. Due to this, I'm not being able to differentiate by using the usual 'diff' command. However, just as one can integrate numerically, by using the quad and quadl functions, is there no way to differentiate numerically on MATLAB (like using the ab initio method or something)?
 
Physics news on Phys.org
You can use diff to differentiate most functions with an appropriate step size. For example,

Code:
h = 0.001;
x = -pi:h:pi;
y = sin(x);
z = diff(y)/h;

If you plot z, you will see that it is equal to cos(x). Similarly, you can use diff to calculate derivatives this way for other functions.

Just remember diff returns a vector with 1 less element.

Alternatively, you could use gradient, which returns a vector of the same size. For 1D problems this is a simple partial derivative. There are additional syntaxes available for higher dimensional problems (see http://www.mathworks.com/help/matlab/ref/gradient.html)
 
Thanks for the info, Kreil! I can't imagine why I didn't see your post in all these days!
 
Back
Top