Вы находитесь на странице: 1из 37

color code: - light purple: code trick general - bold purple : code trick specific topic orange/brown: code

algo - bold yellow or green: question/title/topic of the problem - red : common mistake - blue: commands and package used - grey: notdone - pink: important(general) - cyan: important(specific) - Keyword: @typical, code trick, code algo (more important than code trick), notdone, Cmistake, bug., &best Maple ability : exploit the best abilities(commands) from Maple for solving problem - AppWS = Application Example Worksheet -Code Resources from Maple software: C:\Program Files\Maple 12\samples\AdvPG\graph NEED to rework the consistency of color for this worksheet in the future. Writing this tutorial basic keyword: a[i] : element, multi-dimensional list : [[[..].],[..]], expr: expression, eqs: equation Maple + 1D mode + Notepad + Ctrl J/K/T/M/R/Space+ Tools/Options/Interface/DefaultZoom=125%(big font) PRACTICAL TIPS : - When search for something, it may helpful to refer to this .rtf file. For example, I did want to find the Phi(x) for Gaussian probability distribution. Then I should click Edit/Find/ in this .rtf file or go to the section Resource/Useful help pages/?initialfunctions (for this I found erf(x) which is similar in form to the Phi(x) (but not exactly). - The most useful command I found is printlevel:= 20 (or some large value) , such as when I write the code for QuickSort algo , I could use this prinlevel output to test the code for each iteration of while loop. (This command is very helpful for writing algo -i.e to debug and verify the correctness of the code) Excel-Maple - To export Array,Matrix from Maple to Excel : click on Matrix Brower/Export/Done. - To copy/import data from Excel to Maple we have 2 ways: 1- In Maple go to Tools/Assistant/Import Data and import the entire sheet or range names of the sheet. 2- In Excel, install the Adds-In Maple toolbar, then go to View/Toolbar and find and click on Maple toolbar to pop it up. Then hilight and copy the range of data cells for copying from Excel and then in the Maple toolbar popped up we click on the icon "Copy from Excel to Maple" then we go to Maple and paste to Maple. The pasted data will appear as a Matrix so then we could use convert() to convert it to other desirable datatype.

Important Coding Tips: (al)


-sometimes we should use such as func(...,eval(my_module)) instead of just func(...,my_module) to make the code work (see Example Apps Worksheet : Object.mw) - calling proc(v::Vector,..) or proc(v::Array,...) or proc(v::table) for inline replacement such that if the code in the proc modify v then when the proc exit, v will get the modified value. If don't want inline replacement we could use proc(v::list,..) or sth else. - Use Array() to store data has the advantage over using table() about: we could use many builtin commands for Array() such as rtable_num_elems(Arr);... - Always use simplify() before using other commands such as int(simplify(f),x) - Sometimes using assume() will later make some commands/codes not working. To avoid, we could extract the assumed vars from previous command (using indets()) and write the later command in term of the extracted vars

Common mistake:
>Coding mistake: - use s:-run() instead of s:-run - v:= Vector(...) then should use LinearAlgebra:-Dimension(v) but not nops(v) ===

Some Coding methods


- use table() structure + assigned() as replacement for case or if-else stamenent : use for

distributed tasks. - use array() as global var parameter of proc to store results return from proc - Use module inside a proc , so proc used as constructor to instantiate module. - Use module()/Record() for object-oriented programming (OOP) - Use nested proc() to avoid the side-effect of enviroment vars such as Digits - Put submodules in separage files (not work yet) : see Maple14 Adv Programming about shapes package. - To avoid using global vars, use module's local var in place of global var for encapsulation. Code Snipet: table/array: if assigned(..) and not member(..)..., if member(s, entries(myTable)) then ... select(x->evalb(..), [expr]); ========================================================================= =

Some common added settings to help solve problems


- assume/assuming;== with(RealDomain) // could cause problem for other commands.==

NumericEventHandler(invalid_operation = `Heaviside/EventHandler`(value_at_zero = 0)): === with(RealDomains): _Envsignum0 := 1; (see AppWS/piecewise); _EnvAllSolutions := true; _EnvExplicit := true; Digits:=..; Normalizer := simplify Other common settings:
- interface(displayprecision=2); set autoexcute ;

System:
_EnvAllSolutions := true; solve(equation1); _EnvExplicit:= true; solve(equ1); _Envsignum0 := 1; UseHardwareFloats := false
- Environment vars : Digits:=10 # number significant digits, restart; Normalizer := simplify; int(f....) <=> int(simplify(f)..) , _EnvFormal:=true (?evalf,sum) , _EnvContinuous:=true: (int()) -kernelopts(assertlevel=1); ASSERT(type(x,integer),"x must be an integer"); ===

kernelopts(homedir); currentdir(); interface(verboseproc=3); interface(echo =4); infolevel[procname]:= 5: interface(warnlevel=0); timelimit()- timeout excution, time() === gc()-garbage collection.
NumericStatus(invalid_operation); ## see ?pochhammer ========================================================================= == &Structures : old: table(), array(),vector(),matrix() ==new: rtable(): Array(),Vector(),Matrix() == proc,module == `type/expr`,`evalf/expr`

Most use commands:


simplify(..,symbolic), expand(),normal(), rationalize(), radsimp(),combine(),collect(). - op(),nops(),value(), rhs(),lhs(),indets() ===eval(),subs(),evalf[n](),evalb(),evalc()==== print(procname) == op(0,A) <=> whattype(), about() , eval(procname), print(eval(name)),Array/table: whattype(eval(name));whattype(op(name)),eval(T,1), ,%,%%, fcn(idx)=val :remember table of func, assigned(),assign(), ASSERT(),seq(), convert(), type(),error(),member(a,b,' val ' ),select(),remove(), surd(x,n) : find x^1/n ,fsolve, solve, isolate(eqn,expr),map,map2,seq(),Map,Map2,unapply, zip, foldl, foldr,round() SingPt := rhs(op(singular(Df(x)))) : combine rhs and op to extract result from computed values. -Most useful commands when write code: zip(), map(), seq(), selectremove(), -Most useful packages for general utilities: with(ArrayTools),with(ListTools); Potential Useful commands: ArrayTools[RegularArray]: generate points with equally spacing within a range

Commands categorization :

- Keywords: Digits,lasterror, lastexception, tracelast,printlevel,infolevel, _EnvAllSoltuions,_EnvExplicit, %,%%, - See chapter 8.3 User Manual for Iterative command. C7.3 for Manipulating Expr commands - Data structure(list,sum,exprseq...) manipulations: op(),nops(),supsop(),has(),length() Help typing: macro(v=LinearAlgebra[Determinant]); alias() Strange & helpful : copy(), - Change form: sort(),assume(x,real)+ expand(),rationalize(), convert(parfrac),convert(rational),_EnvExplicit:=true, convert(sqrfree), convert(f,sum), evalc(), eval(), evalindets(), - &Function: f:= x->x^2:| f(x):=x^2 | unapply(f,x) | op(0,func):funcname|op(func):func args|, member(x,f(x,y,z)),membertype() -&Assignment: x:=2; x:=eval(b); Arr1:=copy(Arr2); x:= assign(sol); if(assigned(f))..., -&Clear: forget(): clear assigned vars inside proc() + restart + a:='a'; + unassign() + a:=evaln(a); View details, infor: about(x), Describe(cos), Describe(ImageTools), op(0,eval(A)), eval(procname), print(eval(A)), whattype(), Array/table: whattype(eval(name));whattype(op(name)),eval(T,1) -Parallel processing/mulitple elems/simultaneous: map(),andmap(),ormap(), seq(..,u=[1,2,3]),seq(...,u=1..3), $, zip(), Equate() (2 Matrices\2 Vectors\2 lists), foldl(),foldr(), ? MTM -&Complex: with(GaussInt), a+b*I, evalc()=convert(trig), abs(),Re(),Im(),Complex(),conjugate() ==evalc(abs(f)), interface(imaginaryunit), complexplot(), combine(), simplify(expand()),polar(), convert(polar),evalc(polar()), -Display names currently in session: anames(), anames(user), anames(environment) === &Macro/&name: alias(), macro(), $define -&Naming/&name: ?initnames ?anames ?unames ?envvar ?constants ?undocumentedname -&String/&name:StringTools package, (apply to string&name) cat(), ||, name||(1..3) , length(), S[i..j], substring(-3..-1), parse(string); SearchText(),searchtext(), convert(string), type/suffixed, sprintf(), sscanf(), convert(bytes):ASCII, member(), ?StringTools,Regular_Expressions -Message: WARNING("text") , error "text", cat(`text`,evalf(value), `text`); - Statistics of session : time(),time[real](), profile(), history(),showtime() -Repetition operations: foldl(), foldr(): apply proc repeatedly === related: break, next === for/while/do: for a in [1,2,3] do.., for a from 1 to 3 do .. for a to 3 do... -&substitution: eval (), subs (), simplify(a b c, {a b = Pi}) algsubs(a b = Pi, cos(a b c)); applyrule(), define(), compiletable(). -find &min,&max: diff, grad, minimize(abs,location), maximize(abs),Lagrange,Minimize,Maximize(constrains), extrema(constrained) , solve, SecondDerivativeTest, optimization package (constrained)/simplex package (simplex[maximize]), min,max(list,seq..), ============== almost the boolean below could be use for extraction or use as condition for select(),remove() Extraction from expr/eqs: indets(),select+map,remove(), student[summand](), studnet[integrand], op([i,j,k],expr), a[i], rhs(), lhs(), subsop, applyop &selection : select, selectreomove, remove (syntax in User Manual/ C9 Basic Programming)., select(specfunc) -Testing/Checking/Boolean : type(),whattype (expr)= op(0,expr), hastype(); subtype(), Testzero(),assinged(),typematch, andmap, ormap, TypeTools, type(f,NumericClass(g)) . Test relationship: verify(), evalb()<=>is(), type(verification),type(verify), LinearAlgebra[Equal] (alot of related stuff in ?verify) ?verify,float: approximately equal to some precision (almost equal) - related: convert(), assume(),assuming(), is(),?property, has() <=> depends(), coulditbe, -&Membership:numboccur(), member(),membertype(), has() <=> depends() ,hastype,hasfun,hasoption,hasassumptions, type("b", {"a","b","c"}) (matched string) <<tag>>: belong, contain,sub -Compare: testeq():test 2 polynomial equal, OrderedNE(), evalb(evalf(a-b)<eps) ==============

- Pattern &matching: typematch(), patmatch(), match(), define(), ::, tablelook() (lookup table) ,compiletable(), solve(identity()) &Series: series,taylor, convert(polynom),add/mul(), sum/product(),convert(f,Sum), FunctionAdvisor(sum,tan(x)); add= convert(`+`)., mul=convert(`*`), see also ?evalf,sum, value(Sum()) - &search/&match: with(ListTools), with(ArrayTools), with(StringTools); &inequality: inequal() - plot of inequal , &Hyperbolic sinh,cosh: convert(%, trigh) -&Path/&System/&Library/&Files: ?repository, currentdir(), libname, savelib,savelibname, save(), read(), mpl files -Display output, Print/Read/Write/Scan - Input/Output/Files: printf, print, lprint,sprintf, sscanf, fscanf, read, readline, readdata, ?interface ?kernelopts ,interface(prettyprint=2); === readbytes(), close(),fclose(), - Write to file/pipe: fprintf, save(), FileTools package :WriteString, WriteIntegers,WriteLine,....,writedata():write numerical data, :-writeline(), :-writebyte() ; writeto(),appendto() : write resutls from worksheet to file. support: filepos(), fopen(),fclose() cat("fname",1,".txt"), close(), flush() -GUI/ interactive user input: readline(), readstat(), readline(terminal),readline(default),readline(1). - &Directory: currentdir(), listdir(), kernelopts(mapledir), kernelopts(homedir); - &Date&time: time(statement); iolib(25), StringTools[FormatTime],StringTools[ParseTime] -&Random number: rand(),rand(a..b), randpoly(), randomize(),numboccur(), with(RandomTools), with(combinat), [Statistics]Shuffle(), Statistics[FrequencyTable](), Statistics[TallyInto](), Statistics[Tally](), Statistics[SelectInRange](),Statistics[Sample](), LinearAlgebra[RandomMatrix] (). - &sign: signum(),sign(), csgn(), CopySign(), -- &Tree structure: not found a command for parsing tree structure for Maple expr yet ( but in Mathematica we have TreeForm,InputForm, FullForm.

&MATH
- Limit (), limit(f(x),x=0,right), limit(expr,{x=x0,y=y0}), isdifferentiable(), discont, iscont, fdiscont // find &discont points , -&Polynomial: randpoly, indets,series,polynom, ?type,polynom,degree(),coeff,lcoeff,diff, $,testeq, divide, expand, numer, denom, norm(), surd(x,n)=x^(1/n), collect(), discrime (quadratic determinant), compoly,content, primpart(), DistDeg(), divide(), fixdiv (fixed divisor) - &Algebra: isprime,ithprime,nextprime,quo,gcd,lcm, modp(),convert(parfrac):partial fraction,numer,denom,frac, ifactor(): prime factor, isqrfree(), - &Integer: ?round, irem,iquo, floor, frac (), ifactor () ,ceil (), trunc (). issqr () - &Integration: with(IntegrationTools); int (), int(f,'AllSolutions'); value(Int()), evalf(Int()); int(f,numeric); student[integrand](), int(f(x,y), [x=a..b,y=c..d]);// double int. , intat() , _EnvContinuous:=true: infolevel[IntegrationTools]:=5; diff(f(x),x$(-n)) -&Derivative: see ?D vs. ?diff for the difference D & diff. + with(PDETools) ,with(DETools); fdiff() : numerical diff diff,value(Diff), %diff, D(f)(x),D(f)(0,0), implicitdiff(), diff(cos(t), t$5) // 5th order deriv\, dchange(), isdifferentiable() -&linear algebra: Norm(x,2) Normalize(x,2), Det(), Gausselim(), Gaussjord(), =====================================================

Specific Topics/packages: (not yet read commands will be in olive color)


***ODE: with(DEtools): with(inttrans),with(difforms) === dsolve(), dsolve(type=numeric)===plots[odeplot](), DEtools[DEplot](), dfieldplot(),phaseportrait()===laplace(), taylor(),Heaviside() === diff(y(t),t$2), D(y)(0)=0, (f@@n) (arg), (D@@n)(f)(t), convert(f,ODEs) dolsve(eq,y(x),output=basis) (see ?piecewise) ***Integral: int,Int(),student[trapezoid](), Student[Calculus1][ApproximateInt]()

*** laplace transform: laplace(), invlaplace(), alias() ***z-transform: ztrans(), invztrans(), alias() Common functions: Heaviside(): unit step, charfcn[0]: impulse, Dirac(): impulse ***with(difforms) : exterior derivative + wedge product + forms + scalarpart() : find part of expr which is scalar ***permutation/combination/to hop, chinh hop,C[n,k],P[n,k]: combinat[numbcomb], combinat[numbperm], binomial(). ***subexpression: applyop(),subsop() ***SpaceCurve: arrow(), spacecurve() ***Arclength: Vector, TangentVector, Norm(x,2), Normalize(x,2), ArcLength(), arrow() ***Curvature: Curvature, Tangent, CrossProduct or &x, curvature(user defined) ***&Data manipulations: with(Statistics), with(RandomTools), with(ArrayTools), with(combinat), numboccur() ==================================== All Packages Categorization -Polynomial related: Algebraic, algcurves (multivariate poly), PolynomialTools,PolynomialIdeals, orthopoly, - Array,list,matrix,vector : ArrayTools, ListTool, LinearAlgebra -Link to other software: CAD(Solid Work, Inventor), ExcelTools, Spread (spreadsheet) - Link to other programming: codegen, CodeGeneration, ExternalCalling, Matlab, MmaTranslator(Mathematica to Maple),XMLTools. - Probability & Statistics: Statistics, combinat, combstruct (permuation), RandomTools, numboccur(). - Engineering related: DiscreteTransforms, inttrans (integral transform), DynamicSystems (signal processing),LinearFunctionalSystems, ImageTools, Sockets, - Logic: Bits, Logic - Maple thao tac tool: ContextMenu, DocumentTools, Maplets, Typesetting, Worksheet. - Regression: Statistics, CurveFitting, - Differential equations: DEtools, PDEtools, diffalg,difforms - Efficiency of code: CodeTools - Complex number: GaussInt, -conversion of equations form (series to list,...) : gfun -Numerical: numapprox, - Format output: LargeExpressions, MathematicalFunctions, - Useful packages: IntegrationTools, Optimization, Physics,Units,RealDomain,RootFinding, SolveTools, SumTools(closed form),TypeTools ========================================================================= == Commands description/What command good for a task? (see also the "Commands Categorization" above for list of all commands available) - For commands to deals with numeric values, numbers : see the specific categories for list, set, Array,Vector,Matrix.... - copy(): rtable duplicate : a:= b (copy() assign a to b but if b change then a will not change to value of a) - Extract specific elements, range of elements in multi-dimensional list: op() - Find or count the number of elements in a list : nops() - Find or count the number of occurences, frequency of specific item, element in a list : numboccur() - Find or Count the number of elements, items in a table : nops({indices}(my_table)) or nops([entries](my_table)); #note that table could have the redudant elems such as t[0]:= 10; t[1]:=10. - Count the number of operators (additions,multiplications,assignments) : codegen[cost] - Remove redundant values : {a,b,a}={a,b} - To find the entries, elements in a list statisfying specific conditions : select(),select(verify) - apply functions repeatedly, automatically,many times : foldl(),foldr()

- convert expr to function: unapply() - convert from function to expr: f:=x->x+1 then write f(x); to get expr= x+1. -convert string to expression,statement : parse() - convert .mw document to XML document : Worksheet:-ReadFile() - To extract the substring, subname, suffix,prefix, end characters, start chars: type(x,suffixed(y)), StringTools[IsSuffix](), StringTools[IsPrefix]() - Change format : codegen[eqn] === Format output: packages LargeExpressions, MathematicalFunctions - convert decimal numbers to radical/convert radical/ convert sqrt : identify() File: - Read text from .txt file to a string : readbytes() +fclose() === read worksheet (.mw) files to XML strucure : Worksheet:-ReadFile() === read .xml file to XML structure : XMLTools:- ParseFile() - Write text string to .txt file : fprintf() +cat() +fclose()

Usage of specific commands


-minimize(f), maximize(f): find abs min and abs max but not local min and max, (could use with conditions,constraints, bound for vars) - be careful for the decision to use map() or map2(). Wrong choice may give unexpected result. geom3d package: projection(): can't project a line onto a line simplify: can't simplify(expr) such as simplify(x^2,y^2) but could do simplify(list)...such as simplify([x^2,y^2]) =====================================================================

Displaying
- interface(echo=2); interface(verboseproc=2); printlevel:= 20; -display array/Array/table : op(arr),eval(arr),print(arr), eval(arr,1); === Arr; (table same as array) - display proc/function: print(funcname), print(procname) , eval(procname) + interface(verboseproc=2) === display operands/components of proc: op(eval(proc)) , op(n,eval(proc)); === A[m..n] ; others : display(plot1,plot2..) lprint() about(x) >>num:=5; error("this is %1 and %2",num1,num2) // replace % with num1 and num2 // Placeholder for error func only For printf : printf("this is %d and %f", num1,num2): ?printf ================================================================== ==================================================================

&Proc/&Module:
Maple return the last line of proc to worksheet by default, but could use print(),printf(), a,b,c.. to return multiple results. === To write code: use Shift+Enter or Insert/ Code Edit Region interface(warnlevel=0); // turn of many uneccesary warning from proc() === interface(verboseproc=3) # print full code of proc === Proc keywords: procname, args[3..-1], nargs,varargin, _rest,_nrest, $: end (no more arg),

evaln, uneval syntax: 'procname(args)' . ex: `procname`(arg1,arg2...), global call :-procname , option remember commands: whattype(eval(proc)),print(procname),forget(procname), Describe(procname),description, kernelopts(assertlevel=2) # check arg type, error(),warning()

op(4,eval(procname)) // we should use eval() with procname,modulename,table...which are of types last_name_uneval === macro: test:= proc() uses LA= LinearAlgebra;... LA[Determinant]
(M);...end proc:

Module= object-oriented programming . Module keyword : thismodule. ===

kernelopts(opaquemodules=false)

Declareations:description, local,global,option === Module commands:exports(),member(export,mName), membertype()

syntax: with(module_name); op(eval(my_module)) :extract the exports, module call: moduleName:-exportName()=== test:= module() option package; end module: with(test); === attributes(eval(modulename)) : see the option of module ===

Special use: proc(..) module()..end module: end proc # oop : init module instances by proc === a:=proc() ...return func1,func2 end proc: a[1](..), a[2](..) # call funcs returned from proc
========================================================================= ======================

&Package
-with(package) -with(package,list of commands) such as with(difform,[defform,d,`&`]) - package[func](expr...) or -with(Student[Precalculus]) or -with(stats[fit],leastsquare) - with(RealDomain) unwith(RealDomain) LinearAlgebra:-Transpose(R) // module based package ----------------To use packages inside proc: test:=proc() uses LinearAlgebra;... end proc: // uses should be put right after local vars... or before it (local vars; should end with ; but not with colon: to avoid error) test:= proc() use LinearAlgebra in Determinant(M); end use: ...end proc: # use..end use syntax (if use with nested proc- module, have to use 1D mode) test:= proc() LinearAlgebra[Determinant](M) ...end proc macro: test:= proc() uses LA= LinearAlgebra;... LA[Determinant](M);...end proc: # note the difference between uses LinearAlgebra and uses LA= LinearAlgebra : for the later case we have to call LA[Determinant](M) but for the former we just call Determinant(M); ---------------Support commands: packages() , use..end use ========================================================================= ==

==========================

Common Directives
$include <assert.mi> $define (macro)

================================================================

General
restart : clear all varibale ===== Clear specific var: unassign('x'); x : = 'x', x:=evaln(x) Comment : # Description.....xyx Ditto operator % %% %%% :previous value, prev of prev value, prev of prev of prev value Operators: 12344\234\233 (use \ as separator or line continution) ==Help : ?topic Basic Coding x^n, x_n : superscript, subscript exp or e + Esc + choose exponential : get exp(...) (typing e without Esc is invalid exp) To enter the squareroot symbol in expr, click sqrt then click Esc then choose squareroot to get this. save sqrtcomplex, "myProc1.m" then restart then read "myProc1.m" anames (user) : see a list of assign name (such as a:=2; b:=3...) -----------------------------Thao tac co ban -------------------------------------- Type a command name and press F2 in middle of the name: open Help page for the command -Esc or Ctrl +Space: command completion : !! Parameters Template available for 2D mode only (try typing dsol..+Esc) == Use HandWritting palettle if want to find name for a symbol - Ctrl+R: switch to 2D mode == Ctrl+M : switch to 1D mode == Ctrl+T : switch to Text mode -Clt+Del : Delete line(dont' have to highligh) -shift+Enter : Enter a new line in middle of text or use to write code in for/while loop() or proc() // note that shift+Enter will not excute the command (so it 's used to write text) -Clt+C : terminate excution // better click on the termination icon on the right of the menubar of Maple. or click the next icon to go into Debug mode -Go to Maple menu and choose Insert/Label- Format-Label: use result of previous lines such as int((19)) : take integral of result computed from line 19. Ctrl + Drag: drag figure and expression (to plot for ex,)

Common useful thao tac tren Maple


Edit/Remove Output: save memory when loading worksheet. Click on the tiny left/right arrow triangle: to hide/view panels Click on the hand icon near ! and !!!: interrupt the current operation ============================================= ========================================================================= ==

Improve Efficiency/ Improve coding: (see also ?efficiency)


- View statistics(time,memory..): showtime(), time() , profile,showprofile,unprofile - Proc: option remember ============================================== First things to check when get error: 1- check for typo if return unevaluated 2- check lowercase or uppercase (i.e pi or Pi) 3- Check if we already cleared assigned vars ========================================================================= ==

&Debug:

?debugger When get an error message, the first to try is set printlevel:=100; and excute the code.
if we define f:= proc(.)...end proc: and click enter, then printlvel also show the initialization of f. printlevel not only just show infor when we call f(..) but it also show the initalization of definition of f.

see also the Help/Contents/Progamming/Debugging - Tip: wrap your code into a Maple procedure, then use the Maple debugger to step through the code. (such as test:=proc() your code end proc; stopat(test); ) The most convenient tools is list first here: 1=best, 2= next best, 3= next next best... 1) tracelast; (Excute tracelast; immediately after geting error message or the trace info

will be lost) 2) - Use print() extensively : such as use print(val) inside a proc,module,loop,... to see if val is what we expected if we suspect sth wrong with val. 3)-set printlevel:= a large value to debug nested for,while loop &nested proc & module problem... -4)Debugger commands: DEBUG(), stopat (), showstat() ,list(), where(), stopwhen() : watch point, stoperror(all) , unstopat()/unstopwhen() : clear all breakpoints/watchpoints=== showstop(): show all breakpoints/watchpoints=== showerror, showexception. To use: type stopat(f) then excute f(...); === catch specific error by: excute the statement that cause error and then excute lasterror; then copy the error output string displayed and paste to stoperror() such as stoperror("%1 index out of range") When a proc is excuting in middle , could click on the icon "debug" on the menubar to go into DEBUG mode. Conditional watch point: stopwhenif([f,var]) : use cond for global var of proc f only (global var outside f not allowed)=== stopat(f,3,i=10): could be use in case i is local var of proc f. Tip: On the Debugger GUI, hover the mouse over the button will display the functionality text of the button === stopat(evalf) =>error but stopat(`evalf/Sum`)... => good. Trick: for multitlvel-nested internal functions error we could use: stoperror(traperror); then excute the command that cause error; then the GUI Debugger will appear then type where; in the GUI then locate the error by oberving the outputs of where; (note that without using stoperror(traperror); then where return the top-level calls only (no internal commands calls shown up). -5) trace, untrace,<=> debug, undebug could use trace(MAX) then excute MAX(....) to get tracing of MAX:=proc(..) // printlevel prints more details than trace - To trace local proc g of module m : use trace(m::g) -- Conversion from 2D mode to 1D mode to reveal hidden error (see my WS Common mistake/Tool diagnose mistake) - ASSERT, kernelopts(ASSERT), kernelopts(ASSERT=true) - try.. catch.. finally, === traperror() interface(verboseproc=3); // print out proc code in more details( such as assignment of vars) -If can't determine the cause of the error use parse(..) to find location of error . See ?parse for more details. -- mint() -maplemint(procname) : checking syntax Global vars: lasterror , lastexception, tracelast; ## return last statement + value of local vars & last error. Commands: error "string %1..%2",placeholder; ===== WARNING("string %1..%2",placeholder) === interface(warnlevel=0); debugopts(traceproc= procname) // see others options in ?debugopts ========================================================================= ==

Specific Topics
-----------------------------------------------------------------&assume(x>2) => x = x~; or assuming x>2 // var which is assumed will have the form x~ // then use about(x) to see infor of x use x='x' to clear assumption ; use additionally() to add assumption without remove old assumptions, use is() or coulditbe() to check assumption . getasumptions(x), (see ?assume for all commands related to assume) - Sometimes using assume() will later make some commands/codes not working. To avoid, we could extract the assumed vars from previous command (using indets()) and write the later

command in term of the extracted vars ========================================================================= == &TYPES ?type,structure : list of all strange type + ?numeric_type : all numeric types -Related: NumericClass() , whattype(expr),whattype(op(s)), whattype(eval(s)), op(0,s) -If you are using the assume facility, it is recommended that you use the is () function. (see ? property for assume()). hastype() : type for operands of input. - x=1..2 => ::name=range Common &type() : type(`+`),type(`*`), type(function) <> type(procedure),type(builtin), type(evenfunction),type(oddfunction), type(name),type(symbol), type(expr,list(set)); type(expr,array(1,nonnegint)),type(constant),type(realcons),type(polynom),type(tabular), type(type), type(expr, 'Matrix(square)'), type(anything), type(`=`), type(equation),type(linear) Numberic type: type(algebraic), type(algnum), type(algnumext) , type(radnum), type(radical), type(complex(numeric)), type(litetal), type(integer),type(float), type(radalgnum), type(rational), type(numeric) Strange type(): type(dependent), type(freeof), type(identical), type/structure, type(set), type(posint), type(nonnegint), type(negint), type(complex(numeric)), type(anything) type/last_name_eval : for proc,module,table : eval(t); type(t,last_name_eval);

&PLOT
related: with(Statistics) -&plot3D: plot3d(),spacecurve, textplot3d, arrow(),PLOT3D(CURVES(..)), PLOT3D(GRID)MESH(), &plot: with(plots),with(plottools), ?plot,structure, display, display3d(), lprint(plot(..)), plot(),plot3d, display(array[p1p2]); plot kinds: plottools[arrow], plots[curve],PLOT(POLYGONS())-CURVES()POINTS,PLOT(TEXT()),contourplot(),contourplot3d(), &animation: plot(p1,..,pn,insequence=true), plots[animate],plots[animatecurve], animate() plotoption: scaling=constrained,style=patchnogrid,filled=true, COLOR(RGB,1,0,0); view=,lablel=,numpoints=,symbolsize= plot support: convert(listlist): convert from Array of plot data ||evalf(plotdata)|| convert(f,numericproc)|| hasoptions(),convert(gridpoints) , convert(f,PLOToptions), convert(POLYGONS), convert(red,colorRGB) - plot(...., scaling = constrained) // make y-unit = x-unit => circle not become ellipse - plots[display](seq(plot(A[i],color=COLOR(HSV,(i+2)/5,0.9,0.9)),i=1..3)); - plots[display](seq(plot(A[i],color=COLOR(RGB,(i+2)/5,0.9,0.9)),i=1..3)); Common commands: listplot(), pointplot() -----------------------------------------------------------------&Solve equations: (tags: roots, zeros) solve(f(x)=0, x=a..b) // solve roots in interval a..b === fsolve(eq,complex) solve(eq,{x}) solve(..,complex), solve({eq, x>0},x) or solve(eq,[x], UseAssumptions) Assuming x>0; solve(identity(...)) related: _EnExplicit:=true; _EnvAllSolutions:=true; assign(solutions), assuming, assume(), rhs(),lhs(), lhs(2..5) = 2, rhs(2..5)=5; -isolate(equ, expr) // solve for the expr in equ=> could be use to solve x^2=... instead of let t= x^2 and then solve equ for t. - solve(identity()) == match(),patternmatch(),typematch(): patern-matching, partial fraction -rsolve() : solve recurrence relation, recursion, recursive.=== roots (), root[n] == isolve (), -a = RootOf(z^4-z^2+1) then allvalues(a); then convert(a,radical); (see ?RootOf () ) -a = RootOf(z^3+1, index = 2) : if there are n roots , then idx=2 means a= the 2nd root. allvalues({...}) : to display all values of RootOf(...solution) === convert(a,radical)

- Equate() // use to write equations Commands related to solve() : isolate(), identity(), match()/patmatch()..., with(RootFinding), with(SolveTools), NextZero() &Evaluate: see the difference among ^ , surd() (get nth root), root() in ?surd // surd(8,3) root(8,3) .... evalf (): eval to floating value (i.e from sqrt(2) to 1.4122.. \\ evalf[20](expr); // up to 20 precision digits evalc () // eval complex number; eval(%), evala (), map () // for ex, f:= x^2, then map(f, [1,2,3]) = [1,4,9]); but be careful when apply to list since map(f,{1,3,2}) = {1,4,9} since list is sorted. value (); // Inert objects can be evaluated with the value command. (see ?int) value((4.11)) -common comands: eval, evalc, evalf,evalf[n], evala, evalb, value(),

&Simplification/&simplify
-simplify () + assume (), radsimp () rationalize () , combine () collect () normal () radnormal() evalc(), expand(), eval()/subs()/algsubs() -simplify(symbolic),simplify(expand()), simplify(radical)== combine(symbolic)=== Normalizer:=simplify, Normalizer:=radnormal=== normal(expanded)== ***simplify(symbolic) and radsimp() sometimes give same result=== simplfiy(symbolic) sometimes better then expand() -factor(...,real) Factor (..) mod .. - expandon/expandoff -----------------------------------------------------------------&Set, &List, &Expression sequence - with(ListTools); Def: List:[a,b,c] Set:{a,b,c} exprseq:= a,b,c. {b,a,b}= {a,b} //remove redundant. {b,a}={a,b} //sorted === [b,a,b] = [b,a,b] op([a,b])= a,b. nops([a,b,c])=3. List: L[1..2] <=> [L[1],L[2]]; op(n,L1)<=>L[n]; L[-1]<=>L[nops(L1)]; [seq](i,i=1..3)<=> [seq](1..3), L:=[$(1..3)]; related: length(L1); nops(L1); convert list to exprseq: K:= op(g); L:= [[1,2,3],[4,5,6]]: ArrayTools:Dimensions(L) convert(..,list) seq () : // use seq instead of for loop for multiple computations &Set: intersect(), union(), minus() == a\b, remove(), member(), s[i], subset() , for a in {1,2,3}.. S[2..-3] : if S has 10 elements then S[2..-2] return elem 2 to 7 -----------------------------------------------------------------&Matrix/ &Vector/ &rtable ; with(LinearAlgebra):with(ArrayTools); with(linalg); with(VectorCalculus): with(Student[LinearAlgebra]): with(Statistics); MTM[command]() // process all elems simultaneously interface(rtablesize=20): UseHardwareFloats := false ?LinearAlgebra,General,MVshortcut: Matrix and Vector Construction Shortcuts - new: Matrix(),Vector() - old: matrix(),vector() -All commands: copy(), - rtable_dims(), rtables_num_dims(), rtable_options()...more ?rtable, Charpoly(), Matrix: LinearAlgebra:- RandomMatrix(10); ScalarMatrix(3.2, 4, outputoptions = [shape = 'rectangular']) -<<1,-2,3>|<-4,5,-6>>: Here 2 cols [1,-2,3] and [-4,5,-6] : | is col separator also have <<1|2|3>,<4|5|6>>; <1,2,3> is row 1 and <4,5,6> is row 2 Matrix([1,2,3],[3,4,5]> : 2 rows [1,2,3] and [3,4,5]. Matrix([1,2,3]): 1*3 mat; Matrix([[1],[2],[3]]): 3*1 mat; - transpose: M^%T, LinearAlgebra[Transpose(M); === convert(matrix),convert(Matrix) ---------------------Vector: <1,2,3> : col vector <1|2|3> : row vector

Vector[row] Vector[col] // see convert(M,Vector[row]) ----------------------to find dot product: can't type a*b but should type a.b (where . is in the same key with >). For matrix, also use M1.M2. -Use the user-defined func to calc the norm of vector in vectorfuncs.txt since the one from Maple package gives too complicated answ and can't be simplify. -For large matrix,array... matrix not shows in full in worksheet but as placeholder, so we have to double click on placeholder to open linalg package : dot product: &*, evalm(A&*B); - Should include the datatype in defining Matrix such as M2:= Matrix(M1,datatype='float') to reduce overhead checking.

&Array/&Table ( ArrayTools package)


- array(-1..3): table(-1=a,0=b,..3=d); - commands: entries(), indices(), member(..entries()) , assigned() - display array/table: eval(arr), op(arr), print(arr); === - display Array : ArrayName; === whattype(eval(myTable)); - A::array(1,numeric) : array A of type 1-D array having numeric elems. - When modify array inside proc; when proc exit , modified array return outside proc. - Common Syntax: proc(x::Array(numeric,5..7))=== indices(table_name,'nolist) Empty list,set,table,array...: seq1:=NULL:list1:=[]:list2:=NULL: table1:=table(): set1:={}: array1:=array(1..5): vector1:=vector(1..5): , Array(0..1); - Commands: ArrayDims(), ArrayNumDims(), ArrayElems(),ArrayNumElems(), ========================================================================= == ========================================================================= == &Conversion/&convert : type ?convert and check for all types of conversions listed convert(f(x),float);=== convert string to ASCII : convert(f,bytes) and convert back from ASCII to string convert(2.345, rational) , identify(f) // convert f to closed form. convert from boolean to 0-1 : evalhf(); // but note that evalhf() can't convert a list but one at a time. -convert the expression into a function of x, however, by using the unapply command. (x^3; d3:=unapply(%); =>d3:=x^3) could also use makeproc() My favorite convert() / conversion: compose, base:(decimal-binary), radical, ln, rational, elementary:to elementary functions, to_special_function, (abs/signum), (degree/radians), FormalPowerSeries, parfrac, vector,Matrix, (trig/trigh), truefalse, surd, ratpoly, polynorm, expsincos, listlist,list, - convert(f,Sum) : convert to power series form. - Tip: convert(f(exp()),trig) : exp->cosh,sinh ========================================================================= =

&Keywords/&Glossary/&Terminology

-Context Menu: right click-menu, built-in commands, built-in functions. Context Sensitive Menu

-Palettes: right panel , left panel, symbols

-statement (could be multiple commands ) , command (save(),nops()..) , function (x->f(x)), procedure (test:=proc(...)).

-worksheet session, terminal (interactive)

-hyperlink, repository, Maple internal storage manager,

Keywords: FAIL, true, false, infinity, NULL,x:=[]; undefined, rtable(rectangular table), type(f,anything), if a <> b, if not negint,posint (is(5,posint)) , radical : such as sqrt(2)^(1/2) === rational: such as 1/2 (integer/integer)

- Back quote (name,symbol) : ``: `module` === Forward quote (= unevaluation quote) :'name' ===double quotation mark (string): " "

-backslash :\ (" \"test\" ") === double backslash: C:\\my_dir\\file.txt -ditto operator: %,%%,%% %:===

-terminal (suchas writeto(terminal)) ===

- _Zk : integer, _NNk: nonnegative, _Bk: binary, _Nk: negative integer // use s.a. about(_Z5); to see the range of _Z5 (see ?solve)

-rtable : Array,Matrix, Vector === table: array,matrix,vector.

Strange symbol:

abs(1, x). This is signum(x) for all non-0 real numbers

-x~ : assume, tilde === -proc(var1::integer) : validate arg === -proc(x,y,$) : end marker === ========================================================================= ===========

Rule:
-Different between Sum, Int, Limit and sum,int,limit... Sum is inert form and is unevaluated but sum eval to a value. -When use : assume(x,condition) such as assume(x>0)... then expr involving x will have the form x~ which is x under condition. -A_3..() : ( ) is similar to end in Matlab (i.e A(1:end)) - Array() : rtable= rectangular table - When we see: a U b then we know that the author uses the Symbolic Panel to get the symbol U for union. Multiply matrix and dot product, we use .(same key as >) instead * Enter spacebar for implicit multiplication such as x y = x*y Binary infix operators : write <1,2,3>.<2,3,4> is equiv to `.`(<1,2,3>,<2,3,4>) (dotproduct) The backup file from Maple have extension .bak &* : matrix multiplication in old version of Maple operator form: `if`(cond,A,B) normal form: if (cond) then A else B end if; {B}) and A union B; for ex, `union`({A},

eval() is built-in, but can call to `eval/piecewise` a Library routine ========================================================================= ========== ========================================================================= ==

How to Type
To type conjugate of a number , type conju then use command completion to get conjugate. -Tab icon (for typing tab): this button work on Text and 1D mode only ========================================================================= ===========

FAQ - Look for something


-Look for placeholder meaning such as %d, %f... go to ?printf -brace matching in writing code ( search keyword brace matching in Most Important of Maple.mw). Note that Maple not only provide finding of match brace but also find match in " " and '' File extension in Maple: .mpl,.m, .wm, .wms,.lib, .mla, .maplet (see ?file and ?file_types)

========================================================================= == ================================================================== ==========================================

Resources from Help pages


Help/Manual&Dictionary and more/ topics: List of Packages, List of Commands, Plotting

Guide, Task, Manual, Dictionary, Resources - Go to application examples worksheets: 2 ways : 1- go to Help/Manual&Dictionary and more/ Application & Example 2- type ?index Useful help pages: -Tip: Put the details after ?name to view more details such as ?solve,details. ?index : list of all packages, functions, programming, expression, Application Example.... ?worksheet : plotting, shortcut, documents... ?worksheet/Worksheet Shortcut Keys/2DMathShortcutKeys : include subscrip/literal subscriptGreek alphabet... ( alternatively, goto Help/Manual & Dictionary/ ShortCutKey/ 2D MathShortcutKeys) ? initialconstants : list of all names such as infinity, NULL ... avail in Maple. : === ?constants (list names of Maple constants) ? initialfunctions : list of all mathematical functions (known to diff(), simplify()...) (&functions, list functions) === ?precedence : list of operator precedence ?operator : all topics related to operators. === ?selection: indexing of array/table/list/set... ? io_errors: list of all io errors ?parameter_modifiers: proc argument constraints ?type : list all avail Maple types === ?type,structure: special type such as specfunc, list(name)... === ?numeric_type: list of all numeric types such as complex, float, extended_numeric. ?property : property used with assume() ?coords: all coord in Maple - ?printf: see a list of place holder such as %c , %f.... help("worksheet,expressions,mathobjects"): know about list,set,expr,table,array.... ?units/index: list all things about units -For repository,lib : ?repository,management ?libname ?march ?worksheet,reference,initialization : about and create Maple initialization file. ?file : all types of extension for files. ?compatibility : classic and modern worksheet ?last_name_eval : for display array,matrix,vector,table,proc,module using eval(A,1) Include other useful infor: ?numerics:(computation commands), ?efficiency ?extension, Connectiviy with other softwares: ?Excel: use Maple commands in Excel Strange Help topics ?boolean: true, false, FAIL... ?reserved == ?keyword , ?protected: proctected and reserved words. ?gc : garbage collection ? StringTools[RegMatch] : curry() (al)

Resources / Searching
Table of Conversion of All Coordinate Systems to Cartesian ?VectorCalculus,Coordinates -anames(builtin) : List built-in functions in Maple kernel. -Help/TableOfContent\Error Message Guide: List common Error code and Corrections ========================================================================= ==

View Built-in Maple code or code inside Proc


1) interface('verboseproc'=2): print(procname); or op(procname); For example, interface(verboseproc=3); print(GAMMA); note: if use print(pdesolve) to view the code then we find that this code will call `pdsolve/numeric` so we could use print(`pdsolve/numeric`) to view the code of `pdsolve/numeric`. Tip: when see a command such as simplify/size and we want to view the code, we have to put backward quote around the command name when print() such as : print(`simplify/size`) or print(`type/stack`)

2) could also use LibraryTools[Browse](). Then choose a package and click on Edit and choose a command and click View button.(note: some commands don't show code) . This is best since could view code inside Maple built-in module and also have search for keyword feature (so that could search for name of the module we want to view code). For ex, use this tool to look for module: stack to view code. But this method is limited for several libraries (i.e , it can't find combinats:-fibonacci , for examle). 3) kernelopts(opaquemodules=false) : view local + exports routines of module. (Use in case LibaryTools:-Browse() can't find code for the command) (We could view the code of the local members of module also)=== ( Usually the built-in packages from Maple didn't upload the help pages for all internal modules/procs of the packages so to know the code of the internal modules/procs, we should set kernelopts(opaquemodules=false) for ex : print(Statistics:ProcessDistribution);) Usage example: kernelopts(opaquemodules=false) ;+ interface(verboseproc=3); + print(combinat:-fibonacci);

View algo : forget(int), infolevel[int]:=5; int(...); (sometimes I set this but it not working , so
have to do many time) // print out steps/traces used when doing int() infolevel[Student[LinearAlgebra]]:=1 ProjectionPlot(...) // display more details of results besides the plot ( normal, proj, ...) infolevel[hints]: // return hint (such as assume cond so that unsolved prob could be solved) eq := x^2=sin(x); infolevel[all]:=5: solve( eq, x ); 5)p1:= plot(..); about(p1) // use about() to view all the coords of points in the plots

6) FunctionAdvisor('definition', BesselI) : ?BesselI then click on definition// didn't display the formula for this func but FA could give some infor... such as function definition. ========================================================================= == Code tricks: - Exchange, swap: a[i],a[j]:= a[j],a[i]: === when encounter a function structure f(g(x,y),h(x,y,z)... the command op(0,expr) is very useful. - convert list to set : {op}(alist), map(Sample@RandomVariable,[R1,R2]); - (CDF,PDF,Moment) (R,t) or map(apply,[CDF,PDF,Moment],R,t) === Syntax: - Floating points evaluation: evalf(expr) or write expr = sin(3.). - infolevel[LinearAlgebra]:= 2: - Boolean: And(x>0,y>0,z<0) === x>0 and y>0 === if not evalb() .., if not And(a,b)..., - for i in [a,b,c] do... === seq(i,i=[a,b,c]), seq(1..3); === if(a>b) then...elif... else ... end if; or `if `(a>b,res1,res2) or ' `if` ' (a>b,res1,res2) - ` intersect ` (a,b,c), a intersect b === union, minus - myver:= And(Not(set),`subset`) ; verify({a,b},{a,b,c},myver); === remove(type,["a","b","c"], {"a","b"}) - verify([x*(x-1)],[x^2-x], list(expand)) - error "there are less than %1 documents", 10; - test:= proc() use LinearAlgebra in ..... end use: end proc: === LinearAlgebra[Transpose](A) === LinearAlgebra:-Transpose(A)=== with(LinearAlgebra); Transpose(A) - Difference between proc()...end proc: and f:=(arg) ->command : we could excute many commands inside proc but could have only 1 command inside f:= (arg)->comm - We could also use %,%% inside proc() end proc: - Initialize: t:= table() == alist:= [] == x:=NULL:== A:= Array(1..0); - Vector(1..n, i-> f(i))== Matrix(m,n, (i,j)->f(i,j)) - create [a1,a2,a3]: a||($1..3) - Record(':-id'=id, ':-fetch'=fetch, ':-filter'=filter) - sort(mylist, (x,y)->lhs(x)>lhs(y)) - [a,b](x,y), (a and b)(x,y) -constants := constants, my_const; # if want to define my_const as constant (this is very helpful trick) or use assume(my_const::realcons) Some useful commands: `tools/get_functions_called`(sin); // give the functions dependencies/relation ========================================================================= =========== Already read MaplePrimes : all articles for search keywords "sample" , "debug" , Some other keywords: - Strange result when calculating Mean symbolically - sqrt(x^2) -Extract specific coefficients of a multivariate polynomial -Not yet understand > Keyword "context menu" : downwards context-menu actions & output === 2-D plot with context menu === ==================================== Current work: Help/List of Commands to this wordpad : ( I already put to this wordpad up to the command Gausselim(), but not finish since I think future Maple version will change the commands)

Вам также может понравиться