April 23, 2019 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. ********************************************************** CLEARING VARIABLE VALUES At the start of the cell, put ClearAll["Global`*"] Remove["Global`*"] << Utilities`CleanSlate` CleanSlate[] One of these three commands should do it, so use all of them. ********************************************************** TESTING THE SIGN OF AN EXPRESSION: temp1 = b^2 - 3; FullSimplify[Sign[temp1], Assumptions -> {b > 0, q > 0, b < 1, q < 1}] ********************************************************** LATEX x1 = ToExpression[ "-\\frac{1}{12} + E^{-\\alpha_1 \\frac{x_1 }{x_1+x_2}} *( \ \\frac{1}{12} - (1- \\frac{x_1+x_2}{12}) * \\alpha_1 * (\\frac{1 }{x_1+x_2} - \ \\frac{x_1 }{(x_1+x_2)^2})) ", TeXForm] You need to put * in between parenthetic expressed mulitpiong each otehrs. You can't use [ or \cdot . You need E for e, exponent. You need to use \\alpha, not \alpha. ------------------------------------------------------------ NUMERICAL INTGRATION AND MINIMIZATION You have to have all of the numerical integration inside your minimand function AND write it like this so it doesn't try to evalute the numerical integral with the symbol instead of the specific number it is trying out for the minimization: minimand[a0_,a1_?NumericQ] = a0 + NIntegrate[a0*p/(a0+a1), {p, 1, 100}] ------------------------------------------------------------ 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 or a number to be useful. First you do temp1=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 gives you {x->x^2+4}.Then to make it an expression called qb1, do this: qb1= x /. temp1 That says qb1 = x^2+4 You can do this with a bunch of variables too. result1 ={a->34, b->45} {a, b} = {a,b}/.result1 I'm not absolutely sure that this works, tho. To make a function f[x]=x^2+4, follow up the last command with f[x_]:=qb1 . Then f[7] = 53. Here is an example where we get just a number out: In[63]= temp1 = Solve[24 - 2 p == p - 16] temp2 = Part[temp1, 1] p = p /. temp2 Out[64]= {{p -> 40/3}} Out[65]= {p -> 40/3} Out[66]= 40/3 EASY EXAMPLE OF GETTING A NUMBER OUT FROM MAXIMIZATION Maximize[qprofit, w] temp1 = N[Part[%, 2]] wmax = w /. temp1 OUT[42]: {3481/8, {w -> 99/40}} OUT[43]: {w -> 2.475} OUT[44]: 2.475 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} ] Another example, with two optimal solutions coming from a maximization where I want to then set the variable value equal to the optimal solution in expressions b, w, and welfare: temp = NMaximize[{welfare, s > 0, s < sbar, p > 0, p < 1}, {s, p}] temp1 = Part[temp, 2] temp2 = Part[temp1, 1] sstar = s /. % temp3 = Part[temp1, 2] pstar = p /. % s = sstar p = pstar Print["b = ", b] Print["w = ", w] Print["welfare=", welfare] SOLVE: can be done like this: qd = a - b*p ; qs = c + d*(p - c/d - c ) ; temp1 = p /. Part[Solve [qd == qs, p], 1] -------------------------------- iuanyware.edu has Mathematica, STATA and other program useable from anywhere. You first download the Citrix receiver program and install that. It will have access to the C: directory of your computer. You can open and save files to your home computer as C: or D:, but if you export a figrue or other file it disappears onto c:Users/erasmuse/Documents on the rmote inaccessible server. ********************************************************** PLOTTING, TABLES, AND TITLES OF FIGURES I have had the wrong approach to this. What is best is to use the coding to make the elements of the plot and the text labels, but then to use the interactive TOOLS to make the diagram look pretty. That is quicker, and it isn't bad even to reproduce. In Drawing Tools, CTRL-V will make Mathematica close. To plot a function, use Plot[f[t], {t, 0, vmax + 1}]. VERTICAL LINES at discontinuities in a plot are inserted if you say Plot[f[t], {t, 0, vmax + 1}, Exclusions->None]. TO PUT TEXT INTO A PLOT and then save the plot: plot1 = Plot[{P = 2 Q, P = 48 - 3 Q, P = Q}, {Q, 0, 15}]; plot2 = Graphics[Text["Demand", {4, 40}, BaseStyle -> {FontWeight -> "Bold", FontSize -> 14}] ]; finished = Show[plot1, plot2, AxesLabel -> {"Q", "P"}, BaseStyle -> {FontWeight -> "Bold", FontSize -> 14}] Export["ans06-5.msc.pdf", finished] To just get decimalized values for an expression at 4 values, not a plot, do this: myname= Sin[x]/2 N[Table [myname, {x, {-2.3, -1.1, 0, 10}}] ] or without decimalization, and for values from 1 to 10, Table [myname, {x,1,10} ] 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 do 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. STANDARD PLOT OPTIONS: Axes setting to True, True makes it be the standard two axes, not four or zero. AxesOrigin -> {0, 0}, Axes->{True, True}, 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. For a vertical line, add as a plot option: Epilog -> Line[{{6, 4}, {6, 16}} ] Mathematica has a Mayra-Paintbrush style drawing tools under the GRaphics menu. It doesn't have bezier curves, tho. 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. Here is another success: pstar1 = 2 - 4/v; pstar2 = (v/2 - 1)/(3 v/4 - 1); Table[{pstar1, pstar2}, {v, 2, 3, .1}] ; plot1 = Plot[{pstar1, pstar2 }, {v, 2, 3}, AxesLabel -> {"Prize/cost (V/c)", "P_{even}"}, PlotRange -> {{2, 3}, {0, .6}}, Ticks -> {{2, 2.5, 3}, {0, .25, .5}} , AspectRatio -> 1/1, PlotStyle -> {{Thick, Thick}, Dashing[{0.03, 0.01}] }] ; plot3 = Graphics[Text["Rival 2 first", {2.8, .44} ]]; Show[plot1, plot3, PlotRange -> {{2, 3}, {0, .7}}] ---------------------------------------------------------------------- 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] ---------------------------------------------------------------------- Hre is how I inputted my tex equation, called it x1, and then had Mathematica sovle it out for r: x1 = ToExpression["5+ \\frac{1}{1+r} \\frac{2}{r} = (\\frac{1}{1+r})^2 \\left( 30 \\right)", TeXForm] NSolve[x1, r] If theq euation is not polynomial, NSolve wo't work adn you need to use, with starting valeus 5 and 5, FindRoot[{x1 == 0, x2 == 0}, {{Subscript[x, 1], 5}, {Subscript[x, 2], 5}}] ********************************************************** SendMail["From" -> "erasmuse@indiana.edu", "To" -> "erasmuse@indiana.edu", "Subject" -> "Sending Email from Wolfram Language", "Body" -> "Testing", "Server" -> "mail-relay.iu.edu"] This will send email. Possibly, anybody can send email pretnending it is from someone else. ********************************************************** 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 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/ ---------------------------------------------------------------------- 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? ------------------------------------------------- (* Here is a comment *) p=x3+3x2+3x+1 answer=Solve[{x1^2 + x2==0, 3x1 + x2^2 ==3, x1>0},{x1, x2}, Reals] x1star = x1./answer[[1]] x2star = x2./answer[[1]] 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] ---------------------------------------------------------------------- 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[%] ---------------------------------------------------------------------- --------------------------------------- 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. --------------------------------------- ------------------------------------- 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 - 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