A Short Maple Primer

Krister Forsman, Dept. of Electrical Engineering Linköping University, S-581 83 Linköping, Sweden

                      email: krister@isy.liu.se

1992-02-28

Preface

Maple is a nice and powerful computer algebra system. There is also a very readable manual for Maple. However, many people do not do symbolic calculations every day and may need to use the program only occasionally. This is a manual for those people. It is totally incomplete, it has examples instead of general syntax description of the commands, it only accounts for a small fraction of the existing functions.

The basic idea is: look here for the function you need, and if there is not enough information about it here (there typically won’t be) use the on-line documentation or read the real manual. The Maple-version described here is version V. Caveat: since the functions are mostly explained by examples, most of them have more facilities and are more powerful than it appears here.

STARTING MAPLE

Start Maple by typing maple. If you wish the file foo to be read when Maple is started, type maple < foo. If there is a file called .mapleinit in your home directory it is automatically read. There is also an X-windows version of Maple, which is started with the command xmaple.

BASIC FACTS

The prompter is > Each command is terminated by a semi colon (;) or a colon (:).

; ⇒ the result is showed. : ⇒ the result is not showed.

Maple is case sensitive. Comments start with # and run to the end of the line. > k!; denotes k factorial. Exponentiation is written ^or ** . The logarithm function is called ln. e^{πi} is exp(Pi*I). ∞ is called infinity. For numerical evaluation apply

evalf.

The repetition operator, $, is very useful. The dot-operator (.) denotes concatenation. The composition operator is written @.

“The latest expression” is called by ". The latest expression but one is "" etc. For a history encompassing more than the three latest expressions returned, use the command history. Here are some examples

> ln(3^2);
                                 ln(9)

> evalf(");
                              2.197224577
> [0$4];
                             [0, 0, 0, 0]
> {$1..5};
                            {1, 2, 3, 4, 5}
> diff(x(t),t$6): #Sixth derivative of x(t) w.r.t. t
> x.(1..4);
                             x1, x2, x3, x4
> (sin@arcsin)(x);
                                   x

The function convert(expr,type) converts between different data types.

If you run Maple under UNIX, clear the screen by typing > !clear; (Thus ! means “escape to host”.)

For translation of an expression into LaTEX, type > latex(expr,foo); The second argument, which is optional, is a file name. There are similar functions for C and FORTRAN.

HELP FACILITIES

> ?fname; displays a help message about fname, and a general help message can be obtained by typing a sole question mark: > ? The call > anames(); returns a list of all names that have been assigned a value. Assign the global variable printlevel to an integer and Maple will trace the execution of all its code. The trace function can be used to trace the execution of a specific procedure.

READING and SAVING FILES

To save all data on the file foo type > save(foo);

If you just want to save some assignments type > save(name1,name2,foo);

The command used for reading from a file is called read: > read(foo);

SEQUENCES, LISTS and SETS

Sequences are expressions separated by commas. Sequences can be generated using the seq command.

> 1, (2,3,4), 5;
                           1, 2, 6, 24, 120
> seq( i!, i=1..5 );
                           1, 2, 6, 24, 120

A list is of the form [op1, ..., opn] and a set {op1,...,opn}. The i:th element of the list L is addressed L[i]. (also works for sets). Examples:

> L:=[17,f,ln(y),[1,9]]:  L[2];
                                   f
> S:={9,L[1],L[4][2],9};
                             S := {9, 17}

There is no special append function; instead, to append x to the list L you write

> L:=[op(L),x];
                     L := [17, f, ln(y), [1, 9], x]

Some operations you can perform on sets are: union, intersect, minus:

> {1,2,3} union {a,2,b} minus {c,3};
                                  {1, 2, a, b}

> map(fcn,L); means “apply the function fcn on every element in the list L”. This also works for sets, vectors, matrices etc. If fcn takes several arguments you type

   > map(fcn,L,arg2,arg3);

ASSIGNMENT and EVALUATION

Assignments are made with := whereas the equality sign = is used for equations. To check the current value of a variable type its name: > a; The exceptions are vectors, matrices, arrays, tables and procedures for which the print or op command has to be used: > print(A); or > op(A);

To check if the variable a has been assigned a value you can type > assigned(a); To unassign the variable a write > a:='a';

The main evaluation rule in Maple is that every expression is evaluated as far as possible, i.e. all variables in the expression are substituted by their value if they have been assigned one. Thus the order in which assignments are made is of importance, as is illustrated by the following example.

> a:=b;
                                 a := b
> b:=3:
> c:=b;
                                 c := 3

> b:=4:
> [a,b,c];
                               [4, 4, 3]
> b:='b': [a,b,c];
                               [b, b, 3]

This principle does not work for vectors and matrices. E.g. no evaluation of the entries of the matrix A is made at the call > op(A); The best way to circumvent this is to use subs (see Elementary Manipulation below).

For complex evaluation of expr, use > evalc(expr);

To evaluate the expression expr numerically with n digits, type > evalf(expr,n); If n is left out the floating point precision is determined by the variable Digits.

The function evalhf uses the hardware floating-point of the system, to enhance speed.

ELEMENTARY MANIPULATION

> op(n,expr); extracts operand number n in expr. Example:

> a:=x+2*y*z^2;
                                              2
                                a := x + 2 y z
> op(2,a);
                                          2
                                     2 y z
> op(2,");
                                       y

> nops(expr); number of operands of expr, e.g. the length, if expr is a list.

> subs(a=b,expr); Substitute a by b in expr. If the second argument is a vector, matrix etc. you have to use op: > subs(a=b,op(M));

rhs, lhs right and left hand sides of equations

Re, Im Real and imaginary part

> coeff(pol,var); gives the coefficient of var in the polynomial pol.

USER-DEFINED FUNCTIONS

There are several possibilities for writing your own functions in Maple. The simplest is probably the arrow-construct. An example:

> f:=x -> x^2-a;
                                      2
                           f := x -> x  - a
> g:=(x,y) -> x*y-1;

                         g := (x,y) -> x y - 1
> g(f(1),2);
                               - 2 a + 1

If the function is more complicated and local variables are needed the function proc should be used. In the example below the function myfcn takes one argument (a number) and returns another number using the local variables t and u during the computation.

myfcn:=proc(x)
   local t,u:
   if x>=0 then t:=evalf(sqrt(x),3) else t:=x^2 fi:
   if t>2 then u:=t+x else u:=t-x fi:
   max(t,u)
end:

The value returned from the procedure is the one of the last expression - the one before end. If the number of in-arguments is not predetermined, use args and nargs.

The alias facility is quite useful. An example:

alias(tp=transpose,SE=simplify@expand,choose=binomial):

LOOPS

General for-loop: for i from 1 by 1 to 10 do x[i]:=i^2: y[i]:=i^3 od:
Simplified: for i to 10 do x[i]:=i^2: y[i]:=i^3 od:

Writing for t in L do t^2 od; is equivalent to

 for i to nops(L) do t:=op(i,L); t^2 od;
While-loop: > while i<3 do i:=i^2+1 od;

CONDITIONAL CLAUSES

General syntax: if x>0 then a:=x else a:=-x fi:
    if x>0 then s:=1 elif x=0 then s:=0 else s:=-1 fi;

PLOTTING

If you are interested in plotting, run Maple under X-windows or on a 386, etc. Useful plot

commands are: plot, plot3d, tubeplot, spacecurve

The syntax of plot and plot3d is hopefully obvious from the examples below. They can both take a set of functions as their first argument.

The advanced plot-functions have to be loaded with the command > with(plots); Some simple examples:

> plot(sin(x), x=0..2*Pi);
> plot({sin(x), x-x^3/6}, 0..2);
> f:=exp(-x^2-2*y^2)-sin(7*x)/8:
> plot3d(f,x=-1..1,y=-1..1);

SIMPLIFICATION

Some pretty obvious commands are: simplify, expand, factor

> factor(x^4+4);
                        2              2
                      (x  - 2 x + 2) (x  + 2 x + 2)
> expand(sin(x+y));
                      sin(x) cos(y) + cos(x) sin(y)
Sometimes simplify(expand(expr)) differs from simplify(expr).

The opposite of expand is combine, in some sense.

For simplification of rational expressions, use normal:

> normal((x+1)/y+x/(x+y));
                             2
                            x  + 2 x y + x + y
                            ------------------
                                 y (x + y)

> collect(pol,var); returns the multivariate polynomial pol written as a univariate one, in the variable var. More advanced uses are possible.

> collect(y^2*x^2+7*x*y+a*y^2-y+u*x,y);
                           2   2
                     (a + x ) y  + (7 x - 1) y + u x

SOME MATHEMATICAL FUNCTIONS

> diff(f,x); means “differentiate f with respect to x” > diff(f,x$n); yields the n:th derivative. > grad(f,[x1,x2]); computes the gradient of f w.r.t. [x1,x2]. > jacobian(f,[x1,x2]); jacobian matrix of the vector f. > laplace(f,t,s); yields the laplace transform of f(t) > int(f,x); int(f,x=a..b); indefinite and definite integration For numerical integration apply evalf. For complex integration, apply evalc. > sum(f,i); sum(f,i=a..b); indefinite and definite summation For products use product which has the same syntax as sum.

> limit(f,x=a); limit of f as x goes to a
> limit(f,x=a,right); a directional limit

> taylor(f,x=a,n); a Taylor expansion of f about x=a to O(x^{n}) See also series for more general series expansions.

> int(sin(x)*x,x);
                               sin(x) - x cos(x)
> evalf(int(sin(x)/x,x=0..1),15);
                                .946083070367183
> sum(binomial(n,k)*x^k,k=0..n);
                                           n
                                    (1 + x)

EQUATIONS

The call solve(eq,var); solves the equation eq w.r.t. var. If there is no = in eq the right hand side is supposed to be zero, and if var is left out all variables occurring are considered unknown. If there are several solutions to eq then solve returns an expression sequence, i.e. several expressions separated by commas. It is up to the user to collect the solutions in a set or a list etc. An equation system is given as a set of equations; in this case the second argument is a set of variables.

> eq:=x^2-x+1=0:
> solve(eq);
                                    1/2               1/2
                       1/2 + 1/2 I 3   , 1/2 - 1/2 I 3
> S:=[solve(2*z^3-z^2+11*z-21)];
                                    1/2                 1/2
          S := [3/2, - 1/2 + 3/2 I 3   , - 1/2 - 3/2 I 3   ]
> solve({x*y-y,x^2-y^2});
            {x = 0, y = 0}, {x = 1, y = 1}, {x = 1, y = -1}

Sometimes Maple answers using RootOf, which is short for “the solution of the equation”. This function uses the global parameter _Z. To force a (numerical) solution, use

fsolve or allvalues.

To solve the differential equation deq with y as unknown, type > dsolve(deq,y(x)); An example of deq:

   > deq:=diff(y(x),x,x)-y(x)=0;

Initial conditions are treated like this:

   > deq:={diff(y(x),x,x)-y=0,y(0)=1, D(y)(0)=0};

You can also solve a DE numerically with a 4-5:th order Runge-Kutta. Type > ?dsolve[numeric] for more information about this.

VECTORS and MATRICES

Before starting matrix calculations, load the linear algebra package:

   > with(linalg):

Vectors and matrices are created with the commands vector and matrix respectively. A vector (which is not a special case of a matrix) is regarded as a column vector by multiplication. Some examples:

> A:=matrix([[4,34],[-a,sqrt(2)]]):
> a12:=A[1,2]:
> v:=vector([x,-12]):
> w:=v[2]:

The command array can also be used to create a matrix. Whenever doing matrix calculations the function evalm has to be applied. Matrix multiplication is written &* which has to be surrounded by spaces. Multiplication with a scalar is called * Thus to perform A = 2B′C + D, where the operands are matrices, you type

   > A:=evalm(2* transpose(B) &* C + D);

The characteristic polynomial of A with s as variable is obtained by > charpoly(A,s); and > eigenvals(A); gives the eigenvalues of A as an expression sequence. Example:

> B:=matrix([[1, sqrt(2)], [-ln(3), 3]]):
> evalf([eigenvals(B)],5);
                    [2. + .74404 I, 2. - .74404 I]

TYPES and TYPE CHECKING

Maple is not strongly typed. Variables may be assigned an object of any type. The type function is used to test if a value is of a given type, e.g.

> type(3/2,integer);
                                     false
> type(3/2,rational);
                                      true
> type([1,3/2],list(integer));
                                     false
> type([1,3/2],list(rational));
                                      true