Sei sulla pagina 1di 3

Mathematica commands summary (cheat sheet)

Hugo Touchette School of Mathematical Sciences, Queen Mary University of London Last updated: October 8, 2010 Equalities, assignments [DC] = := == =. === f[x ]:=f[x]=... Assign value Delayed eval Equality Clear value Boolean test Remember computed vals Also used for repeated eval Same as Clear Same as SameQ

Abbreviations approx Approximation arg Argument char Character cnt Counter cond Condition dist Distribution elem Element eqn Equation eval Evaluation expr Expression fct Function patt Pattern rand Random str String val Value var Variable

Patterns [DC, Tut] Blank: any expr Double blank: any seq of expr Triple blank: zero or more args Any expr named x Expr named x with head h Exact matching x x+2/.x->2 Named expr matching patt f[a b]/.f[x: ]->p[x] Optional arg with default val v Typed arg with optional val v f with any named arg n f with identical args x to any named power n Any expr to any power Sum of two named exprs List of two named exprs Pattern with cond (x /;NumberQ[x]&&Im[x]==0) Rule with cond Pattern matching boolean test f[x ?NumberQ]:=x+2 patt1 or patt2 or ... {1,x,x 2,y 3}/.(x|x n )->q Replacement in expr with rule x+2/.x->2 f[a]+f[b]/.f[x ]->x 2 Position[f[a],g[b],f[b],f[x ]] {1,x,x 2,x 3}/.x n ->r[n] Anything except c Pattern patt except c Cases[{1,0,2},Except[0]] Cases[{1,x,0},Except[0, Integer]] Files [DC] Import["file"] Export["file",expr] ImageResolution->pts ReadList["file"] <<File Import le or url Export expr in le Image resolution in pts Returns list from le Load content of le

x xh x x:patt x :v x h:v f[n ] f[n ,n ] x n x n a +b {a1 ,a2 } patt/;cond rule/;cond patt?test (patt1|patt2|...)

Output: 4 Output: p[a b]

Rules and replacements [DC, Tut] patt->expr patt:->expr expr/.rule expr/.{rule1,rule2} expr//.rule Transformation rule Delayed rule Replacement 1+2 x/.x->3 Multiple replacements Replace until no changes Can be assigned to names Same as :> Same as ReplaceAll Output: 7 Same as ReplaceRepeated

Read: patt such that cond Any real number

Applications, functions and maps [DC, Tut] f@expr expr//f xfy f@@expr Prex form f[expr] Postx form f[expr] Inx form f[x,y] Replaces the head of expr by f Plus@@{1,2} Similar to: f[x]/.f->g Map f on list Map f on parts of expr Map[f,a+b] Function with arg x Function[x,x 2][n] Map[Function[x,x 2],a+b] Many args Pure (anonymous) function (# 2&)[5] Map[# 2&,a+b] (1+g[#])&/@{1,2} nth arg in pure function Seq of all args

Output: {1,q,q,y 3} Output: Output: Output: Output: 4 a 2+b 2 {{1}, {2}} {1,x,r[2],r[3]}

f/@list f/@expr Function[x,body]

Same as Apply[f,expr] Output: 1 + 2 = 3 Output: g[x] Same as Map[f,list] Output: f[a]+f[b] Same as pure functions Output: n2 Output: a2 + b2

expr/.rule

Except[c] Except[c,patt]

Output: {1,2} Output: {1}

Function[{vars},...] body&

Type specication Output: 25 Output: a2 + b2 Output: {1+g[1],1+g[2]} Integer Real Complex Rational List Symbol String Head N Esc -dsN- Esc R Esc -dsR- Esc C Esc -dsC- Esc Z Esc -dsZ- Esc List type or head Any symbol String type of head Type Head MatchQ[x 2, Power]

#n ## Formatting [DC] FullForm MatrixForm Column TableForm TreeForm

Display full head form Display in matrix form Display in column form Display in tabular form Display in tree structure

Shortcuts [DC] Ctrl -@ Ctrl -/ Ctrl - Ctrl Ctrl - Enter Ctrl -,

Fraction Superscript Subscript New row New column

Lists [DC, Tut] {i,imax} {i,imin,imax,di} Table[expr,cnt] list[[i]] list[[i,j]] list[[i;;j]] Drop[list,n] Drop[list,{n}] Extract[expr,list] Array[f,n] Range[n] Range[nmin,nmax,dn] Position[expr,patt] Count[list,patt] Min[list], Max[list] Append[expr,elem] AppendTo[expr,elem] Prepend[expr,elem] Insert[list,elem,n] Delete[expr,elem,n] ReplacePart[expr,i->new] ReplaceList[expr,rule] Flatten[list] Flatten[list,n] Take[list,n] Cases[list,patt] Cases[list,patt,n] Cases[list,rule] Select[list,boolean] Position[expr,patt] Join[l1,l2,...] Union[l1,l2,...] Riffle[{e1,e2,...},x] Intersection[l1,l2,...] Subsets[list] DeleteDuplicates Thread[f[{a,b,c}]] Sort[list] Reverse[list] PadLeft[list,n,x] PadRight[list,n,x] Partition[list,n] Split[list] Tuples[list,n] Permutations[list] Outer[f,l1,l2] Simple counter from 1 to imax Counter with step di Generate list ith elem (list or expr) (i, j ) elem Range i to j First n elems dropped nth elem dropped Extract in expr at pos list {f (1), f (2), . . . , f (n)} Array[1+# 2&,2] {1, 2, 3, . . . , n} Full syntax List matching positions Number of matches Min, max of list expr with elem added at end Append and update expr Inset at beginning Insert elem in list at pos n Delete elem in list at pos n Replaces expr[[i]] by new Replace according to rule Flattens nested lists Flattens to level n Take rst n elem Take[#,1]&/@{{1,2},{3,1}} Elems of list matching patt Cases[{2,x 2},x n ] First n matching patt Results for which rule applies Boolean selection in list Pos where patt appears Join lists Set union {e1,x,e2,x,...} Set intersection All subsets of list Delete duplicates from list {f[a],f[b],f[c]} Sorts list list in reverse order Add x n times left of list Add x n times right of list Partition list in n sublists Splits list in identical elems n-tuples of list Permutations Outer (cartesian) product

Boolean functions [DC] SameQ[x,y] OrderedQ[list] Multiple counters possible IntegerQ[x] Same as Part[list,i] or list[ [i] ] MemberQ[list,patt] Same as list[[i]][[j]] MatchQ[expr,patt] Same as Part[list,i;;j] ValueQ[expr] Last if -n AtomQ[expr] FreeQ[expr,patt] EvenQ[n] OddQ[n] Output: {2, 5} PrimeQ[n] Same as Array[#&,n] NumberQ[expr] NumericQ[expr] PolynomialQ[expr,var] VectorQ[expr] Same as: Min[i,j,...] MatrixQ[expr] DigitQ[str] Same as expr=Append[expr,elem] LetterQ[str] See also: PrependTo Strings [DC, Tut]

Programming [DC, Tut1, Tut2] Same? (x===y) list ordered? x integer? Elems match patt? expr matches patt? expr has value? expr is atomic? expr free of patt? n even integer? n odd integer? n prime integer? expr a number? expr numerical? expr a polynomial? expr 1D array (list)? expr 2D array (list)? All digits in str? All letters in str? Do[expr,cnt] While[test,body] If[cond,t,f] Return[expr] Module[{x,...},expr] Block[{x,...},expr] With[{x=x0,...},expr] Trace[expr] Compile[{vars},expr] i++ i-i+=di i-=di i*=c i/=c Do loop While loop If statement Output expr and stop Proc with local vars (vars localization) Eval with global vars Local constants Trace eval of expr Compiled expr

Incrementation Decrementation Increment by di Decrement by di Multiply by c and override val Divide by c and override val

Output: {{1},{3}} Output: x2

Same as Same as

Pad with 0 if no x

"chars" ToString[expr] StringJoin[str1,str2,...] StringLength[str] StringTake[str,n] StringDrop[str,n] StringInsert[str1,str2,n] StringPosition[str,substr] StringCount[str,substr] StringReplace[str,rule] StringMatchQ[str,patt] StringFreeQ[str,patt] StringSplit[str] StringSplit[str,patt] Sort DateString["elem"] Characters[str] ToUpperCase[str] ToLowerCase[str] CharacterRange["char1","char2"] patt.. Whitespace Dynamic objects [ DC, Tut2 ] Dynamic[expr] DynamicModule[{vars},...] Manipulate[expr,{u,...}]

String Transforms expr to string Join strings Number of chars in str n rst chars of str First n chars dropped Insert str2 at pos n Start and end of substr in str Number of occurrences of substr Replace with rule patt appears in str? str free of patt? Split where whitespace Split according to patt Alphabetical (canonical) sort String version of date List of chars Capitalize Lower case List from char1 to char2 patt followed by symbols White space

Same as <> Last if -n Last if -n

Dynamically updated expr Module with dynamical vars Interactive widget

Useful functions Sum[f,{i,imin,imax,di}] Product[f,{i,imin,imax,di}] Mod[m,n] Solve[f[x]==0,x] Expand[p] Factor[p] Length[expr] Numerator[expr] Denominator[expr] Options[cmd] SetOptions[cmd] Evaluate[expr] Piecewise[{{val,test},...}] InverseFunction[f][x] Nest[f,x,n] NestList[f,x,n] FixedPoint[f,x] FixedPointList[f,x] NestWhile[f,x,test] NestWhileList LinearModelFit NonlinearModelFit GraphPlot[m] GraphData["name"] FinancialData["tag","date"] CountryData["tag","prop"] WeatherData["tag","prop"] Probability and statistics [DC] RandomReal[{a,b}] RandomReal[dist] RandomInteger[{i,j}] RandomInteger[dist] RandomSample[list,n] RandomSeed[] PDF[dist,x] CDF[dist,x] Histogram[list,w] Uniform rand real in [a, b] Rand real from dist Uniform integer in [i, j ] Rand integer from dist n samples from list Reset seed Density fct of dist Cumulant density fct of dist Histogram (bin width w) From [0, 1] if no arg Uniform 0 or 1 if no arg Sum Product Remainder of m/n Solves polynomial eqn Expand polynomial p Factorize p Number of elems in expr Numerator of expr Denominator of expr Display options for cmd Set options for cmd Explicit eval Piecewise denition Inverse fct n-fold fct composition List of compositions Iterate until xed point Iteration list While iteration While iteration list Linear model Nonlinear model Graph (network) for adjacency m Graph with name Financial data from date Country data Weather data

Linear algebra [DC] a.b Cross[a,b] Norm[a] IdentityMatrix[n] Diagonal[m] Diagonal[m,k] Dimensions[m] Inverse[m] Det[m] Tr[m] Transpose[l] Eigenvalues[m] Eigenvectors Dot or matrix product Cross product Euclidean norm n n identity matrix Diagonal of m kth elem in diagonal of m Dimensions of m Inverse square matrix m Determinant square matrix Trace matrix or tensor m Transpose rst two levels Eigenvals square matrix Eigenvects square matrix

Parallel computation [DC, Tut] Parallelize[expr] ParallelEvaluate[expr] DistributeDefinitions ParallelNeeds ParallelMap ParallelSum ParallelProduct ParallelTable ParallelDo ParallelSubmit WaitAll Direct parallelization Eval on kernels Put def on kernels Package on kernels Parallel Map Parallel Sum Parallel Product Parallel Table Parallel Do Submit to kernel Collect with WaitAll Results from kernels

Numerical routines [DC, Tut] N[expr] NSolve[eqn,var] FindRoot[eqn,{x,x0}] FindRoot[eqn,{x,x0,a,b}] NDSolve[eqn,y,{x,a,b}] NIntegrate[f,{x,a,b}] Numerical eval of expr Approx polynomial eqn Approx eqn in var x with seed x0 Approx eqn in [a, b] Solve differential eqn Numerical integration. Methods: "SymbolicProcessing"->0 "GlobalAdaptive" "LocalAdaptive" "Oscillatory" "PrincipalValue" "MonteCarlo" "AdaptiveMonteCarlo" Find local min with seed x0 Find global min. Methods: "DifferentialEvolution" "NelderMead" "RandomSearch" "SimulatedAnnealing"

Initial cond specied in eqn Fully numerical eval Default 1D integrals; automatic detection Cauchy principal value Random sampling

FindMinimum[f,x,x0] NMinimize[f,x]

Option: "SearchPoints" Option: "SearchPoints" Option: "SearchPoints"

Option:"Probability" "ProbabilityDensity"

NumericalCalculus package: NLimit[expr,x->x0] Numerical limit ND[expr,x,x0] Numerical D at x0 NSeries[f,{x,x0,n}] Numerical series Notes

BinCounts[list,w] Counting dist of list (bin width w) Mean[list] Also Mean[dist] Variance[list] StandardDeviation[list] ChiSquareDistribution[ ] ExponentialDistribution[] NormalDistribution[, ] BinomialDIstribution[n,p] BernoulliDistribution[p]

Copyright c 2010 Hugo Touchette Available at: http://www.maths.qmul.ac.uk/ht Mathematica is a trademark of Wolfram Research

Potrebbero piacerti anche