Maple and Matlab
Total Page:16
File Type:pdf, Size:1020Kb
Appendix A Maple and Matlab As becomes evident when treating complicated mechanisms with long chains of linked observers, the intensity of the algebra grows rapidly. Only the simplest of problems are amenable to back-of-the-envelope cal- culations, and there is a serious risk for errors at any step in more complex situations. In the past several decades, tools have emerged for perform- ing algebraic manipulations using interactive computer environments. Programs such as Maple and Mathematica have grown to encom- pass much of algebra, analysis, and numerics. In addition to a plethora of commands for prepackaged mathematical operations, these programs generally contain a programming environment reminiscent of high-level programming languages such as Pascal or C, allowing the user to add functionality and to automate repetitive actions. A.1 General Syntax The Mambo toolbox described in the main body of this text is based on a set of procedures written using the Maple programming language and compatible with Maple V and later versions as well as with Matlab's extended symbolic toolbox. Illustration A.1 In the sample Maple session below, we highlight some fundamental syn- tactic conventions and basic operations of the Maple system. For ex- ample, the result of a computation is only revealed if the command line ends with a semicolon, being suppressed if it ends with a colon. If either is missing, the system will not recognize the end of the line. > factor(a^2-b^2); (a ¡ b)(a + b) > simplify((x^3-y^3)/(x-y)); 476 A Maple and Matlab x2 + yx+ y2 > soln:=solve(x^2+p*x+q,x); 1 1 p 1 1 p soln := ¡ p + p2 ¡ 4 q; ¡ p ¡ p2 ¡ 4 q 2 2 2 2 > simplify(subs(x=soln[1],x^2+p*x+q)); 0 > diff(x*ln(x)-sin(x)^2,x); ln(x)+1¡ 2sin(x) cos(x) > int(1/sqrt(1+x^2),x=0..t); p ln(t + t2 +1) > with(linalg): Warning, new definition for norm Warning, new definition for trace > A:=matrix(3,3,[[1,0,0],[0,cos(t),sin(t)], [0,-sin(t),cos(t)]]); 2 3 10 0 A := 4 0cos(t)sin(t) 5 0 ¡sin(t)cos(t) > eigenvals(A); p p 1; cos(t)+ cos(t)2 ¡ 1; cos(t) ¡ cos(t)2 ¡ 1 > simplify(multiply(A,transpose(A))); 2 3 100 4 0105 001 Placeholders for complicated algebraic expressions are assigned through the assignment operator := as in the example with the matrix A above. The statement > A:='A'; A := A unassigns the placeholder A. To unassign all placeholders and global vari- ables, use the restart command. Note the excellent Maple help facility, accessible through the menu system or by typing a question mark followed by the command one re- quires help with, e.g., ?subs. For the majority of commands, the help window will contain a number of examples that further highlight the grammar and syntax. Take some time to explore Maple and familiarize yourself with its functionality. A.1 General Syntax 477 All Maple statements included in this text will run in a Matlab sys- tem with the extended symbolic toolbox, provided that they are entered as maple('statement'), where statement is one or several syntactically correct Maple statements. For example, >> maple('factor(a^2-b^2);') ans = (a-b)*(a+b) >> maple('simplify((x^3-y^3)/(x-y));') ans = x^2+y*x+y^2 are equivalent to the ¯rst two Maple statements above. Here, the Maple statements are passed to the maple function in Matlab within single apostrophes corresponding to a Matlab string. Note that Matlab uses a semicolon to suppress output, so that the statement >> maple('factor(a^2-b^2);'); resultsinnooutput. In a Maple session, it is possible to break statements across sev- eral lines without any special indication. In Matlab, a statement that doesn't ¯t on one line may be continued to the next line, provided that an ellipsis (i.e., :::) is inserted at the line break. Thus, we might write >> 2+3*... (2-3) ans = -1 To break a Matlab string across several lines requires extra care, since the ellipsis should not be included in the string. Consider the following examples: >> ['tree',... 'stump'] ans = treestump 478 A Maple and Matlab >> maple(['with(linalg):',... 'A:=matrix(3,3,[[1,0,0],[0,0,-1],[0,1,0]])']) ans = A:=matrix([[1,0,0],[0,0,-1],[0,1,0]]) where we have enclosed the substrings within square brackets and sepa- rated the two substrings with a comma followed by the ellipsis. Maple variable assignments, such as the above de¯nition of the ma- trix A, allocate memory within the Matlab session and can be accessed in subsequent Maple statements. For example, >> maple('eigenvals(A)') ans = 1, i, -i These variables do not become part of the Matlab workspace, however. To allow the inclusion of single apostrophes within the Maple state- ment (as within any Matlab string), it is necessary to double each apos- trophe as in >> 'The dog''s owner' ans = The dog's owner >> maple('A:=''A'';') ans = A:='A' Finally, it is syntactically incorrect to use an upper-case I on the left-handsideofanassignmentwithinMaple, since I represents the imaginary unit and may not be rede¯ned. In contrast, a lower-case i or j represents the imaginary unit in Maple statements within a Matlab session and must be avoided on the left-hand side of an assignment or within for loops and seq statements (see below). A.2 Maple Data Structures We di®erentiate between data structures and the actions that can be performed on them. The Mambo toolbox makes use of four di®erent types of constructs that serve di®erent, and quite intuitive, purposes in the programming paradigm. These are the set,thelist,thetable,and the array. A.2 Maple Data Structures 479 Sets In Maple, the set data structure retains the everyday meaning of the terminology. A set is an unordered sequence of elements, delimited by curly braces. Thus, the statements > r:=fa,b,cg: > s:=fg: assign a set with three elements, a, b, and c,tothevariabler, and an empty set to s. The following statements perform some useful actions on sets: > r[2]; b > r union ff,dg; fa; b; f; c; dg > r minus ff,cg; fa; bg > member(a,r); true The ¯rst line selects the second element of r, but since r is unordered, the answer may change if r is assigned the same set again. The second line creates a new set, which is the union of r and ff,dg,whiletheset that results from the third line is the di®erence between r and ff,cg. Finally, the result of the last line is true if a is an element in r, and false otherwise. Lists The list data structure di®ers from the set in that the elements are or- dered, and thus selecting the i-th element always returns the same vari- able. Lists are delimited by square brackets. Except for the set-theoretic statements above, everything else would hold by replacing braces with brackets. > r:=[a,b,c]: > s:=[]: > r[2]; b Instead of the union command, we would write > [op(r),f,d]; [a; b; c; f; d] 480 A Maple and Matlab to create a list that contains the elements of r followed by f and d. Here, the operator op extracts the elements of r. A related useful command is nops, which returns the number of elements. Tables A Maple table is essentially a look-up table, such that to each index element there corresponds at most one expression. For example, the statements > r:=table(): > r[a]:=15: > r[a,b]:=Pi: assign an empty table to r after which the correspondences a$15 and (a,b)$ ¼ are established within r. In fact, any expressions are valid as indices. To check whether a table contains a particular index element, one can use the assigned command, as in > assigned(r[a]); true which returns true since r[a] does exist. Similarly, an index together with the corresponding entry may be removed from a table using the unassign command, as in > unassign('r[a]'); after which the statement > assigned(r[a]); false returns false. It should be noted that the statement > r; r will return only the name r. In order to see the actual table, one could write > print(r); table([ (a; b)=¼ ]) Similarly, to access the content of a table, we use the eval command, as in > subs(Pi=3.14,eval(r)); A.3 Maple Programming 481 table([ (a; b)=3:14 ]) where every occurrence of ¼ in r is replaced by 3:14. Arrays The array construct di®ers from tables in that the indices are limited to integers. For example, the statement > r:=array(1..3,1..3): assigns a three-by-three array to r. Array entries are accessed by the selection operator, but an error is returned if an index lies outside the prescribed range. Thus, r[1,2] is allowed, while r[0,2] would return an error. A special type of array is a matrix. This is a two-dimensional array, whose indices always start at 1. Maple contains all the standard linear algebra operations on matrices, including determinants, eigenvalues and eigenvectors, and many others. These are accessed by ¯rst typing with(linalg): at the command prompt. As with tables, one can use the print command to see the actual array or the eval command to access the actual array. A.3 Maple Programming We turn to actual programming in Maple.