The software described in this document is furnished under a license agreement. The software may be used
or copied only under the terms of the license agreement. No part of this manual may be photocopied or
reproduced in any form without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation
by, for, or through the federal government of the United States. By accepting delivery of the Program or
Documentation, the government hereby agrees that this software or documentation qualifies as commercial
computer software or commercial computer software documentation as such terms are used or defined
in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and conditions of
this Agreement and only those rights specified in this Agreement, shall pertain to and govern the use,
modification, reproduction, release, performance, display, and disclosure of the Program and Documentation
by the federal government (or other entity acquiring for or through the federal government) and shall
supersede any conflicting contractual terms or conditions. If this License fails to meet the government’s
needs or is inconsistent in any respect with federal procurement law, the government agrees to return the
Program and Documentation, unused, to The MathWorks, Inc.
Trademarks
MuPAD is a registered trademark of SciFace Software GmbH & Co. KG. MATLAB and Simulink
are registered trademarks of The MathWorks, Inc. See
of additional trademarks. Other product or brand names may be trademarks or registered
trademarks of their respective holders.
Patents
The MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
y SciFace Software GmbH & Co. KG.
www.mathworks.com/trademarks for a list
Preface
This book explains the basic use of the MuPAD®computer algebra system, and
gives some insight into the power of the system. MuPAD is available as part of the
Symbolic Math Toolbox™ in MATLAB®.
The book does not include the information about the latest features available in
MuPAD. The updated documentation is available in the MuPAD Help Browser.
To open the Help Browser, start MuPAD and click the Open Help button on the
desktop toolbar or use the Help menu. Also see the Release Notes section in the
MuPAD Help Browser for the short summary of the new features, bug fixes, and
upgrade issues.
This introduction addresses mathematicians, engineers, computer scientists,
natural scientists and, more generally, all those in need of mathematical
computations for their education or their profession. Generally speaking, this
book addresses anybody who wants to use the power of a modern computer
algebra package.
There are two ways to use a computer algebra system. On the one hand, you may
use the mathematical knowledge it incorporates by calling system functions
interactively. For example, you can compute symbolic integrals or generate and
invert matrices by calling appropriate functions. They comprise the system’s
mathematical intelligence and may implement sophisticated algorithms.
Chapters 2 through 14 discuss this way of using the MuPAD engine.
On the other hand, with the help of the MuPAD programming language, you can
easily add functionality to the system by implementing your own algorithms as
MuPAD procedures. This is useful for special purpose applications if no
appropriate system functions exist. Chapters 15 through 17 are an introduction to
MuPAD programming.
You can read this book in the standard way “linearly” from the first to the last
page. However, there are reasons to proceed otherwise. This may be the case, e.g.,
if you are interested in a particular problem, or if you already know something
about MuPAD.
For beginners, we recommend to start reading Chapter 2, which gives a first
survey of MuPAD. The description of the online help system in Section 2.2 is
probably the most important part of this chapter. The help system provides
information about details of system functions, their syntax, their calling
Preface
parameters, etc. It is available online whenever the MuPAD notebook interface is
running. In the beginning, requesting a help page is probably your most frequent
query to the system. After you have grown familiar with the help system, you may
start to experiment with MuPAD. Chapter 2 demonstrates some of the most
important system functions “at work.” You will find further details about these
functions in later parts of the book or in the help pages. For a deeper
understanding of the data structures involved, you may consult the corresponding
sections in Chapter 4.
Chapter 3 discusses the MuPAD libraries and their use. They contain many
functions and algorithms for particular mathematical topics.
The basic data types and the most important system functions for their
manipulation are introduced in Chapter 4. It is not necessary to study all of them
in the same depth. Depending on your intended application, you may selectively
read only the passages about the relevant topics.
Chapter 5 explains how MuPAD evaluates objects; we strongly recommend to read
this chapter.
Chapters 6 through 11 discuss the use of some particularly important system
functions: substitution, differentiation, symbolic integration, equation solving,
random number generation, and graphic commands.
Several useful features such as the history mechanism, input and output routines,
or the definition of user preferences are described in Chapters 13.2 through 13.
Preferences can be used to configure the system’s interactive behavior after the
user’s fancy to a certain extent.
Chapters 15 through 17 give an introduction to the basic concepts of the MuPAD
programming language.
MuPAD provides algorithms that can handle a large class of mathematical objects
and computational tasks related to them. Upon reading this introduction, it is
possible that you encounter unknown mathematical notions such as rings or
fields. This introduction is not intended to explain the mathematical background
for such objects. Basic mathematical knowledge is helpful but not mandatory to
understand the text. Sometimes you may ask what algorithm MuPAD uses to
solve a particular problem. The internal mode of operation of the MuPAD
procedures is not addressed here: we do not intend to give a general introduction
to computer algebra and its algorithms. The interested reader may consult text
ii
books such as, e.g., [GCL 92] or [GG 99].
This book gives an elementary introduction to MuPAD. Somewhat more abstract
mathematical objects such as, e.g., field extensions, are easy to describe and to
handle in MuPAD. However, such advanced aspects of the system are not
discussed here. The mathematical applications that are mentioned in the text are
intentionally kept on a rather elementary level. This is to keep this text plain for
readers with little mathematical background and to make it applicable at school
level.
We cannot explain the complete functionality of MuPAD in this introduction.
Some parts of the system are mentioned only briefly. It is beyond the scope of this
tutorial to go into the details of the full power of the MuPAD programming
language. You find these in the MuPAD help system, available online during a
MuPAD session.
This tutorial refers to MuPAD version 5 and later. Since the development of the
system advances continuously, some of the details described may change in the
future. Future versions will definitely provide additional functionality through
new system functions and application packages. In this tutorial, we mainly
present the basic tools and their use, which will probably remain essentially
unchanged. We try to word all statements in the text in such a way that they stay
basically valid for future MuPAD versions.
To explain the notion of computer algebra, we compare algebraic and numerical
computations. Both kinds are supported by a computer, but there are
fundamental differences, which are discussed in what follows.
1
1Introduction
Numerical Computations
Many a mathematical problem can be solved approximately by numerical
computations. The computation steps operate on numbers, which are stored
internally in floating-point representation. This representation has the drawback
that neither computations nor solutions are exact due to rounding errors. In
general, numerical algorithms find approximate solutions as fast as possible.
Often such solutions are the only way to handle a mathematical problem
computationally, in particular if there is no “closed form” solution known. (The
most popular example for this situation are roots of polynomials of high degrees.)
Moreover, approximate solutions are useful if exact results are unnecessary (e.g.,
in visualization).
1-2
Computer Algebra
In contrast to numerical computations, there are symbolic computations in
computer algebra. [Hec 93] defines them as “computations with symbolsrepresenting mathematical objects.” Here, an object may be a number, but also a
polynomial, an equation, an expression or a formula, a function, a group, a ring,
or any other mathematical object. Symbolic computations with numbers are
carried out exactly. Internally, numbers are represented as quotients of integers
of arbitrary length (limited by the amount of storage available, of course). These
kinds of computations are called symbolic or algebraic. [Hec 93] gives the
following definitions:
1. “Symbolic” emphasizes that in many cases the ultimate goal of mathematical
2. “Algebraic” means that computations are carried out exactly, according to
Computer Algebra
problem solving is expressing the answer in a closed formula or finding a
symbolic approximation.
the rules of algebra, instead of using approximate floating-point arithmetic.
Sometimes “symbolic manipulation” or “formula manipulation” are used as
synonyms for computer algebra, since computations operate on symbols and
formulae. Examples are symbolic integration or differentiation such as
x dx =
2
x
2
4
,
x dx =
1
15
d
,
2
ln ln x =
dx
1
x ln x
or symbolic solutions of equations. For example, we consider the equation
x4+ p x2+ 1 = 0 in x with one parameter p. Its solution set is
√
2−p −p2− 4
±
√
2−p +p2− 4
2
, ±
2
.
The symbolic computation of an exact solution usually requires more computing
time and more storage than the numeric computation of an approximate solution.
However, a symbolic solution is exact, more general, and often provides more
information about the problem and its solution. The above formula expresses the
solutions of the equation in terms of the parameter p. It shows how the solutions
1-3
1Introduction
depend functionally on p. This information can be used, for example, to examine
how sensitive the solutions behave when the parameter changes.
Combinations of symbolic and numeric methods are useful for special
applications. For example, there are algorithms in computer algebra that benefit
from efficient hardware floating-point arithmetic. On the other hand, it may be
useful to simplify a problem from numerical analysis symbolically before applying
the actual approximation algorithm.
1-4
Characteristics of Computer Algebra Systems
Most of the current computer algebra systems can be used interactively. The user
enters some formulae and commands, and the system evaluates them. Then it
returns an answer, which can be manipulated further if necessary.
In addition to exact symbolic computations, most computer algebra packages can
approximate solutions numerically as well. The user can set the precision to the
desired number of digits. In MuPAD®, the global variable DIGITS handles this.
For example, if you enter the simple command DIGITS:= 100, then MuPAD
performs all floating-point calculations with a precision of 100 decimal digits. Of
course, such computations need more computing time and more storage than the
use of hardware floating-point arithmetic.
Moreover, modern computer algebra systems provide a powerful programming
language1and tools for visualization and animation of mathematical data. Also,
many systems can produce layouted documents (known as notebooks or
worksheets). The MuPAD system has such a notebook concept, but we will only
sketch it briefly in this tutorial. Please check the user interface documentation
instead for more details. The goal of this book is to give an introduction to the
mathematical power of the MuPAD language.
Characteristics of Computer Algebra Systems
1
The MuPAD programming language is structured similarly to Pascal, with extensions such as lan-
guage constructs for object oriented programming.
1-5
1Introduction
MuPAD®Software
In comparison to other computer algebra systems, MuPAD®has the following
noteworthy features, which are not discussed in detail in this book:
• There are MuPAD language constructs for object oriented programming.
You can define your own data types, e.g., to represent mathematical
structures. Almost all existing operators and functions can be overloaded.
• There is a highly interactive MuPAD source code debugger.
• Programs written in C or C++ can be added to the kernel by the MuPAD
dynamic module concept.
The heart of the MuPAD engine is its kernel, which is implemented in C++. It
comprises the following main components:
– The parser reads the input to the system and performs a syntax check. If no
errors are found, it converts the input to a MuPAD data type.
1-6
– The evaluator processes and simplifies the input. Its mode of operation is
discussed later.
– The memory management is responsible for the efficient storage of MuPAD
objects.
– Some frequently used algorithms such as, e.g., arithmetical functions are
implemented as kernel functions in C.
Parser and evaluator define the MuPAD language as described in this book. The
MuPAD libraries, which contain most of the mathematical knowledge of the
system, are implemented in this language.
In addition, MuPAD offers comfortable user interfaces for generating notebooks
or graphics, or to debug programs written in the MuPAD language. The MuPAD
help system has hypertext functionality. You can navigate within documents and
execute examples by a mouse click.
Symbolic Math Toolbox™ also offers a way of using the MuPAD engine to solve
problems directly from the MATLAB®environment, using either commands as
MuPAD®Software
presented here or, for a selected subset of commands, alternatives fitting more
closely into a MATLAB language program. This book does not discuss these
options, but limits itself to using the MuPAD engine directly, along with the
MuPAD GUIs.
1-7
2
First Steps in MuPAD
Computer algebra systems such as MuPAD®are often used interactively. For
example, you can enter an instruction to multiply two numbers and have MuPAD
compute the result and print it on the screen.
The following section will give a short description of the user interface. The next
one after that describes the help system. Requesting a help page is probably the
most frequently used command for the beginner. The section after that is about
using MuPAD as an “intelligent pocket calculator”: calculating with numbers.
This is the easiest and the most intuitive part of this tutorial. Afterwards we
introduce some system functions for symbolic computations. The corresponding
section is written quite informally and gives a first insight into the symbolic
features of the system.
®
2First Steps in MuPAD
Notebook interface
®
After you call the MuPAD®program, you will see the welcome dialog. From there,
you can enter the help system (which is, of course, also available later and will be
described on page 2-4), open an existing file, create a new MuPAD source file or
open a new notebook. Usually, you will wish to open an existing or a new
notebook.
After starting the program, you can enter commands in the MuPAD language.
These commands should be typed into “input regions,” which look like this:
If you press the <Return> key, this finishes your input and MuPAD evaluates the
command that you have entered. Holding <Shift> while pressing <Return>
provokes a linefeed, which you can use to format your input.
After invoking the command, you will see its result printed in the same bracket,
below the input, and if you were at the end of the notebook, a new input region
will be opened below:
2-2
sin(3.141)
0.0005926535551
The system evaluated the usual sine function at the point 3.141 and returned a
floating-point approximation of the value, similar to the output of a pocket
calculator.
You can at any time go back to older inputs and edit them. Also, you can click
between the brackets and add text. Editing output is not possible, but you can
copy formulas from the output and paste them someplace else. (When copying a
formula to an input region, it will be automatically translated into an equivalent
command in textual form.)
If you terminate your command with a colon, then MuPAD executes the command
without printing its result on the screen. This enables you to suppress the output
of irrelevant intermediate results.
Notebook interface
You can enter more than one command in one line. Two subsequent commands
have to be separated by a semicolon or a colon, if the result of the first command
is to be printed or not, respectively:
diff(sin(x^2), x); int(%, x)
2 x cosx
sin
2
2
x
Here x^2 denotes the square of x, and the MuPAD functions diff and int
perform the operations “differentiate” and “integrate” (Chapter 7). The character
% returns the previous expression (in the example, this is the derivative of sin(x
2
The concept underlying % is discussed in Chapter 13.2.
In the following example, the output of the first command is suppressed by the
colon, and only the result of the second command appears on the screen:
equations := {x + y = 1, x - y = 1}:
solve(equations)
{[x = 1, y = 0]}
In the previous example, a set of two equations is assigned to the identifier
equations. The command solve(equations) computes the solution. Chapter 8
discusses the solver in more detail.
To quit a MuPAD session, use the corresponding entry in the “File” menu.
)).
2-3
2First Steps in MuPAD
®
Explanations and Help
If you do not know the correct syntax of a MuPAD®command, you can obtain this
information directly from the online help system. For a brief explanation, simply
type the command name, point your mouse cursor at the command and let it rest
there for a moment. You will get a tooltip with a brief explanation.
The help page of the corresponding function provides more detailed information.
You can request it by entering help("name"), where name is the name of the
function. The function help expects its argument to be a string, which is
generated by double quotes " (Section 4.11). The operator ? is a short form for
help. It is used without parenthesis or quotes:
The help system is a hypertext system, i.e., similar to browsing the web. Active
keywords are underlined. If you click on them, you obtain further information
about the corresponding notion. The tooltips mentioned above also work in the
help system. You can edit and execute the examples in the help system or copy
and paste them to a notebook.
?solve
2-4
Exercise 2.1: Find out how to use the MuPAD differentiator diff, and compute
the fifth derivative of sin(x
2
).
Computing with Numbers
To compute with numbers, you can use MuPAD®like a pocket calculator. The
result of the following input is a rational number:
1 + 5/2
7
2
You see that the returns are exact results (and not rounded floating-point
numbers) when computing with integers and rational numbers:
(1 + (5/2*3))/(1/7 + 7/9)^2
67473
6728
The symbol ^ represents exponentiation. MuPAD can compute big numbers
efficiently. The length of a number that you may compute is only limited by the
available main storage. For example, the 123rd power of 1234 is a fairly big
integer:
The function isprime checks whether a positive integer is prime. It returns either
TRUE or FALSE.
isprime(123456789)
FALSE
Using ifactor, you can obtain the prime factorization:
ifactor(123456789)
32· 3607 · 3803
Exact Computations
2-6
Now suppose that we want to “compute” the number
56. The problem is that the
value of this irrational number cannot be expressed as a quotient
numerator/denominator of two integers exactly. Thus “computation” can only
√
mean to find an exact representation that is as simple as possible. When you
√
input
56 via sqrt, MuPAD returns the following:
sqrt(56)
2√14
√
The result of the simplification of
56 is the exact value 2 ·√14. In MuPAD,√14
(or, sometimes, 14^(1/2)) represents the positive solution of the equation
x2= 14. Indeed, this is probably the most simple representation of the result. We
stress that
√
14 is a genuine object with certain properties (e.g., that its square can
be simplified to 14). The system applies them automatically when computing with
such objects. For example:
sqrt(14)^4
196
Computing with Numbers
As another example for exact computation, let us determine the limit
e = lim
n→∞
1 +
n
1
.
n
We use the function limit and the symbol infinity:
limit((1 + 1/n)^n, n = infinity)
e
To enter this number in MuPAD, you have to use E or exp(1), where exp
represents the exponential function. MuPAD knows exact rules of manipulation
for this object. For example, using the natural logarithm ln we find:
ln(1/exp(1))
−1
We will encounter more exact computations later in this tutorial.
Numerical Approximations
Besides exact computations, MuPAD can also perform numerical approximations.
For example, you can use the function float to find a decimal approximation to
√
56. This function computes the value of its argument in floating-point
representation:
float(sqrt(56))
7.483314774
The precision of the approximation depends on the value of the global variable
DIGITS, which determines the number of decimal digits for numerical
computations. Its default value is 10:
DIGITS; float(67473/6728)
10
10.02868609
2-7
2First Steps in MuPAD
®
Global variables such as DIGITS affect the behavior of MuPAD, and are also called
environment variables.2You find a complete list of all environment variables in
Section “Environment Variables” of the MuPAD Quick Reference in the online
documentation. The variable DIGITS can assume any integral value between 1 and
232− 1, although 1000 can already be considered very large and it is unlikely that
using more than 10 000 digits is reasonable for anything but the most unusual
calculations:
We have reset the value of DIGITS to 10 for the following computations. This can
also be achieved via the command delete DIGITS. For arithmetic operations with
numbers, MuPAD automatically uses approximate computation as soon as atleast one of the numbers involved is a floating-point value:
(1.0 + (5/2*3))/(1/7 + 7/9)^2
10.02868609
Please note that none of the two following calls
2-8
2/3*sin(2), 0.6666666666*sin(2)
results in an approximate computation of sin(2), since, technically, sin(2) is an
expression representing the (exact) value of sin(2) and not a number:
2/3*sin(2), 0.6666666666*sin(2)
2 sin(2)
, 0.6666666666 sin(2)
3
(The separation of both values by a comma generates a special data type, namely a
sequence, which is described in Section 4.5.)
2
You should be particularly cautious when the same computation is performed with different values
of DIGITS. Some of the more intricate numerical algorithms in MuPAD employ the option “remember.”
This implies that they store previously computed values to be used again (Section 17.9), which can lead
to inaccurate numerical results if the remembered values were computed with lower precision. To be
safe, you should restart the MuPAD session using reset() before increasing the value of DIGITS. This
command clears memory and resets all environment variables to their default values (Section 13.4).
Computing with Numbers
You have to use the function float to compute floating-point approximations of
the above expressions:
float(2/3*sin(2)), 0.6666666666*float(sin(2))
3
0.6061982846, 0.6061982845
Most arithmetic functions,such as the square root, the trigonometric functions,
the exponential function, or the logarithm, automatically return approximate
values when their argument is a floating-point number:
sqrt(56.0), sin(3.14)
7.483314774, 0.001592652916
The constants π and e are denoted by PI and E = exp(1), respectively. MuPAD can
perform exact computations with them:
cos(PI), ln(E)
−1, 1
If desired, you can obtain numerical approximations of these constants by
applying float:
27 − 2√3 and cos(π /8) exactly. Determine numerical
approximations to a precision of 5 digits.
Complex Numbers
The imaginary unit
and an upright i in the typeset output:
3
Take a look at the last digits. The second command yields a slightly less accurate result, since
0.666 . . . is already an approximation of 2/3 and the rounding error is propagated to the final result.
√
−1 is represented in MuPAD by the symbol I in the input
2-9
2First Steps in MuPAD
®
sqrt(-1), I^2
i, −1
You can input complex numbers in the usual mathematical notation x + y i. Both
the real part x and the imaginary part y may be integers, rational numbers, or
floating-point numbers:
(1 + 2*I)*(4 + I), (1/2 + I)*(0.1 + I/2)^3
2 + 9 i, 0.073 − 0.129 i
If you use symbolic expressions such as, e.g., sqrt(2), MuPAD may not return the
result of a calculation in Cartesian coordinates:
1/(sqrt(2) + I)
1
√
2 + i
The function rectform (short for: rectangular form) ensures that the result is split
into its real and imaginary parts:
rectform(1/(sqrt(2) + I))
√
2
i
−
3
3
2-10
The functions Re and Im return the real part x and the imaginary part y,
respectively, of a complex number x + y i. The functions conjugate, abs, and arg
compute the complex conjugate x − y i, the absolute value |x + y i| =
This section comprises some examples of MuPAD®sessions that illustrate a small
selection of the system’s power for symbolic manipulation. The mathematical
knowledge is contained essentially in the MuPAD functions for differentiation,
integration, simplification of expressions etc. This demonstration does not
proceed in a particularly systematic manner: we apply the system functions to
objects of various types, such as sequences, sets, lists, expressions etc. They are
explained in detail one by one in Chapter 4.
Introductory Examples
A symbolic expression may contain undetermined quantities (identifiers). The
following expression contains two unknowns x and y:
f := y^2 + 4*x + 6*x^2 + 4*x^3 + x^4
x4+ 4 x3+ 6 x2+ 4 x + y
Symbolic Computation
2
Using the assignment operator :=, we have assigned the expression to an
identifier f, which can now be used as an abbreviation for the expression. We say
that the latter is the value of the identifier f. We note that MuPAD has exchanged
the order of the terms.
4
MuPAD offers the system function diff for differentiating expressions:
diff(f, x), diff(f, y)
4 x3+ 12 x2+ 12 x + 4, 2 y
Here, we have computed both the derivative with respect to x and to y. You may
obtain higher derivatives either by nested calls of diff, or by a single call:
diff(diff(diff(f, x), x), x) = diff(f, x, x, x)
24 x + 24 = 24 x + 24
4
Internally, symbolic sums are ordered according to certain rules that enable the system to access
the terms faster. Of course, such a reordering of the input happens only for commutative operations such
as, e.g., addition or multiplication, where changing the order of the operands yields a mathematically
equivalent object.
2-11
2First Steps in MuPAD
®
Alternatively, you can use the differential operator ', which maps a function to its
derivative:
sin', sin'(x)
cos, cos(x)
The symbol ' for the derivative is a short form of the differential operator D. The
call D(function) returns the derivative:
D(sin), D(sin)(x)
cos, cos(x)
Note: MuPAD uses a mathematically strict notation for the differential operator: D
(or, equivalently, the ' operator) differentiates functions, while diff differentiates
expressions. In the example, the ' maps the (name of the) function to the (name
of the) function representing the derivative. You often find a sloppy notation such
as, e.g., (x + x
2)′
for the derivative of the function F : x 7→ x + x2. This notation
confuses the map F and the image point f = F (x) at a point x. MuPAD has a
strict distinction between the function F and the expression f = F (x), which are
realized as different data types. The map corresponding to f can be defined by
2-12
F := x -> x + x^2:
Then
diff(F(x), x) = F'(x)
2 x + 1 = 2 x + 1
are equivalent ways of obtaining the derivative as expressions. The call
f:= x + x^2; f'; does not make sense in MuPAD.
You can compute integrals by using int. The following command computes a
definite integral on the real interval between 0 and 1:
int(f, x = 0..1)
26
y2+
5
Symbolic Computation
The next command determines an indefinite integral and returns an expression
containing the integration variable x and a symbolic parameter y:
int(f, x)
5
x
+ x4+ 2 x3+ 2 x2+ x y
5
2
Note that int returns a special antiderivative, not a general one (with additive
constant).
If you try to compute the indefinite integral of an expression and it cannot be
represented by elementary functions, then int returns the call symbolically:
integral := int(1/(exp(x^2) + 1), x)
1
dx
2
x
e
+ 1
Nevertheless, this object has mathematical properties. The differentiator
recognizes that its derivative is the integrand:
diff(integral, x)
1
2
x
e
+ 1
Definite integrals may also be returned symbolically by int:
int(1/(exp(x^2) + 1), x = 0..1)
1
1
dx
2
x
e
+ 1
0
The corresponding mathematical object is a real number, and the output is an
exact representation of this number, which MuPAD was unable to simplify further.
As usual, you can obtain a floating-point approximation by applying float:
float(%)
0.41946648
As already noted, the symbol % is an abbreviation for the previously computed
expression (Chapter 13.2).
MuPAD knows the most important mathematical functions such as the square
2-13
2First Steps in MuPAD
®
root sqrt, the exponential function exp, the trigonometric functions sin, cos, tan,
the hyperbolic functions sinh, cosh, tanh, the corresponding inverse functions ln,
arcsin, arccos, arctan, arcsinh, arccosh, arctanh, as well as a variety of other
special functions such as, e.g., the gamma function, the error function erf, Bessel
functions (besselI, besselJ, …), etc. (Section “Special Mathematical Functions”
of the MuPAD Quick Reference gives a survey.) In particular, MuPAD knows the
rules of manipulation for these functions (e.g., the addition theorems for the
trigonometric functions) and applies them. It can compute floating-point
approximations such as, e.g., float(exp(1)) = 2.718..., and knows special
values (e.g., sin(PI) = 0).
If you call these functions, they often return themselves symbolically, since this is
the most simple exact representation of the corresponding value:
sqrt(2), exp(1), sin(x + y)
√
2, e, sin(x + y)
For many users, the main feature of the system is to simplify or transform such
expressions using the rules for computation. For example, the system function
expand “expands” functions such as exp, sin, etc. by means of the addition
Generally speaking, one of the main tasks of a computer algebra system is to
manipulate and to simplify expressions. Besides expand, MuPAD provides the
functions collect, combine, factor, normal, partfrac, radsimp, rewrite,
simplify, and Simplify for manipulation. They are presented in greater detail in
Chapter 9. We briefly mention some of them in what follows.
The function normal finds a common denominator for rational expressions:
f := x/(1 + x) - 2/(1 - x): g := normal(f)
x2+ x + 2
x2− 1
Symbolic Computation
Moreover, normal automatically cancels common factors in the numerator and
the denominator:
normal(x^2/(x + y) - y^2/(x + y))
x − y
Conversely, partfrac (short for “partial fraction”) decomposes a rational
expression into a sum of rational terms with simple denominators:
partfrac(g, x)
2
x − 1
−
1
x + 1
+ 1
The functions simplify and Simplify are universal simplifiers and try to find a
representation that is as “simple” as possible:
simplify((exp(x) - 1)/(exp(x/2) + 1))
x
2
e
− 1
You may control the simplification by supplying simplify or Simplify with
additional arguments (see the online documentation for details).
The function radsimp simplifies arithmetical expressions containing radicals
(roots):
f := sqrt(4 + 2*sqrt(3)): f = radsimp(f)
√
√
2
3 + 2 =√3 + 1
Here, we have generated an equation, which is a genuine MuPAD object.
Another important function is factor, which decomposes an expression into a
product of simpler ones:
The function limit does what its name suggests. For example, the function
sin(x)/x has a removable pole at x = 0. Its limit for x → 0 is 1:
limit(sin(x)/x, x = 0)
1
In a MuPAD session, you can define functions of your own in several ways. A
simple and intuitive method is to use the arrow operator -> (the minus symbol
followed by the “greater than” symbol):
F := x -> (x^2):F(x), F(y), F(a + b), F'(x)
x2, y2, (a + b)2, 2 x
In Chapter 17, we discuss MuPAD programming features and describe how to
implement more complex algorithms as MuPAD procedures.
You can also use the graphics facilities to visualize mathematical objects
immediately. The relevant MuPAD functions for generating graphics are the plot
command and the routines from the graphics library plot. Here, we present
simple calls only, please consult Chapter 11 for in-depth information:
2-16
plot(sin(x^2), x = -2..5)
Symbolic Computation
plot(sin(x^2 + y^2), x = 0..PI, y = 0..PI, #3D)
Solving equations or systems of equations is certainly an important task for a
computer algebra system. This is done via solve:
equations := {x + y = a, x - a*y = b}:
unknowns := {x, y}:
solve(equations, unknowns, IgnoreSpecialCases)
x =
a2+ b
a + 1
, y =
a − b
a + 1
Here, we have generated a set of two equations and a set of unknowns which we
wish to solve for. solve returns the result in terms of simplified equations, from
which you can read off the solution. In the above example, there are two more
symbolic parameters a and b. This is why we have told solve which of the symbols
it should express in terms of the others. The “option” IgnoreSpecialCases tells
MuPAD to ignore the possibility that a could be −1, where the above solution
would be incorrect. Without this option, MuPAD returns a complete solution with
three branches:
2-17
2First Steps in MuPAD
®
solve(equations, unknowns)
a2+b
x =
a+1
, y =
{[x = −z − 1, y = z]}if a = −1 ∧ b = −1
∅if a = −1 ∧ b = −1
a−b
a+1
if a = −1
In the following example, we have only one equation in one unknown. MuPAD
automatically recognizes the unknown and solves for it:
solve(x^2 - 2*x + 2 = 0)
{[x = 1 − i] , [x = 1 + i]}
If we supply the unknown x to solve for, the format of the output changes:
solve(x^2 - 2*x + 2 = 0, x)
{1 − i, 1 + i}
The result is a set containing the two (complex) solutions of the quadratic
equation. You find a detailed description of solve in Chapter 8.
2-18
The functions sum and product handle symbolic sums and products. For example,
the well-known sum 1 + 2 + ·· · + n is:
sum(i, i = 1..n)
n (n + 1)
2
The product 1 · 2 ···n is known as factorial n!:
product(i^3, i = 1..n)
3
n!
Symbolic Computation
There exist several data structures for vectors and matrices. In principle, you may
use arrays (Section 4.9) to represent such objects. However, it is far more intuitive
to work with the data type “matrix.” You can generate matrices by using the
system function matrix:
A := matrix([[1, 2], [a, 4]])
1 2
a 4
Matrix objects constructed this way have the convenient property that the basic
arithmetic operations +, *, etc. are specialized (“overloaded”) according to the
appropriate mathematical context. For example, you may use + or * to add or
multiply matrices, respectively (if the dimensions match):
B := matrix([[y, 3], [z, 5]]):
A, B, A + B, A*B
1 2
a 4
,
y 3
z 5
,
y + 1 5
a + z 9
,
y + 2 z13
4 z + a y 3 a + 20
The power A^(-1), equivalent to 1/A, denotes the inverse of the matrix:
A^(-1)
−
2 a−4
2
a−21a−2
a
−
1
2 a−4
The function linalg::det, from the MuPAD linalg library for linear algebra
(Section 4.15), computes the determinant:
linalg::det(A)
4 − 2 a
Column vectors of dimension n can be interpreted as n × 1 matrices:
b := matrix([1, x])
1
x
2-19
2First Steps in MuPAD
®
−1
You can comfortably determine the solution A
equations Ax =
b, with the above coefficient matrix A and the previously definedb
b of the system of linear
on the right-hand side:
solutionVector := A^(-1)*b
x
−
a−2
a
−
2 a−4
2
a−2
x
2 a−4
Now you can apply the function normal to each component of the vector by means
of the system function map, thus simplifying the representation:
map(%, normal)
x−2
a−2
a−x
2 a−4
To verify the computation, you may multiply the solution vector by the matrix A:
A * %
x−2
a−2
4 (a−x)
2 a−4
+
+
2 (a−x)
2 a−4
a (x−2)
a−2
2-20
After simplification, you can check that the result equals b:
map(%, normal)
1
x
Section 4.15 provides more information on handling matrices and vectors.
2
Exercise 2.3: Compute an expanded form of the expression (x
Exercise 2.4: Use MuPAD to check that
x2− 1
x + 1
= x − 1 holds.
+ y)
5
.
Exercise 2.5: Generate a plot of the function 1/ sin(x) for 1 ≤ x ≤ 10 .
Symbolic Computation
Exercise 2.6: Obtain detailed information about the function limit. Use
MuPAD to verify the following limits:
lim
x→0
lim
x→0
lim
x→0+
The limit lim
x→0
sin(x)
x
sin(x)
x
ln(x)
x
cot(x)
e
= 1 ,lim
= 1 ,lim
= ∞ ,lim
does not exist. How does MuPAD react?
x→0
x→∞
x→∞
1 − cos(x)
x
1 +
1 +
1
x
π
x
= 0 ,lim
x
= e ,lim
x
= eπ,lim
x→0+
x→∞
x→0−
ln(x) = −∞,
ln(x)
= 0 ,
x
e
2
= 0 .
−1/x
1 + e
Exercise 2.7: Obtain detailed information about the function sum. The call
sum(f(k), k = a..b) computes a closed form of a finite or infinite sum, if possible.
Use MuPAD to verify the following identity:
n
(k2+ k + 1) =
k=1
n (n2+ 3 n + 5)
3
.
Determine the values of the following series:
∞
(k + 1) (k + 2) (k + 3)
k=0
2 k − 3
∞
,
(k − 1)2(k + 1)
k=2
k
.
2
Exercise 2.8: Compute 2 · (A + B), A · B, and (A − B)−1for the following
matrices:
A =
1 2 3
4 5 6
7 8 0
,B =
1 1 0
0 0 1
0 1 0
.
Curve Sketching
In the following sample session, we use some of the system functions from the
previous section to sketch and discuss the curve given by the rational function
f : x 7→
(x − 1)
x − 2
2
+ a
2-21
2First Steps in MuPAD
®
with a parameter a. First, we determine some characteristics of this function:
discontinuities, extremal values, and behavior for large x. We assume that a is a
real number.
assume(a in R_):
f := x -> (x - 1)^2/(x - 2) + a:
singularities := discont(f(x), x)
{2}
The function discont determines the discontinuities of the function f with
respect to the variable x. It returns a set of such points. Thus, the above f is
defined and continuous for all x = 2. Obviously, x = 2 is a pole. Indeed, MuPAD
finds the limit ∓∞ when you approach this point from the left or from the right,
respectively:
limit(f(x), x = 2, Left), limit(f(x), x = 2, Right)
−∞, ∞
You find the roots of f by solving the equation f (x) = 0:
roots := solve(f(x) = 0, x)
1 −
√
a2+ 4 a
√
a
2
,
a2+ 4 a
2
−
−
2
a
+ 1
2
®
2-22
Depending on a, either both or none of the two roots are real. Now, we want to
find the local extrema of f . To this end, we determine the roots of the first
derivative f′:
f'(x)
2 x − 2
x − 2
extrema := solve(f'(x) = 0, x)
−
(x − 1)
(x − 2)
2
2
{1, 3}
These are the candidates for local extrema. However, some of them might be
saddle points. If the second derivative f′′does not vanish at these points, then
both are really extrema. We check:
Symbolic Computation
f''(1), f''(3)
−2, 2
Our results imply that f has the following properties: for any choice of the
parameter a, there is a local maximum at x = 1, a pole at x = 2, and a local
minimum at x = 3. The corresponding values of f at these points are
maxvalue := f(1); minvalue := f(3)
a
a + 4
f tends to ∓∞ for x → ∓∞:
limit(f(x), x = -infinity), limit(f(x), x = infinity)
−∞, ∞
We can specify the behavior of f more precisely for large values of x. It
asymptotically approaches the linear function x 7→ x + a:
series(f(x), x = infinity)
1
2
x + a +
+
x
4
+
2
x
+
3
x
x
8
+ O
4
1
5
x
Here we have employed the function series to compute an asymptotic expansion
of f (Section 4.13). We can easily check our results visually by plotting the graph
of f for several values of a:
F := f(x) | a = -4: G := f(x) | a = 0: H := f(x) | a = 4:
F, G, H
(x − 1)
x − 2
2
− 4,
(x − 1)
x − 2
2
,
(x − 1)
x − 2
2
+ 4
The operator | (Chapter 6) evaluates an expression at some point: in the example,
we have substituted the concrete values −4, 0 and 4, respectively, for a. We now
can plot the three functions together in one picture:
2-23
2First Steps in MuPAD
®
plot(F, G, H, x = -1..4)
Elementary Number Theory
2-24
MuPAD®provides a lot of elementary number theoretic functions, for example:
• isprime(n) tests whether n ∈ N is a prime number,
• ithprime(n) returns the n-th prime number,
• nextprime(n) finds the least prime number ≥ n,
• prevprime(n) finds the largest prime number ≤ n,
• ifactor(n) computes the prime factorization of n.
These routines are quite fast. However, since they employ probabilistic primality
tests, they may return wrong results with very small probability.5Instead of
isprime, you can use the (slower) function numlib::proveprime as an error-free
primality test.
5
In practice, you need not worry about this because the chances of a wrong answer are negligible:
the probability of a hardware failure is much higher than the probability that the randomized test returns
the wrong answer on correctly working hardware.
Symbolic Computation
Let us generate a list of all primes up to 10 000. Here is one of many ways to do
this:
primes := select([$ 1..10000], isprime)
[2, 3, 5, 7, 11, 13, 17, ..., 9949, 9967, 9973]
First, we have generated the sequence of all positive integers up to 10 000 by
means of the sequence generator $ (Section 4.5). The square brackets [ ] convert
this to a MuPAD list. Then select (Section 4.6) eliminates all those list elements
for which the function isprime, supplied as second argument, returns FALSE. The
number of these primes equals the number of list elements, which we can obtain
via nops (“number of operands,” Section 4.1):
nops(primes)
1229
Alternatively, we may generate the same prime list by
primes := [ithprime(i) $ i = 1..1229]:
Here we have used the fact that we already know the number of primes up to
10 000. Another possibility is to generate a large list of primes and discard the
ones greater than 10 000:
primes := select([ithprime(i) $ i=1..5000],
x -> (x<=10000)):
Here, the object x -> (x <= 10000) represents the function that maps each x to the
inequality x <= 10000. The select command then keeps only those list elements
for which the inequality evaluates to TRUE.
In the next example, we use a repeat loop (Chapter 15) to generate the list of
primes. With the help of the concatenation operator . (Section 4.6), we
successively append primes i to a list until nextprime(i+1), the next prime greater
than i, exceeds 10 000. We start with the empty list and the first prime i = 2 :
primes := []: i := 2:
repeat
primes := primes . [i];
i := nextprime(i + 1)
until i > 10000 end_repeat:
2-25
2First Steps in MuPAD
®
Now, we consider Goldbach’s famous conjecture:
“Every even integer greater than 2 is the sum of two primes.”
We want to verify this conjecture for all even numbers up to 10 000. First, we
generate the list of even integers [4, 6, …, 10000]:
list := [2*i $ i = 2..5000]:
nops(list)
4999
Now, we select those numbers from the list that cannot be written in the form
“prime + 2.” This is done by testing for each i in the list whether i − 2 is a prime:
list := select(list, i -> (not isprime(i - 2))):
nops(list)
4998
The only integer that has been eliminated is 4 (since for all other even positive
integers i − 2 is even and greater than 2, and hence not prime). Now we discard all
numbers of the form “prime + 3”:
2-26
list := select(list, i -> (not isprime(i - 3))):
nops(list)
3770
The remaining 3770 integers are neither of the form “prime + 2” nor of the form
“prime + 3.” We now continue this procedure by means of a while loop
(Chapter 15). In the loop, j successively runs through all primes > 3, and the
numbers of the form “prime + j” are eliminated. A print command (Section 12.1)
outputs the number of remaining integers in each step. The loop ends as soon as
the list is empty:
j := 3:
Symbolic Computation
while list <> [] do
j := nextprime(j + 1):
list := select(list, i -> (not isprime(i - j))):
print(j, nops(list)):
end_while:
5, 2747
7, 1926
11, 1400
...
163, 1
167, 1
173, 0
Thus we have confirmed that Goldbach’s conjecture holds true for all even
positive integers up to 10 000. We have even shown that all those numbers can be
written as a sum of a prime less or equal to 173 and another prime.
In the next example, we generate a list of distances between two successive primes
up to 500:
The indexed call primes[i] returns the ith element in the list.
2-27
2First Steps in MuPAD
®
The function zip (Section 4.6) provides an alternative method. The call
zip(a, b, f) combines two lists a = [a
, a2, . . . ] and b = [b1, b2, . . . ]
1
componentwise by means of the function f : the resulting list is
[f(a1, b1), f (a2, b2), . . . ]
and has as many elements as the shorter of the two lists. In our example, we apply
this to the prime list a = [a
, . . . , an], the “shifted” prime list b = [a2, . . . , an], and
1
the function (x, y) 7→ y − x. We first generate a shifted copy of the prime list by
deleting the first element, thus shortening the list:
b := primes: delete b[1]:
The following command returns the same result as above:
distances := zip(primes, b, (x, y) -> (y - x)):
We have presented another useful function in Section 2.3, the routine ifactor for
factoring an integer into primes. The call ifactor(n) returns an object of the
same type as factor: it is a special data type called Factored. Objects of this type
are printed on the screen in a form that is easily readable:
2-28
ifactor(-123456789)
−32· 3607 · 3803
Internally, the prime factors and the exponents are stored in form of a list, and
you can extract them by using op or by an indexed access. Consult the help pages
of ifactor and Factored for details. The internal list has the format
[s, p1, e1, . . . , pk, ek]
with primes p
n = s · p
op(%)
, . . . , p
1
e
e
1
2
· p
2
···p
1
, their exponents e
k
e
k
:
k
, . . . , e
1
, and the sign s = ±1, such that
k
−1, 3, 2, 3607, 1, 3803, 1
Symbolic Computation
We now employ the function ifactor to find out how many integers between 2
and 10 000 are divisible by exactly two distinct prime numbers. We note that the
object returned by ifactor(n) has 2 m + 1 elements in its list representation,
where m is the number of distinct prime divisors of n. Thus, the function
m := n -> (nops(ifactor(n)) - 1)/2:
returns the number of distinct prime factors. We construct the list of values m(k)
for k = 2, . . . , 10000:
list := [m(k) $ k = 2..10000]:
The following for loop (Section 15) displays the number of integers with precisely
i = 1, 2, . . . , 6 distinct prime divisors:
for i from 1 to 6 do
print(i, nops(select(list, x -> (x = i))))
end_for:
1, 1280
2, 4097
3, 3695
4, 894
5, 33
6, 0
Thus there are 1280 integers with exactly one prime divisor in the scanned
interval,
6
4097 integers with precisely two distinct prime factors, and so on. It is
easy to see why the interval contains no integer with six or more prime divisors:
the smallest such number 2 · 3 · 5 · 7 · 11 · 13 = 30 030 exceeds 10 000.
The numlib library comprises various number theoretic functions. Among others,
it contains the routine numlib::numprimedivisors, equivalent to the above m, for
computing the number of prime divisors. We refer to Chapter 3 for a description
of the MuPAD libraries.
6
We have already seen that the interval contains 1229 prime numbers. Can you explain the difference?
2-29
2First Steps in MuPAD
®
Exercise 2.9: Primes of the form 2
n
± 1 always have produced particular
interest.
a) Primes of the form 2
p
− 1, where p is a prime, are called Mersenne primes.
Find all Mersenne primes for 1 < p ≤ 1000.
b) For a positive integer n, the n-th Fermat number is 2
Fermat’s conjecture that all those numbers are primes.
(2n)
+ 1. Refute
2-30
The MuPAD®Libraries
Most of MuPAD®’s mathematical knowledge is organized in libraries. Such a
library comprises a collection of functions for solving problems in a particular
area, such as linear algebra, number theory, numerical analysis, etc. Library
functions are written in the MuPAD programming language. You can use them in
the same way as kernel functions, without knowing anything about the
programming language.
Section “Libraries and Modules” of the MuPAD Quick Reference contains a survey
of all libraries. Alternatively, the help viewer contains a list of libraries (and
third-party packages installed) in its contents pane on the left.
3
The libraries are developed continuously, and future versions of MuPAD will
provide additional functionality.
In this chapter, we do not address the mathematical functionality of libraries but
rather discuss their general use.
3The MuPAD
®
Libraries
Information About a Particular Library
You can obtain information and help for libraries by calling the functions info
and help. The function info gives a list of all functions installed in the library.
The numlib library is a collection of number theoretic functions:
info(numlib)
Library 'numlib':the package for elementary
number theory
The commands help or ? supply a more detailed description of the library.
3-2
The function numlib::decimal of the numlib library computes the decimal
expansion of a rational number:
numlib::decimal(123/7)
1
17, [5, 7, 1, 4, 2, 8]
As for other system functions, you will see information when hovering your mouse
pointer over the name of a library function and you may request information on
the function by means of help or ?:
?numlib::decimal
1
The result is to be interpreted as: 123/7 = 17.571428 = 17.571428 571428 . . .
Information About a Particular Library
You can have a look at the implementation of a library function by using expose:
expose(numlib::decimal)
proc(a)
name numlib::decimal;
local p, q, s, l, i;
begin
if not testtype(a, Type::Numeric) then
...
end_proc
3-3
3The MuPAD
®
Libraries
Exporting Libraries
In the previous section, you have seen that the calling syntax for a library function
is library::function, where library and function are the names of the library
and the function, respectively. For example, the library numeric for numerical
computations contains the function numeric::fsolve. It implements a modified
version of the well-known Newton method for numerical root finding. In the
following example, we approximate a root of the sine function in the interval [2, 4]:
numeric::fsolve(sin(x), x = 2..4)
[x = 3.141592654]
The function use2makes functions of a library “globally known,” so that you can
use them without specifying the library name:
use(numeric, fsolve): fsolve(sin(x), x = 2..4)
[x = 3.141592654]
If you already have assigned a value to the name of the function to be exported,
use returns a warning and the function is not exported. In the following, the
numerical integrator numeric::quadrature cannot be exported to the name
quadrature, because this identifier has a value:
3-4
quadrature := 1: use(numeric, quadrature)
Warning: 'quadrature' already has a value, not exported.
After deletion of the value, the name of the function is available and the
corresponding library function can be exported successfully. One can export
several functions at once:
delete quadrature:
use(numeric, realroots, quadrature):
Now you can use realroots (to find all real roots of an expression in an interval)
and quadrature (for numerical integration) directly. Please refer to the
corresponding help pages for the meaning of the input parameters and the
returned output. Please note that neither tooltips nor the help command will
2
This function used to be called export, but that name is more appropriately used for the library
exporting data in formats for other programs.
Exporting Libraries
react to exported names. You will need to use the full name (or the search
functionality of the help browser) in these cases.
If you call use with only one argument, namely the name of the library, then all
functions in that library are exported. If there are name conflicts with already
existing identifiers, then use issues warnings:
eigenvalues := 1: use(numeric)
Info: 'numeric::quadrature' already is exported.
Info: 'numeric::realroots' already is exported.
Warning: 'indets' already has a value, not exported.
Info: 'numeric::fsolve' already is exported.
Warning: 'rationalize' already has a value, not
exported.
Warning: 'linsolve' already has a value, not exported.
Warning: 'sum' already has a value, not exported.
Warning: 'int' already has a value, not exported.
Warning: 'solve' already has a value, not exported.
Warning: 'sort' already has a value, not exported.
Warning: 'eigenvalues' already has a value, not
exported.
After deleting the value of the identifier eigenvalues, the library function with the
same name can be exported successfully:
delete eigenvalues: use(numeric, eigenvalues):
However, the other name conflicts int, solve etc. cannot be resolved. The
important symbolic system functions int, solve etc. should not be replaced by
their numerical counterparts numeric::int, numeric::solve etc.
3-5
3The MuPAD
®
Libraries
The Standard Library
The standard library is the most important MuPAD®library. It contains the most
frequently used functions such as diff, simplify, etc. (For an even more
restricted selection of frequently used commands, check the command bar at the
right-hand side of the notebook interface and the MuPAD source code editor.)
The functions of the standard library do not have a prefix separated with ::, as
other functions do (unless exported). In this respect, there is no notable
difference between the MuPAD kernel functions, which are written in the C++
programming language, and the other functions from the standard library, which
are implemented in the MuPAD programming language.
You obtain more information about the available functions of the standard library
by navigating to the relevant section in the help system, which is the first
reference section. The MuPAD Quick Reference lists all functions of the standard
library in MuPAD version 5.
Many of these functions are implemented as function environments
(Section 17.12). You can view the source code via expose(name):
3-6
expose(exp)
proc(x)
name exp;
local y, lny, c;
option noDebug;
begin
if args(0) = 0 then
error("expecting one argument")
else
if x::dom::exp <> FAIL then
return(x::dom::exp(args()))
else
if args(0) <> 1 then
error("expecting one argument")
end_if
end_if
end_if;
...
end_proc
MuPAD®Objects
In Chapter 2, we introduced MuPAD®objects such as numbers, symbolic
expressions, maps, or matrices. Now, we discuss these objects more
systematically.
The objects sent to the kernel for evaluation can be of various forms: arithmetic
expressions with numbers such as 1 + (1+I)/3, arithmetic expressions with
symbolic objects such as x + (y + I)/3, lists, sets, equations, inequalities, maps,
arrays, abstract mathematical objects, and more. Every MuPAD object belongs to
some data type, called the domain type. It corresponds to a certain internal
representation of the object. In what follows, we discuss the following
fundamental domain types. As a convention, the names of domains provided by
the MuPAD kernel consist of capital letters, such as DOM_INT, DOM_RAT etc., while
domains implemented in the MuPAD language such as Series::Puiseux or
Dom::Matrix(R) involve small letters:
domain typemeaning
4
DOM_INTintegers, e.g., -3, 10^5
DOM_RATrational numbers, e.g., 7/11
DOM_FLOATfloating-point numbers, e.g., 0.123
DOM_COMPLEXcomplex numbers, e.g., 1 + 2/3*I
DOM_INTERVALfloating-point intervals, e.g., 2.1 ... 3.2
DOM_IDENTsymbolic identifiers, e.g., x, y, f
DOM_EXPRsymbolic expressions, e.g., x + y
Series::Puiseuxsymbolic series expansions, e.g.,
DOM_TABLEtables
DOM_BOOLBoolean values: TRUE, FALSE, UNKNOWN
DOM_STRINGstrings, e.g., "I am a string"
Dom::Matrix(R)matrices and vectors over the ring R
DOM_POLYpolynomials, e.g., poly(x^2 + x + 1, [x])
DOM_PROCfunctions and procedures
Moreover, you can define your own data types, but we do not discuss this here.
The system function domtype returns the domain type of a MuPAD object.
In the following section, we first present the important operand function op,
which enables you to decompose a MuPAD object into its building blocks. The
following sections discuss the above data types and some of the main system
functions for handling them.
4-2
Operands: the Functions op and nops
It is often necessary to decompose a MuPAD®object into its components in order
to process them individually. The building blocks of an object are called operands.
The system functions for accessing them are op and nops (short for: number of
operands):
Operands: the Functions op and nops
nops(object): the number of operands,
op(object,i): the i-th operand, 0 ≤ i ≤ nops(object),
op(object,i..j) : the sequence of operands i through j ,
where 0 ≤ i ≤ j ≤ nops(object),
op(object): the sequence op(object, 1), op(object, 2), ...
of all operands.
The meaning of an operand depends on the data type of the object. We discuss this
for each data type in detail in the following sections. For example, the operands of
a rational number are the numerator and the denominator, the operands of a list
or set are the elements, and the operands of a function call are the arguments.
However, there are also objects where the decomposition into operands is less
intuitive, such as series expansions as generated by the system functions taylor
or series (Section 4.13). Here is an example with a list (Section 4.6):
list := [a, b, c, d, sin(x)]: nops(list)
5
op(list, 2)
b
op(list, 3..5)
c, d, sin(x)
op(list)
a, b, c, d, sin(x)
By repeatedly calling the op function, you can decompose arbitrary MuPAD
expressions into “atomic” ones. In this model, a MuPAD atom is an expression
4-3
4MuPAD
®
Objects
that cannot be further decomposed by op, such that op(atom) = atom holds.1This
is essentially the case for integers, floating-point numbers, identifiers that have
not been assigned a value, and for strings:
op(-2), op(0.1234), op(a), op("I am a text")
−2, 0.1234, a, ”I am a text”
In the following example, a nested list is decomposed completely into its atoms
This model is a good approximation to MuPAD’s internal mode of operation, but there are some
exceptions. For example, you can decompose rational numbers via op, but the kernel regards them as
atoms. On the other hand, although strings are indecomposable with respect to op, it is still possible to
access the characters of a string individually (Section 4.11).
4-4
Operands: the Functions op and nops
Instead of the annoying nested calls of op, you may also use the following short
form to access subexpressions:
A rational number is a compound object: the building blocks are the numerator
and the denominator. Similarly, a complex number consists of the real and the
imaginary part. You can use the operand function op from the previous section to
access these components:
op(111/223, 1), op(111/223, 2)
111, 223
op(100 + 200*I, 1), op(100 + 200*I, 2)
100, 200
4-6
Alternatively, you can use the system functions numer, denom, Re, and Im:
Besides the common arithmetic operations +, -, *, and /, there are the arithmetic
operators div and mod for division of an integer x by a non-zero integer p with
remainder. If x = k p + r holds with integers k and 0 ≤ r < |p|, then x div p
returns the “integral quotient” k and x mod p returns the “remainder” r:
25 div 4, 25 mod 4
6, 1
Table 4.2 gives a compilation of the main MuPAD functions and operators for
handling numbers. We refer to the help system (i.e., ?abs, ?ceil etc.) for a
detailed description of these functions. We stress that while expressions such as
√
2 mathematically represent numbers, MuPAD treats them as symbolic
expressions (Section 4.4):
Numbers
+, -, *, /, ^ : basic arithmetic operations
abs: absolute value
ceil: rounding up
div: quotient “modulo”
fact: factorial
float: approximation by floating-point numbers
floor: rounding down
frac: fractional part
ifactor, factor : prime factorization
isprime: primality test
mod: remainder “modulo”
round: rounding to nearest
sign: sign
sqrt: square root
trunc: integral part
Table 4.2: MuPAD®functions and operators for numbers
domtype(sqrt(2))
DOM_EXPR
Exercise 4.3: What is the difference between 1/3 + 1/3 + 1/3 and
1.0/3 + 1/3 + 1/3 in MuPAD?
Exercise 4.4: Compute the decimal expansions of π
(ππ)
and e
1
π√163
3
with a
precision of 10 and 100 digits, respectively. What is the 234-th digit after the
decimal point of π?
Exercise 4.5: After you execute x:= 10^50/3.0, only the first DIGITS decimal
digits of x are guaranteed to be correct.
a) Truncating the fractional part via trunc is therefore questionable. What
does MuPAD do?
b) What is returned for x after increasing DIGITS?
4-7
4MuPAD
Identifiers
®
Objects
Identifiers are names such as x or f that may represent variables and unknowns.
They may consist of arbitrary combinations of letters, digits, the hash mark “#,”
and the underscore “_,” with the only exception that the first symbol must not be a
digit. Identifiers starting with a hash mark can never have values or properties.
MuPAD®distinguishes uppercase and lowercase letters. Examples of admissible
identifiers are x, _x23, and the_MuPAD_system, while MuPAD would not accept
12x, p-2, and x>y as identifiers. MuPAD also accepts any sequence of characters
starting and ending with a ‘backtick’ ` as an identifier, so `x>y` is, in fact, an
identifier. We will not use such identifiers in this tutorial.
Identifiers that have not been assigned a value evaluate to their name. In MuPAD,
they represent symbolic objects such as unknowns in equations. Their domain
type is DOM_IDENT:
domtype(x)
DOM_IDENT
Identifiers can contain special characters, such as an α. We recommend using the
Symbol library for generating these. Using _, ^, $, and {}, you can also create
identifiers with super- and subscripts, as in a
1
. We recommend using the Symbol
1
library for generating these, too.
4-8
You can assign an arbitrary object to an identifier by means of the assignment
operator :=. Afterwards, this object is the value of the identifier. For example,
after the command
x := 1 + I:
the identifier x has the value 1 + I, which is a complex number of domain type
DOM_COMPLEX. You should be careful to distinguish between an identifier, its value,
and its evaluation. We refer to the important Chapter 5, where MuPAD’s
evaluation strategy is described.
If an identifier already has been assigned a value, another assignment overwrites
the previous value. The statement y:= x does not assign the identifier x to the
identifier y, but the current value (the evaluation) of x:
Identifiers
x := 1: y := x: x, y
1, 1
If the value of x is changed later on, this does not affect y:
x := 2: x, y
2, 1
However, if x is a symbolic identifier, which evaluates to itself, the new identifier y
refers to this symbol:
delete x: y := x: x, y; x := 2: x, y
x, x
2, 2
Here we have deleted the value of the identifier x by means of the function delete.
After deletion, x is again a symbolic identifier without a value.
The assignment operator := is a short form of the system function _assign, which
may also be called directly:
_assign(x, value): x
value
This function returns its second argument, namely the right-hand side of an
assignment. This explains the screen output after an assignment:
y := 2*x
2 value
You can work with the returned value immediately. For example, the following
construction is allowed (the assignment must be put in parentheses):
y := cos((x := 0)): x, y
0, 1
Here the value 0 is assigned to the identifier x. The return value of the assignment,
i.e., 0, is fed directly as argument to the cosine function, and the result cos(0) = 1
is assigned to y. Thus, we have simultaneously assigned values to both x and y.
4-9
4MuPAD
®
Objects
Another assignment function is assign. Its input are sets or lists of equations,
which are transformed into assignments:
delete x, y: assign({x = 0, y = 1}): x, y
0, 1
This function is particularly useful in connection with solve (Section 8), which
returns solutions as a set containing lists of equations of the form
identifier = value without assigning these values.
There exist many identifiers with predefined values. They represent mathematical
functions (such as sin, exp, or sqrt), mathematical constants (such as PI), or
MuPAD algorithms (such as diff, int, or limit). If you try to change the value of
such a predefined identifier, MuPAD issues a warning or an error message:
sin := 1
Error: Identifier 'sin' is protected [_assign]
You can protect your own identifiers against overwriting via the command
protect(identifier). The write protection of both your own and of system
identifiers can be removed by unprotect(identifier). However, we strongly
recommend not to overwrite predefined identifiers, since they are used by many
system functions which would return unpredictable results after a redefinition.
Identifiers starting with a hash mark (#) are always protected and cannot be
unprotected. The command anames(All) lists all currently defined identifiers.
4-10
You can use the concatenation operator “.” to generate names of identifiers
dynamically. If x and i are identifiers, then x.i generates a new identifier by
concatenating the evaluations (see Chapter 5) of x and i:
x := z: i := 2:x.i
z2
x.i := value: z2
value
In the following example, we use a for loop (Chapter 15) to assign values to the
identifiers x1, ..., x1000:
delete x:
for i from 1 to 1000 do x.i := i^2 end_for:
Identifiers
Due to possible side effects or conflicts with already existing identifiers, we
strongly recommend to use this concept only interactively and not within MuPAD
procedures.
The function genident generates a new identifier that has not been used before in
the current MuPAD session:
X3 := (X2 := (X1 := 0)): genident()
X4
You may use strings enclosed in quotation marks " (Section 4.11) to generate
identifiers dynamically:
a := email: b := "4you": a.b
email4you
Even if the string contains blanks or operator symbols, a valid identifier is
generated, which MuPAD displays using the backtick notation mentioned above:
a := email: b := "4you + x": a.b
email4you + x
Strings are not identifiers and cannot be assigned a value:
"string" := 1
Error: Invalid left-hand side in assignment [line 1, col 10]
Exercise 4.6: Which of the following names x, x2, 2x, x_t, diff, exp,
caution!-!, x-y, Jack&Jill, a_valid_identifier, #1 are valid identifiers?Which
of them can be assigned values?
Exercise 4.7: Read the help page for solve. Solve the system of equations
x1+ x2= 1, x2+ x3= 1, . . . , x19+ x20= 1, x20= π
in the unknowns x
, x2, . . . , x
1
. Read the help page for assign and assign the
20
values of the solution to the unknowns.
4-11
4MuPAD
®
Objects
Symbolic Expressions
We say that an object containing symbolic terms such as the equation
0.3 + sin(3) +
f(x, y)
5
= 0
is an expression. Expressions of domain type DOM_EXPR are probably the most
general data type in MuPAD®. Expressions are built of atomic components, as all
MuPAD objects, and are composed by means of operators. This comprises binary
operators, such as the basic arithmetic operations +, -, *, /, ^, and function calls
such as sin(·), f(·), etc.
Operators
MuPAD®throughout uses functions to combine or manipulate objects.2It would
be little intuitive, however, to use function calls everywhere,3say, _plus(a, b) for
the addition a + b. For that reason, a variety of important operations is
implemented in such a way that you can use the familiar mathematical notation
(“operator notation”) for input. Also the output is given in such a form. In the
following, we list the operators for building more complex MuPAD expressions
from atoms.
The operators +, -, *, / for the basic arithmetic operations and ^ for
exponentiation are valid for symbolic expressions as well:
a + b + c, a - b, -a, a*b*c, a/b, a^b
a
a + b + c, a − b, −a, a b c,
b
, a
b
4-12
You may input these operators in the familiar mathematical way, but internally
they are function calls:
2
Remarkably, the MuPAD kernel treats not only genuine function calls, such as sin(0.2), assignments, or arithmetical operations in a functional way, but also loops (Chapter 15) and case distinctions
(Chapter 16).
The same holds for the factorial of a nonnegative integer. You may input it in the
mathematical notation n!. Internally it is converted to a call of the function fact:
n! = fact(n), fact(10)
n! = n!, 3628800
The arithmetic operators div and mod4were presented in Chapter 4.2. They may
also be used in a symbolic context, but then return only symbolic results:
x div 4, 25 mod p
x div 4, 25 mod p
Several MuPAD objects separated by commas form a sequence:
sequence := a, b, c + d
a, b, c + d
The operator $ is an important tool to generate such sequences:
i^2 $ i = 2..7;x^i $ i = 1..5
4, 9, 16, 25, 36, 49
x, x2, x3, x4, x
5
Equations and inequalities are valid MuPAD objects. They are generated by the
equality sign = and by <>, respectively:
equation := x + y = 2; inequality := x <> y
x + y = 2
x = y
4
The object x mod p is converted to the function call _mod(x, p). The function _mod can be redefined,
e.g., _mod:= modp or _mod:= mods. The behavior of modp and mods is documented on the corresponding
help pages. A redefinition of _mod also redefines the operator mod.
4-13
4MuPAD
®
Objects
The operators <, <=, >, and >= compare the magnitudes of their arguments. The
corresponding expressions represent conditions:
condition := i <= 2
i ≤ 2
In a concrete context, they usually can be evaluated to one of the truth (“Boolean”)
values TRUE or FALSE. Typically, they are used in if statements or as termination
conditions in loops. You may combine Boolean expressions via the logical
operators and and or, or negate them via not:
condition3 := condition1 and (not condition2)
condition1 ∧ ¬condition2
You can define maps (functions) in several ways in MuPAD. The simplest method
is to use the arrow operator -> (the minus symbol followed by the “greater than”
symbol):
f := x -> x^2
2
x → x
4-14
After defining a function in this way, you may call it like a system function:
f(4), f(x + 1), f(y)
16, (x + 1)2, y
2
If you wish to define a function that first treats the right-hand side as a command
to be performed, use the double arrow operator -->:
g1 := x -> int(f(x), x);
g2 := x --> int(f(x), x)
x →f(x) dx
3
x
x →
3
Symbolic Expressions
The composition of functions is defined by means of the composition operator @:
c := a@b: c(x)
a(b(x))
The iteration operator @@ denotes iterated composition of a function with itself:
f := g@@4: f(x)
g(g(g(g(x))))
Some system functions, such as definite integration via int or the $ operator,
require a range. You generate a range by means of the operator ..:
range := 0..1;int(x, x = range)
0..1
1
2
Ranges should not be confused with floating-point intervals of domain type
DOM_INTERVAL, which may be created via the operator ... or the function hull:
Table 4.3: The main operators for generating MuPAD®expressions
Symbolic Expressions
[i $ i = 3..5] = [_seqgen(i, i, 3..5)];
[3, 4, 5] = [3, 4, 5]
a < b = _less(a, b);
(a < b) = (a < b)
(f@g)(x) = _fconcat(f, g)(x)
f(g(x)) = f (g(x))
We remark that some of the system functions such as _plus, _mult, _union, or
_concat accept arbitrarily many arguments, while the corresponding operators
are only binary:
_plus(a, b, u, v), _concat(a, b, u, v), _union()
a + b + u + v, abuv, ∅
It is often useful to know and to use the functional form of the operators. For
example, it is very efficient to form longer sums by applying _plus to many
arguments. You may generate the argument sequence quickly by means of the
sequence generator $:
_plus(1/i! $ i = 0..100): float(%)
2.718281828
The function map is a useful tool. It applies a function to all operands of a MuPAD
object. For example:
map([x1, x2, x3], function, y, z)
[function(x1, y, z) , function(x2, y, z) , function(x3, y, z)]
If you want to apply operators via map, use their functional equivalent:
Some operations are invalid because they do not make sense mathematically:
3 and x
Error: Illegal operand [_and]
The system function _and recognizes that the argument 3 cannot represent a
Boolean value and issues an error message. However, MuPAD accepts a symbolic
expression such as a and b with symbolic identifiers a, b. As soon as a and b get
Boolean values, the expression can be evaluated to a Boolean value as well:
c := a and b: a := TRUE: b := TRUE: c
TRUE
The operators have different priorities, for example:
4-18
a.fact(3) means a.(fact(3)) and returns a6,
a.6^2means (a.6)^2 and returns a6^2,
a * b^cmeans a* (b^c),
a + b * cmeans a + (b * c),
a + b mod c means (a + b) mod c,
a = b mod c means a = (b mod c),
a, b $ 3means a, (b $ 3) and returns a, b, b, b.
If we denote the relation “is of lower priority than” by ≺, then we have:
, ≺ $ ≺ = ≺ mod ≺ + ≺ ∗ ≺ ^ ≺ . ≺ function call.
You find a complete list of the operators and their priorities in Section “Operators”
of the MuPAD Quick Reference. Parentheses can always be used to enforce an
evaluation order that differs from the standard priority of the operators:
1 + 1 mod 2,1 + (1 mod 2)
0, 2
Symbolic Expressions
i := 2: x.i^2, x.(i^2)
2
x2
, x4
u, v $ 3; (u, v) $ 3
u, v, v, v
u, v, u, v, u, v
Expression Trees
A useful model for representing a MuPAD®expression is the expression tree. It
reflects the internal representation. The operators or their corresponding
functions, respectively, are the vertices, and the arguments are subtrees. The
operator of lowest priority is at the root. Here are some examples:
a + b * c + d * e *sin(f)^g
+
a*
int(exp(x^4), x = 0..1)
exp
^
x4
bc
int
x..
*
de^
=
01
sin
f
g
4-19
4MuPAD
®
Objects
The difference a - b is internally represented as a + b * (-1):
+
a*
b-1
Similarly, a quotient a/b has the internal representation a * b^(-1):
*
a^
b-1
The leaves of an expression tree are MuPAD atoms.
The function prog::exprtree allows to display expression trees. Operators are
replaced by the names of the corresponding system functions:
prog::exprtree(a/b):
_mult
|
+-- a
|
`-- _power
|
+-- b
|
`-- -1
4-20
Exercise 4.8: Sketch the expression tree of a^b - sin(a/b).
Exercise 4.9: Determine the operands of 2/3, x/3, 1 + 2*I, and x + 2*I. Explain
the differences that you observe.
Symbolic Expressions
Operands
You can decompose expressions systematically by means of the operand functions
op and nops, which were already presented in Section 4.1. The operands of an
expression correspond to the subtrees below the root in the expression tree.
expression := a + b + c + sin(x): nops(expression)
4
op(expression)
a, b, c, sin(x)
Additionally, expressions of domain type DOM_EXPR have a “0th operand,” which is
accessible via op(·,0). It corresponds to the root of the expression tree and tells
you which function is used to build the expression:
You may regard the 0th operand of an expression as a “mathematical type.” For
example, an algorithm for differentiation of arbitrary expressions must find out
whether the expression is a sum, a product, or a function call. To this end, it may
look at the 0th operand to decide whether linearity, the product rule, or the chain
rule of differentiation applies.
4-21
4MuPAD
®
Objects
As an example, we decompose the expression
expression := a + b + sin(x) + c^2:
with the expression tree
+
absin
x
^
c2
systematically by means of the op function:
op(expression, 0..nops(expression))
_plus, a, b, sin(x) , c
2
We can put these expressions together again in the following form:
Note that the output order visible on the screen is different from the internal
order accessible by op. You can access the building blocks of an expression in
output order with the index operator [ ], as in the following:
expression[1], expression[4]
c2, sin(x)
In the following example, we decompose an expression completely into its atoms
(compare with Section 4.1):
4-22
expression := sin(x + cos(a*b)):
The operands and subexpressions are:
Symbolic Expressions
op(expression, 0):sin
op(expression, 1):x+cos(a*b)
op(expression, [1, 0]):_plus
op(expression, [1, 1]):x
op(expression, [1, 2]):cos(a*b)
op(expression, [1, 2, 0]):cos
op(expression, [1, 2, 1]):a*b
op(expression, [1, 2, 1, 0]):_mult
op(expression, [1, 2, 1, 1]):a
op(expression, [1, 2, 1, 2]):b
Exercise 4.10: Sketch the expression tree of the following Boolean expression:
condition := (not a) and (b or c):
How can you use op to pick the symbolic identifiers a, b, and c out of the object
condition?
4-23
4MuPAD
Sequences
®
Objects
Sequences form an important MuPAD®data structure. Lists and sets are built
from sequences. As discussed in Section 4.4, a sequence is a series of MuPAD
objects separated by commas.
sequence1 := a, b, c; sequence2 := c, d, e
a, b, c
c, d, e
You may also use the comma to concatenate sequences:
sequence3 := sequence1, sequence2
a, b, c, c, d, e
Sequences are MuPAD expressions of domain type DOM_EXPR.
If m and n are integers, the call object(i) $ i = m..n generates the sequence
object(m), object(m + 1), . . . , object(n) :
4-24
i^2 $ i = 2..7, x^i $ i = 1..5
4, 9, 16, 25, 36, 49, x, x2, x3, x4, x
5
The operator $ is called the sequence generator. The equivalent functional form is
_seqgen(object(i), i, m..n)
_seqgen(i^2, i, 2..7), _seqgen(x^i, i, 1..5)
4, 9, 16, 25, 36, 49, x, x2, x3, x4, x
5
Usually, you will prefer the operator notation. The functional form is useful in
connection with map, zip or similar functions.
You may use $ in the following way to generate a sequence of successive integers:
$ 23..30
23, 24, 25, 26, 27, 28, 29, 30
Sequences
The command object $ n returns a sequence of n identical objects:
x^2 $ 10
x2, x2, x2, x2, x2, x2, x2, x2, x2, x
2
You can also use the sequence generator in connection with the keyword in. (The
functional equivalent in this case in _seqin.) The loop variable then runs through
all operands of the stated object:
f(x) $ x in [a, b, c, d]
f(a) , f (b) , f (c) , f (d)
f(x) $ x in a + b + c + d + sin(sqrt(2))
f(a) , f (b) , f (c) , f (d) , f
√
sin
2
It may be tempting to abuse the $ operator for loops, as in these commands:
(x.i := sin(i); y.i := x.i) $ i=1..4:
For readability, memory consumption and therefore speed, we recommend
against this usage. The assignments above should use a loop instead (cf.
Chapter 15):
for i from 1 to 4 do
x.i := sin(i);
y.i := x.i;
end_for:
As a simple application of sequences, we now consider the MuPAD differentiator
diff. The call diff(f(x), x) returns the derivative of f with respect to x. Higher
derivatives are given by diff(f(x), x, x), diff(f(x), x, x, x) etc. Thus, the
10-th derivative of f (x) = sin(x2) can be computed conveniently by means of the
sequence generator:
diff(sin(x^2), x $ 10)
242
30240 cos(x ) - 403200 xcos(x ) +
8222
23040 xcos(x ) - 302400 xsin(x ) +
62102
161280 xsin(x ) - 1024 xsin(x )
4-25
4MuPAD
®
Objects
The “void” object (Section 4.19) may be regarded as an empty sequence. You may
generate it by calling null() or _exprseq(). The system automatically eliminates
this object from sequences:
Seq := null(): Seq := Seq, a, b, null(), c
a, b, c
Some system functions such as the print command for screen output
(Section 12.1) return the null() object:
sequence := a, b, print(Hello), c
Hello
a, b, c
You can access the i-th entry of a sequence by sequence[i]. Redefinitions of the
form sequence[i]:= newvalue are also possible:
F := a, b, c: F[2]
b
4-26
F[2] := newvalue: F
a, newvalue, c
Alternatively, you may use the operand function op (Section 4.1) to access
subsequences:
F := a, b, c, d, e: op(F, 2); op(F, 2..4)
5
b
b, c, d
5
Note that, in this example, the identifier F of the sequence is provided as argument to op. The op
function regards a direct call of the form op(a,b, c, d, e, 2) as an (invalid) call with six arguments and
issues an error message. You may use parentheses to avoid this error: op((a, b, c, d, e), 2).
You may use delete to delete entries from a sequence, thus shortening the
sequence:
F; delete F[2]: F; delete F[3]: F
a, b, c, d, e
a, c, d, e
a, c, e
The main usage of MuPAD sequences is the generation of lists and sets and
supplying arguments to function calls. For example, the functions max and min
can compute the maximum and minimum, respectively, of arbitrarily many
arguments:
Seq := 1, 2, -1, 3, 0: max(Seq), min(Seq)
3, −1
Sequences
Exercise 4.11: Assign the values x
x1, x2, . . . , x
100
.
= 1, x2= 2, . . . , x
1
= 100 to the identifiers
100
Exercise 4.12: Generate the sequence
x1, x2, x
2
, x3, x3, x
2
, . . . , x10, x10, . . . , x
3
3
.
10
10
Exercise 4.13: Use a simple command to generate the double sum
10
i
1
.
j=1
i + j
i=1
Hint: the function _plus accepts arbitrarily many arguments. Generate a suitable
argument sequence.
4-27
4MuPAD
Lists
®
Objects
A list is an ordered sequence of arbitrary MuPAD®objects enclosed in square
brackets:
list := [a, 5, sin(x)^2 + 4, [a, b, c], hello,
3/4, 3.9087]
a, 5, sin(x)2+ 4, [a, b, c] , hello,
3
, 3.9087
4
A list may contain lists as elements. It may also be empty:
list := []
[]
The possibility to generate sequences via $ is helpful for constructing lists:
sequence := i $ i = 1..10: list := [sequence]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
4-28
list := [x^i $ i = 0..12]
1, x, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x
12
A list may occur on the left hand side of an assignment. This may be used to
assign values to several identifiers simultaneously:
[A, B, C] := [a, b, c]: A + B^C
c
a + b
A useful property of this construction is that all the assignments are performed at
the same time, so you can swap values:
a := 1: b:= 2: a, b
1, 2
[a, b] := [b, a]: a, b
2, 1
The function nops returns the number of elements of a list. You can access the
elements of a list by means of indexed access: list[i] returns the i-th list
element, and list[i..j] returns the sub-list starting at the i-th and extending up
to and including the j-th element. Negative values for i and j are counted from
the end:
list := [a, b, c, d, e, f]: list[1], list[3..-2]
2, [c, d, e]
As with almost any MuPAD object, you can also access the elements of a list with
the op function: op(list) returns the sequence of elements, i.e., the sequence
that has been used to construct the list by enclosing it in square brackets [ ]. The
call op(list, i) returns the i-th list element, and op(list, i..j) extracts the
sequence of the i-th up to the j-th list element:
delete a, b, c: list := [a, b, sin(x), c]: op(list)
a, b, sin(x) , c
op(list, 2..3)
b, sin(x)
Lists
You may change a list element by an indexed assignment:
list := [a, b, c]: list[1] := newvalue: list
[newvalue, b, c]
Writing to a sublist may change the length of the list:
list[2..3] := [d,e,f,g]: list
[newvalue, d, e, f, g]
Alternatively, the command subsop(list, i = newvalue) (Chapter 6) returns a
copy with the i-th operand redefined:
Caution: If L is an identifier without a value, then the indexed assignment
L[index] := value:
generates a table (Section 4.8) and not a list:
delete L: L[1] := a: L
1 a
You can remove elements from a list by using delete. This shortens the list:
list := [a, b, c]: delete list[1]: list
[b, c]
The function contains checks whether a MuPAD object belongs to a list. It
returns the index of (the first occurrence of) the element in the list. If the list does
not contain the element, then contains returns the integer 0:
contains([x + 1, a, x + 1], x + 1)
1
4-30
contains([sin(a), b, c], a)
0
The function append adds elements to the tail of a list:
list := [a, b, c]: append(list, 3, 4, 5)
[a, b, c, 3, 4, 5]
The dot operator . concatenates lists:
list1 := [1, 2, 3]: list2 := [4, 5, 6]:
list1.list2, list2.list1
[1, 2, 3, 4, 5, 6] , [4, 5, 6, 1, 2, 3]
The corresponding system function is _concat and accepts arbitrarily many
arguments. You can use it to combine many lists:
_concat(list1 $ 5)
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
A list can be sorted by means of the function sort. This arranges numerical values
according to their magnitude, strings (Section 4.11) are sorted lexicographically:
Note that the lexicographical order only applies to strings generated with ".
Names of identifiers are sorted according to different (internal) rules, which only
reduce to lexicographic order for short identifiers (and may change in future
releases):
delete A, B, C, a, b, c, a1, abc:
sort([A, b, a, c, C, c, B, a1, abc])
[A, B, C, a, a1, abc, b, c, c]
Lists
sort([x10002, x10011, x10003])
[x10002, x10011, x10003]
MuPAD regards lists of function names as list-valued functions:
[sin, cos, f](x)
[sin(x) , cos(x) , f (x)]
The function map applies a function to all elements of a list:
map([x, 1, 0, PI, 0.3], sin)
[sin(x) , sin(1) , 0, 0, 0.2955202067]
4-31
4MuPAD
®
Objects
If the function has more than one argument, then map substitutes the list elements
for the first argument and takes the remaining arguments from its own argument
list:
map([a, b, c], f, y, z)
[f(a, y, z) , f(b, y, z) , f(c, y, z)]
This map construction is a powerful tool for handling lists as well as other MuPAD
objects. In the following example, we have a nested list L. We want to extract the
first elements of the sublists using op(·, 1). This is easily done using map:
The MuPAD function select enables you to extract elements with a certain
property from a list. To this end, you need a function that checks whether an
object has this property and returns TRUE or FALSE. For example, the call
has(object1, object2) returns TRUE if object2 is an operand or suboperand of
object1, and FALSE otherwise:
has(1 + sin(1 + x), x), has(1 + sin(1 + x), y)
TRUE, FALSE
4-32
Now,
select([a + 2, x, y, z, sin(a)], has, a)
[a + 2, sin(a)]
extracts all those list elements for which has(·,a) returns TRUE, i.e., those which
contain the identifier a.
The function split divides a list into three lists, as follows. The first list contains
all elements with a certain property, the second list collects all those elements
without the property. If the test for the property returns the value UNKNOWN for
some elements, then these are put into the third list. Otherwise, the third list is
empty:
split([sin(x), x^2, y, 11], has, x)
sin(x) , x
2
, [y, 11] , []
The MuPAD function zip combines elements of two lists pairwise into a new list:
[a + d, b + e, c + f ] , [a d, b e, c f] ,ad, be, c
f
The third argument of zip must be a function that takes two arguments. This
function is then applied to the pairs of list elements. In the above example, we
have used the MuPAD functions _plus, _mult, and _power for addition,
multiplication, and exponentiation, respectively. If the two input lists have
different lengths, then the behavior of zip depends on the optional fourth
argument. If this is not present, then the length of the resulting list is the
minimum of the lengths of the two input lists. Otherwise, if you supply an
additional fourth argument, then zip replaces the “missing” list entries by this
argument:
L1 := [a, b, c, 1, 2]: L2 := [d, e, f]:
zip(L1, L2, _plus)
[a + d, b + e, c + f ]
Lists
zip(L1, L2, _plus, hello)
[a + d, b + e, c + f, hello + 1, hello + 2]
Table 4.4 gives a summary of all list operations that we have discussed.
Exercise 4.14: Generate two lists with the elements a, b, c, d and 1, 2, 3, 4,
respectively. Concatenate the lists. Multiply the lists pairwise.
Exercise 4.15: Multiply all entries of the list [1, x, 2] by 2. Suppose you are
given a list, whose elements are lists of numbers or expressions, such as
[[1, x, 2], [PI], [2/3, 1]], how can you multiply all entries by 2?
4-33
4MuPAD
®
Objects
. or _concat: concatenating lists
append: appending elements
contains(list, x) :does list contain the element x?
list[i]: accessing the i-th element
map: applying a function
nops: length
op: accessing elements
select: select according to properties
sort: sorting
split:split according to properties
subsop: replacing elements
delete: deleting elements
zip: combining two lists
Table 4.4: MuPAD®functions and operators for lists
Exercise 4.16: Let X = [x
, . . . , xn] and Y = [y1, . . . , yn] be two lists of the same
1
length. Find a simple method to compute
• their “inner product” (X as row vector and Y as column vector)
4-34
x1y1+ ··· + xnyn,
• their “matrix product” (X as column vector and Y as row vector)
You can achieve this by using zip, _plus, map and appropriate functions
(Section 4.12) within a single command line in each case. Loops (Chapter 15) are
not required.
Exercise 4.17: In number theory, one is often interested in the density of prime
numbers in sequences of the form f (1), f (2), . . . , where f is a polynomial. For
each value of m = 0, 1, . . . , 41, find out how many of the integers n
2
+ n + m with
n = 1, 2, . . . , 100 are primes.
Exercise 4.18: In which ordering will n children be selected for “removal” by a
counting-out rhyme composed of m words? For example, using the rhyme
“eenie–meenie–miney–moe–catch a–tiger–by the–toe”
with 8 “words,” 12 children are counted out in the order
8–4–1–11–10–12–3–7–6–2–9–5. Hint: represent the children by a list [1, 2, …]
and remove an element from this list after it is counted out.
Lists
4-35
4MuPAD
Sets
®
Objects
A set is an unordered sequence of arbitrary objects enclosed in curly braces. Sets
are of domain type DOM_SET:
{34, 1, 89, x, -9, 8}
{−9, 1, 8, 34, 89, x}
The order of the elements in a MuPAD®list seems to be random. The MuPAD
kernel sorts the elements according to internal principles. You should use sets
only if the order of the elements does not matter. If you want to process a sequence
of expressions in a certain order, use lists as discussed in the previous section.
Sets may be empty:
emptyset := {}
∅
A set contains each element only once, i.e., duplicate elements are removed
automatically:
4-36
set := {a, 1, 2, 3, 4, a, b, 1, 2, a}
{1, 2, 3, 4, a, b}
The function nops determines the number of elements in a set. As for sequences
and lists, op extracts elements from a set:
op(set)
a, 1, 2, 3, 4, b
op(set, 2..4)
1, 2, 3
Warning: Since elements of a set may be reordered internally, you should check
carefully whether it makes sense to access the i-th element. For example,
subsop(set, i = newvalue) (Section 6) replaces the i-th element by a new value.
However, you should check in advance (using op) that the element that you want
to replace really is the i-th element. Especially note that replacing an element of a
set often reorders other entries.
The command op(set, i) returns the i-th element of set in the internal order,
which usually is different from the i-th element of set that you see on the screen.
However, you can access elements by using set[i], where the returned elements
is the i-th element as printed on the screen.
The functions union, intersect, and minus form the union, the intersection, and
the set-theoretic difference, respectively, of sets:
M1 := {1, 2, 3, a, b}: M2 := {a, b, c, 4, 5}:
M1 union M2, M1 intersect M2, M1 minus M2, M2 minus M1
In particular, you can use minus to remove elements from a set:
{1, 2, 3, a, b} minus {3, a}
{1, 2, b}
You can also replace an element by a new value without caring about the order of
the elements:
set := {a, b, oldvalue, c, d}
{a, b, c, d, oldvalue}
Sets
set minus {oldvalue} union {newvalue}
{a, b, c, d, newvalue}
The function contains checks whether an element belongs to a set, and returns
either TRUE or FALSE:
contains({a, b, c}, a), contains({a, b, c + d}, c)
6
TRUE, FALSE
MuPAD regards sets of function names as set-valued functions:
{sin, cos, f}(x)
{cos(x) , f (x) , sin(x)}
6
Note the difference to the behavior of contains for lists: there the ordering of the elements is
determined when you generate the list, and contains returns the position of the element in the list.
4-37
4MuPAD
®
Objects
contains(M, x) :does M contain the element x?
intersect: intersection
map: applying a function
minus: set-theoretic difference
nops: number of elements
op:accessing elements
select: select according to properties
split: split according to properties
subsop: replacing elements
union: set-theoretic union
Table 4.5: MuPAD®functions and operators for sets
You can apply a function to all elements of a set by means of map:
map({x, 1, 0,PI, 0.3}, sin)
{0, 0.2955202067, sin(1) , sin(x)}
You can use the function select to extract elements with a certain property from
a set. This works as for lists, but the returned object is a set:
select({{a, x, b}, {a}, {x, 1}}, contains, x)
{{1, x}, {a, b, x}}
4-38
Similarly, you can use the function split to divide a set into three subsets of
elements with a certain property, elements without that property, and elements
for which the system cannot decide this and returns UNKNOWN. The result is a list
comprising these three sets:
split({{a, x, b}, {a}, {x, 1}}, contains, x)
[{{1, x}, {a, b, x}}, {{a}}, ∅]
Table 4.5 contains a summary of the set operations discussed so far.
MuPAD also provides the data structure Dom::ImageSet for handling infinite sets;
see page 8-9 in Chapter 8.
Exercise 4.19: How can you convert a list to a set and vice versa?
Exercise 4.20: Generate the sets A = {a, b, c}, B = {b, c, d}, and C = {b, c, e}.
Compute the union and the intersection of the three sets, as well as the difference
A \ (B ∪ C ).
Exercise 4.21: Instead of the binary operators intersect and union, you can
also use the corresponding MuPAD functions _intersect and _union to compute
unions and intersections of sets. These functions accept arbitrarily many
arguments. Use simple commands to compute the union and the intersection of
all sets belonging to M:
A table is a MuPAD®object of domain type DOM_TABLE. It is a collection of
equations of the form index = value. Both indices and values may be arbitrary
MuPAD objects. You can generate a table by using the system function table
(“explicit generation”):
T := table(a = b, c = d)
a b
c d
You can generate more entries or change existing ones by “indexed assignments”
of the form Table[index]:= value:
T[f(x)] := sin(x): T[1, 2] := 5:
T[1, 2, 3] := {a, b, c}: T[a] := B:
T
a B
c d
f(x) sin(x)
1, 2 5
1, 2, 3 {a, b, c}
4-40
It is not necessary to initialize a table via table. If T is an identifier that does not
have a value, or has a value which does not allow indexed access (such as an
integer or a function), then an indexed assignment of the form T[index]:= value
automatically turns T into a table (“implicit generation”):
delete T: T[a] := b: T[b] := c: T
a b
b c
A table may be empty:
T := table()
You may delete table entries via delete Table[index]:
T := table(a = b, c = d, d = a*c):
delete T[a], T[c]: T
d a c
You can access table entries in the form Table[index]; this returns the element
corresponding to the index. If there is no entry for the index, then MuPAD returns
Table[index] symbolically:
T := table(a = b, c = d, d = a*c):
T[a], T[b], T[c], T[d]
b, Tb, d, a c
The call op(Table) returns all entries of a table, i.e., the sequence of all equations
index = value:
op(table(a = A, b = B, c = C, d = D))
a = A, b = B, c = C, d = D
Tables
Note that the internal order of the table entries may differ both from the order in
which you have generated the table and from the order of entries printed on the
screen. It may look quite random:
The function contains checks whether a table contains a particular index. It
ignores the values:
T := table(a = b): contains(T, a), contains(T, b)
TRUE, FALSE
You may employ the functions select and split to inspect both indices andvalues of a table and to extract them according to certain properties. This works
similarly as for lists (Section 4.6) and for sets (Section 4.7):
T := table(1 = "number", 1.0 = "number", x = "symbol"):
select(T, has, "symbol")
4-42
x ”symbol”
select(T, has, 1.0)
1.0 ”number”
split(T, has, "number")
1 ”number”
1.0 ”number”
,
x ”symbol”
,
Tables are particularly well suited for storing large amounts of data. Indexed
accesses to individual elements are implemented efficiently also for big tables:
a write or read does not file through the whole data structure.
Loading...
+ hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.