Josh Thompson
Postdoc: Colorado State University
Home  >  Teaching

  Symbolic Computations in MATLAB

Contents
1. Declaration of symbolic variables
2. Symbolic expressions and operations
3. Using the MAPLE kernel

Numerical computations are performed by operating on arrays of double-precision floating-point numbers. (In MATLAB also a single number is considered as an array.) A given numeric array is an instant (called object) of the class double. MATLAB has a number of other buildt in classes (and a user can create her/his own, new classes if desirable). The class of a variable describes the structure of operations and functions that can be applied to the variable. You can access the class to which a variable belongs by invoking the command class:

» x=5;class(x)

ans =

double

By typing the command whos you get as answer a list of the variables defined in the workspace together with their classes (try it).

1. Declaration of symbolic variables

Symbolic computations are performed with variables of the class sym (defined by the Symbolic Toolbox). If you want to perform symbolic computations with a certain set of variables, you first have to declare that these variables belong to this class. This can be done in two ways.

1.1 The command sym

» y=sym('alpha')
 
y =
 
alpha
 
creates a variable of class sym whose variable name is y and which is assigned to alpha. The argument of sym must be a character-string, i.e. a sequence of symbols. Character strings (more precisely arrays of character strings) form another class called char. In MATLAB strings are marked by apostrophes. If you omit the apostrophes, i.e type sym(alpha) and alpha is not defined properly, you get an error message. Note that you can also create a variable of class char and then simply pass the name of that variable as argument to sym. The commands

» k='alpha';y=sym(k)
 
y =
 
alpha

produce the same symbolic variable as the command sym(‘alpha’).

1.2 The command syms

» syms x a b c

is a short-cut for

» x=syms(‘x’);a=sym(‘a’);b=sym(‘b’); c=sym(‘c’);

whence the strings of the created variable names and their assignments coincide. Note that you don’t get an answer when executing this command. Instead of‘x,a, or b you can use any alphanumeric string which starts with a letter, but syms 1x will produce an error message. For introducing basic symbolic variables it is probably best to use this command.
 

The power of the command sym relies on the fact that you can also use it to convert variables from the class double to the class sym. For example, suppose you arrived through some numerical computation at a value of 1.2345 which you have stored in the variable k. The command

» sym(k)
 
ans =
 
2469/2000

assigns to the generated symbolic variable by default a rational rational number that approximates the given decimal number stored in k. Note that, instead of k, you can pass directly a decimal number, a rational number or even an array of such numbers as argument to the command sym:

» sym(1.2345),sym(12345/100000),sym([1.2345 2.3456])
 
ans =
 
2469/2000
 
 
ans =
 
2469/20000
 
 
ans =
 
[ 2469/2000,  1466/625]

Instead of the default rational format you can also choose floating-point formats by passing a second, option parameter to the command sym. Type help sym for details.
Notice the subtle difference in the symbolic answers as compared to the answers of numerical manipulations: the output is left aligned.

2. Symbolic expressions and operations

If symbolic variables are defined you can construct symbolic expressions by applying arithmetic operations. For example,

» f=5.1*x^3+a*x^2+b*x+c
 
f =
 
51/10*x^3+a*x^2+b*x+c

defines a cubic polynomial in x with a symbolically (by default in rational form) represented numerical cubic coefficient and whose lower order coefficients are symbolic variables. You can also access standard functions such as trig-functions, exponentials etc:

» g=sin(x)*exp(-x)-sinh(x)*x^2
 
g =
 
sin(x)*exp(-x)-sinh(x)*x^2

In MATLAB the expressions f, g are nothing than other symbolic variables and you can combine them to define further expressions:

» f*g+a*c+1
 
ans =
 
(51/10*x^3+a*x^2+b*x+c)*(sin(x)*exp(-x)-sinh(x)*x^2)+a*c+1

There are numerous operations you can perform with symbolic expressions. Type help symbolic for an overview. If you want a detailed description of a particular operation, e.g. subs, type help subs. We describe shortly four of these operations.

2.1  The command subs. With this command you can replace variables in an expression by other variables or numbers:

» subs(f,a,c),subs(f,a,1)
 
ans =
 
51/10*x^3+c*x^2+b*x+c
 
 
ans =
 
51/10*x^3+x^2+b*x+c

For multiple substitutions you need parantheses:

» subs(f,{a,b},{c,1})
 
ans =
 
51/10*x^3+c*x^2+x+c

replaces a by c and b by 1. If a substitution is made such that all variables are replaced by numbers, the answer is a floating-point number (class double):

» subs(g,x,1)

ans =

   -0.8656

2.2 The command diff. Three Examples:

» diff(f),diff(f,x),diff(f,a)
 
ans =
 
153/10*x^2+2*a*x+b
 
 
ans =
 
153/10*x^2+2*a*x+b
 
 
ans =
 
x^2

With the command diff(f) the derivative of f with respect to the default variable is found. The default variable is x or, if x does not occur, the variable ‘closest to’ x. You can specifiy the variable with respect to which you want the derivative to be computed in the second argument. Thus diff(f,x) and diff(f) yield the same answer while diff(f,a) finds the derivative with respect to a. Higher derivatives can be computed easily as well by specifying in the third argument the order of the derivative:

» diff(f,2),diff(f,a,2)
 
ans =
 
153/5*x+2*a
 
 
ans =
 
0

You can use this command to verify (or falsify) that a given function is a solution to an ODE.

Example: Verify that  y(x) = c  (arbitrary constant c) is a solution to y’+2xy=0.

Answer: The variables x, c and y are already declared, so we only need to assign to y the given function and substitute this in the ODE:

» y=c*exp(-x^2);
» diff(y)+2*x*y
 
ans =
 
0

Since the l.h.s. of the ODE evaluates to zero when y(x) is substituted, y(x) is indeed a solution.

2.3 The command int. This command finds the indefinite integral (antiderivative) of a function. The synatx is basically the same as for diff. Examples:

» int(f),int(f,a)
 
ans =
 
51/40*x^4+1/3*a*x^3+1/2*b*x^2+c*x
 
 
ans =
 
51/10*a*x^3+1/2*a^2*x^2+b*x*a+a*c

2.4 The command expand. Example:

» h=(1+1/x+x)^2
 
h =
 
(1+1/x+x)^2
 
» h=expand(h)
 
h =
 
3+2/x+2*x+1/x^2+x^2
 
The command pretty(h) will give you a nicer display of the output (try it).

MATLAB provides a number of pedagogical and graphical applications. For example, with funtool (just type funtool and press the enter key) you can edit functions, perform symbolic operations by mouse clicks and at the same time get graphs of the functions. This and other tools are listed when typing help symbolic.


3. Using the MAPLE kernel
(Skip this if you are not familiar with or interested in using MAPLE.)

If you are familiar with MAPLE, you probably have realized that the symbolic commands used so far are more or less MAPLE commands. What actually happens in a symbolic computation is that the expressions and commands are passed to the MAPLE kernel, evaluated by MAPLE and then returned to the MATLAB workspace. MATLAB offers the possibility to directly access the MAPLE kernel (but not in the student version!) and execute MAPLE commands. Although most of the symbolic calculations you may want to do in M340 can be performed with the symbolic tools buildt into MATLAB, there are some useful MAPLE operations for which MATLAB does not provide equivalent commands. It therefore follows a short description of how to use MAPLE directly.

Suppose you want to expand the symbolic expression   using the MAPLE kernel. MATLAB provides the command maple through which you can access this symbolic package:

» y=maple('expand((1+x)^2)')

y =

1+2*x+x^2

Obviously you get the right answer, but if you want to manipulate the result further symbolically in the MATLAB workspace,

» y^2
??? Error using ==> ^
Matrix must be square.

you get an error message. The reason is that the answer of a MAPLE calculation is not returned to MATLAB as a symbolic variable but as a character string:

» class(y)

ans =

char

Note that this is also the format of the argument passed to the maple command which is signalled by the apostrophes. It is important to realize that the maple command accepts and returns only character strings. It is however not difficult to change the class of y to symbolic:

» y=sym(y);
» y^2
 
ans =
 
(1+2*x+x^2)^2
 
» class(y)

ans =

sym

via the previously discussed command sym. Remember that this command also accepts only character strings. Since before sym was applied y was already declared as a variable of the class char, the apostrophes had to be omitted.

Things become a bit trickier if you want to process a symbolic MATLAB expression in MAPLE.
The variable y is now in the class sym, so we can use y for demonstration. Through the command

» y=char(y);

we can change the class of y to char again. But if write

» maple('expand(y)')

ans =

y

we don’t get the answer we want because the string marked by the apostrophes is taken literally and not associated to our MATLAB variable y – despite the fact that y is a character string. To solve this problem we have to make an extended use of the maple command:

» z=maple('expand',y);z=sym(z);z^2
 
ans =
 
(1+2*x+x^2)^2

The first argument passed to the maple command is a valid MAPLE operator (expand) which has to be marked as a charcter string. The second argument is the character string that represents the symbolic expression to which the operator is to be applied – our variable y. Since y has already been converted to the class char, we must omit the apostrophes. Note that you can directly pass char(symvar) as second argument to maple if symvar is a defined symbolic variable, i.e. you don’t need to do the conversion first in an extra step.

Until now there exists no symbolic MATLAB tool for finding a partial fraction decomposition, but MAPLE can do this. Using the maple command as described before, a short way to find the partial fraction decomposition of a symbolic MATLAB expression would be as follows. The nominator of

» z=1/(1+x)^2/(2+x)

has a double zero at x=-1 and a simple zero at x=-2. The command

» maple('convert',char(z),'parfrac','x');sym(ans)
 
ans =
 
1/(1+x)^2-1/(1+x)+1/(2+x)

then directly returns the partial fraction decomposition of z as valid symbolic MATLAB expression. Note that in this case three operands had to be passed to the convert – command.

Another (more tedious) method to access MAPLE is to create a full character string that represents a or several valid MAPLE commands. Suppose we want to factorize the sum y+z, where y, z are the symbolic variables defined by

» y=(1+x)^2;z=(1-x^2)^2;

One way to find the factorization with MAPLE is simply to just type (using ‘Copy’ and ‘Paste’ from The Editor menue of the Command Window) the formuale of y,z into the maple command:

» maple(‘y:=(1+x)^2:z:=(1-x^2)^2:w:=factor(y+z):w’);w=sym(ans)

w =
 
(x^2-2*x+2)*(1+x)^2

Here we have executed three MAPLE commands in succession. The string passed to maple has exactly the form you would use in a command line of a MAPLE worksheet. The first two commands have been ended by colons to suppress printing - if semicolons would be used the resulting output string would not be convertible to a symbolic MATLAB expression without further manipulation. Through the first two commands the definitions of y,z are now also stored in MAPLE and you can access them in further MAPLE computations and convert the results to symbolic MATLAB expressions, e.g.

v=sym(maple('expand(w^2)'))
 
v =
 
4+8*x+4*x^5-2*x^6+x^8+5*x^4-4*x^3

Editing formulae may become cumbersome if the expressions associated with symbolic variables are very long. In such cases it may become desirable to construct the string passed to maple in a different way. Since we have already access to the formulae of the variables as character strings, we just have to concatenate strings appropriately. For string concatenation MATLAB provides the command strcat. The syntax is strcat(string1,string2,…), where a string which is not defined in the workspace must be marked by apostrophes as usual. The command

» string=strcat('y:=',char(y),':z:=',char(z),':w:=factor(y+z):w')

string =

y:=(1+x)^2:z:=(1-x^2)^2:w:=factor(y+z):w

creates the string which before was generated by ‘typing’. Then the commands

» maple(string);w=sym(ans)

produce the same symbolic variable w as before.