November 7, 2012 Eric Rasmusen, erasmuse@indiana.edu This file is now at http://www.rasmusen.org/a/mathematica.rasmusen.txt These notes are latest Mathematica tips and tricks that I have found useful or thought might be useful. I wrote these for my own use and have not tried to make them clear for others, but some other people will find them useful. ********************************************************** At the start of every file put: (* Date and title *) SetOptions[Plot, AxesOrigin -> {0, 0}]; SetOptions[Plot3D, {AxesOrigin -> {0, 0, 0}, Axes -> True}]; SetOptions[Graphics, {AxesOrigin -> {0, 0}, Axes -> True}]; SetOptions[Graphics3D, {AxesOrigin -> {0, 0, 0}, Axes -> True}]; Clear["Global`*"] (*This allows you to clear all the variable values \ as needed.*) I have Mathematica 6, site license L2889-8203. NOw I have 8. Googling often works better than the official help site. http://www.pa.msu.edu/~duxbury/MathemIntro.html is a very good list of tips. https://pantherfile.uwm.edu/sorbello/www/classes/mathematica_commands.html A very good list of important Mathmetica commands. http://www.wolfram.com/solutions/highered/homeuse.cgi For getting started: http://www.indiana.edu/~statmath/math/mma/gettingstarted/doingmath.htm l The company documentation site: http://reference.wolfram.com/mathematica/guide/Mathematica.html?docs See also: http://reference.wolfram.com/mathematica/guide/Mathematica.html For my old input and output files for mathematica diagrams, go to: http://www.rasmusen.org/a/math/ ---------------------------------------------------------------------- iuanyware.edu has Mathematica, STATA and other program useable from anywhere. You first download the Citrix receiver program and install that. Go up to the Evaluation tab to actually do the things you've typed in, or do SHIFT-ENTER. Clear["Global`*"] for clearing everythign. I can make a macro by defining clearing1= Clear["Global`*"] and SHIFT-ENTER on its output. For a Greek alpha in a text label, try this: \[Alpha] CTRL-Z undoes the previous command. \[Element] gives the "in" element of sign. Sqrt[5] gives the square root of 5. ---------------------------------------------------------------------- ANIMATIONS--TRYING OUT DIFFERENTP PARAMETER VALUES This will give a slider bar to try changing f in values in [1,5]. Animate[Plot[(f/q) + q, {q, 0, 10}], {f, 1, 5}, AnimationRunning -> False] You can make a slider that changes the value of x wherever you've made something dynamic by putting the Dynamic command around it, going back and changing the value from what you put in earlier. Slider[Dynamic [x ], {0, 10 }] The next command makes a local slider that just changes x for inside the square brackets DynamicModule[{x }, {Slider[Dynamic[x], {0, 1}], Dynamic[x], Dynamic[Plot[y^x , {y, 0, 3}] ] } ] Here, we create a two-ple point x that we can vary by dragging the point in the control: Control[{x, {0, 0}, {1, 1}}] Dynamic[x] Dynamic[x^2] Graphics[Line[{Dynamic[x], Dynamic[x^2]}] ] -------------------------------------------------------- FINDING THE SIGN OF AN EXPRESSION Start with Sign[x^2+1] Then use Simplify [y, {x \[Element] Reals}] And it will return 1, because it is positive. Or, just do Simplify[Sign[x^2+1]] -------------------------------------- PROGRAMMING Use the WHILE command. ------------------------------ COMBINATORICS Needs["Combinatorica`"] This is MAYBE needed for the KSubsets command. KSubsets[variables, 3] gives the 3-element Combinations of the file variables ---------------------------------------------------------------------- COMMENTS Right click on a selection and you get a menu which allows you to comment or uncomment that selection. 2. I want a macro that will make comments a one-character thing as in Latex --%. How can I make a macro for that? ------------------------------------------------- OPEN CIRCLES AND AXES IN DIAGRAMS A problem is that mathematica won't add anything to a diagram outside the plotrange, and the axis goes all the way to the edge of it. To solve that , use AxesStyle -> White, TicksStyle -> {Black, Black}, which keeps the axes lables and ticks but makes the axes white. Then draw lines in to represent the axes,e.g., Line[{{0, 0}, {12, 0}}], Line[{{0, 0}, {0, 14}}] I couldn't get opaque circles, even tho Mathematica has commands that supposed put some objects in front and make them opaque. ---------------------------------------------------------------------- DATA PLOTTING DATA ENTRY Clear["Global`*"] SetDirectory["C:/__PAPERS-1stCURRENT1st-tier/Lost-Decade/graphs"] FileNames[] Directory[] gg = Import["jan6b.csv"] That tells the current directory, shows the files and folders in it, and changes it. Put the data into a csv file with no labels, e.g. jan6a,csv.Set the working directory and import the data into a list. To see it as a matrix, use MatrixForm[gg]. The rows are years and the columns are variables. To create a year vector or a variable vector, type: y1980 = gg[[5]] gdp = gg[[All, 2]] To plot one variable or two, or make a fancier plot: ListLinePlot[gg[[All, 2]], DataRange -> {1980, 2010}] ListLinePlot[{gg[[All, 2]], gg[[All, 4]]}, DataRange -> {1980, 2010}] plot1 = ListPlot[gdp, DataRange -> {1961, 2010}, AxesLabel -> {"Year", "Growth in GDP per Capita"}, Filling -> Axis, FillingStyle -> Red] ---------------------------------------------------------------------- (* Here is a comment *) p=x3+3x2+3x+1 Solve[p==0] Here is how to expand the previous output, called %: Expand[%] Simplify[%] Here is a function defined: f[x_]:=x^2 and the function can be used like this: f[2] ---------------------------------------------------------------------- FINDING AND SETTING OPTIONS Options[Plot] This gives all the default options settings for Plot SetOptions[Plot, AxesOrigin->{0,0}] This resets the default options for all plots in the session. ---------------------------------------------------------------------- TITLES OF FIGURES plot1 = Plot[Sin[x], {x, 0, 10}, AxesOrigin -> {0, 0}]; Graphics[ {Inset[plot1, {0, .8}], Inset[Text["A Sine Wave"], {0, .4}] } ] These commands put the plot above the caption. Using Inset allows positioning. ---------------------------------------------------------------------- POLYGONS VS LINEPLOTS Graphics[{ Opacity [0.3], EdgeForm[Thick], Polygon[{{0, 0}, {1, 1}, { 2, 4}, {3, 1}}, VertexColors -> {Red, Green, Blue}] } ] ListPlot[{{0, 0}, {1, 1}, { 2, 4}, {3, 1}}, Joined -> True] Listplot puts the same points on a graph with an axis but with the points not all connected. ----------------------------------------------------------------- Here is how to get Pi to 20 digits: N[Pi,20] Here is how to make the previous expression into decimal form: N[%] ------------------------------------------------------------------------------- DIAGRAMS STANDARD PLOT OPTIONS: AxesOrigin -> {0, 0}, PlotRange -> {{6, 0}, {0, 6}}, AspectRatio -> 1/1,AxesLabel-> {"Firm 2's Output","Firm 1's Output" }, PlotStyle -> {Thickness[.009], Dashing[{0.03, 0.01}], PointSize[.02]}, Ticks -> {{1, 1.5, 2}, {-1, .5, 0 }}] All of the Plotsttyle stuff must go in one Plotstyle command. Mathematica has a Mayra-Paintbrush style drawing tools under the GRaphics menu. It doesn't have bezier curves, tho. --------------------------------------- TEXT caption1 = Text[Style[Subscript[w, 0], FontSize -> 14] ] caption1 = Text [Style[ "fun(w)" , FontSize -> 18,FontFamily -> "Helvetica"]] ] Better, for subscripts type CTRL-minus and then whatever is in the subscript "To set font for all future graphics text: $TextStyle command is not in Math 6,7,8. It is replaced by the DefaultBaseStyle command, which I can't get to work and which is poorly documented. Stylesheets are mixed up in that oo. You can use the FORMAT menu to change the appearance of highlighted things in the notebook. Don't highlight items on the Plot itself--do it on the PLot command that creates the chart. --------------------------------------- Here is a 3D plot. First is the function, then the range for each dimension, with an option for a 0,0 origin: Plot3D[ Sin[x y], {x,0, 3}, {y, 0, 3},AxesOrigin={0,0}] ------------------ HERE IS HOW TO PUT THREE PLOTS SIDE BY SIDE: plot1 = Graphics[GraphicsArray[{plot2x, plot3x, plot1x}]] ------------------ ListPlot[{{{1, 2}, {4, 4}}, {{1, 3}, {4, 4}}}, Joined -> True, AxesOrigin -> {0, 0},ListPlot[{{{1, 2}, {4, 4}}, {{1, 3}, {4, 4}}}, Joined -> True, AxesOrigin -> {0, 0}, PlotRange -> {{6, 0}, {0, 6}}]] This will generate two line segments on one graph, each from one point to another. The Joined option makes them line segements instead of just 4 points. PlotRange gives the two points for the SE and NW corners of the graph. Below is code I used to make a reaction curve diagram. It could be improved, but it does OK. plot1=Plot[{{120 - 2 q}, {60 - q}, {60-q/2}}, {q, 0, 120}] plot2 = ListPlot[{{0, 60}, {30,30}, {40,40}, {60,0}}, PlotStyle -> PointSize[.02]] Show[plot2, plot1, PlotRange -> {{0, 130}, {0, 130}}, AspectRatio -> 1/1] plot3 = Graphics[Text["Firm 1's Reaction Curve", {80,30}]] plot4= Graphics[Text["Firm 2's Reaction Curve", {30,80}]] plot5 = Graphics[Text["Cournot equilibrium", {42,42}]] plot6 = Graphics[Text["Cartel Output", {32,32}]] Show[plot2, plot1,plot4, plot3, plot5, plot6, PlotRange -> {{0, 130}, {0, 130}}, AspectRatio -> 1/1, AxesLabel->{"Firm 2's Output","Firm 1's Output" }] I think I could just have Text["Firm 1's Reaction Curve"] with the Graphics outside it. ------------------------------------- http://reference.wolfram.com/legacy/teachersedition/MathematicaBook/31.2.html http://www.physics.mun.ca/~cdeacon/laboratories/graphs/graphplot.pdf I coudl not get the Export command to work to go to a particular location. Instead, just right-click on the ojbect and save to a pdf file wherever you like ---------------------------------------------------------------------------------- TURNING A RULE INTO AN EXPRESSION Solutions give output like z= {{x->x^2=4}},which is a "rule". It must be reduced to an expression to be useful. First you do z1=Part[z,1] to get rid of the outer brackets. If the rule were z= {{x-> x^2+4},{x->3} } it would take out just the first one and give you {x->x^2+4} . To make it an expression called qb1, do this: qb1= x /. rule1 That says qb1 = x^2+4 To make a function f[x]=x^2+4, follow up the last command to make a definition with f[x_]:=n Here is an example: In[292]:= a1 = Solve[x^2 + 5 x + 2 == 0, x] a2 = a1[[1]] a3 = x /. a2 a3 Out[292]= {{x -> 1/2 (-5 - Sqrt[17])}, {x -> 1/2 (-5 + Sqrt[17])}} Out[293]= {x -> 1/2 (-5 - Sqrt[17])} Out[294]= 1/2 (-5 - Sqrt[17]) Out[295]= 1/2 (-5 - Sqrt[17]) y=p/.p->3+x This sets y= = 3+x. Look for How to Use Rule Solutions in Help. RUles can be used to put specific parameters into plots: Plot[v /. {s -> 3}, {p, 0, 1}] a1 = Plot[ {{return[.4], return[.01], return[.08], return[.15]} /. s -> 1.5 } , {r, 0, 1.5} ] -------------------------------- Plot[ PDF[NormalDistribution[0, 1], x], {x, -2, 2}, Filling -> Axis] ---------------------------------------------------------------------------------- FOR A DEMAND CURVE AND INVERSE DEMAND CURVE BASED ON VALUE DISTIRUBITON f(x) f[x_] := PDF[NormalDistribution[4, 2], x] q[p_] := Integrate[f[x], {x, p, 8}] Plot[ q[p], {p, 0, 7}] sol= Solve[ q[p1] == q, p1 ] p2 = Max[0, p1 /. sol] Plot[p2, {q, 0, 7}] p1[q_ ] := Max[12 - 2 q , 0] sol = Solve[p1[q] == p, q] q4[x_] := Max[0, Evaluate[q /. sol[[1]] /. p -> x] ] q4[20] Plot[q4[p], {p, 0, 20}] Plot[Max[0, 2(2 + Sqrt[2] InverseErf[-2 x + Erf[Sqrt[2]]])], {x,0, 1.1} ] c=7 p[x_] := Max[0, 20 - x^2] out1 = N[Maximize [{ p[x]*x - c*x, x > 0} , x]] xmaxp = x /. Part[out1, 2] profitmaxp = Part[out1, 1] xsocialmaxp = w/. Part[Solve[p[w]==c, w],2] surplusp = N[Integrate[p[x], {x,0,xsocialmaxp}]]-c*xsocialmaxp c=7 r[x_] := Max[0, (x+2)^(-1/3) ] out1 = N[Maximize [{ r[x]*x - c*x, x > 0} , x]] xmaxr = x /. Part[out1, 2] profitmaxr = Part[out1, 1] xsocialmaxr = w/. Part[Solve[r[w]==c, w],2] surplusr = N[Integrate[r[x], {x,0,xsocialmaxr}]]-c*xsocialmaxr -------------------------- A DIAGRAM p1[q_] := If[q < 1, (mu + s1/2) - s1*q, 0] p2[q_] := If[q < 1, (mu + s2/2) - s2*q, 0] plot1 = Plot[{c, p1[q] , p2[q] }, {q, 0, 2}, PlotStyle -> {Thickness[.009]} ]; plot2 = Graphics[Text["p1(q)", {mu/8 + .2, 2.5}]]; plot3 = Graphics[Text["p2(q)", {mu/4 + .1, 2.5}]]; plot4 = Graphics[Text["Marginal Cost, c", {1.2, c + .11}]]; Show[plot1, plot2, plot3, plot4, PlotRange -> {{0, 1.5}, {0, mu + s1 + .5}}, AspectRatio -> 1/1, AxesLabel -> {"Quantity", "Price"}] -------------------------- The InverseFunction command is a trap. It only gives output useable for symbolic manipulation, not for actual functions. Use Solve instead. http://www.mathkb.com/Uwe/Forum.aspx/mathematica/16077/Inverse-function http://reference.wolfram.com/mathematica/tutorial/PureFunctions.html Pure functions use the pound sign and ampersand. If you are going to use a particular function repeatedly, then you can define the function using f[x_]:=body, and refer to the function by its name f. On the other hand, if you only intend to use a function once, you will probably find it better to give the function in pure function form, without ever naming it. Mathematica to TeX conversion: TeXForm[z = 3x^2/2] This does not work for graphics--they will not convert to Tex. TeX to Mathematica conversion: ToExpression["input",TeXForm], where, for example, input = \sqrt{b^2-4ac} ---------------------------------------------------------------------------------- FUN STUFF Maybe use this unbounded variation example for my quasi.tex paper: Plot [ Sin[1/x], {x, 0, .1} ] Graphics3D[ Sphere[{0, 0, 0}, 3] ] Graphics3D[ {Blue, Sphere[{0, 0, 0}, 3]} ] Graphics3D[ { Green, Cuboid[{.1, 0, 0}, {.2, .3, .2}], Blue, Cuboid[{0, 0, 0}, {.1, .1, .1}] } ] ---------------------------------------------------------------------------------- Questions. 3. How can I make a default diagram style? ---------------------------------------------------------------------------------- SUPPLY AND DMEAND DIAGRAMS ls[l_] := 5 + 3 l; ld[q_] := 20 - 4 q ; mr[l_] := 20 - 8 l; Solve [ld[l] == ls[l]] ; temp = l /. %; l0 = temp[[1]]; w0 = ld [l0] ; Solve [mr[l] == ls[l]] temp = l /. %; l1 = temp[[1]] w1 = ld[l1] plot1 = Plot[ld[q], {q, 0, 5}] ; plot2 = Plot[ mr[l], {l, 0, 24}] ; plot3 = Plot[ ls[l], {l, 0, 24}] ; plot4 = Graphics[ Text[Style[Subscript[w, 0], FontSize -> 14], {-.25, w0}]] ; plot5 = Graphics[ Text[Style[Subscript[w, 1], FontSize -> 14], {-.25, w1 }]] ; plot6 = Graphics[ Text[Style[Subscript[L, 0], FontSize -> 14], {l0, -1}]] ; a = Graphics[Text[Style[Subscript[L, 1], FontSize -> 14], {l1, -1}]] ; b = Graphics[ Text[Style["Demand by employers", FontSize -> 14], {3.3, 5}]] ; c = Graphics[ Text[Style["Marginal revenue", FontSize -> 14], {3, -2}]] ; d = Graphics[ Text[Style["Supply by workers", FontSize -> 14], {3.5, 15}]] ; e = Graphics[ Text[Style["A", FontSize -> 20], {0.5, 16}] ] ; f = Graphics[ Text[Style["B", FontSize -> 20], {0.9, 13}] ] ; g = Graphics[ Text[Style["C", FontSize -> 20], {1.6, 12.5}] ] ; h = Graphics[ Text[Style["D", FontSize -> 20], {1.2, 10}] ] ; i = Graphics[ Text[Style["E", FontSize -> 20], {1.5, 10.5}] ] ; j = Graphics[ Text[Style["F", FontSize -> 20], {0.5, 7.5}] ] ; plot7 = ListPlot[{{0, w0}, {l0, w0} , {l1, w1}, {l0, 0}, {l1, 0}, {0, w1}, {l1, mr[l1]}}, PlotStyle -> PointSize[.02]] ; plot8 = ListPlot[{{{l1, mr[l1]}, {0, mr[l1]}}, {{0, w0}, {l0, w0}}, {{0, w1}, {l1, w1}}, {{l1, w1}, {l1, mr[l1]}}}, Joined -> True, PlotStyle -> { Dashing[{.01}]} ]; Show[plot1, plot2, plot3, plot4, plot5, plot6, plot7, plot8, a, b, c, \ d, e, f, g, h, i, j, PlotRange -> {{-.3, 4.5}, {-3, 23}}, AxesLabel -> {"Hours of Labor", "Wage"}, AxesOrigin -> {0, 0}, AspectRatio -> 1/1] ---------------------------------------------------------------------------------- ParametricPlot[{Sin[t], Cos[t]}, {t, -3, 3} This gives a circle ParametricPlot[{t, t^2}, {t, -3, 3} A parabola ParametricPlot[{t, 1/t}, {t, -3, 3} A hyperbola