Skip to Main Content Skip to Search
Product Documentation

Calculus

Differentiation

To illustrate how to take derivatives using Symbolic Math Toolbox software, first create a symbolic expression:

syms x
f = sin(5*x)

The command

diff(f)

differentiates f with respect to x:

ans =
5*cos(5*x)

As another example, let

g = exp(x)*cos(x)

where exp(x) denotes ex, and differentiate g:

diff(g)
ans =
exp(x)*cos(x) - exp(x)*sin(x)

To take the second derivative of g, enter

diff(g,2)
ans =
-2*exp(x)*sin(x)

You can get the same result by taking the derivative twice:

diff(diff(g))
ans =
-2*exp(x)*sin(x)

In this example, MATLAB software automatically simplifies the answer. However, in some cases, MATLAB might not simply an answer, in which case you can use the simplify command. For an example of such simplification, see More Examples.

Note that to take the derivative of a constant, you must first define the constant as a symbolic expression. For example, entering

c = sym('5');
diff(c)

returns

ans =
0

If you just enter

diff(5)

MATLAB returns

ans =
     []

because 5 is not a symbolic expression.

Derivatives of Expressions with Several Variables

To differentiate an expression that contains more than one symbolic variable, specify the variable that you want to differentiate with respect to. The diff command then calculates the partial derivative of the expression with respect to that variable. For example, given the symbolic expression

syms s t
f = sin(s*t)

the command

diff(f,t)

calculates the partial derivative . The result is

ans = 
s*cos(s*t)

To differentiate f with respect to the variable s, enter

diff(f,s)

which returns:

ans =
t*cos(s*t)

If you do not specify a variable to differentiate with respect to, MATLAB chooses a default variable. Basically, the default variable is the letter closest to x in the alphabet. See the complete set of rules in Finding a Default Symbolic Variable. In the preceding example, diff(f) takes the derivative of f with respect to t because the letter t is closer to x in the alphabet than the letter s is. To determine the default variable that MATLAB differentiates with respect to, use symvar:

symvar(f, 1)
ans = 
t

Calculate the second derivative of f with respect to t:

diff(f, t, 2)

This command returns

ans =
-s^2*sin(s*t)

Note that diff(f, 2) returns the same answer because t is the default variable.

More Examples

To further illustrate the diff command, define a, b, x, n, t, and theta in the MATLAB workspace by entering

syms a b x n t theta

This table illustrates the results of entering diff(f).

f

diff(f)

syms x n
f = x^n;
diff(f)
ans =
n*x^(n - 1)
syms a b t
f = sin(a*t + b);
diff(f)
ans =
a*cos(b + a*t)
syms theta
f = exp(i*theta);
diff(f)
ans =
exp(theta*i)*i

To differentiate the Bessel function of the first kind, besselj(nu,z), with respect to z, type

syms nu z
b = besselj(nu,z);
db = diff(b)

which returns

db =
(nu*besselj(nu, z))/z - besselj(nu + 1, z)

The diff function can also take a symbolic matrix as its input. In this case, the differentiation is done element-by-element. Consider the example

syms a x
A = [cos(a*x),sin(a*x);-sin(a*x),cos(a*x)]

which returns

A =
[  cos(a*x), sin(a*x)]
[ -sin(a*x), cos(a*x)]

The command

diff(A)

returns

ans =
[ -a*sin(a*x),  a*cos(a*x)]
[ -a*cos(a*x), -a*sin(a*x)]

You can also perform differentiation of a vector function with respect to a vector argument. Consider the transformation from Euclidean (x, y, z) to spherical coordinates as given by , , and . Note that corresponds to elevation or latitude while denotes azimuth or longitude.

To calculate the Jacobian matrix, J, of this transformation, use the jacobian function. The mathematical notation for J is

For the purposes of toolbox syntax, use l for and f for . The commands

syms r l f
x = r*cos(l)*cos(f); y = r*cos(l)*sin(f); z = r*sin(l);
J = jacobian([x; y; z], [r l f])

return the Jacobian

J =
[ cos(f)*cos(l), -r*cos(f)*sin(l), -r*cos(l)*sin(f)]
[ cos(l)*sin(f), -r*sin(f)*sin(l),  r*cos(f)*cos(l)]
[        sin(l),         r*cos(l),                0]

and the command

detJ = simple(det(J))

returns

detJ = 
-r^2*cos(l)

The arguments of the jacobian function can be column or row vectors. Moreover, since the determinant of the Jacobian is a rather complicated trigonometric expression, you can use the simple command to make trigonometric substitutions and reductions (simplifications). Simplifications and Substitutions discusses simplification in more detail.

A table summarizing diff and jacobian follows.

Mathematical Operator

MATLAB Command

diff(f) or diff(f, x)

diff(f, a)

diff(f, b, 2)

J = jacobian([r; t],[u; v])

Limits

The fundamental idea in calculus is to make calculations on functions as a variable "gets close to" or approaches a certain value. Recall that the definition of the derivative is given by a limit

provided this limit exists. Symbolic Math Toolbox software enables you to calculate the limits of functions directly. The commands

syms h n x
limit((cos(x+h) - cos(x))/h, h, 0)

which return

ans =
-sin(x)

and

limit((1 + x/n)^n, n, inf)

which returns

ans =
exp(x)

illustrate two of the most important limits in mathematics: the derivative (in this case of cos(x)) and the exponential function.

One-Sided Limits

You can also calculate one-sided limits with Symbolic Math Toolbox software. For example, you can calculate the limit of x/|x|, whose graph is shown in the following figure, as x approaches 0 from the left or from the right.

To calculate the limit as x approaches 0 from the left,

enter

syms x
limit(x/abs(x), x, 0, 'left')

This returns

ans =
 -1

To calculate the limit as x approaches 0 from the right,

enter

syms x
limit(x/abs(x), x, 0, 'right')

This returns

ans =
1

Since the limit from the left does not equal the limit from the right, the two- sided limit does not exist. In the case of undefined limits, MATLAB returns NaN (not a number). For example,

syms x
limit(x/abs(x), x, 0)

returns

ans =
NaN

Observe that the default case, limit(f) is the same as limit(f,x,0). Explore the options for the limit command in this table, where f is a function of the symbolic object x.

Mathematical Operation

MATLAB Command

limit(f)

limit(f, x, a) or

limit(f, a)

limit(f, x, a, 'left')

limit(f, x, a, 'right')

Integration

If f is a symbolic expression, then

int(f)

attempts to find another symbolic expression, F, so that diff(F) = f. That is, int(f) returns the indefinite integral or antiderivative of f (provided one exists in closed form). Similar to differentiation,

int(f,v)

uses the symbolic object v as the variable of integration, rather than the variable determined by symvar. See how int works by looking at this table.

Mathematical Operation

MATLAB Command

int(x^n) or int(x^n,x)

int(sin(2*x), 0, pi/2) or int(sin(2*x), x, 0, pi/2)

g  =  cos(at + b)

g = cos(a*t + b) int(g) or int(g, t)

int(besselj(1, z)) or int(besselj(1, z), z)

In contrast to differentiation, symbolic integration is a more complicated task. A number of difficulties can arise in computing the integral:

Nevertheless, in many cases, MATLAB can perform symbolic integration successfully. For example, create the symbolic variables

syms a b theta x y n u z

The following table illustrates integration of expressions containing those variables.

f

int(f)

syms x n
f = x^n;
int(f)
ans =
piecewise([n == -1, log(x)], [n ~= -1, x^(n + 1)/(n + 1)])
syms y
f = y^(-1);
int(f)
ans =
log(y)
syms x n
f = n^x;
int(f)
ans =
n^x/log(n)
syms a b theta
f = sin(a*theta+b);
int(f)
ans =
-cos(b + a*theta)/a
syms u
f = 1/(1+u^2);
int(f)
ans =
atan(u)
syms x
f = exp(-x^2);
int(f)
ans =
(pi^(1/2)*erf(x))/2

In the last example, exp(-x^2), there is no formula for the integral involving standard calculus expressions, such as trigonometric and exponential functions. In this case, MATLAB returns an answer in terms of the error function erf.

If MATLAB is unable to find an answer to the integral of a function f, it just returns int(f).

Definite integration is also possible.

Definite Integral

Command

int(f, a, b)

int(f, v, a, b)

Here are some additional examples.

f

a, b

int(f, a, b)

syms x
f = x^7;
a = 0;
b = 1;
int(f, a, b)
ans =
1/8
syms x
f = 1/x;
a = 1;
b = 2;
int(f, a, b)
ans =
log(2)
syms x
f = log(x)*sqrt(x);
a = 0;
b = 1;
int(f, a, b)
ans =
-4/9
syms x
f = exp(-x^2);
a = 0;
b = inf;
int(f, a, b)
ans =
pi^(1/2)/2
syms z
f = besselj(1,z)^2;
a = 0;
b = 1;
int(f, a, b)
ans =
hypergeom([3/2, 3/2], [2, 5/2, 3], -1)/12

For the Bessel function (besselj) example, it is possible to compute a numerical approximation to the value of the integral, using the double function. The commands

syms z
a = int(besselj(1,z)^2,0,1)

return

a =
hypergeom([3/2, 3/2], [2, 5/2, 3], -1)/12

and the command

a = double(a)

returns

a =
    0.0717

Integration with Real Parameters

One of the subtleties involved in symbolic integration is the "value" of various parameters. For example, if a is any positive real number, the expression

is the positive, bell shaped curve that tends to 0 as x tends to ±∞. You can create an example of this curve, for a = 1/2, using the following commands:

syms x
a = sym(1/2);
f = exp(-a*x^2);
ezplot(f)

However, if you try to calculate the integral

without assigning a value to a, MATLAB assumes that a represents a complex number, and therefore returns a piecewise answer that depends on the argument of a. If you are only interested in the case when a is a positive real number, use assume to set an assumption on a:

syms a
assume(a > 0);

Now you can calculate the preceding integral using the commands

syms x
f = exp(-a*x^2);
int(f, x, -inf, inf)

This returns

ans =
pi^(1/2)/a^(1/2)

Integration with Complex Parameters

To calculate the integral

for complex values of a, enter

syms a x clear 
f = 1/(a^2 + x^2);
F = int(f, x, -inf, inf)

syms is used with the clear option to clear the all assumptions on a. For more information about symbolic variables and assumptions on them, see Deleting Symbolic Objects and Their Assumptions.

The preceding commands produce the complex output

F = 
(pi*signIm(i/a))/a

The function signIm is defined as:

To evaluate F at a = 1 + i, enter

g = subs(F, 1 + i)
g = 
pi/(2*i)^(1/2)
double(g)
ans =
   1.5708 - 1.5708i

Symbolic Summation

You can compute symbolic summations, when they exist, by using the symsum command. For example, the p-series

sums to , while the geometric series

1 + x + x2 + ...

sums to 1/(1 – x), provided . These summations are demonstrated below:

syms x k
s1 = symsum(1/k^2, 1, inf)
s2 = symsum(x^k, k, 0, inf)
s1 =
pi^2/6

s2 =
piecewise([1 <= x, Inf], [abs(x) < 1, -1/(x - 1)])

Taylor Series

The statements

syms x
f = 1/(5 + 4*cos(x));
T = taylor(f, 'Order', 8)

return

T =
(49*x^6)/131220 + (5*x^4)/1458 + (2*x^2)/81 + 1/9

which is all the terms up to, but not including, order eight in the Taylor series for f(x):

Technically, T is a Maclaurin series, since its expansion point is a = 0.

The command

pretty(T)

prints T in a format resembling typeset mathematics:

 
      6       4      2 
  49 x     5 x    2 x 
  ------ + ---- + ---- + 1/9 
  131220   1458    81

These commands

syms x
g = exp(x*sin(x))
t = taylor(g, 'ExpansionPoint', 2, 'Order', 12);

generate the first 12 nonzero terms of the Taylor series for g about x = 2.

t is a large expression; enter

size(char(t))
ans =
           1       99791

to find that t has about 100,000 characters in its printed form. In order to proceed with using t, first simplify its presentation:

t = simplify(t);
size(char(t))
ans =
           1        6988

To simplify t even further, use the simple function:

t = simple(t);
size(char(t))
ans =
           1        6376

Next, plot these functions together to see how well this Taylor approximation compares to the actual function g:

xd = 1:0.05:3; yd = subs(g,x,xd);
ezplot(t, [1, 3]); hold on;
plot(xd, yd, 'r-.')
title('Taylor approximation vs. actual function');
legend('Taylor','Function')

Special thanks is given to Professor Gunnar Bäckstrøm of UMEA in Sweden for this example.

Calculus Example

This section describes how to analyze a simple function to find its asymptotes, maximum, minimum, and inflection point. The section covers the following topics:

Defining the Function

The function in this example is

To create the function, enter the following commands:

syms x
num = 3*x^2 + 6*x -1;
denom = x^2 + x - 3;
f = num/denom

This returns

f = 
(3*x^2 + 6*x - 1)/(x^2 + x - 3)

You can plot the graph of f by entering

ezplot(f)

This displays the following plot.

Finding the Asymptotes

To find the horizontal asymptote of the graph of f, take the limit of f as x approaches positive infinity:

limit(f, inf)
ans = 
3

The limit as x approaches negative infinity is also 3. This tells you that the line y = 3 is a horizontal asymptote to the graph.

To find the vertical asymptotes of f, set the denominator equal to 0 and solve by entering the following command:

roots = solve(denom)

This returns to solutions to :

roots =
 
   13^(1/2)/2 - 1/2
 - 13^(1/2)/2 - 1/2

This tells you that vertical asymptotes are the lines

and

You can plot the horizontal and vertical asymptotes with the following commands:

ezplot(f)
hold on % Keep the graph of f in the figure
% Plot horizontal asymptote
plot([-2*pi 2*pi], [3 3],'g')
% Plot vertical asymptotes
plot(double(roots(1))*[1 1], [-5 10],'r')
plot(double(roots(2))*[1 1], [-5 10],'r')
title('Horizontal and Vertical Asymptotes')
hold off

Note that roots must be converted to double to use the plot command.

The preceding commands display the following figure.

To recover the graph of f without the asymptotes, enter

ezplot(f)

Finding the Maximum and Minimum

You can see from the graph that f has a local maximum somewhere between the points x = –2 and x = 0, and might have a local minimum between x = –6 and x = –2. To find the x-coordinates of the maximum and minimum, first take the derivative of f:

f1 = diff(f)

This returns

f1 = 
(6*x + 6)/(x^2 + x - 3) - ((2*x + 1)*(3*x^2 + 6*x - 1))/(x^2 + x - 3)^2

To simplify this expression, enter

f1 = simplify(f1)

which returns

f1 =
 -(3*x^2 + 16*x + 17)/(x^2 + x - 3)^2

You can display f1 in a more readable form by entering

pretty(f1)

which returns

     
       2 
    3 x  + 16 x + 17 
  - ---------------- 
       2         2 
     (x  + x - 3)

Next, set the derivative equal to 0 and solve for the critical points:

crit_pts = solve(f1)

This returns

crit_pts =
 
   13^(1/2)/3 - 8/3
 - 13^(1/2)/3 - 8/3

It is clear from the graph of f that it has a local minimum at

and a local maximum at

You can plot the maximum and minimum of f with the following commands:

ezplot(f)
hold on
plot(double(crit_pts), double(subs(f,crit_pts)),'ro')
title('Maximum and Minimum of f')
text(-5.5,3.2,'Local minimum')
text(-2.5,2,'Local maximum')
hold off

This displays the following figure.

Finding the Inflection Point

To find the inflection point of f, set the second derivative equal to 0 and solve.

f2 = diff(f1);
inflec_pt = solve(f2);
double(inflec_pt)

This returns

ans =
  -5.2635          
  -1.3682 - 0.8511i
  -1.3682 + 0.8511i

In this example, only the first entry is a real number, so this is the only inflection point. (Note that in other examples, the real solutions might not be the first entries of the answer.) Since you are only interested in the real solutions, you can discard the last two entries, which are complex numbers.

inflec_pt = inflec_pt(1)

To see the symbolic expression for the inflection point, enter

pretty(simplify(inflec_pt))

This returns

 
                                 /               1/2 \1/3 
                13               |          13 13    | 
  - -------------------------- - | 169/54 - -------- |    - 8/3 
      /               1/2 \1/3   \             18    / 
      |          13 13    | 
    9 | 169/54 - -------- | 
      \             18    /

To plot the inflection point, enter

ezplot(f, [-9 6])
hold on
plot(double(inflec_pt), double(subs(f,inflec_pt)),'ro')
title('Inflection Point of f')
text(-7,2,'Inflection point')
hold off

The extra argument, [-9 6], in ezplot extends the range of x values in the plot so that you see the inflection point more clearly, as shown in the following figure.

  


Free Symbolic Math Interactive Kit

See how symbolic computations can help you find analytical solutions to math and engineering problems.

Get free kit

Trials Available

Try the latest version of symbolic math products.

Get trial software
 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS