Just Enough Mathematica to Make you Dangerous Joe St Sauver,Ph.D.(joe@oregon.uoregon.edu) Algebra. math Use ssh to get to the %prompt In[1]:=Expand[(x+y)2] Mathematica can expand an algebraic or hit control-d Leave Mathematica (when you're ready to!) out[1]=x2+2 x y+y expression...or factor it back to a compact for In[1]:=Exit In[2]:=Factor[&] &math sample.m sample.1st Run Mathematica commands from sample.m out[21=(x+y)2 考more8 ample.lat (non-interactively)with output to sample.Ist In[3]:Solve[x2=-81,x] Find the roots of an equation: note use of== Using Mathematica like a calculator.. out [3]={{x -9},{x->9}】 (rather than just)in writing the equation. 1n[21:=27.50-11.92 Mathematica as a good old calculator..hit In[41:=so1ve[x2==-4,x] Imaginary numbers?No problem.. 0ut[21=15.58 ENTER (or shift-ENTER)afer each comman out[41=({x--2I},(x->2r}】 In[3]:=151 Large value. sare no problem:you could even In[5]:=so1ve[{x+y=1,3x+y=2}] Mathematica can also solve systems of 0ut[3]=1307674368000 compute 1500 factorial if you wanted to 1 algebraic equations in multiple variables 1n[41:=2Log out[51={x->-,y->-} 2 atica fuction.No 2 name?Y u can use a lo see Calculus. base e).Log [b,zl gives the possible matches,e.g..?* logarithm to base b. In[1]:Limit [x/(sqrt [x+1]-1),x-0] Evaluate alimit 0ut111=2 In[5]:=Log[10,3453.8] Note that Mathematica functions are case out[5]=3.538 sensinive and begin with a capital lener. In[2]:=Dt[x3+2x,x] Compute a total derivative 1n[6]:=(4000/23)^3 Operations done on whole numbers are 0ut[2]=2+3x 64000000000 ahways represented exactly when possible. 0ut[61=-------- In[3]:=D[(x2)(y^3)+4y+x+2,x] Partial derivatives work the same way 12167 是neans“ecall the last result"and//N out [3]=1 2 x y3 In[7]:=//N means"provide an approximate numerical In[4]:=D[x^3+2x,x,x] 0ut[71=5.2601310 result' Take the 2nd derivative with respect to x out [4]=6 x In[8]:=sin[60 Degree] uare brackets In[5]:=Integrate[3x2+2x,x] Math ematica can also do integrals.just as Sqrt[3] you'd expect. out [8]= ralue?Remember//8 0ut[5]=x2+x3 Arcsin【/Degree In[6]:=Integrate [E'x,{x,0,1)] Definite integral are also easy to evaluate. 0ut[6]=-1+B In[9]:=sum[i/(i◆1),{1,1,\ Numerically evaluate an infinite sim. Infinity}]//N In[7]:.ccCalculus'VectorAnalysis" 1.62847 commands lines with a at the end of a line In[8]:-Setcoordinates[\ space ihe Out[9]= option.For example.lets the st Culindricall In[101:=Ba8 eForm[223,2] Convert the value 223 (decimal)to base 2 of the narabala=ltrtv where rty < Out [8]-Cylindrical [Rr,Ttheta,Zz] 0ut[10]//Ba8 eForm=11011111 (binary以. In【9]:。Integrate[sgrt[1+4Rr^2]\N Because of the nature of that restriction,it is In[11]:=16*FAE7+162C3E Rr,(Rr,0.1).{Ttheta,0.2Pi)]//N easier to work in cvlindrical co rdinates..形ed 0ut[11J=75557 Add FAE7 (hex)to 2C2E (hex):output by 0ut[95.33041 (note the d wh n[12 BaseForm[&,16] defandt is in decimal,but you can then force kota t12//BaseForm=1272516 that ouput into hex.too.if you like. age Package http://documents.wolfram.com/v4/index20.html
Just Enough Mathematica to Make you Dangerous Joe St Sauver, Ph.D. (joe@oregon.uoregon.edu) % math Use ssh to get to the % prompt In[1]:= Exit or hit control-d Leave Mathematica (when you’re ready to!) % math sample.lst % more sample.lst Run Mathematica commands from sample.m (non-interactively) with output to sample.lst Using Mathematica like a calculator... In[2]:= 27.50-11.92 Out[2]= 15.58 Mathematica as a good old calculator... hit ENTER (or shift-ENTER) after each command In[3]:= 15! Out[3]= 1307674368000 Large values are no problem; you could even compute 1500 factorial if you wanted to In[4]:= ?Log Log[z] gives the natural logarithm of z (logarithm to base e). Log[b, z] gives the logarithm to base b. In[5]:= Log[10,3453.8] Out[5]= 3.538 Need help with a function? Enter a ? followed by the name of a Mathematica function. Not sure of a function’s name? You can use a * to see possible matches, e.g., ?L* Note that Mathematica functions are case sensitive and begin with a capital letter. In[6]:= (4000/23)^3 64000000000 Out[6]= ----------- 12167 In[7]:= %//N Out[7]= 5.26013 106 Operations done on whole numbers are always represented exactly when possible. % means “recall the last result” and //N means “provide an approximate numerical result” In[8]:= Sin[60 Degree] Sqrt[3] Out[8]= ------- 2 Function args must be put in square brackets. Trig functions are in radians by default. Want a numeric value? Remember //N Inverse functions? ArcSin[ ]/Degree In[9]:= Sum[i/(i^i),{i,1,\ Infinity}]//N Out[9]= 1.62847 Numerically evaluate an infinite sum. You can continue long Mathematica commands lines with a \ at the end of a line In[10]:= BaseForm[223,2] Out[10]//BaseForm= 110111112 In[11]:= 16^^FAE7 + 16^^2C3E Out[11]= 75557 In[12]:= BaseForm[%,16] Out12//BaseForm= 1272516 Convert the value 223 (decimal) to base 2 (binary). Add FAE7 (hex) to 2C2E (hex); output by default is in decimal, but you can then force that output into hex, too, if you like. Algebra... In[1]:= Expand[(x+y)^2] Out[1]= x2 + 2 x y + y2 In[2]:= Factor[%] Out[2]= (x + y)2 Mathematica can expand an algebraic expression... or factor it back to a compact form. In[3]:= Solve[x^2==81,x] Out[3]={{x -> -9}, {x -> 9}} Find the roots of an equation; note use of == (rather than just =) in writing the equation. In[4]:= Solve[x^2==-4,x] Out[4]= {{x -> -2I},{x -> 2I}} Imaginary numbers? No problem... In[5]:=Solve[{x+y==1,3x+y==2}] 1 1 Out[5]= {{x -> -, y -> -}} 2 2 Mathematica can also solve systems of algebraic equations in multiple variables. Calculus... In[1]:= Limit[x/(Sqrt[x+1]-1),x->0] Out[1]= 2 Evaluate a limit In[2]:= Dt[x^3+2x,x] Out[2]= 2 + 3 x2 Compute a total derivative In[3]:= D[(x^2)(y^3)+4y+x+2,x] Out[3]= 1 + 2 x y3 Partial derivatives work the same way In[4]:= D[x^3+2x,x,x] Out[4]= 6 x Take the 2nd derivative with respect to x In[5]:= Integrate[3x^2+2x,x] Out[5]= x2 + x3 Mathematica can also do integrals, just as you’d expect. In[6]:= Integrate[E^x,{x,0,1}] Out[6]= -1 + E Definite integral are also easy to evaluate. In[7]:= <<Calculus`VectorAnalysis` In[8]:= SetCoordinates[\ Cylindrical] Out[8]= Cylindrical[Rr,Ttheta,Zz] In[9]:= Integrate[Sqrt[1+4Rr^2]\ Rr,{Rr,0,1},{Ttheta,0,2Pi}]//N Out[9]= 5.33041 Cartesian space is the default, but not our only option. For example, let’s find the surface area of the parabola z=1+x2 +y2 where x2 +y2 <=1. Because of the nature of that restriction, it is easier to work in cylindrical coordinates. We do so via the vector analysis package (note the backtick marks, not apostrophes, used when loading a package!). Package info is at http://documents.wolfram.com/v4/index20.html
Linear Algebra. Page 2 in[1]:=w={{a,b},{c,d} Create a 2x2 matrix (we're using symbols.but In [3]:=!!mydata.dat Work with y)data points from an external file out[1]={a,b},{c,d} vou could equally easily use numeric values) 4.110.7 'mydata.dat shows us the contents of the file. fetcl In[21:=w.{xy}-(k1,k2】 Read in pairs of mumbers from that file,storing b y,c x d y) In[4】:=newvals=ReadList【\ the list of values by the name newvals.Plot the {k1,k2 "mydata.dat",{Number,Number}] dataset.Fit a line to the points plot that. out[41=《{4.1,10.7},tetc1} Finally.overlay both and save as a gif In【3】:m'Transpose【w】//MatrixPorm Mathematica can easil do most standard lot1-ListPlot [n wala outt3】/atr1 xForm.a ions.for example,we out [51= aphics-/not can easily transpose matrix w.. out [6]= in[4]:=Inverse[f{1,-1},{2,2}] Or compute the inverse of a 2x2 numeric In[7]=p1ot2=p1ot[8,{x,1,8}] 11 matrix.. out [7]=-Graphics-[not showrn/ o咖ta-g-g In[8]:=show[plot1,plot2] out【8]=-Graphic8- In[9]:=Display["b.gif",&,"GIP"]0 In[5]:=Det[{{a,b,c},{d,e,f},\ Or compute the determinant of a 3x3 Out [9]=-Graphics- {g,h,i}1 symbolic matrix. 6 out[5]=-(c e g)+b f g +c d h a f h-b d i a e i Mathematica As A Programming Language. In[6]:Table [IE [EvenQ []|EvenQ[jl In addition to entering matrices on an element (Approach No. 1) If Mathematica doesnt have precisely what you need for what it has is overalll.vou ca ahav ct6if.3/arom by element basis mathenatica will also let u w=Join [Table [o,[7}],Table[5,(7],\ 11 i construct matrices using rules,such as this Tab1e[10,{4}】,{25}]: use Mathematica as a programming language example that sets elements of a 3x3 matrix to <<DiscreteMath'Combinatorica" and write your oen code.For example,assume 010 be l if the column or row is an even number. x-Union [KSubsets [w,7]]; ou hare a nile of s.10 and 25 weights Se1ect[x,(P1u80#排)<=45&]\ Using no more than 7 of them in any instance. Plotting in Mathematica... //TableForm Print ["\n "Length[],"soln's"] ou form that wil In[1]:=p1ot[x^2,{x,-5,5} Plot a fiuction over an interval.If commecting out [1]= Graphics rkstation or an X terminal (Approach No.2 * We can solve that problem using Mathematica In[2]:Display["a.gif",,"GIP ow.we als go1n8=0 Do[工4【(251+10j+5k<=45)\ Combinatorica pac age.or we 0ut【2】=-Graph1c8- saving graphic output in gifforma little program to solve that problem directly by (1++k<=7),\ looping through a three way nested do loop. Note:besides GIF format,you can also use 801n8++, wu11】,\ using an if statement to tall only solutions the Display function to save Mathematica {1,0,1},{1.0,5}.{k,0,7}1 Pr1nt【"1五",8o1n8,"801五'8"] that meet the specified restriction. 20 Mathematica on other platforms.. UO has a site license for Mathematica covering For more information.please see its installation on University owned PC's.Macs http://darkwing.uoregon.edw-hak/mathematic and Unix systems. More Information About Mathematica. 5 The Mathematica Book.4th Ed,by Stephen See also htto//www.wolfram com/aud 6 lfram [ISBN0-521-64314-7.1470 p阳gesl is http-documents wolfram co om/for copies of many Mathematica documents
Linear Algebra... In[1]:= w={{a,b},{c,d}} Out[1]= {{a, b}, {c, d}} Create a 2x2 matrix (we’re using symbols, but you could equally easily use numeric values) In[2]:= w.{x,y}=={k1,k2} Out[2]= {a x + b y, c x + d y} == {k1, k2} Use a dot product to apply that matrix of coefficients to two variables to form a system of two equations with constants {k1, k2} In[3]:= Transpose[w]//MatrixForm Out[3]//MatrixForm= a c b d Mathematica can easily do most standard linear algebra operations, for example, we can easily transpose matrix w... In[4]:=Inverse[{{1,-1},{2,2}}] 1 1 1 1 Out[4]={{-, -},{-(-), -}} 2 4 2 4 Or compute the inverse of a 2x2 numeric matrix... In[5]:= Det[{{a,b,c},{d,e,f},\ {g,h,i}}] Out[5]= -(c e g) + b f g + c d h - a f h - b d i + a e i Or compute the determinant of a 3x3 symbolic matrix... In[6]:= Table[If[EvenQ[i]||EvenQ[j]\ ,1,0],{i,3},{j,3}]//MatrixForm Out[6]= 0 1 0 1 1 1 0 1 0 In addition to entering matrices on an element by element basis, Mathematica will also let us construct matrices using rules, such as this example that sets elements of a 3x3 matrix to be 1 if the column or row is an even number. Plotting in Mathematica... In[1]:= Plot[x^2,{x,-5,5}] Out[1]= -GraphicsIn[2]:= Display["a.gif",%,"GIF"] Out[2]= -GraphicsNote: besides GIF format, you can also use the Display function to save Mathematica graphics in PDF, EPS, PCL, PBM and other formats. Plot a function over an interval. If connecting from a Unix workstation or an X terminal, your graph will be shown in a new window; we also show saving graphic output in gif format. Page 2 In[3]:=!!mydata.dat 4.1 10.7 [etc] In[4]:= newvals=ReadList[ \ "mydata.dat",{Number,Number}] Out[4]= {{4.1,10.7},[etc]} In[5]:= plot1=ListPlot[newvals] Out[5]= -Graphics- [not shown] In[6]:= Fit[newvals,{1,x},{x}] Out[6]= 5.14286 + 9.96429 x In[7]:= plot2=Plot[%,{x,1,8}] Out[7]= -Graphics- [not shown] In[8]:= Show[plot1,plot2] Out[8]= -GraphicsIn[9]:= Display["b.gif",%,"GIF"] Out[9]= -GraphicsWork with (x,y) data points from an external file. !!mydata.dat shows us the contents of the file. Read in pairs of numbers from that file, storing the list of values by the name newvals. Plot the dataset. Fit a line to the points & plot that. Finally, overlay both and save as a gif Mathematica As A Programming Language... (* Approach No. 1 *) w=Join[Table[0,{7}],Table[5,{7}],\ Table[10,{4}],{25}]; <<DiscreteMath`Combinatorica` x=Union[KSubsets[w,7]]; Select[x,(Plus@@##)<=45&]\ //TableForm Print["\n ",Length[%]," soln’s"] (* Approach No. 2 *) solns=0; Do[If[((25i+10j+5k<=45)&&\ (i+j+k<=7)),\ solns++, Null],\ {i,0,1},{j,0,5},{k,0,7}]; Print["\n",solns," soln’s"] If Mathematica doesn’t have precisely what you need (or what it has is overkill), you can always use Mathematica as a programming language and write your own code. For example, assume you have a pile of 5, 10 and 25 pound weights. Using no more than 7 of them in any instance, how many combinations can you form that will total no more than 45 pounds? We can solve that problem using Mathematica’s Combinatorica package, or we can just write a little program to solve that problem directly by looping through a three way nested do loop, using an if statement to tally only solutions that meet the specified restriction. Mathematica on other platforms... UO has a site license for Mathematica covering its installation on University owned PC’s, Macs, and Unix systems. For more information, please see http://darkwing.uoregon.edu/~hak/mathematica More Information About Mathematica... The Mathematica Book, 4th Ed., by Stephen Wolfram [ISBN 0-521-64314-7, 1470 pages] is the definitive reference. See also http://www.wolfram.com/ and http://documents.wolfram.com/ for online copies of many Mathematica documents