Page 80 - A Guide to MATLAB for Beginners and Experienced Users
P. 80
Doing Calculus with MATLAB 61
Doing Calculus with MATLAB
MATLAB has commands for most of the computations of basic calculus
in its Symbolic MathToolbox. This toolbox includes part of a separate program
called Maple , which processes the symbolic calculations.
Differentiation
You can use diff to differentiate symbolic expressions, and also to approxi-
mate the derivative of a function given numerically (say by an M-file):
>> syms x; diff(xˆ3)
ans =
3*x^2
Here MATLAB has figured out that the variable is x. (See Default Variables
at the end of the chapter.) Alternatively,
>> f = inline(’xˆ3’, ’x’); diff(f(x))
ans =
3*x^2
The syntax for second derivatives is diff(f(x), 2), and for nthderivatives,
diff(f(x), n). The command diff can also compute partial derivatives
of expressions involving several variables, as in diff(xˆ2*y, y), but to do
multiple partials withrespect to mixed variables you must use diff repeat-
edly, as in diff(diff(sin(x*y/z), x), y). (Remember to declare y and
z symbolic.)
There is one instance where differentiation must be represented by the
letter D, namely when you need to specify a differential equation as input to
a command. For example, to use the symbolic ODE solver on the differential
equation xy + 1 = y, you enter
dsolve(’x*Dy + 1 = y’, ’x’)