Notes on Maple
TABLE OF CONTENTS:
--+1. Using these Notes
--0. RUNNING Maple
--1. Quitting, Stopping:
--2. Strings
--3. Special Characters and Keys: comments,#,%,",`,',\,*,^
--4. Common Problems:
--5. Alias feature:
--6. Macro feature:
--7. File I/O routines
--8. My own library routines:
--9. Unaliasing:
--10. Maple Worksheet and Documents
--11. Maple Help
--12. Data structures: sequences, lists, sets, arrays, etc
--13. Functions and Procedures
--14. Manipulating and Interrogating Maple Structures (op,nops)
--15. Programming Constructs and Statements
--20. Maple initialization, Customization, Environment
--21. Copying outputs of Maple Routines
--22. Maple syntax:
--23. Useful Miscellany:
--24. Newsgroups
--25. Library search path:
--26. Notes on CASA (or Casa or casa) from Linz:
--27. Precision in Maple.
--28.
--29. The interface function
--30. Packages or Modules:
--31. Plotting:
--32. Debugging and Printing:
--33. Global Variables:
--34. Matrices, Arrays, Vectors
--35. MapleX tricks
--36. LinearAlgebra and VectorCalculus supercedes linalg Package
--37. Differentiation
--38. Randomization
--39. Equations
--40. Evaluation
--41. Dollar Operator ($)
--XX. WISH LIST
--YY. BUGS
--ZZ. END
--1000. END
--9999. END
--+1. Using these Notes
To search item number 123, do /^--123/
To look for references to item number 123, do /#123/
--0. RUNNING Maple
There are two versions: standard version is
"maple" and GUI version is called "xmaple".
> maple
> xmaple
In Oxford, I did tunneling to ssh to NYU to use Maple!
But you can also ssh to NYU using -X option to get GUI version:
> ssh -X yap@access.cims.nyu.edu
On my MacOS, Maple 14 has been set up for direct access to NYU.
Maple initialization file in my home directory:
.mapleinit
Upon loging in, type "?" for help. If this does not work, it means
your startup library is not correct.
This changes over time: in CIMS, the latest (2003) path is
libname := `/opt/maple/8/lib`:
NOTE: We have Maple 14 in 2011.
But to guard against changing versions (we have maple 7, maple 6,
etc, we use link from "current",
libname := `/opt/maple/current/lib`:
--1. Quitting, Stopping:
> quit; -- not "exit" or "bye"
<contl-\>: core dump, and exit forcefully from maple
<Contl-x> : to get out of a syntax error (very useful
when you typed something wrong)
<Contl-c> : to get out of current evaluation loop
NOTE: see "errorbreak". Is <Contl-x> = errorbreak 1 ??
--2. Strings
Strings are back-quoted: `...`, and they can by concatenated
using white space:
E.g., "abcde" = "abc" "de"
OBSOLETE: could also use the "||" operator or "."
E.g., "abcde" = "abc" || "de" = "abc" . "de"
NOTE on Maple 11:
"." seems to be used, but in some strange way.
But you always need a name
on the LHS of a "." operator. You can trick the system
by using the empty string `` on the LHS:
> home := `/spunky.b/faculty/yap`;
> localLib := `` . home . `/prog/maple`;
> geomLib := `` . localLib . `/GEOM`;
NOTE: if a variable x is placed in a context where a string
is expected, its "print value" will be substituted. E.g.
> x := 123;
> s := "" . x . " is an integer";
Now, s is equal to "123 is an integer".
QUESTION: seems that double quotes \" are just as good for
defining strings!??
REMARK: when using "print()", double quotes are printed
on the screen! Using back quotes will avoid this...
--3. Special Characters and Keys: comments,#,%,",`,',\,*,^
-- Rest of line comment character is #
(unless it is quoted as `#` or "#")
(REMARK: in these notes, use # for comment, not %)
If the final character of the comment line is
a non-escaped backslash, the comment continues to the next line
-- ? is for help. (?? or ??? will generate more help)
-- Percent symbol (%) is DITTO (ditto),
i.e., the value of the last computed expression
%% is the value of the second last computed expression
%%% is the value of the third last computed expression
These are called the (nullary) ditto operators.
-- How to want to enter a newline in a maple program (within an
Execution Group)? E.g., newline after each statement.
A simple return gives an error!
A: Type [Shift-Enter] or [Shift-Return]. (I never could
not find this trick on Maple help!)
-- Useful key stroke on MacOS is [Command-Delete]
to kill the extra execution groups that Maple gives you each
time you type a [Return].
-- Double quote (") is used as a string delimiter
-- Left single quotes (`) is intended
to delay evaluation one level, and used to form a symbol.
-- A Pair of right single quotes (' ') is used to delay
evaluation of the enclosed expression (see "uneval")
-- Dot denotes concatenation of strings
(and for constructing names).
-- Continuation of an input line is indicated by "\".
-- Multiplication, Exponentiation are
indicated by "*" and "^".
-- OBSOLETE:
-- Double quotes (") used to stand for the last computed expression
-- Backquote denotes strings.
--4. Common Problems:
-- infinite loop if you put a do/od block inside the
if-then statement!!!
BUGGY:
if (n>0) then do
n := n-1 ;
od; fi;
CORRECT:
if (n>0) then
n := n-1 ;
fi;
-- forgetting to put ";" at end of command.
-- forgetting to put "*" (multiplication) between
variables names (e.g., A X instead A*X)
-- using reserved names for variables:
by,...
-- roundoff errors (lack of precision)
-- see below on how to increase precision.
-- forgetting that "if" needs "fi".
-- forgetting that "if" needs "then"
-- "local" in proc must appear before all other statements.
-- forgetting all caps in "RETURN" or
forgetting parenthesis around the argument of RETURN.
-- forgetting to clear a global variable of old value: f:='f';
--5. Alias feature:
-- Calling sequence:
alias(e1,e2, ... , eN)
where ei's are equations.
E.g:
> alias(alpha=RootOf(X^2 -3), beta=RootOf(X^3-3));
> alias(J=BesselJ);
I, J
> diff(J(0,x),x);
- J(1,x)
Thus, the user types "J" but the system sees "BesselJ".
The arguments to alias are equations. These arguments are
evaluation from L to R, and the output is a seq. of all existing
aliases. In the above example, the output is I,J since
I is already assigned to sqrt(-1).
An alias may, in general, be defined for any expr. that is not
a numeric constant.
Aliases cannot be nested (you cannot define one alias in terms
of another) -- i.e., the arguments of alias are not subject
to aliasing. Thus, you can "redefine" or "unalias"
an alias as follows:
> alias(I=NEW); # redefine I
> alias(I=I); # unalias I
BUG: how does one see the definition of an alias???
--6. Macro feature:
Similar to alias, useful as a programming development tool
for naming constants and as abbrev. facility. Thus,
> macro( N=20, M=100);
allows one to use N,M in programs, and to change them
for experimentation.
Again, if you are writing a macro procedure that uses the
Maple library routine "combinat['fibonacci']", you could
define F to stand for this sequence:
>macro( F=combina['fibonacci']";
The differences from alias are:
-- that substitutions happen on input only
(so, an output of 'N' is not replaced by 20 in our e.g.)
-- the RHS of a macro definition can be a numerical const.
-- unlike alias, it does not evaluate its arguments
You can undefine or redefine a macro as for an alias.
--7. File I/O routines
--It is VERY SIMPLE to use files to record your work in classic Maple
(i.e., w/o GUI interface). Just record your work in a
text file "foo" and in Maple, do (> read "foo").
E.g. # this is a sample
with(LinearAlgebra);
m=Matrix(Ma
--To output the value of R to a file "fileOut" do:
> writeto(fileOut);
> print(R);
> writeto(terminal); # revert the output to terminal
--Instead of "writeto", you can use "appendto", which will not overwrite
the contents of the file:
> appendto(fileOut);
> eval(x^2-1,x=2);
> writeto(terminal); # revert
-- print versus lprint: the later prints expressions
in a linear format, while the former uses
a 2-D display format (e.g., exponents are
raised, rather than indicated by "^").
-- print is useful when reading large files. E.g.,
we can print some information on the
screen about what is being read from the file.
-- Q: How do you print the definition of a function or procedure?
A: Use "eval" on the function name!
> p:= proc(x) x^2; end proc;
p := proc(x) x^2 end proc
> eval(p);
proc(x) x^2 end proc
> f:= x->x^2;
2
f := x -> x
> eval(f);
2
x -> x
>
-- To write a variable X out to a text file called "foo", just do:
> save X, foo;
-- To read that file "foo" back, just do:
> read X;
--8. My own library routines:
GEOM: to augment the geometry package.
SOME functions: xcoord(p), midp(p,q), etc.
POLY: for manipulating polynomials.
You load the GEOM routines, say, by calling:
> myread(`GEOM`); # myread is defined in .mapleinit
--9. Unaliasing:
If you had previously assigned "v" to something,
and you want to call a procedure DOTHIS(a,b,v)
that expects v to be just an unassigned name, you
will get an error. So it is useful to UNASSIGN v first:
> v := 3; # original assignment to v
> v := 'v'; # unassignment. Note: it is NOT `v`.
It would be nice to have a procedure called UNASSIGN(v)
to do this:
UASSIGN := proc(v) v:= 'v'; end;
But unfortunately, this would not work,
because UASSIGN will first evaluate its argument "v",
which would then attempt to execute " 3 := '3', ERROR.
Points out the need for procedure arguments that
are passed by REFERENCE.
--10. Maple Worksheet and Documents
FAQs:
Q: There is no need to produce notes using latex if you can use
Maple Documents?
A: PROS of Maple Documents:
It is alive, it knows math, it is interactive
It produces latex output
CONS: you need maple to run (but can view output)
In any case, I should learn this tool.
Q: I want to enter a maple program (within an Execution Group)
with new line for each instruction. A simple return
will give an error. How can I do this?
A: Type [Shift-Enter] or [Shift-Return]. (I never could
not find this trick on Maple help!)
NOTE: another useful key stroke on MacOS is [Command-Delete]
to kill the extra execution groups that Maple gives you each
time you type a [Return].
HINT: You can organize the the document into sections/subsections,
each of which is a minimizable unit !!
Q: What is the difference between a .mws worksheet and a .mw worksheet?
A: Starting with Maple 9, worksheets are encoded in a new XML format
and saved using an .mw file extension. Previous format uses the
.mws files.
Basics of Maple Document:
file extension is .mw ? or .ms ?
--11. Maple Help
* For generic help:
> ?index equiv: > help(index)
* More generally,
> ?index[category] equiv: > help(index,category)
where category is expression, function, misc, module, packages,
procedure, statement,
--12. Data structures: sequences, lists, sets, arrays, etc
See Andrew Hicks' Great tutorial in this directory!
Sequences: MOST BASIC CONCEPT to master in this area...sequences has no "op"
> s := 1,2,3; # or, s:= (1,2,3);
# it is very nice mnemonics to regard "(1,2,3)" as synonymous with
# "1,2,3". E.g. f(1,2,3) takes a sequence as argument!!!
s := 1,2,3
> s;
1,2,3
> ss:= s,x;
1,2,3,x
# You can access individual entries in sequences:
> ss[4];
x
# But you cannot assign to the entries:
> ss[4] := 1 # ILLEGAL!
# Sequences have heterogeneous type:
> s := a, "xzy", array(1..10);
a, "xyz", array(1 .. 10, [])
# There is a "seq" functor:
> ss := seq(i^2, i=1..5);
ss := 1, 4, 9, 16, 25
Sets:
> c := {s};
{1, 2, 3}
> op(c);
1, 2, 3
Lists:
> l := [s];
[1, 2, 3]
# NOTE that sets and lists can be treated like sequences:
> c[2];
2
Arrays:
> a := array(1..10);
array(1 .. 10, [])
> a[1] := 321; # Assigning to s[2] or l[2] would be illegal!
321
Conversion among these types:
> convert(s,list);
[1,2,3]
> convert(l, set);
{1,2,3}
You can sort these sequence-type data:
> sort([y, x, a]);
{a, x, y}
Q: How to append to a list, set, array?
A: By appending to the underlying sequence!!!
> c;
{1,2,3}
> {op(c), 4};
{1,2,3,4}
> l;
[1,2,3]
> [0, op(l)];
[0,1,2,3]
Q: How to get the length of a sequence?
A: (Andrew Hicks) apparently the only way is use nops() on list or set
> s;
1,2,3
> nops([s]);
3
> nops({s{);
3
--13. Functions and Procedures
* To see the definition of function or procedure f, do "print(f)" or "eval(f)"
* To define a function f, it is good to first clear it:
> f := 'f';
> f <- x^2;
* Instead of functions, use procedures !
* Simplest Example (with loop and local vars):
> vander := proc(n, x)
end;
* E.g., proc to compute the order n derivative of f w.r.t. x, but
divided by n! (called pochhammer(1,n):
> myproc:= proc(f,x,n) diff(f,'x' $ 'n')/pochhammer(1,'n'); end proc;
> myproc(x^3*y, x, 2);
Note the quoting of 'x' and 'n' to prevent premature evaluation!
* Calling Sequence: (not too illuminating...)
proc (parameterSequence) :: returnType;
local localSequence;
global globalSequence;
option optionSequence;
description descriptionSequence;
uses usesSequence;
statementSequence
end proc;
Parameters
parameterSequence - formal parameter declarations
returnType - (optional) assertion on the type of the returned value
localSequence - (optional) names of local variables
globalSequence - (optional) names of global variables used
optionSequence - (optional) names of procedure options
descriptionSequence - (optional) sequence of strings describing the procedure
* Example (from Maple help) -- illustrates the "describe" facility:
> lc := proc( s, u, t, v ) description "linear combination of the
> arguments"; s * u + t * v end proc;
lc := proc(s, u, t, v) ... end;
> lc( Pi, x, -I, y );
Pi x - I y
> Describe(lc);
# form a linear combination of the arguments lc( s, u, t, v )
> lc;
lc
> eval(lc); # SO THIS IS HOW YOU PRINT THE DEFINITION OF PROCEDURES!!!
proc(s, u, t, v) ... end;
> op(1,eval(lc));
s, u, t, v
* Example from Maple help: illustrates local vas and typing:
> addList := proc(a::list,b::integer)::integer;
> local x,i,s;
> description "add a list of numbers and multiply by constant";
> x:=b; s:=0;
> for i in a do
> s:=s+a[i]; end do;
> s:=s*x;
> end proc;
addList := proc(a::list, b::integer)::integer; ... end;
> sumList:=addList([1,2,3],2);
sumList := 12
--14. Manipulating and Interrogating Maple Structures (op,nops)
-- Two useful functions are op() and nops():
> s := a, b, c;
a, b, c
> l := [s];
[a, b, c]
> op(l);
a, b, c
> nops(l);
3
-- The function "type" is extremely versatile and extensive!
> type(1.2, 'float'); # note that you must know 'float' to ask!
-- true
> type( a+b, 'polynom');
-- true
--15. Programming Constructs and Statements
0. Sample programs:
1. Information on Maple statements that can be used in procedures:
! # assignment break by
catch description do done elif
else empty end do end if error
export finally for from function
if in local module next
option proc quit read restart
return save separator stop then
to try use uses while
2. General Maple programming information:
comment DEBUG indexfcn indexfcn/exception keyword
lasterror macro maplemint mint profile
rtable indexfcn showstat showstop stopat stoperror
stoplast stopwhen stopwhenif trace tracelast
traperror unprofile unstopat unstoperror unstopwhen
untrace where
3. Names
Initially, the value of a name it itself.
E.g., The value of x is x.
You can assign to x using
E.g., x := 1;
You can un-assign to x (but must use single-quotes on x):
>unassign('x'); OR > x := 'x';
A name is one of these two:
--a sequence alphanumeric chars including "_",
and beginning with an alphabetic char
E.g. a, abc, a_2
NOT: 2ab, _ab
--a sequence of characters enclosed within left
single quotes
E.g., `_ab`, `2ab`, `abc`
4. if statements (if-statement)
if then
| elif then
| else
end if
E.g., if (a > b) then a else b end if;
5. Repetition statement (for...while...do)
E.g., for i from 1 to n do x := x+i; end do;
Calling Sequence:
| for || from ||by ||to ||while |
do end do;
OR:
| for || in || while |
do end do;
NOTE: Phrases located between || are optional,
and can appear in any order, except that the for-clause,
if used, must appear first.
E.g., > for i from 6 by 2 to 10 do print(i) end do;
6
8
10
> tot := 0:
for z in [1, x, y, q^2, 3] do
tot := tot + z
end do:
tot;
2
4 + x + y + q
6. Is there ++ or --?
--20. Maple initialization, Customization, Environment
* Initialization file in my home directory:
.mapleinit
* Environment: Do "?environment" for online help:
Digits -- number of significant digits [=10 default]
> anames('environment') # returns current environment variables.
> print(Digits);
--21. Copying outputs of Maple Routines
Some maple library routines (e.g., geometry/inter)
do not copy their outputs so that repeated calls to the same
routine puts the answers in the same location!
This gives error unless you "copy" the output. E.g.
########################################
# circenter(p,q,r) is the center of the CIRCUMcircle thru' p,q,r
circenter := proc(p,q,r)
local L,LL;
bisect(p,q,L);
bisect(q,r,LL);
copy(inter(L,LL)); # We need "copy" here -- O.W., the
# returned value is in location
# "L_intersect_LL". Then invoking
# > u:= circenter(a,b,c);
# > v:= circenter(b,c,d);
# gives ERROR: now, u=v=L_intersect_LL !
# In fact the old value of u is lost.
end;
########################################
--22. Maple syntax:
-- the return function is "RETURN(expr1, expr2,...)" (all caps!)
-- You can return the null value (useful to avoid printing
some output at the end of a function call)
RETURN(NULL); # can I do "RETURN()"?
-- You cannot omit parenthesis for return value;
-- IF/if statement:
-- Be sure to have the "then" keyword!
-- e.g., factorial function is
fact := proc(n)
if (n=1) then 1;
else (n * fact(n-1)); fi;
end;
-- Quirky! If you use "else" then you need "fi".
But a plain "if-then" does not need "fi".
-- FOR/for statement:
-- syntax is quirky:
FOR i FROM 0 [BY inc] TO n DO
END DO;
-- for-while-do statement:
-- the FOR statement can be combined with WHILE!
--23. Useful Miscellany:
-- to see the definition of a procedure P, type "op(P)" or "eval(P)" or
"print(P)". 3 different solutions!
--24. Newsgroups
The following appeared in one article of the newsgroup sci.math.symbolic:
* Daniel Dubois Maple: (519) 747-2505 *
* Maple/Prescience Prescience: (519) 747-3636 *
* Technical Support Supervisor FAX: (519) 747-5284 *
*********************************************************************
* email: support@maplesoft.on.ca (support issues) *
* ddubois@maplesoft.on.ca (personal address) *
*********************************************************************
--25. Library search path:
This value is stored in the variable "libname"
which is a comma separated string of paths.
(initially, the name 'libname' only has the
system maple directory)
--26. Notes on CASA (or Casa or casa) from Linz:
-- not available with MAPLE release 2 (which
is what we have at CSD). But the visualization
lab has release 4 which works with casa.
-- to load, type "with(casa);" at maple.
--27. Precision in Maple.
Digits is an environment variable, defaulted to 10.
It is the number of digits carried in floats.
--28.
--29. The interface function
This provides communication between Maple and the user interface
('Iris'). This function is used to set and query variables
that affect format of output, not of computation.
To Query about the "echo" variable, do:
> interface(echo);
To set the echo variable to 4, do:
> interface(echo=4);
--30. Packages or Modules:
-- use "with(package-name);"
E.g., with(LinearAlgebra);
-- to undo, use "unwith(package-name)"
-- networks package: contains functions such as
addedge, graph, shortpathtree, vertices,
connectivity, vweight, span, etc.
-- To display the help page for a particular PackageName
command, enter any one of the following commands
(where command is a name chosen from the PackageName command list).
?PackageName[command]
?PackageName, command
?command (in the case where command is a unique name in Maple)
-- To list functions in package
ShowFunctions := proc()
print(`Functions in this package: `);
print(AllFunctions);
end;
--31. Plotting:
-- trivial plot:
> plot(f, x=0..1); -- plots f from x=0 to x=1 on screen.
-- with title:
> plot(f, x=0..1, title='my plot');
-- saving plot structure:
> p := plot(f, x=0..1); -- now can zoom and manipulated p.
-- postscript output
>interface(plotdevice=postscript);
>interface(plotoutput=`out.ps`); -- else default is postscript.ps
>plot(f, x=-1..1);
-- equivalently:
>interface(plotdevice=postscript, plotoutput=`out.ps`);
-- I do not think maple could make the output in portrait mode
-- you need to manipulate the ps file yourself.
-- apparently, you can mess around with the
translate, rotate and scale functions in postscript
but the results is not what you expect???
-- I tried to use XV to convert the ps file to portrait mode,
but it resulted in a file that is over 1900 KB,
from an initial 12 KB file!
-- complex plot of multiple functions:
To plot a parametric curve (px,py) and two circles
parametrically on the same plot:
-- plot( {
[px,py, t=-15..15],
[xa+ra*cos(t), ya+ra*sin(t), t=-Pi..Pi],
[xb+rb*cos(t), yb+rb*sin(t), t=-Pi..Pi]
},
x=0..15, y=-5..15, scaling=CONSTRAINED);
-- with(plots); -- to get the plots package
-- plot3d(...); -- for 3D plotting
--32. Debugging and Printing:
-- Useful for debugging!
> print(e1, e2,..., en)
will print the values of the expressions e1, ..., en (comma separated)
-- Problem with printing of double-quotes.
To avoid it, use back-quotes instead:
print("this is a test"); # will show double quotes
print(`this is the next test`); # this is unadorned!
-- The Maple Debugger:
The Debugger prompt is "DBG>" instead of ">".
HOW to call the debugger? Four ways:
(1) At errorpoints: to (NOT automatic !)
>stoperror (errMsg); - add "errMsg" to error points
>unstoperror (errMsg); - remove "errMsg" from error points
>stoperror (); -- show curr error points
(2) At breakpoints: call "stopat(f)" to set breakpoint at f
(3) At watchpoints: To set and unset watchpoints do:
>stopwhen (globVar);
>stopwhen (procName, locOrGlobVar);
>stopwhenif (globVar, value) - conditional watchpoint
>unstopwhen (globVar);
>unstopwhen (procName, locOrGlobVar);
>unstopwhenif (globVar, value) - conditional watchpoint
showerror
showexception
(4) Executing the DEBUG(expr1,expr2, ...) stmt in a procedure. E.g.,
f := proc(x, y) local a;
a := x^2; DEBUG();
a := y^2; DEBUG(Hello);
a := (x + y)^2
end proc;
-- Maple Debugger Commands:
For a graphical user, see the Interactive Maple Debugger help page.
For command-line usage, see the following Description section.
Both the command-line and interactive debugger use these Commands:
cont - Continues execution until another breakpoint or watchpoint
next - executes the next statement at the current nesting level.
step - Executes the next statement at any level.
into - Between next and step: executes next stmt.
Execution stops before the following stmt within the curr. func.
outfrom - If stopped in a loop, execution continues until exits loop.
return - return from a function call
quit/done/stop - returned to top level of Maple (the prompt)
MORE:
where [numLevels] -- show stack of proc calls
showstat [procname, ...]
stopwhen [var]
showstack
===================================================================
ILUSTRATION: The computation below started by calling proc1. It is
stopped at The line marked . The other lines marked
show where execution would stop if "command" were issued at :
proc3 := proc()
statement1;
statement2;
true;
end proc;
proc2 := proc()
statement1;
statement2;
if 1 < 2 then
if proc3() then
statement5;
statement6;
end if;
statement7;
end if;
statement8;
end proc;
proc1 := proc()
statement1;
statement2;
proc2();
statement4;
statement5;
end proc;
--33. Global Variables:
-- Undeclared variables in a function are automatically
declared to be local, with a warning!
-- To really get global variables, you need to explicitly
say this, as in the following example:
I wanted functions to keep track of all functions
in my library: here is how it is done:
AllFunctions := []; # global variable
AddFunction := proc(f)
global AllFunctions; # this is needed!!
AllFunctions := [op(AllFunctions), f];
RETURN (NULL); # NOTE!
end;
--34. Matrices, Arrays, Vectors
-- Difference between Matrices and Arrays?
Ans: there are 4 subtypes of rtable: Array, Matrix, Vector[row],
Vector[column]. Indices of Arrays can start from any integer
(0 or negative) but Matrices and Vectors begin from 1.
* Vectors are members of a vector space, and Matrix is a linear map
between such spaces. These objects are understood by LinearAlgebra
package. Vector is a 1D rtable, Matrix a 2D rtable.
* Vector() and Matrix() have angle-bracket shortcut syntax.
* Arrays can be ANY dimension (number of indices) up to 64,
So for higher dimensional stuff (tensors), you need Arrays.
-- Specifying a vector:
or Vector([a,b,c]) -- column vector
or Vector[row]([a,b,c]) -- row vector
-- Specifying an array:
> A := [a,b,c]; # NO GOOD!!!
> A := Array([a,b,c]); # GOOD!!!
-- Specifying a matrix:
use a matrix palette
Matrix([[1,2,3], [4,5,6]]); -- a 2x3 matrix
Matrix(3,4, [[1,2,3],[4,5,6]], fill=2+i);
-- a 3x4 matrix whose upper right 2x3 submatrix
as indicated; the rest filled with "2+i"
-- Accessing entries of Vectors:
v :=
v[1] returns a
v[-1] returns d
v[[2,3]] returns
v[2..4] returns
-- Accessing entries of Matrices:
M := <<1, 0, 0>, <0, cos(t), -sin(t)>, <0, sin(t), cos(t)>>
M[2..-1, 2..-1] returns <, >
-- Subblock of matrix:
M[2..3, 1..4] returns a 2x4 submatrix of M
-- The end and start of a range can be left unspecified:
M[2.., 3..] returns a (m-1)x(n-2) submatrix of M (where M=mxn)
M[..3, ..4] returns a 3x4 submatrix of M
M[.., 2..5] returns a mx4 submatrix (!!)
-- How about discontinuous ranges?
M[[1,3],[2,4]] returns the 2x2 submatrix of M from the 1st and 3rd
rows and 2nd and 4th columns!
-- Negative index counts from the end of a range:
M[..-1, ..-2] returns a mx(n-1) submatrix.
THUS, "..-1" and ".." and "1..m" are all referring to
the same (row) range!
-- Can we assign an entire row to a matrix?
with(ArrayTools), there is a block copy function.
-- Filling matrix entries with function:
> f := (i,j)->x^(i+j-2); # fill function
> M := Matrix(3,f); # 3x3 matrix with M(i,j)=f(i,j).
-- Expanding a Matrix:
> M := Matrix(2,3,[1,2,3,4,5]);
[1 2 3]
[ ]
[4 5 0]
> Matrix(3,5, M ,fill=-1); # expand M
[ 1 2 3 -1 -1]
[ ]
[ 4 5 0 -1 -1]
[ ]
[-1 -1 -1 -1 -1]
-- Concatenate two matrices:
> with(ArrayTools);
> A := Vector([a,b,c]); # column vector
> X := Vector([x,y,z]); # column vector
> Concatenate(2,A,X); # 2x3 matrix
-- Matrix Transpose:
> Transpose(M); or > M ^ %T;
-- Array Dimensions: (number of dimensions
> A:=Array([[a,b,c],[x,y,z]]);
[a b c]
A := [ ]
[x y z]
> ArrayNumDims(A);
2
> ArrayDims(A); # equvalently, op(2,A):
1 .. 2, 1 .. 3
BUT I DO NOT SEE A SIMPLE WAY TO GET the ARRAY SIZE (2x3)!!!
Remrk: is A is simple list (NOT sequence), then nops(A) is simpler!
> ArrayNumElems(A); # total array size
6
> ArrayNumElems(A[1]); # number of columns
3
> ArrayNumElems(A[..,1]); # number of rows
2
-- Deprecated: "array" has been replaced by "Array". E.g.,
> with(linalg);
> M := array(1..2, 1..2,
[[a, b], [c, d]]);
> det(M);
-- What is the difference between Matrix and Array?
Seems like most of the basic constructs are the same!
--35. MapleX tricks
--On Mac OS:
Q: How to do Right Click to get context menu?
A: Place mouse at the object, then do [Cntl+Click]
(not [Cmd+Click]).
--Command completion: Esc or Cntl+Shift+Space
E.g., eps[Cntl+Shift+Space]
or eps[Esc]
will offer various ways to complete "eps",
including the symbol epsilon.
--Interrupt computation: [Cmd+.]
--Switch between Text and Math modes: F5
--Equation Labels: to insert the result of a previous
labeled result, type [Cmd+L] and type the number
of the label upon prompt.
NOTE: Unfortunately, there is no short way to
refer the the imeediate previous result!
--36. LinearAlgebra and VectorCalculus supercedes linalg Package
LinearAlgebra (Maple 6 onwards) and VectorCalculus (Maple 8 onwards)
There is an online help on migrating to the new package
-- new matrix and vector constructors (called Matrix and Vector)
are more intuitive and flexible, different from arrays/lists
-- Constructions:
Entering matrices by data entry
linalg
A := matrix( 3, 3, [1,2,3,3,1,2,2,3,1]);
B := matrix( 3, 3, [a,b,c,c,a,b,b,c,a]);
v := vector( 3, [5.05, 6.125, 2.980] );
LinearAlgebra
P := Matrix( [[1,2,3],[3,1,2],[2,3,1]] );
Q := Matrix( [[a,b,c],[c,a,b],[b,c,a]] );
w := Vector( [5.05, 6.125, 2.980] );
w2 := Vector( 8, fill = Pi + sqrt(2) );
For small Vectors and Matrices, the <..> and <<..>> constructor
shortcuts may be more convenient
< , >;
;
-- Determiant(W); # must follow "with(LinearAlgebra)"
--37. Differentiation
> f:= x^7*y^2 -y^3 +x -5; -- get a function
7 2 3
f := x y - y + x - 5
> diff(f,x); -- basic differentiation
6 2
7 x y + 1
> diff(exp(x),x); -- differentiation of std function
exp(x)
> diff(f,x,y); -- repeated differentiation
6
14 x y
> diff(f,x,x); -- can repeat with same var!
5 2
42 x y
> diff(f, x$2); -- higher order derivative (order 2)
5 2
42 x y
> diff(f,x$3, y$2); -- iterated
4
420 x
> n:=2;
> diff(f, x$n); -- same as order 2 derivative
-- but n can even be symbolic!
> diff(f, [x,y]); -- list argument, same as diff(f,x,y)
> diff(f, []); -- empty list argument (returns f)
ADDITIONAL TOPICS: see ?differentiate
"Diff" -- symbolic diff
`diff/f` := proc(g,x) ... -- teach Maple to differentiate f
--38. Randomization
Random numbers:
rand() -- random 12 digit non-neg integer
rand(a..b) -- returns a procedure which, when called
generates random integers in range
rand(n) -- equivalent to rand(0..n-1)
E.g., dice := rand(1..6);
dice();
Random Polynomials:
randpoly(x) -- gives a random poly in x
randpoly([x,y]) -- gives a random poly in x and y
randpoly([x, sin(x), cos(x)])
randpoly(x, terms=10) -- a (sparse) poly with 10 terms
randpoly(x, dense, degree=4) -- dense poly
randpoly([x,y], homogeneous) -- homogeneous poly
See other examples!
--39. Equations
Equations are first class objects! So they can be assigned:
E.g., eq := y = mx +b;
Now you can manipulate eq. E.g.,
rhs(eq) refers to mx +b.
This explains why assignment is not "=" but ":=".
--40. Evaluation
There are several related functions:
eval -- evaluate an symbolic expression at numerical values
e.g., eval(x^2+1, x=1) returns 2.
value
Eval
evalf -- evaluate numerically using floating point arithmetic
evala
evalb
evalc
evalhf
evalm
evaln
evalr
ExtendingMaple
limit
RealDomain
rtable_eval
subs
--41. Dollar Operator ($)
* See its use in differentiation (#37)
* Basic use: "expr $ i=m..n" means do repeated substitution for i in expr
> x $ x=2..5;
2, 3, 4, 5
> x $ i=2..5; -- expr is just duplicated!
x, x, x, x
> $ 2..5;
2, 3, 4, 5
> x $ 2;
x, x
* Suggestion: enclose 'expr' and 'i' in single quotes to prevent premature
evaluation. E.g., if i is already assigned, then "expr $ i=2..5"
would not work. You need to use "expr $ 'i'=2..5".
Tell tale error message of this kind:
Error, invalid input: $ expects its 2nd argument, range, to be of type
{numeric, algebraic, name = literal .. literal, name = algebraic
.. algebraic}, but received 3 = 1 .. 3
> i^2 $ i= 2/3 .. 8/3; -- i need not be integer!
4/9, 25/9, 64/9
--XX. WISH LIST:
Call by reference for procedures.
--YY. BUGS
--ZZ. END
--1000. END
--9999. END