title: Double integral over a parallelogram

text: Problem: Evaluate the following double integral $$\int \\!\\!\\! \int_D (14 x^2+61 xy+42 y^2)^{3} \, dxdy$$ where $D$ is a parallelogram between these four lines: $2x+7y=6$, $2x+7 y=-6$, $7x+6 y=6$ and $7x+6y=-6$. I have defined the lines as graphs of functions $a, b, c, d$ and plotted them in _Mathematica_. Lines $a$ and $c$ intersect at $x=-\frac{78}{37}$ while $b$ and $d$ intersect at $x=\frac{12}{5}$ according to my calculations. Then I try to integrate the function as follows, getting the answer $-4400.1$, but it is not correct.               NIntegrate[       Boole[-(78/37) <= x <= 12/5 && Max[a[x], b[x]] <= y <= Min[c[x], d[x]]]       ((14 x^2 + 61 x*y + 42 y^2)^3),       {x, -4, 4}, {y, -2, 2}]      What am I doing wrong?


title: how to make graphic timelines in mathematica

text: Hi does anyone know how to make timelines with mathematica? http://images.nationmaster.com/images/motw/atlas_middle_east/turkey_timeline.jpg something like that would be great! thanks


title: Exporting multiple arrays in a single HDF5 file in Mathematica 7

text: I am using _Mathematica_ 7 and I need to export a table of data and the corresponding `x` and `y` arrays. I would like to format them as a single file, say `grid.h5`, and need the arrays named for import in a different program. Unfortunately, applying the command:               Export["MGfunc.h5", {data, x1, y1}, {"Datasets", {"MGfunc", "x", "y"}}]      only seems to save the last array in the file `MGfunc.h5`. Does anyone know how to get this working using the HDF5 format? Here is an example:               In[13]:=  ki = N[Table[i, {i, 0, 3}]]      kj = N[Table[j, {j, 0, 3}]]      testgrid = Table[ki*kj, {ki, 0, 3}, {kj, 0, 3}]           Out[13]= {0., 1., 2., 3.}      Out[14]= {0., 1., 2., 3.}      Out[15]= {{0, 0, 0, 0}, {0, 1, 2, 3}, {0, 2, 4, 6}, {0, 3, 6, 9}}           In[16]:= Export["testgrid.h5", {testgrid, ki, kj}, {"Datasets", {"gridtest", "x", "y"}}]      Out[16]= "testgrid.h5"           In[19]:= Import["testgrid.h5"]      Out[19]= {"/y"}           In[20]:= Import["testgrid.h5", "Data"]      Out[20]= {{0., 1., 2., 3.}}


title: How do I add options to a built in function, which only apply to a certain class of argument?

text: I'd like to add an option to a built-in function that only applies when it is given an argument of a certain form. For example, something like this approach to extending `DateString` to support an extra option when it is given a date argument that matches the form `zoned[...]` (forget that `zoned` does nothing here):               DateString[zoned[x_], spec_, opts : OptionsPattern[{TimeZone -> 0,ShowZone->True}]] ^:=      DateString[x, If[OptionValue[ShowZone],        Append[spec, If[OptionValue[TimeZone] != 0, "UTC" <> ToString[OptionValue[TimeZone]], "Z"]], spec]]      Since `ShowZone` is not an option for `DateString`, I get an error. > "DateString::optx: Unknown option ShowZone in DateString..." But I can't just associate `TimeZone` as an up value for `zoned` with               zoned/:Options[DateString]={ShowZone->True}      because that also results in an error: > Options::tag: Rule for Options of Options[DateString] can only be attached > to DateString. It seems I have to (unprotect `DateString` and) then add a new option globally, which is generally just ignored:               Unprotect[DateString];      Options[DateString] = Union[Options[DateString], {ShowZone -> False}];      Protect[DateString];      Is this the only approach? Even this approach leaves `ShowZone` blue in the function definition and red in function invocations.


title: What Method options does FindInstance accept?

text: While answering Trouble getting FindInstance to return multiple results for certain constraints it became clear that for this problem `FindInstance` would be better starting with small numbers, but it does not. The function has the `Method` option:               Options[FindInstance, Method]   (*  Out: {Method -> Automatic}  *)      Yet, I cannot find documentation for the methods (and methods sub-options) that it accepts.   * What `Method` values does `FindInstance` accept?   * Will any of them scan an `Integer` search space small-values first?


title: Linear programming with many variables and parameters

text: I am trying to reconstruct the answer that is given in this report. (page 153 in Appendix B; Section B.2.1). They are given variables, parameters, constraints, and the objective function to minimize. Summary of the problem:               Minimize: q01 + q11 + q21 + q31 - q02 - q12 - q22 - q32     Variables: {q00 , q01 , q02 , q03 , q10 , q11 , q12 , q13 ,                  q20 , q21 , q22 , q23 , q30, q31 , q32 , q33}     Parameters: {p000 , p010 , p100 , p110 , p001 , p011 , p101 , p111}     Constraints:        1) all q's nonnegative       2) [sum all q's] == 1       3) p000 == q00 + q01 + q10 + q11       4) p010 == q20 + q22 + q30 + q32       5) p100 == q02 + q03 + q12 + q13       6) p110 == q21 + q23 + q31 + q33       7) p001 == q00 + q01 + q20 + q21       8) p011 == q10 + q12 + q30 + q32       9) p101 == q02 + q03 + q22 + q23       10) p111 == q11 + q13 + q31 + q33      Their output is given on page 155 as the maximum of a set of eight linear functions of the parameters:                Minimum of Objective Function is the Maximum of:      p111 + p000 - 1      p110 + p001 - 1      -p011 - p101      -p010 - p100      p110 - p111 - p101 - p010 - p100      p111 - p110 - p100 - p011 - p101      p001 - p011 - p101 - p010 - p000      p000 - p010 - p100 - p011 - p001      When trying to reproduce it in _Mathematica_ 8.0, first tried simple test case of using parameters               LinearProgramming[{1, 1}, {{1, 2}}, {a}]      which gave an error, but using Minimize does give a full answer               Minimize[x + y, x + 2*y >= a && x >= 0 && y >= 0, {x, y}]      I then rephrased the original problem in terms of Minimize function and even after running overnight it was still thinking:               Minimize[q01 + q11 + q21 + q31 - q02 - q12 - q22 - q32,        q00 + q01 + q02 + q03 + q10 + q11 + q12 + q13 + q20 + q21 + q22 +          q23 + q30 + q31 + q32 + q33 == 1 &&        q00 >= 0 && q01 >= 0 &&        q02 >= 0 && q03 >= 0 && q10 >= 0 && q11 >= 0 && q12 >= 0 &&        q13 >= 0 && q20 >= 0 && q21 >= 0 && q22 >= 0 && q23 >= 0 &&        q30 >= 0 && q31 >= 0 && q32 >= 0 && q33 >= 0 &&        p000 == q00 + q01 + q10 + q11 && p010 == q20 + q22 + q30 + q32 &&        p100 == q02 + q03 + q12 + q13 && p110 == q21 + q23 + q31 + q33 &&        p001 == q00 + q01 + q20 + q21 && p011 == q10 + q12 + q30 + q32 &&        p101 == q02 + q03 + q22 + q23 &&        p111 == q11 + q13 + q31 + q33, {q00, q01, q02, q03, q10, q11, q12,        q13, q20, q21, q22, q23, q30, q31, q32, q33}]      Is there a way for _Mathematica_ (8.0) to reproduce their results? Have a feeling I'm either missing a function that would answer it, or not inputting some restriction or assumption which Mathematica needs. Thank you! ### EDIT I tried the suggestion of @Anon:               Minimize[{f, constraints}, {q00, q02, ...}]       instead of               Minimize[f, constraints, {q00, q01, ...}]      hoping that was the answer. It still was thinking overnight, with no answer produced. Is Minimize the correct function to use for this problem? _(Originally posted inStackOverflow, first response recommended posting the question here)_


title: Odd behavior of GridGraph and DirectedEdges

text: For some reason the option `DirectedEdges->True`, albeit working internally with grid graph, does not appear in the visualisation for 1D and 2D graphs. It also changes the drawing scheme for 3D grids. **1D Grid-Graphs** Using               g1 = GridGraph[{2}, VertexLabels -> "Name", ImagePadding -> 20, DirectedEdges -> True]      prints: ![enter image description here](http://i.stack.imgur.com/fIVfq.jpg) which shows no directed edges, even though the incidence matrix is modified correctly: \begin{equation} \text{IncidenceMatrix[g1]} = \left( \begin{array}{c} -1 \\\ 1 \end{array} \right) \end{equation} Conversely, issuing the command               GridGraph[{1,2}, VertexLabels -> "Name", ImagePadding -> 20, DirectedEdges -> True]      prints ![enter image description here](http://i.stack.imgur.com/LN8hI.jpg) ie, with the directed edges correctly drawn. **2D Grid-Graphs** For 2D graphs, small dimensions print as a directed edge whereas higher dimensions do not. For instance               g = GridGraph[{2, 2}, VertexLabels -> "Name", ImagePadding -> 20, DirectedEdges -> True]      produces: ![enter image description here](http://i.stack.imgur.com/7Xy9i.jpg) For dimensions {4,2} the graph is: ![enter image description here](http://i.stack.imgur.com/z2DHz.jpg) where some very tiny arrows can in fact be observed. Conversely, for dimensions {2,4} it produces ![enter image description here](http://i.stack.imgur.com/KNsC5.jpg) It thence seems like a problem in adjusting the size of the arrows. But this seems unrelated to the 1D graph since there, no arrow can be seen in any dimension (unless drawn horizontally, in which case a 2D Grid-Graph is actually being called). **3D Grid-Graphs** Apparently, the arrows are drawn correctly for dimensions 3 and larger. However, the drawing scheme is affected, which is not the case in 2D graphs. For instance                GridGraph[{4, 2, 2}, VertexLabels -> "Name", ImagePadding -> 20]      produces ![enter image description here](http://i.stack.imgur.com/RBvkP.jpg) whereas adding `DirectedEdges->True` yields ![enter image description here](http://i.stack.imgur.com/cLOkx.jpg) In summary: odd stuff. Any thoughts? Thank you in advance for the attention.


title: Keywords to find documentation for this syntax

text: _Mathematica_ allows this syntax, but I cannot find any documentation (or books) that discuss the various uses/advantages of it               g[1] := Plus;     g[2] := Times;     g[1][3, 5]     (* 8 *)          g[2][3, 5]     (* 15 *)      What keywords can I use to find this in the documentation?


title: Doing vector manipulations on Mathematica

text: This is hopefully a simpler version of this previous unanswered question of mine. Let me just focus on the two expressions $F_2^{(s)}$ and $F_3^{(s)}$ given in A.3 and A.4 of page 19 of this paper.   * How do I get Mathematica to just even manipulate such vector expressions? Like if I want to calculate $(F_2^{(s)})^2$ or $F_2^{(s)} F_3^{(s)}$ etc?  * * * To make the question clear let me add in some more details about what I exactly want, I define the function F2s as,               F2s[q_, k1_] := (5/     14) + (3 (Norm[k1])^2)/(28 (Norm[q])^2) + (3 Norm[        k1]^2)/(28 (Norm[q - k1])^2) - (5)/(28 (Norm[q])^2 (Norm[         q - k1])^(-2)) - (5)/(28 (Norm[q])^(-2) (Norm[         q - k1])^(2)) + ( (Norm[        k1])^4)/(14 (Norm[q])^2 (Norm[q - k1])^2 )      But when I ask it to be squared all I get is this! (basically nothing has been done and the situation doesn't change with taking a FullSimplify either)               (2 Norm[k1]^4 - 5 (Norm[q]^2 - Norm[-k1 + q]^2)^2 + 3 Norm[k1]^2 (Norm[q]^2 + Norm[-k1 + q]^2))^2/(784 Norm[q]^4 Norm[-k1 + q]^4)      I would have wanted the answer to be given in the way I gave the functions $F2s$ - as a sum of fractions each of which is a product of powers of $q$, $k1$ and $\vert \vec{q} - \vec{k1}\vert$. How do I get that?


title: Can Map operations be compiled or otherwise sped up for large lists?

text: I'm performing a series of `Map` operations in the following script:               inputList = Table[RandomReal[100, {60, 2}], {i, 1, 10^3}];     scalingFactor = 10;     i = 1;     listX = Round[scalingFactor*Table[{inputList[[i, k]], # - inputList[[i, k]] & /@ inputList[[i]]}, {k, 1, Length[inputList[[i]]]}]];     i = 2;     listY = Round[scalingFactor*Table[{inputList[[i, k]], # - inputList[[i, k]] & /@ inputList[[i]]}, {k, 1, Length[inputList[[i]]]}]];          selectedIndices = RandomInteger[{1, 30}, {10^3, 2}];     pairList = {listX[[#[[1]], 1]], listY[[#[[2]], 1]]} & /@ selectedIndices;      The above code is mostly meant to illustrate the kind of `Map` operations I'm doing, however, a description of what's going on would be as follows: (1) We first generate `inputList`, which, at the outermost level, contains $10^3$ lists, each with $60$ pairs of real numbers (the pairs are of the form: `{RandomReal[{0,100}],RandomReal[{0,100}]}`). (2) `listX` and `listY`, computed in precisely the same way but for different lists in `inputList` (with indices $i = 1$ and $2$, respectively), generate $60$ two-element lists (one for each point in `inputList[[i]]`) that look like this:               listXexample = {{{440, 663}, {{0, 0}, {467, 333}, {376, -548}, {-178, -128}, {-254, -560}, {262, -533}, {-203, 202}, {63, -68}, {160, -604}, {382, -187}, {471, -162}, {-292, 336}, {-317, -196}, {-75, 253}, {-199, -125}, {-214, -543}, {246, -456}, {363, -455}, {-366, 235}, {-178, 309}, {211, 255}, {27, -360}, {495, -458}, {-34, -452}, <<12>>, {-259, -133}, {-232, 103}, {-375, -387}, {-98, -455}, {253, -548}, {233, -418}, {207, 245}, {367, -100}, {107, 19}, {419, -85}, {324, -526}, {465, -434}, {-342, -506}, {216, 35}, {452, 254}, {-252, 215}, {307, -110}, {-344, 277}, {387, -449}, {-62, -542}, {140, -78}, {-249, -49}, {-66, -425}, {-251, 175}}}, <<58>>, {<<1>>, {<<1>>}}};         The first element in each list, e.g. `{440, 663}` as above, represents a chosen element, and the second element represents a list of the differences between this chosen element and all other elements in inputList[[i]], e.g. `# - {440, 663}` in the above example. All values in these lists are then rounded, as shown. (3) `pairList` is computed by taking a (here random) set of integer indices of the form `{{20,40},{40,15},...}`, and then performing the mapping operation:               pairList = {listX[[#[[1]], 1]], listY[[#[[2]], 1]]} & /@ selectedIndices;      Where we `#[[1]]` and `#[[2]]` represents the first and second element, respectively, in a particular integer pair in `selectedIndices`. To simulate the script inputs, we're using the following randomly generated test values:               scalingFactor = 10;     inputList = Table[RandomReal[100, {60, 2}], {i, 1, 10^3}];     selectedIndices = RandomInteger[{1, 30}, {10^3, 2}];      As well as the $i = (1,2)$ values. * * * * * * * * * Is there a way to compile and speed up the sort of `Map` operations above? * * * Also, can anyone replicate my finding that changing:               inputList = Table[RandomReal[100, {50, 2}], {i, 1, 10^3}];      To:               inputList = Table[RandomReal[100, {100, 2}], {i, 1, 10^3}];      Counterintuitively halves the effective time to compute:               pairList = {listX[[#[[1]], 1]], listY[[#[[2]], 1]]} & /@ selectedIndices      Why would this happen? * * * * * * * * * Update: Running Mr. Wizard's reformulated code:               inputList = RandomReal[100, {1000, 60, 2}];     selectedIndices = RandomInteger[{1, 30}, {10^3, 2}];     scalingFactor = 10;          t1 = AbsoluteTime[];          i = 1;     listX = Round[scalingFactor*Table[{inputList[[i, k]], # - inputList[[i, k]] & /@ inputList[[i]]}, {k, 1, Length[inputList[[i]]]}]];     i = 2;     listY = Round[scalingFactor*Table[{inputList[[i, k]], # - inputList[[i, k]] & /@ inputList[[i]]}, {k, 1, Length[inputList[[i]]]}]];          myPairList = {listX[[#[[1]], 1]], listY[[#[[2]], 1]]} & /@ selectedIndices;                    t2 = AbsoluteTime[];          f1[m_] := With[{t = m\[Transpose]}, {m, Subtract[t, #]\[Transpose] & /@ m}\[Transpose]]          {listX, listY} = Round[scalingFactor * f1 /@ inputList[[{1, 2}]]];          pairList = {listX[[#, 1]], listY[[#2, 1]]}\[Transpose] & @@ (selectedIndices\[Transpose])               t3 = AbsoluteTime[];               myPairList == pairList      Outputs `True`. We can also note that the timing for my code vs. Mr. Wizard's               myTiming = t2 - t1     mrWizardTiming = t3 - t2      Is about $\approx 65$ milliseconds (me) and $\approx 3$ milliseconds (Mr. Wizard), respectively. Nicely done Mr. Wizard!


title: How to disable the small pop-up windows when mouse is over a Mathematica command in V10?

text: In version 10, when the mouse is over a Mathematica command, a small pop-up window comes up that one can click on for help on the command. Is there an option to disable this feature? Screen shot: ![Mathematica graphics](http://i.stack.imgur.com/CYLLQ.png) I tried number of options here, but no effect. It must be in the advanced perferences? But not sure what to look for. **Update:** Thanks to Martin answer below. These options can be changed permanently in advanced options ![Mathematica graphics](http://i.stack.imgur.com/nVmbF.png) I also turned off the "ShowCodeAssist" just in case ![Mathematica graphics](http://i.stack.imgur.com/crjVw.png)


title: How to get rid of Mathematica 10's help tooltips?

text: Since _Mathematica 10_ every time your mouse cursor appears above some function or even variable, an annoying tooltip appears offering help: ![enter image description here](http://i.stack.imgur.com/Agjlt.png) I've become quite used to _Mathematica_ now and I don't need these tooltips everywhere every second, and I can just as easily click the function and press `F1` to get help. I've tried almost every promising-looking option in `Edit->Preferences->Interface` page, but I couldn't remove these tooltips. So, how do I finally get rid of them?


title: FindRoot: getting number of iteration

text: I'm using FindRoot to solve a nonlinear system. I'd like to see what FindRoot is doing while computation, something like the _display_ option for Matlab _fsolve_. At the end of the day, I want the number of iterations and the residual at each step. Is there an option like that? I found this link, but if I use FindRootPlot the execution is 3 times slower, and since I'm using a vector input, it does not display any plot. My code:               SYS1[X_, U_?VectorQ, RHS_, fun_] := Module[...]          t1 = Timing[            U1 = UU /. Flatten[FindRoot[SYS1[XX, UU, F1, fun1] == 0, {UU, U0}]]        ];      or               << Optimization`UnconstrainedProblems`          t1 = Timing[            U1 = UU /. Flatten[FindRootPlot[SYS1[XX, UU, F1, fun1] == 0, {UU, U0}]]        ];      Thanks in advance for any suggestions. Petrus


title: Summation limits

text: The `Sum` is a built-in function in _Mathematica_ , so the summation limits must be assigned. What I need to know is how to use a value computed in a separate `Module` as a Sum upper limit.


title: Generating replacement rules programatically

text: I would like to generate sets of replacement rules programatically for predefining some permutations. So a function               MakeRule[cycles_List (* permute cycles *), n_Integer (* rule length *)]`      called as               MakeRule[{{2,3}}, 4]      will generate               {e1_, e2_, e3_, e4_} -> {e1, e3, e2, e4}      For the permutations, I have               Permute[l, Cycles[cycles]]      but I cannot find a way of generating the list of patterns. Something subscripted or indexed would be nice as per the example. I have tried:               1) Pattern[Subscript[e, 1], Blank[]]     2) Pattern[Symbol["e1"], Blank[]]     3) Pattern[e[[1]], Blank[]]      I have a feeling I am missing something obvious. Edit: Apologies for an oversight on my part. The second pattern example works correctly while the first and third do not. Thanks to all who responded.


title: Basins of Attraction

text: How does one shade the basin(s) of attraction of a phase plot in _Mathematica_? I have been trying to do this using the system $$\begin{align*} \dot x &= y\\\ \dot y &= -9\sin(x) - 0.20y \end{align*}$$ but I have gotten nowhere.


title: Manipulate not accepting default values

text: I have pasted my _Mathematica_ code below. For some reason, the default value for h, or Δx, while set to 4.5 in the code, keeps displaying at -4 instead. I have been over and over this example, and I don't understand why this is happening. If someone would be willing to help me to understand what is going on here and how to fix it, I would really appreciate it.               Manipulate[       f[x_] = 2.195^x - 1;       Grid[{         {Row[{Style[            Text["  approximation of the derivative f'(x) :  " <>               ToString[(f[a + h] - f[a])/h]], Green, 15]}]},         {Row[{Style[            Text["  derivative: f'(x) \[TildeTilde] " <>               ToString[D[f[x], x] /. x -> a]], Red, 15]}]},         {Plot[{f[x],              f[a] + (D[f[t], t] /. t -> a)*(x - a),              f[a] + ((f[a + h] - f[a])/h)*(x - a)},           {x, -0.5, 6.5},           PlotStyle -> {Blue, Red, Green},          PlotRange -> {{-0.5, 6.25}, {-50, 130}}, Axes -> True,           AxesOrigin -> {0, -50},           AxesLabel -> {"time (sec)", "distance (ft)"},          ImageSize -> 450,          Prolog -> {            {Line[{{a + h, f[a + h]}, {a, f[a + h]}}]},            {Line[{{a, f[a + h]}, {a, f[a]}}]},             {PointSize[.02], Blue, Point[{a, f[a]}]},            {Blue, Text["(x,f(x))", {a + .3, f[a] - 5}]},             {Text["Δx", {a + h/2, f[a + h] - 5}]},             {Text["f(x+Δx) - f(x)", {a + .6, f[a] - (f[a] - f[a + h])/2}]},             {PointSize[.02], Green, Point[{a + h, f[a + h]}]},             {Green, Text["(x+Δx,f(x+Δx))", {a + h - .4, f[a + h] + 7}]}}]}}],        {{a, 1, "x"}, 0, 6},       {{h, 4.5, "Δx"}, -a, 6 - a},       TrackedSymbols -> {a, a + h},       SaveDefinitions -> True]


title: How do I evaluate the terms in an expression, but not the expression itself?

text: I am trying to write a set of homework questions. I would like the output to evaluate the constants but not the sum, so that I may present the homework question as something like this: $$\sum_{n=1}^{340}(-4n^2-n+3)$$ Here's what I have:               c1 = RandomInteger[{-5, 5}];     c2 = RandomInteger[{-5, 5}];     c3 = RandomInteger[{-5, 5}];     c4 = RandomInteger[{1, 50}]*20     f[x_] := c1*x^2 + c2*x + c3      f[n]      (* 340        3 - n - 4 n^2 *)          Defer[Sum[f[n], {n, 1, c4}]]      $\sum _{n=1}^{\text{c4}} f(n)$ It seems like I am not using `Defer` correctly. How can I fix this?


title: Custom ticks failing with Frame

text: I know I can manipulate ticks:                Plot[PDF[NormalDistribution[0, 1.5], x], {x, -7, 7},         Ticks -> {{          {-6, "-6σ"}, {-5, "-5σ"}, {-4, "-4σ"}, {-3, "-3σ"}, {-2, "-2σ"}, {-1, "-σ"},           {1, "σ"}, {2, "2σ"}, {3, "3σ"}, {4, "4σ"}, {5, "5σ"}, {6, "6σ"}      }}]      But the ticks disappear when I add `Frame -> True`. What am I doing wrong?


title: How to set axes scale for Plot?

text: Well, maybe its a dumb question, but I can't find how to set axes scale factor for my `Plot`. For example, if I have x and y axes, I want to have 1 unit on the x axis same size as on the y axis.


title: What properties make this equation difficult to symbolically solve?

text: I tried to solve the following equation with Mathematica's solve:               Solve[K*(2*Tan[L/2*Sqrt[P/(EI)]]-L*Sqrt[P/(EI)])+4*P*Sqrt[P/(EI)] == 0, P]      It gave the following error:               Solve::nsmet: This system cannot be solved with the methods available to     Solve.      I do not see any strange functions being called here, and I am curious about what properties make this expression difficult for Mathematica.


title: Taking real and imaginary parts of indexed functions and speeding up ComplexExpand

text: I am setting up a large system of ODEs and in order to use the IDA method (which is sig. faster for my system and thus attractive), I must split my equations into real and imaginary parts. I am experiencing a severe bottleneck in taking real and imaginary parts of my functions, using `ComplexExpand`, and I suspect that this slowdown has to do with my inability to specify that the range of certain functions are real. A simple example is given below: Consider two tables, whose elements I would like to decompose into real and imaginary parts:               A1 = Table[ar[n]+I*ai[n], {n, 1, 500}];     A2 = Table[(n+I*n),{n,1,500}];      Now, to find the real part of, e.g., `A1.A1`, I would take               Re[ComplexExpand[A1.A1]];      The timing for these computations, however, is radically different. That is               Timing[Re[ComplexExpand[A1.A1]];]       > >     {0.203348, Null} >                 Timing[Re[ComplexExpand[A2.A2]];]       > >     {0.000585, Null} >   So we see there is a difference of around `400`! Intuitively, it would seem that if I can tell _Mathematica_ to treat `{ar[n],ai[n]}` as being functions with ranges over the reals, I can significantly improve the timing. Right now the `{ar[n],ai[n]}` are effectively constants, but in the future they might be functions. For the purpose of `ComplexExpand`, is it possible to have _Mathematica_ treat these objects simply as real constants? **Note:** For completeness, I add that the system of equations I am going to be decomposing, in terms of real and imaginary parts, will be a sum of maximum degree 4 polynomials in the variables `A[n][t]=Ar[n][t]+I*Ai[n][t]` where `n` is some index number on the dependent variables, which will take values between `1` and `N`(right now I have `N` at 40, but in the future it'll be something around `100` or `200`). For each equation, there are around `N+N^2` terms. For my governing equations, with `N=40`, this real/imaginary decomposition is taking around `3500` CPU seconds.


title: How to represent a continuous monotonic phase of Airy functions?

text: _Note: In this question I am concerned only with real-valued variables and functions._ * * * DLMF, §9.8 _Airy Functions, Modulus and Phase_, formula $9.8.4$ defines the phase of Airy functions: $$\theta(x)=\arctan\frac{\operatorname{Ai}x}{\operatorname{Bi}x}.$$ The corresponding _Mathematica_ definition is               θ[x_] := ArcTan[AiryAi[x]/AiryBi[x]]       Apparently, in this form the phase has a countable infinite number of jump discontinuities for negative values of $x$. I need to construct a _Mathematica_ expression that represents a continuous monotonic version of the phase $\theta(x)$ (let's name it $\vartheta$), where all pieces between discontinuities are properly shifted and stitched, as shown on the following graph: ![Phases](http://i.stack.imgur.com/7M8Uo.png) One approach would be to get the derivative of $\theta(x)$: $$\theta'(x)=-\frac1\pi\frac1{\operatorname{Ai}^2 x+\operatorname{Bi}^2 x},$$ so that all information about jumps is lost, and then consider the definite integral: $$\vartheta(x)=\frac1\pi\int_x^\infty\frac{dz}{\operatorname{Ai}^2 z+\operatorname{Bi}^2 z}.$$ Or, in _Mathematica_ notation:               1/π Integrate[1/(AiryAi[z]^2 + AiryBi[z]^2), {z, x, ∞}]      Unfortunately, _Mathematica_ leaves this integral unevaluated, even if an explicit value for the boundary $x$ is provided. > Is it possible to write a closed-form _Mathematica_ expression, possibly > containing special functions, that represents the continuous monotonic phase > $\vartheta(x)$?


title: How do I find the Euclidean distance between one point and all the points in a list?

text: I want to find the Euclidean distance between one point (x1) and a list of points (y1), which contains a lot of coordinates               x1 = killer[[2]]      > {6.05102, 5.87667}               y1 = victim[[2 ;;]]      > {{1.40687, 4.92494}, {0.419206, 1.70406}, {6.29657,0.577941}, {4.12022, > 4.94952},   >  {2.04784, 5.94545}, {1.29192,1.43152}, {3.26737, 1.90134}, {4.27274, > 0.528028},   >  {2.79659,1.37788}, {5.43955, 1.81355}} Is it possible for me to find the `EuclideanDistance` between x1 and y1, where it will show all results between x1 and each elements in y1.


title: Speed up Mathematica code involving Convolve

text: I'm trying to plot the averaged autocorrelation function of a random wire profile $\xi(x)$ which is build from unitsteps which are each L units long. To calculate the average I'm generating nMax realizations of the profile, then I proceed to calculate the autocorrelator $\langle \int_{-\infty}^{\infty} \xi(x)\xi(x-y)~dx \rangle$. Brackets indicate averaging over the `nMax` copies of the profile. My final goal is to plot this expression as a function of `y`. I started out by using both the built-in `Mean` and `Convolve` functions, however it is ridiculously slow on my machine (late 2007 MacBook). To give you an idea, it takes 150 seconds to calculate `corr[0]` alone (even with `nMax=1`). Is there anything I'm completely missing here? Or can someone of you even hint at a faster and more elegant approach to this?               L = 1.; (* step length *)     nMax = 1; (* number of realizations for averaging *)     nSteps = 1; (* number of modules in wire *)          (* define module *)     mod[x_] := UnitStep[x - L + 1.5]*UnitStep[L - x - 0.5]     (* define random profile *)       xi[x_] :=        Sum[RandomReal[{-0.5, 0.5}]*mod[x - n L], {n, -nSteps, nSteps}];     (* get nMax realizations of random profile *)     xiTmp[x_] = Table[xi[x], {n, 1, nMax}]     (* define correlator; normalized to corr[0]=1 *)     corr[y_]:=Table[Convolve[xiTmp[x][[n]], xiTmp[x][[n]], x, y]/      Convolve[xiTmp[x][[n]], xiTmp[x][[n]], x, 0], {n, 1, nMax}]     (* plot mean autocorrelator *)     Plot[Mean[corr[y]],{y,-5,5},PlotRange->All,Filling->Axis]


title: Elegant way to handle columns operations

text: Inspired by this question from @sjdh and by my recurrent use of columns operations in database sets, I was looking for one way to make columns operations more symetric, so I can handle with matrix and lists in a more clean way when working with this kind of data. For instance, I think it's not very practical to append a list data to a matrix using `Join[matA, {colA} // Transpose, 2]` or prepend using `Prepend[Transpose@matA, colA] // Transpose`. It's very clumsy, but we get used to it (I realized that teaching to a friend). I created this function called `colAppend`, that I would like to share here, and ask for performance tuning, tips on code organization and maybe another combinations of row operations that I have missed. Here are our test matrix and lists:               matA={{mA1,mA2},{mA3,mA4},{mA5,mA6}};     matB={{mB1,mB2},{mB3,mB4},{mB5,mB6}};     colA={cA1,cA2,cA3};     colB={cB1,cB2,cB3};      Now there are the function `colAppend` definitions. I separated it in 3 blocks: **1- Basic Join Operations**               colAppend[mat1_,mat2_]/;(Length@Dimensions@mat1>1&&Length@Dimensions@mat2>1):=         Join[mat1,mat2,2]          colAppend[mat1_,col1_,pos_:-1]/;(Length@Dimensions@mat1>1&&Length@Dimensions@col1==1):=         Insert[mat1//Transpose, col1, pos]//Transpose          colAppend[col1_,col2_]/;(Length@Dimensions@col1==1&&Length@Dimensions@col2==1):=         Transpose[{col1,col2}]          colAppend[col1_,mat1_,pos_:1]/;(Length@Dimensions@col1==1&&Length@Dimensions@mat1>1):=         Insert[mat1//Transpose, col1, pos]//Transpose          colAppend[colA,matA]//MatrixForm     colAppend[colA,colB]//MatrixForm     colAppend[matA,matB]//MatrixForm     colAppend[matA,colA]//MatrixForm      ![enter image description here](http://i.stack.imgur.com/ly1Vb.png) **2- Deleting Columns** Maybe it could be another function `colDelete`, so we could remove the `Null` parameter.               colAppend[mat1_,Null,pos_:-1]/;(Length@Dimensions@mat1>1):=     Module[{temp=mat1},         temp[[All,pos]]=Sequence[];         temp     ]          colAppend[Null,mat1_,pos_:1]/;(Length@Dimensions@mat1>1):=     Module[{temp=mat1},         temp[[All,pos]]=Sequence[];         temp     ]          colAppend[matA,Null]//MatrixForm     colAppend[Null,matA]//MatrixForm      ![enter image description here](http://i.stack.imgur.com/1ugcZ.png) **3- Join Multiple Elements** Combine all the above function (with except Null one)               colAppend::badargs = "Incompatible Dimensions";     colAppend[args__]:=Module[{list=List[args]},         If[\[Not]Equal@@(First@Dimensions@#&/@list),Return[Message[colAppend::badargs]]];         Fold[colAppend,First@list,Rest@list]     ]          MatrixForm@colAppend[matA,colA,matB,colB]      ![enter image description here](http://i.stack.imgur.com/UDeMc.png) What another functionality I'm missing? **What is the best way to create such function?** **Update 1** As VLC has posted in the comments. For part 3, this answer from @Mr.Wizard is the best option, not just in simplicity, but in performance too!               columnAttach2[ak__List]:=Replace[Unevaluated@Join[ak,2],v_?VectorQ:>{v}\[Transpose],1]


title: Integrating over Bessel Function erroreous? (Hankel Transform)

text: The Hankel Transform is given by               Integrate[f[x] x BesselJ[0,x t],{x,0,Infinity}]      It is self-inverse, so               Integrate[F[t] t BesselJ[0,x t],{t,0,Infinity}]      gives the back-transformation. I tried out a simple case:               Integrate[UnitBox[x/2] x BesselJ[0,x t],{x,0,Infinity}]      which promptly results in               BesselJ[1,t]/t      This is correct. However, if I do the back-transformation:               Integrate[BesselJ[1,t]/t t BesselJ[0,x t],{t,0,Infinity}]      the integration takes noticably longer (which is expected since the function oscillates) and the result is               ConditionalExpression[0,x>1]      While that single condition would be correct - UnitBox[x/2] == 0 for x>1 - the rest of the function won't show up. Is there any way to make the obviously missing parts show up? (I am not sure what tags to use. Please retag as appropriate) Related but not quite what I'm asking:   Hankel Transform integrals won't work in Mathematica   Strange result when integrating BesselJ functions


title: Incompleteness of FindInstance

text: I've been playing around with `Resolve` and `FindInstance`. I know that `Resolve` should always be decidable when the domain is `Reals` by Tarski's theorem, but I don't know about `FindInstance`. I tried using `FindInstance` to find a lower bound on the absolute value of a real number, but it didn't succeed.               (* First-order logic characterization of absolute value. a = |x|. *)     MyAbs[x_, a_] := (x > 0 \[Implies] a == x) ∧ (x <= 0 \[Implies] a == -x)          (* Returns True, so yes there is a lower bound. *)     Resolve[Exists[l, ForAll[{x, a}, (MyAbs[x, a]) \[Implies] a >= l]], Reals]          (* Returns True, so yes 0 is a lower bound. *)     Resolve[ForAll[{x, a}, (MyAbs[x, a]) \[Implies] a >= 0], Reals]          (* Returns {}, so Mathematica can't find a specific lower bound. *)     FindInstance[ForAll[{x, a}, (MyAbs[x, a]) \[Implies] a >= l], {l}, Reals]          (* Using the standard Abs also returns {} *)     FindInstance[ForAll[x, Abs[x] >= l], {l}, Reals]      Why is `FindInstance` not returning `{{l -> 0}}`?


title: Does anyone have experience with performing symbolic regression using Mathematica?

text: I understand that there is at least one Mathematica package, DataModeler commercially available for symbolic regression. I'm seeking any observations with this or any other similar tool. I'm interested in solving single input/single output as well as multi input/single output problems.


title: Generate a list of all user defined functions including their argument patterns

text: I have defined a bunch of functions over several different files, and I would like a list of prototypes of all the functions I have defined in my current session (I want the mathematica equivalent of the .h file for my .c file). For example, if I defined two functions,               f[arg1_, arg2_]:= Module[...];     g[t_]:= Module[...];      Then I would want the following list (alphabetized, of course):               f[arg1_, arg2_]     g[t_]      It would be nice if the list could be exported to a notebook or pdf for quick viewing. How can I accomplish this task?


title: Initialization Time Out (Weighted Financial Data)

text: I've been playing with `WeightedData` and wanted a financial engineering example, a colleague suggested working with the fractional return (`FinancialData["Name","FractionalChange"`) of a weighted portfolio. Things were going well until I tried to build a `Manipulate`:               Manipulate[     Grid[     {{Style[DateString[fractionalChanges[[1, day, 1]], {"DayName", " ", "Day", " ",         "MonthName", " ", "Year"}], "Text"], SpanFromLeft},     {Style["Unweighted Mean Fractional Change:", "Text"],      Style[ToString@Mean[fractionalChanges[[All, day, 2]]], "Text"]},     {Style["Weighted Mean Fractional Change:", "Text"],      Style[ToString@Mean[allWeightedFChanges[[day]]], "Text"]},     {Pane[      Plot[{PDF[HistogramDistribution[allWeightedFChanges[[day]], 10],          x], PDF[HistogramDistribution[          allWeightedFChanges[[day]]["InputData"], 10], x]}, {x, -0.03,         0.03}, Filling -> Axis, PlotStyle -> {Red, Blue},       PlotLegends -> {"Weighted Fractional \nChange Distribution",          "Unweighted Fractional \nChange Distribution"},        AxesLabel -> {"Fractional Change", " "}], {700, 280},       ImageSizeAction -> "ResizeToFit", Alignment -> {Center, Center}],      SpanFromLeft}}, Frame -> All], {day, 1, 253, 1},     Initialization :> (thirtyRandomStocks =      RandomChoice[FinancialData["FTSE100", "Members"], 30];     fractionalChanges =      Chop@Map[FinancialData[#, "FractionalChange", DatePlus[-360]] &,        thirtyRandomStocks];     stockWeights = RandomInteger[{100, 10000}, 30];     allFChange = fractionalChanges[[All, All, 2]];     allWeightedFChanges =      Table[WeightedData[allFChange[[All, i]], stockWeights], {i, 1,        Min[Table[         Length[allFChange[[i, All]]], {i, 1,           Length[allFChange]}]]}];)]      I get an "Initialization Time Out" error and can't figure out how to give the `Manipulate` more time to initialise. Therefore, I have two questions:   * How can I give Mathematica more time to initialise, or else ensure the `Manipulate` gets the necessary data for the calculations?   * Note: This `Manipulate` will always be used within notebooks, so Free CDF limitations aren't important for me at this point.   * Are there any suggestions you'd be willing to share to improve the code in general? I'm aware that if you look closely I'm not working with the data correctly; `allWeightedFChanges` doesn't really do what it should do.


title: Making mathematical animations with Mathematica

text: I recently stumbled upon the Cycloid and was working on finding its length and such when I found this animation on Wikipedia. ![](http://upload.wikimedia.org/wikipedia/commons/6/69/Cycloid_f.gif) Strikingly pretty and small in size too (66KB) So on searching how he made that particular animation and others I stumbled upon this talk > What software edited the animations? > > ... None at all. I used MSVC++ to write a little program that calls some > GDI+ functions and draws a multi-layer TIF picture each layer of which is a > single frame (Only Math, C++ & some Windows API that are well-documented). > ... I went on searching libraries to program with but ultimately quit because it was too much of a bother. Somewhile later I saw this and thank goodness the author used a software package (MuPAD). But the software costs a lot and is now part of MATLAB, and the size of the `.gif` was way too large. Finally I've come back to Mathematica and want to know how to go about it. Don't just tell me the code right away; give me some pointers, text, documentation, other questions, etc. EDIT : Thank you people, here's my rendering (not exactly, because I used J.M.'s code) ![](http://i.stack.imgur.com/xTRNt.gif)


title: Writing a function that returns a (usable) function

text: I am trying to create a function that returns Arnold's Cat Map of size _n_ iterated _k_ times. I can get something out of the `Function` command, but I can't figure out how to use that output as a function. The non-iterated version of the problem is trivial. I define my mapping function:               G[x_, y_, n_] := Mod[{{2, 1}, {1, 1}}.{x, y}, n];      I want it to work with `ImageTransformation`, so I define an appropriate function for that:               CatMapStep[{x_, y_}] := G[x, y, side];      where `side` is calculated somewhere earlier. Now I can call ImageTransformation (let's say I have an image `kitty`):               ImageTransformation[kitty, CatMapStep]      Done. But what do I do if you want to iterate CatMap _k_ times? Well, I can hard-code k:               CatMapFiveTimes[u_] := Nest[CatMapStep[u], u, 5];      And I discovered the `Function' command, but I can't figure out how to use it. What I would _really_ like to do is create a function that takes _k_ as an argument, and returns a function of _u_. Such is the sentiment of the following **incorrect** snippet:               IteratedCatMap[k_] := Function[u, Nest[CatMapStep[u], u, k];   <--- DOESN'T WORK      In my fantasy world, I would then be able to define CatMapFiveTimes by invoking the following line:               CatMapFiveTimes[u_] = IteratedCatMap[5];     <--- HYPOTHETICAL      And then using it as I would the previous definition. How can I create this function that returns a function? Thanks, David PS: Note that I am using Mathematica 8, although my officemate has Mathematica 9 and she couldn't get it, either. PPS: I am _completely_ open to a totally different approach to this problem. Ultimately, my only goal is to use `Manipulate` to let my students specify how many iterations of the cat map they want to see. I will be doing similar things for the Mandelbrot set, as well.


title: Underlying Algorithms for List Manipulation Functions

text: Does anyone know, or know of a link for the underlying algorithms used for list manipulation functions? Specifically:   * `Union` with and without the `SameTest` option   * `DeleteDuplicates` with and without a _test_ function.    * `Gather` with and without a _test_ function   * `Sort` with and without an _ordering function_ This question came about as there has been numerous questions that have asked about removing duplicates or some other list manipulation function. Some of the best answers often included usage of `GatherBy` due to the performance it offers (a few hundred times over `DeleteDuplicates` in some cases). Related: usages of `GatherBy` and `Union`:   Checking for duplicates in sublists `GatherBy`   Ordering function with recognition of duplicates `GatherBy`   Gather list elements by index `GatherBy`   Retrieving duplicates from nested list `GatherBy`   Delete duplicates in a list, depending on the sequence of numbers `Union`   How to delete duplicate solutions of this system of equations? `Union`


title: Mathematica quits calculation automatically

text: I have this little program that is adopted from a Wolfram demonstrations project (link here: http://demonstrations.wolfram.com/PercolationOnASquareGrid/). I want to see what happen if I increase the matrix size to 1000 or even above but Mathematica quits me. If I made the change inside Manipulate, it just showed "Manipulate Aborted". If it is without Manipulate, it quits the Kernel. I don't if it there is a glitch in my version (9.00) or simply because the limit of Mathematica... Thanks a lot for your time!!               h = 1000;     p = 0.59;          Block[{a, $RecursionLimit = 25000, w = h},       per[{i_, j_}] :=        If[1 <= i <= w && 1 <= j <= h && a[[i, j]] == 1, a[[i, j]] = 2;        per[{i, j} + #] & /@ {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}];      SeedRandom[2424];      a = Map[Boole[# < p] &, RandomReal[{0, 1}, {w, h}], {2}];      a[[All, 1]] = a[[All, h]] = 1; Do[per[{i, 1}]; per[{i, h}], {i, w}];      ArrayPlot[Transpose[a], ImageSize -> 1000, Mesh -> True,        ColorRules -> {0 -> White, 1 -> Darker[Blue], 2 -> Red}]]      Another piece that doesn't work:               L = 1000;     p1 = 0.6;     seed = 2000;          perColation[{i_, j_}] :=            If[1 <= i <= L && 1 <= j <= L && a[[i, j]] == 1,        a[[i, j]] = 2;        perColation[{i + 1, j}];        perColation[{i - 1, j}];        perColation[{i, j + 1}];        perColation[{i, j - 1}];        ];          SeedRandom[seed];          Block[{a, $RecursionLimit = Infinity},      a = RandomReal[{0, 1}, {L, L}];      For[j = 1, j <= L, j++,       For[i = 1, i <= L, i++,        If[a[[i, j]] < p1,         a[[i, j]] = 1,         a[[i, j]] = 0         ]]];           a[[IntegerPart[L/2], IntegerPart[L/2]]] = 1;      perColation[{IntegerPart[L/2], IntegerPart[L/2]}];      ArrayPlot[Transpose[a], ImageSize -> 1000,        ColorRules -> {0 -> White, 1 -> White, 2 -> Red}]]


title: TreePlot, VertexRenderingFunction and stretched vertices issue

text: Recently I found the following `TreePlot` issue. For simplicity, I took an example from Mathematica Tree Drawing Tutorial and set `TreePlot` orientation to `Left`:               TreePlot[{1 -> 4, 1 -> 5, 2 -> 8, 3 -> 4, 4 -> 8, 6 -> 8, 7 -> 8, 7 -> 9}, Left,         VertexRenderingFunction -> ({EdgeForm[Black], Yellow, Disk[#1, 0.2],              Black, Text[#2, #1]} &)]      ![TreePlot with Left orientation](http://i.stack.imgur.com/Cn0qA.png) But when I specified the root node to `5` (which differs from an automatically selected root node `4`), I recieved an image with stretched verticies:               TreePlot[{1 -> 4, 1 -> 5, 2 -> 8, 3 -> 4, 4 -> 8, 6 -> 8, 7 -> 8, 7 -> 9}, Left, 5,         VertexRenderingFunction -> ({EdgeForm[Black], Yellow, Disk[#1, 0.2],              Black, Text[#2, #1]} &)]      ![TreePlot with Left orientation and root node 5](http://i.stack.imgur.com/ihcWe.png) Is there a generic solution to this problem? Thanks.


title: Identifying when two graphic objects overlap

text: I'm designing a small demonstration that helps to visualize the reason behind shaping an electrode that is used to probe a surface:               tip[rg_] := {EdgeForm[Thin], FaceForm[White],Polygon[{{0, 4}, {0, 0.2},        {0.5 - rg, 0}, {0.5 + rg, 0}, {1, 0.2}, {1, 4}}],        FaceForm[Black], Rectangle[{0.4, 0}, {0.6, 1}]};     box = {EdgeForm[Thin], FaceForm[Blue], Rectangle[{-3, -1}, {3, 3}]};     surface = {FaceForm[Green],        Polygon@Partition[Flatten@{{-3, -1}, {3, -1},            Table[             BezierFunction[{{-3, 0}, {0, 1}, {2, -1}, {3, 0}}][x], {x, 1,               0, -0.05}]}, 2]};     Manipulate[Graphics[{box, surface, GeometricTransformation[         GeometricTransformation[tip[rg], TranslationTransform[{a, b}]],         RotationTransform[t Degree, 0.5 + {a, b}]]},        PlotRange -> {{-3, 3.1}, {-1.1, 3}}],      {{a, 0, "Left/Right"}, -3, 2}, {{b, 2, "Up/Down"}, -0.5,        2}, {{t, 0, "UME tilt"}, -15,        15}, {{rg, 0.4, "UME sharpness"}, 0.11, 0.5}]      ![Mathematica graphics](http://i.stack.imgur.com/HLRG6.png) I would like the demonstration to show some type of visualization (perhaps just a big red "CRASH warning" text) whenever the tip graphic is positioned below the surface graphic, but I do not know how to construct a conditional statement that compares the multiple points in each graphic object. I'm happy to alter the structure of either the surface or tip objects if that makes the problem easier to solve.


title: How to select TransformationFunctions based on Assumptions made when using Simplify?

text: I am re-writing the question using a very simple example so not to confuse matters with the another question being asked where I used the example from there. In general, how to add logic to switch between one `TransformationFunctions` or another inside `Simplify` or any function that uses `TransformationFunctions`? For example,               ClearAll[n, tf, e, cf];     cf[e_] := LeafCount@e     tfForIntegerOnly[e_] := If[MatchQ[e, 2 n], n, e]     tfForRealOnly[e_] := If[MatchQ[e, 2 n], n^2, e]          Assuming[Element[n, Integers],       Simplify[2 n, TransformationFunctions -> {Automatic, tf}, ComplexityFunction -> cf]]      How to make it use `tfForIntegerOnly` when `Element[n, Integers]` and use `tfForRealOnly` when `Element[n, Reals]` **Where to add this logic**? How to pass the assumptions around or check for it and what it contains? Since Mathematica does not have types (in traditional sense) associated or attached with the symbols themselves (other than looking at Head, which in this case provides no information), one needs a general way to handle this. ## Original question below I'd like to simplify an expression under one set of assumptions using one `TransformationFunctions` function and use another `TransformationFunctions` function (or use `Automatic`) for different set of assumptions. The problem is that the `TransformationFunctions` itself has no access to these `Assumptions` used before in calling `Simplify` and hence it is hard to find a way to add logic to detect which assumptions is used at that level. To explain, I want to apply `TransformationFunctions` to transform `Gamma[1/2 + n]` to `Sqrt[Pi] (Factorial2[2 *(n - 1/2) - 1])/2^(n - 1/2)` but only when `Element[n, Integers] && n > 1`. I am not able to find a way to pass these assumptions from the `Assuming` call to the `TransformationFunctions` or a way to make 2 different `TransformationFunctions` and use vs. the other inside `Simplify` itself. Here an example               ClearAll[n, tf, e, cf];     cf[e_] := Count[e, Gamma, Infinity, Heads -> True] 1000 + LeafCount@e      tf[e_] := If[MatchQ[e, Gamma[1/2 + n]],Sqrt[Pi] (Factorial2[2 *(n - 1/2) - 1])/2^(n - 1/2), e]          Assuming[Element[n, Integers] && n > 1,Simplify[Gamma[1/2 + n] + Gamma[1/3 + n],      TransformationFunctions -> {Automatic, tf},ComplexityFunction -> cf]]      ![Mathematica graphics](http://i.stack.imgur.com/X6AVz.png) But now if I assume `n` is `Real`, I do not want to modify the code above, but I want the `TransformationFunctions` to automatically to detect this and in this case not apply this transformation rule or add some logic inside `Simplify` to use one `TransformationFunctions` vs. the other based on `Assumptions`               ClearAll[n, tf, e, cf];     cf[e_] := Count[e, Gamma, Infinity, Heads -> True] 1000 + LeafCount@e      tf[e_] := If[MatchQ[e, Gamma[1/2 + n]], Sqrt[Pi] (Factorial2[2 *(n - 1/2) - 1])/2^(n - 1/2), e]          Assuming[Element[n, Reals], Simplify[Gamma[1/2 + n] + Gamma[1/3 + n],        TransformationFunctions -> {Automatic, tf},        ComplexityFunction -> cf]]      ![Mathematica graphics](http://i.stack.imgur.com/xM5b0.png) which is wrong since now `n` is not an integer now. I'd like to be able to write               Assuming[Element[n, Reals], Simplify[Gamma[1/2 + n] + Gamma[1/3 + n],     TransformationFunctions ->Cases[Element[n, Reals], Automatic, Element[n, Integers] && n > 1,tf],       ComplexityFunction -> cf]      ]      But the above is not valid syntax. * * *


title: Clear and Unset doesn't free memory

text: Example: Try this example only if you have > 4G ram               d = 2000;      f[x_, y_, d_] =           Sum[Subscript[a, i, j]*x^i*y^j,             {i, 0, d - 1}, {j, 0, d - i}];      Then               Clear[f]      or               f[x_, y_, d_] =.      You will see that the memory usage is not reduced after calling `Clear` or using `Unset`. _**Question: How to free the memory when I don't need a function anymore which is already evaluated?_** Edit: I look at the memory usage in taskmgr under Windows OS. As the answers report that the memory is indeed reduce by using MemoryInUse to check it.


title: How to set restrictions in Manipulate parameters?

text: I´m trying to insert the typicall 3 variables for probability, with the restriction x+y+z=1 How can I insert this values in a Manbipulate I try               Manipulate[x*y*(1-x-y), {x, 0, 1 - y}, {y, 0, 1 - x} ]      but when I move x, y is moving without I want it.


title: Finding max value of each column of 4x4 Array

text: I have the following array in both `MatrixForm` and `List` form               0.474042    0.507508    0.4977      0.539773          0.473447    0.50765     0.483809    0.52489          0.46797     0.483669    0.494823    0.516956          0.467079    0.483509    0.478704    0.501286               A = {{ 0.474042, 0.507508, 0.4977,   0.539773},          { 0.473447, 0.50765,  0.483809, 0.52489 },          { 0.46797,  0.483669, 0.494823, 0.516956},          { 0.467079, 0.483509, 0.478704, 0.501286}         }      I want to get the max value of each column. I've tried the following for the first columns but no help:               Max[A[[All, 1]]]      Any comment will be greatly appreciated.


title: Faster way to test if an expression equals zero

text: I want to test if expressions (mix of variables, functions and numbers) are zero valued, as fast as possible, and `PossibleZeroQ` is sometimes very slow. One solution I found was to substitute the variables for random reals and test if the value of the substituted expression is less than, say, $0.0001$. It works good, but maybe there are other solutions out there. I know it can cause some wrong answers, but what is most important is the speed, since I can check the false positive later with `PossibleZeroQ`. Can you think of an algorithm that can perform fast zero value tests in detriment of some loss of accuracy? Edit: I'll post my algorithm here:               TestZeroValuedExpression[expression_,symbolslist_]:=Module[{numericvalue},     Quiet[TimeConstrained[If[Check[         numericvalue=N[Expand[expression/.Table[symbolslist[[i]]->RandomReal[{1,2}],{i,Length[symbolslist]}]]];     ,False]=!=False,         If[Abs[numericvalue]>0.00001,False,PossibleZeroQ[expression]],         PossibleZeroQ[expression]     ],3,False]]     ];


title: Sorting Eigensystems

text: SO I have this code:               {evalueb1,evectorsb1} = Eigensystem[Coefficientsp1];      evalueb1 = 1/(evalueb1*2\[Pi]);           For[i=1,i<(2TruncationOrder+1),i++,If[Abs[Im[evalueb1[[i]]]]                                                  <10^-14,evalueb1[[i]]=Re[evalueb1[[i]]],evalueb1[[i]]=evalueb1[[i]]]];           \[Rho]plus1 = Sort[Select[evalueb1,Im[#]>0\[Or](Im[#]==0\[And]Re[#]>0)&],Im[#2]>Im[#1]&];      \[Rho]minus1 = Sort[Select[evalueb1,Im[#]<0\[Or](Im[#]==0\[And]Re[#]<0)&],Im[#2]Im[#1]&];      What I did was sort the eigenvalues based on the sign of the complex part. How can I make it so that I can find the correct eigenvector associated with the sorted eigenvalues?


title: How to place Plot Information within a Text box on top of a Bar Chart?

text: How could I place a text box on the top of a bar chart where the top line would have a larger font size than the second line? My Data:               totals4={{1093, "AUSTRALIA"}, {235, "BELGIUM"}, {474, "BERMUDA"}, {187, "BRAZIL"}, {103, "BAHAMAS"}};      This code will plot the `PlotLabel->` as a long string. I would like to move " - excludes USA, as of: June 2012" to the second line with a smaller font and not bold. Ideally this text would be within a box, however I would just be happy to get the second line to display correctly.               BarChart[#, ChartStyle -> "DarkRainbow", PlotLabel ->      Style["Entities with LEI Number - excludes USA, as of: June 2012",      Bold, FontSize -> 12],       ChartLabels -> (Placed[     Rotate[Style[#, Black], Pi/3] & /@ #2, {{.7, 0}, {1, 1}}])] & @@     Transpose[totals4]      ![enter image description here](http://i.stack.imgur.com/ZUnxK.jpg) I have tried this code but it is not displaying correctly:               BarChart[#, ChartStyle -> "DarkRainbow",                  PlotLabel -> Style[TraditionalForm[Grid[{         {TextCell[                  Row[{"Entities with LEI Number (excludes USA)",             HoldForm[Subscript[a, b]], " As of June 2012"}],            TextJustification -> 1], SpanFromLeft},         }, Frame -> All]       ], FontFamily ._ "Times"],       ChartLabels -> (Placed[       Rotate[Style[#, Black], Pi/3] & /@ #2, {{.7, 0}, {1, 1}}])] & @@      Transpose[totals4]      Any help would be appreciated.


title: Probable Bug in HighlightMesh with 2D Convex Hulls created via ConvexHullMesh

text: One nice way to view the new and exciting `Mesh` objects introduced in **Version 10** is by utilizing the function `HighlightMesh`, so I've been using it heavily. Problem is, when trying to visualize 2D convex hull regions (3D case works fine) created using `ConvexHullMesh`, `HighlightMesh` essentially ignores the `Options` for styling the face of the 2D polygon region. Here is an example:               SeedRandom[0];     pts = RandomReal[4, {200, 2}];     chull = ConvexHullMesh[pts]      ![Mathematica graphics](http://i.stack.imgur.com/sKju8.png) Now let's `Style` it using `HighlightMesh`               HighlightMesh[chull, {Style[0, Directive[PointSize[0.02], Red]],        Style[1, Thin, Green], Style[2, Directive[Yellow]]}]      ![Mathematica graphics](http://i.stack.imgur.com/4kTSH.png) Notice the `Yellow` `Color` under `Style[2, ..]`, that's for the `Polygon` face. This is obviously ignored for the `Default` color used above. Can anyone reproduce this on **Windows 8.1** and other operating systems and is there an easy workaround for this?


title: Using PatternTest and/or Condition to detect equal list lengths as well as list element formats

text: On searching Mathematica.SE for information about overloading functions, I came across several threads about `PatternTest` and `Condition`, and I understand the basic examples like matching by `EvenQ`. However I'm having trouble imagining how I'd use these features to implement checks having to do with "whole" lists. * * * For example, I'd like to define a function `Convert` of the form               Convert[quantities_, prices_] :=      _only_ if `quantities` and `prices` are equal-length lists. In other words, if `Length[quantities] != Length[prices]` then `Convert` should behave as if undefined. * * * For a more complex example, I'd like to define an overloaded version,               Convert[dateQuantityList_, datePriceList_] :=      where `dateQuantityList` and `datePriceList` look like               {{{2012, 1, 1, 9, 30, 7}, 150},      {{2012, 1, 1, 9, 30, 12}, 130},      {{2012, 1, 1, 9, 30, 33}, 470},      ...     }      and               {{{2012, 1, 1, 9, 30, 7}, 24.56},      {{2012, 1, 1, 9, 30, 33}, 24.58},      ...     }      such that the function is only defined if all elements in `dateQuantityList[[All, 1]]` and `datePriceList[[All, 1]]` are valid `DateList`s. (Is there something like a `DateListQ`? But even supposing so, again, I'm not clear on how to apply `PatternTest` or `Condition` to a property of an entire list, not its elements...) (The goal of the latter overload is to do a "left join" based on the date, _i.e._ discard prices that don't have corresponding dates in the quantities list, and calling the original form, `Convert[q_, p_]`. I know how to do that part using `GatherBy`--it's the `PatternTest`/`Condition` part that's completely new to me.) I have many more overloads I'd like to write, but if I can get started with those two examples, I think I can figure the rest out.


title: Passing lists to functions in a manner that works like pass-by-reference in other languages?

text: Is it possible to use a list as a variable, i.e., to pass it by reference to a function? In particular, I have a two-dimensional array and a function to get one element specified by its position:               s = {{1, 1, 1, -1}, {1, 1, -1, -1}, {-1, -1, 1, -1}, {-1, 1, -1, 1}};     valueAtPos[positionX_, positionY_, lattice_List] :=         Flatten[Take[lattice, {positionY, positionY}, {positionX, positionX}]]      This works just fine, it does exactly what I want. Now, what I'm actually aiming at is "flipping" the value at a certain position, i.e. $-1 \rightarrow 1$ and vice versa. I tried it with a function and a fixed list and it worked, but since I have more than one list, I want to pass the actual list not a copy as an argument as well. So I tried this:               flip[posX_, posY_, lattice_List] :=        Module[{latticeLocal = lattice, x = posX, y = posY},         latticeLocal =            ReplacePart[latticeLocal, {y,x} -> -valueAtPos[x, y, latticeLocal]] //.             {{1} :> 1, {-1} :> -1};]      If I run, for example, `flip[1, 1, s]`, it should change `s` to               s = {{-1, 1, 1, -1}, {1, 1, -1, -1}, {-1, -1, 1, -1}, {-1, 1, -1, 1}}.      but it doesn't; `s` is left untouched, exactly the same as before. If I run               s = ReplacePart[s,{1,1} -> -valueAtPos[1, 1, latticeLocal]] //. {{1} :> 1, {-1} :> -1};      it does exactly what it's supposed to do. My question is: How can I pass a list, not a copy of the list, to a function so the list I pass will really get modified. (I tried using the list like a normal argument of a function and I got errors. Modules, at least, didn't give me errors) ### Edit Nasser told me to delete the semicolon in `flip` and to assign the output of the function to my original list. That works, of course, but is not quite what I wanted, so I am going to clarify this here. I want to use the `flip` in another function. And I not only want to run the function, I also want to use its output. Look at this:               algorithm[steps_, T_, lattice_List] :=        Module[{latticeLocal = lattice},         For[i = 0, i < steps, i++,            {             (* definig some variables inside the for-loop *)             If[(* some expression *),                latticeLocal = flip[posX, posY, latticeLocal],               0]            }];]      This doesn't work. I need to use the output of `flip` in the for-loop, and I don't have an idea how to do that.


title: General form of a linear transformation

text: > Let $v_1 = \begin{bmatrix} 2 \\\ -1 \end{bmatrix}$ and $v_2=\begin{bmatrix} > 1 \\\ -1 \end{bmatrix}$ and let $A= \begin{bmatrix} 3 & 2 \\\ -2 & 1 > \end{bmatrix}$ be a matrix for $T\colon \Bbb R^2\to \Bbb R^2$ relative to > the basis $B = \\{v_1, v_2\\}$. From this I found that: $T(v_1) = \begin{bmatrix} 4 \\\ -1 \end{bmatrix}$ and $T(v_2) = \begin{bmatrix} 5 \\\ -3 \end{bmatrix}$ How would I find a formula for $T\begin{pmatrix} \begin{bmatrix}x_1 \\\ x_2\end{bmatrix} \end{pmatrix}$. The answer in my book is $\begin{bmatrix} -x_1-6x_2 \\\ 2x_1+5x_2 \end{bmatrix}$


title: Problem with FrameLabel in the ErrorListPlot function

text: I've been trying to print information on the axes of a graphic. I'm doing that by the option `FrameLabel` in the `ErrorListPlot` function. But it failed. Here the code I'm using               Needs["ErrorBarPlots`"];          d    = Import["teste.txt", "TSV"];     dNew = Table[{{d[[i, 1]], d[[i, 2]]}, ErrorBar[d[[i, 3]]]}, {i, 2, Length[d]}];          ErrorListPlot[dNew, FrameLabel -> {"Position, x (inches)", "Photodetector output (V)"}]      The result ![enter image description here](http://i.stack.imgur.com/vHfJH.jpg) How can I fix it? Thanks for the attention. Hellon


title: How can I find the derivative of a combinatorial expression?

text: I want to differentiate the following equation:               n = (nchoosek)*p*(1 - p)^(n - k)      After differentiating my result is:               n = -1/log(1 - p)      But my problem is that I cannot differentiate this. Can anyone please help me to do this?


title: Difference between sub MathKernel and MathKernel

text: When I try to run Mathematica processes in parallel on a Linux based server, I see that my server allows 7 MathKernels and 28 sub MathKernels. I was wondering what the difference is and how I can take advantage of the 28 sub MathKernels. I generally run my job like:               for i in $var       do       "path"/math -noprompt -script "scriptname" "parameters" &       done      This results in using different MathKernels. Therefore I am able to do this iteration at most 7 times. I was wondering if I could take use of the sub MathKernel licenses, I can somehow tweak this to run 28 times. Is that possible?


title: Most convenient way to set legend marker size?

text: If I add a legend using               Legended[..., SwatchLegend[..., ...]]      then I can explicitly set the legend marker size using the `LegendMarkerSize` option. But I also need to explicitly set the style/colour of the legend elements a second time within the legend expression. It is usually much more convenient to use the `PlotLegens` or the `ChartLegends` option. It spares me the trouble of having to manually match up the legens with the plot or chart. If I use this, can I still control the marker size? Example:               cm = 72/2.54;     BarChart[{{1, 2, 3}, {1, 3, 2}}, ChartLegends -> {"a", "b", "c"}, ImageSize -> 4 cm]      How can I control the legend marker size in the above graphic? Is there anything simpler than an explicit legend specification as below?               colours = {Red, Blue, Black};     Legended[      BarChart[{{1, 2, 3}, {1, 3, 2}}, ImageSize -> 4 cm, ChartStyle -> colours],      SwatchLegend[colours, {"a", "b", "c"}, LegendMarkerSize -> 7]     ]


title: How to make "Text" Cell which does not auto-format in TraditionalForm in-line math expressions?

text: This is a continuation of the previous post: How to enter textual subscripts and superscripts?. When dealing with complex in-line math expressions inside a `"Text"` cell _Mathematica_ by default formats them in `TraditionalForm`. Is it possible to force _Mathematica_ to create in-line cells with the same style as the style of enclosing cell?


title: Function does not compile with Greater in it

text: I have to speed up a matrix-calculation and would like to use `Compile` for it, though it fails and produces an unknown error message:               compiledFunc =        Compile[{{w, _Real, 2}, {v, _Integer, 1}, {hb, _Real,           1}, {vb, _Real, 1}}, Module[{h, hs, vr, hr},         h = 1./(1. + Exp[-(w.v + hb)]);         hs = Boole@Thread[h > RandomReal[{0, 1}, {Length@hb}]];         vr = 1./(1. + Exp[-((Transpose@w).hs + vb)]);         hr = 1./(1. + Exp[-(w.vr + hb)]);         w + (0.01*(Outer[Times, h, v] - Outer[Times, hr, vr]))         ], Parallelization -> True];          (*       ==> Compile::argcompten: The comparison, Greater, is invalid for tensor arguments. >>     *)      Any idea how I can overcome this and/or speed it up? **Update:** According to the answers, the problem is that `Thread` is not compilable. Substituting it with `MapThread` indeed allows compilation. But then running the code gives another error. (I thought that since it is about the same piece of code, I won't start a new post.)               cFunc = Compile[{{w, _Real, 2}, {v, _Integer, 1}, {hb, _Real,           1}, {vb, _Real, 1}}, Module[{h, hs, vr, hr},         h = 1./(1. + Exp[-(w.v + hb)]);         hs = Boole@           MapThread[Greater, {h, RandomReal[{0, 1}, {Length@hb}]}];         vr = 1./(1. + Exp[-((Transpose@w).hs + vb)]);         hr = 1./(1. + Exp[-(w.vr + hb)]);         w + (0.01*(Outer[Times, h, v] - Outer[Times, hr, vr]))],        Parallelization -> True];          cFunc[w, v, hb, vb]          (*        CompiledFunction::cfse: Compiled expression 1.7+3.2 I should be a machine-size real number. >>             CompiledFunction::cfex: Could not complete external evaluation at instruction 2; proceeding with uncompiled evaluation. >>     *)


title: How can I close a stream without knowing its name?

text: If I initialise a stream as follows               OpenWrite["~/example"]      How do I close this stream? `Close` seems to expect a name, but I do not know the name of the stream in this format. [edit] - Thanks for all the responses. It seems the simplest solution was               Close[<full path name to file>]      I had previously tried Close["~/example"] but to no avail.


title: Finding time-series direction reversal of certain magnitude

text: I'd like to find the points of a time-series that are a certain distance away (in value, not in time) from the previous maximum, which I consider a reversal. For example, for `{1, 2, 3, 5, 10, 8, 6, 3}` with a threshold of `4`, the reversal point would be `6`, since it's `4` units away from the previous maximum of `10`. I want to find all such reversal points, but at each one I need to reset the running maximum (or split the list and start again on the new list). Here is some code to find the first reversal. It computes the distance from each element to a rolling maximum, then looks for the first difference bigger than the threshold.               ts = {1, 2, 3, 5, 10, 8, 6, 3};     rollmax = FoldList[Max, First[ts], Rest[ts]];     delta = rollmax - ts;     sel = Map[# >= 4 &, delta];     index = Position[sel, True, 1, 1]      I can do this in a procedural way, but it's probably not the preferred way. I'm new to functional programming and I don't quite know what sort of patterns are available that would help me here. And if there was a better way of writing the above code, please let me know.


title: Workarounds for a possible bug in the linearity of FourierTransform

text: This is somewhat similar to this question, except the problem I am encountering is to do with Fourier transforms of scalar multiples of functions and their derivatives. I wish to input `FourierTransform[a*f[t],t,x]` and have Mathematica simplify it to `a*FourierTransform[f[t],t,x]`, and, equivalently, to input `FourierTransform[f'[t],t,x]` and have Mathematica simplify it to `ix*FourierTransform[f[t],t,x]`. I'm taking the Fourier transform of a system of differential equations for functions `f[t]`,`g[t]`, etc., in order to instead only have to solve a system of algebraic equations for their Fourier transforms, but Mathematica seems to be having some problems doing this. Note that `LaplaceTransform` works exactly as expected, but for some reason `FourierTransform` doesn't perform the expected simplification. If someone could suggest a solution that also incorporates the distributive property that `FourierTransform` was shown to have a problem with in the question I linked, that would be ideal. # Example This is essentially what I'd like `FourierTransform` to do:               LaplaceTransform[{a*f[t]+b*g'[t]==0,c*f'[t]+d*g[t]==0},t,x]      which returns:               {a*LaplaceTransform[f[t],t,x]+b*(-g[0]+x*LaplaceTransform[g[t],t,x])==0,     c*(-f[0]+x*LaplaceTransform[f[t],t,x])+d*LaplaceTransform[g[t],t,x]==0}      Instead, however, `FourierTransform` of the same expression returns:               {FourierTransform[a*f[t]+b*g'[t]==0,t,x],FourierTransform[c*f'[t]+d*g[t]==0,t,x]}      # Edit There is a solution to this problem here, although it doesn't actually explain `FourierTransform`'s strange functionality.


title: Ugly font rendering (ubuntu 12, overrides system settings)

text: Mathematica 9 on Ubuntu 12 renders fonts very poorly. Text is readable, but it makes it very hard to concentrate on programming. Since smoothing on Ubuntu on low DPI screens isn't very good either, I turned it off and have been using fonts that are friendly without smoothing (e.g. Courier New). Mathematica completely ignores this fact and smoothes them anyway (in some proprietary way that seems to be different from the way how ubuntu smoothes them (when smoothing is system-wide enabled)). Is there any option how to modify/disable this behavior ?


title: Inverse on a restricted domain

text: I have a function, whose domain is [0,1]. The function is               f = Piecewise[{{Exp[-β * (-Log[#])^α], 0 < # <= 1}}, #]&      with `β > 0` and `α > 0` (side note: is this the best way of defining the function such that it's `Exp[-β * (-Log[#])^α]` on (0,1] and 0 at 0?) I would now like to use the inverse of this function, which I'm pretty sure exists (and is `E^(-(-1)^((1/α)) β^(-1/α) Log[w]^(1/α))`). However,               InverseFunction[f]      simply returns the call and not the actual inverse. At this point I'm not sure whether it's my lousy _Mathematica_ skills that keep me from getting the correct inverse or whether there's something in the math that I've neglected to consider. What am I doing wrong? How do I tell _Mathematica_ to just find the inverse on [0,1] and how do I tell it that both parameters are positive?


title: Make a table of changes in US coinage

text: I thought of an innovative use of Mathematica/Alpha that I think Stephen Wolfram would really love, but I can't figure out how to get it to work. The idea is to make a table that would chart the changes in US coinage over time pictorially. So, the rows would be time periods, and the columns would be denominations (penny, nickel, dime, quarter, half dollar, dollar, possibly eagle and double eagle). So, for example, I think the coinage did not change from 1921 (when the Peace Dollar was first issued) to 1932 (when the Washington Quarter was adopted). So, that would be one row in the table, 1921-1932 and each cell in that row would show the coin from that period. I tried using Wolfram Alpha to get the coin images but it was hard. For example, "Washington Quarter" just returns information about the quarter fraction, not the coin. How can I go about making an expression/module that will build this table?


title: Defining a function (but not explicitly)

text: I have a question that must have a simple answer, but googling and searching this website did not produce an answer, so I'm asking it here. I'm working with three variables $x, y, \theta$, and I want to tell mathematica that I have a function $f$, which is a function of $x$ and $y$ alone. I **do not** have an expression for $f$; all I want is for mathematica to produce outputs like $f_x, f_y, f_{xx}$, etc, when asked to differentiate $f$, for instance. But I do want to get $0$ when I ask mathematica for $f_{\theta}$, since $f$ doesn't depend on $\theta$. How do I define this $f$? Thank you very much!


title: Is mathematica storing information it shouldn't store?

text: I'm seeking to find solutions to a numerical integration with a large set of parameter combinations (basically, I'm doing a brute parameter sampling). Yet, I believe the memory of the computer is storing unnecessary information, but I can't understand why: the memory stores near 16Gb of memory coming from Mathematica Kernel, while the output is only ~25mb. This sometimes makes the computer run out of memory and Kernel quitting. I am also afraid this may slow my computations. I will abbreviate a lot the code because I just want to know if I'm doing something fundamentally wrong with my rationale, specially on **point 3 below**. Basically, I am numerically integrating some equations for many parameter values. The output of the integration is then used to compute values of the dependent variables at specific time points. These values are my output ~25 mb. ## **Note that I simplified my code a lot** , and also left some of it blank because it is unnecessary to explain what I am doing. What I'm doing is the following: **1- Considering a very large table**               Table4 =       Sort[        Flatten[         Table[          {10^b, 10^g, 10^v, 10^k}, {b, -5, 5, 0.5}, {g, -7, 3,            0.5}, {v, -11, -1, 0.5}, {k, -8, 2, 0.5}          ],         3]        ];      **2- I have a function`deqns4` that is simply a system of ODEs to be numerically integrated** and is called several times in **point 3** (This is a random system of equations, my real one has 13 dependent variables).               deqns4[b_, g_, v_, k_] :=       {A'[t] == ki H[t] + k X[t] - b A[t],        X'[t] == g A[t] - v X[t] - kc X[t],        A[0] == 2,        X[0] == 1        };      **3- Then, the following function calls`deqns4` several times, to **numerically integrate the equations and output the values of the dependent variables** at some time points, for the given parameter values in `Table4`:               lsim4[{b_, g_, v_, k_}, ba_] :=       Block[{ep, initconds, sssol0, tsim4, tsim3, tsimc50, tsimc100, c1,     c2, c3, c4, c5, c6, c7},          (*This finds initial conditions*)        sssol0 = Cases[          NSolve[           Rationalize[            Evaluate[{                ki H + k X - b A == 0,                g A - v X - kc X == 0} /. ki -> 2 /. kc -> 0.1             ],            0            ],           {A, X}           ],          {Rule[_, _?NonNegative] ..}          ] /. {A -> A0, X -> X0};          (*This and the following commands use the initial conditions above to numerically integrate the system of equations "deqns4"*)     tsim4 = Flatten[         NDSolve[          Rationalize[           Evaluate[            Join[               {H[t] == 0.009 Exp[-0.1 t] + ba },               deqns4[b, g, v, k]               ] /. kc -> 0.1 /. sssol0],           0           ],          {A, X, H},          {t, 0, 9720}, MaxSteps -> 1*^12          ],         1         ];          (*tsim3, tsimc50, and tsimc100 are also numerical integration of deqns4,    similarly to tsim4*)     tsim3 = Flatten[NDSolve[(*...left blank to simplify...*)], 1];     tsimc50 = Flatten[NDSolve[(*...left blank to simplify...*)], 1];     tsimc100 = Flatten[NDSolve[(*...left blank to simplify...*)], 1];          (*then I want the output to be a set of values computed from the \ numerical integration above*)   c1 = (A[324] + X[324]) 100 /. tsim4;          c2 = (A[9720]) 100/(A[0]) /. tsim4;          c3 = (X[3240]) 100 /. tsim4;          c4 = (X[9720]) 100 /. tsim4;          c5 = (A[3240] + X[3240]) 100 /. tsim3;          c6 = (X[3240]) 100 /. tsimc100;          c7 = (X[3240]) 100 /. tsimc50;          {c1, c2, c3, c4, c5, c6, c7}          ];          lsimsols = ParallelMap[lsim4[#, 1.2] &, Table4];          (*output is a list with the form lsimsols={{0.1,0.99,100,0.52,76,100,100},{0.01,0.99,90,53,75,100},etc}*)      ## My questions are the following:   1. Is `NDSolve`storing information each time it runs, though it is within a `Block` function?   2. The function `lsim4` is only outputing `c1` to `c7` for each element of `Table4`. This is what is being stored by `lsimsols`, and is the only information I am interested in. Yet, a lot more data is being stored by the kernel. Is there any way for me to avoid storage of so much information?   3. Even without specifying `MaxStepSize`, takes me ~4 hours to run all the values of parameters. Is there any more efficient way of doing this parameter sampling other than `ParallelMap`? Thanks in advance! **Edit:**   * as suggested in the comments, I set `$HistoryLength=0` **which did not change all the memory allocated to Mathematica** \- I still get about 16 Gbs of stored information.   * Also, `ParametricNDSolve` seems to produce faster results than `NDSolve`. **Edit #2:**   * Someone suggested to use `Map` instead of `ParallelMap`, as this would possibly allow less memory usage. This didn't make any improvements.   * The only way I was able to attain a partial solution to the problem above is by splitting `Table4` in multiple parts and run `deqns4` for each part separately and then joining everything.


title: Exporting PDF file - incorrect graphic

text: I export graphics to PDF using:               Export["/path/figure.pdf", plotname]      It gives me more than enough quality for PDFLatex. But somehow, some exported plots have 'extra' lines (it doesn't happen when I export to PNG/JPG for example): ![image showing plot with extra lines](http://i.stack.imgur.com/J7JVN.pngFunctions) It doesn't happen to all exported plots, and in Mathematica itself, the plot looks correct: no extra lines visible. The `ListPlot` is more than just a `ListPlot` (it uses external data to make five different `ListPlot`s and is then showed in one plot using `Show`), but the other plots made in the same way are perfectly fine, so I guess it has nothing to do with how the plot has been generated. Sorry I am sich a n00b, I don't know how to add all this code. So again, I have shared it online: [link to notebook code].2 The funny thing is, I have 'built' three of these plots, only the one in the shared code, gives this problem. This plot is the 'middle' plot, i.e., there has been a plot made before, then I clear the counters, and start again. FYI: You can't run the code, because it needs external data. The external data are many CSV files containing 9 rows of each a text string and a numeric value. I am using Mathematica 9.0.1.0 on Ubuntu 13.04. Thinking it might be some 'leftover' information, I've tried to clear all parameters/variables, quit the kernel (local), quit Mathematica as a whole. But the problem isn't solved. I hope someone here knows what might be going on. I prefer not to change all my figures to a different format. If there is a best format for PDFLatex, then of course I will reconsider, at least for the future. But I expect PDF to fit perfectly with PDFLatex...


title: How to insert a zoom inside the main plot

text: As the title indicates, I want to add inside the main plot (preferably at the lower left part) a zoom. Here is the corresponding Mathematica code:               Clear["Global`*"];       Off[General::spell];          Vd = -(Md/Sqrt[b^2 + R^2 + (a + Sqrt[h^2 + z^2])^2]);     Vn = -(Mn/Sqrt[R^2 + z^2 + cn^2]);     Vper = k*R^3 + λ*(R^2 + β*z^2)^2;     Vtot = Vd + Vn + Vper;     Veff = Vtot + Lz^2/(2*R^2);          Md = 12000; b = 8; a = 3; h = 0.1;     Mn = 400; cn = 0.25;     k = -0.35; λ = 0.01; β = 0.01;     Lz = 20;     E0 = -1100;          C0 = ContourPlot[Veff, {R, 0.001, 35}, {z, -80, 80}, Contours -> {E0},     PlotPoints -> 200, ContourShading -> False,      ContourStyle -> {Black, Thickness[0.003]},      PerformanceGoal -> "Quality", ImageSize -> 550];          SetDirectory[" ... "];     data = ReadList["orb_RR.out", Number, RecordLists -> True];     S0 = ListPlot[Flatten[List /@ data[[All, {2, 3}]], 1], Joined -> True,      PlotStyle -> Darker[Gray]];          P0 = Show[{C0, S0}, Frame -> True, FrameLabel -> {"R", "z"},      RotateLabel -> False, Axes -> False,      FrameStyle -> Directive[FontSize -> 17, FontFamily -> "Helvetica"],       PlotRange -> {{0, 35}, {-80, 80}}, ImageSize -> 550]     P1 = Show[{C0, S0}, Frame -> True, FrameLabel -> {"R", "z"},      RotateLabel -> False, Axes -> False,      FrameStyle -> Directive[FontSize -> 17, FontFamily -> "Helvetica"],      PlotRange -> {{0.3, 4.5}, {-5, 5}}, ImageSize -> 550]      The main plot which is produced by `P0` is the following ![enter image description here](http://i.stack.imgur.com/avTWI.jpg) Obviously, it is impossible to understand and interpret the orbit which is inside the closed curve. One may argue, that this issue could be easily solved by just changing the ranges of plot. However, this is not very wise approach, since I need to present the entire area defined by the closed curve and then point out that the orbit is indeed confined only at a very small sub-area. So, I have to incorporate the zoom plot created by `P1` ![enter image description here](http://i.stack.imgur.com/akB8Z.jpg) using the specified ranges preferably at the lower left side of the main plot (where there is plenty of available space). It would be very nice if there were also arrows pointing the original position of the zoom. The file containing the orbit data can be downloaded from here: enter link description here Any ideas on how this could be done? Many thanks in advance!


title: ListLinePlot x-axis units label

text: If I want to label the $x$-axis of a `ListLinePlot` , how do I do that? There are two types of label:   * a **units label** which would go to the **right of the axis** ,  and then potentially you could have an   * **axis label below it**.  What would be the way to enter both types of text?


title: truncating terms in symbolic expression basing on their values

text: I need to simplify big symbolic solution of equations system by truncating terms that are orders of magnitude less then others in subexpressions like a + b. The solution is big fraction with sum of terms in numerator and denominator like _a b + c ( d - f + g + ..._ where every symbol has value (real number). Is it possible to apply rule like this to solution: _replace a + b by a, if Abs[a] >> Abs[b] (say, 1000 times more), by b, if Abs[a] << Abs[b], or leave it as a + b in other cases_. Repeated application of such a rule should result in symbolic expression that is much simpler then exact solution, but is good enough approximation for concrete values of symbols. I am new to Mathematica, searched for similar questions but didn't find any. Minimal working example: solving eq gives solution that should be simplified by truncating terms basing on parameters alpha and beta below:               v1 = α1 a - β1 b;     v2 = α2 a;     v3 = α3 c;     eq = {-v1 - v2 == 0, v1 + v3 == 0, a + b + c == p};     Solve[eq, {a, b, c}]          α1 = 1000; β1 = 1000; α2 = 1; α3 = 1;


title: Feed a Manipulate[] Output into a Graphics[]

text: Please consider :               allTeamsOf5 = Subsets[Range[12], {5}];          rosterRandomAttributes = Table[Table[Round[RandomReal[], .1], {10}], {12}];          rosterRAMean = Mean@rosterRandomAttributes;          rosterRASD = StandardDeviation@rosterRandomAttributes;          allTeamStats = rosterRandomAttributes[[allTeamsOf5[[#]]]] & /@                     Range[Length@allTeamsOf5];          allTeamAverageStats = Mean /@ (allTeamStats[[#]]\[Transpose]) & /@ Range[792];          allTeamsDistToMean =     Total[(allTeamAverageStats[[#]] - rosterRAMean)/rosterRASD] & /@ Range[792];          distToMean = (rosterRandomAttributes[[#]] - rosterRAMean) & /@ Range[12];      The below essentially compute the best team we can get out of this roster emphasizing on different attribute through weight. It output a list of 10 value representing the distance to the mean for each.               Manipulate[(Flatten@         allTeamAverageStats[[          Flatten@Position[            Total[{v1, v2, v3, v4, v5, v6, v7, v8, v9, v10}/            Total@{v1, v2, v3, v4, v5, v6, v7, v8, v9, v10} (            allTeamAverageStats[[#]] - rosterRAMean)/rosterRASD] & /@          Range[792],         Max[Total[{v1, v2, v3, v4, v5, v6, v7, v8, v9, v10}/             Total@{v1, v2, v3, v4, v5, v6, v7, v8, v9, v10} (             allTeamAverageStats[[#]] - rosterRAMean)/rosterRASD] & /@           Range[792]]]]]) - rosterRAMean,      {v1, Range[.1, 1, .1]},      {v2, Range[.1, 1, .1]},      {v3, Range[.1, 1, .1]},      {v4, Range[.1, 1, .1]},      {v5, Range[.1, 1, .1]},      {v6, Range[.1, 1, .1]},      {v7, Range[.1, 1, .1]},      {v8, Range[.1, 1, .1]},      {v9, Range[.1, 1, .1]},      {v10, Range[.1, 1, .1]}, ControlType -> Manipulator]      ![enter image description here](http://i.stack.imgur.com/bUDxy.png) Now I would like the result of that manipulate to feed the below plot : (using solution posted on How can I create a ColorFunction using Blend? )               Show[      Function[attributes,        Graphics[{        Blend[{        {-Max[Abs[distToMean[[1]]]], Red},        {0, LightRed}, {0, LightGreen},        {+Max[Abs[distToMean[[1]]]], Green}},        distToMean[[1]][[attributes]]],       Rectangle[{If[distToMean[[1]][[attributes]] < 0,          distToMean[[1]][[attributes]]*10, 0],         attributes - 1}, {If[distToMean[[1]][[attributes]] < 0, 0,          distToMean[[1]][[attributes]]*10], attributes}],       PlotRange -> {{-6, 6}, {0, 10}}}, AspectRatio -> 16/9,      Epilog -> {Black, Thickness[.05], Line[{{0, 0}, {0, 11}}]}]] /@      Range[10], Frame -> False, FrameTicks -> False]      ![enter image description here](http://i.stack.imgur.com/8vJh8.png) **I would like the output of the manipulate to feed the Graphics instead of distToMean[1]** Trying to nest a With[] to avoid repeating the long code, failed for reason I came to understand. I still don`t know how I could solve my problem


title: How can I fix my keyboard-free panning?

text: I'm trying to make a graphics display on a touchscreen device in Mathematica. This means that there will not be a keyboard available for functions such as Panning and Zooming. Because of this, I have created a scaling system to allow zooming, and a series of Events that are bound to aspects of panning. My code worked fine on a simple object, using for example a green cylinder and just moving the center of view:               EventHandler[     Dynamic[Graphics3D[{color, Cylinder[]},      ViewCenter -> {{1/2, 1/2,        1/2}, {x = CurrentPosition[[1]] + value[[1]],        y = CurrentPosition[[2]] - value[[2]]}},      RotationAction -> "Clip"],      Initialization :> (color = Green; value = {0, 0};      CurrentPosition = {1/2, 1/2})],     {{"MouseDown", 2} :> (a = CurrentValue[MousePosition];      pt = CurrentValue[ImageSize]), {"MouseDragged",      2} :> {b = CurrentValue[MousePosition], drag = b - a,      val1 = drag[[1]]/(pt[[1]]), val2 = drag[[2]]/(pt[[2]]),      value = {val1, val2}}, {"MouseUp", 2} :> {value = {0, 0},      CurrentPosition[[1]] = x, CurrentPosition[[2]] = y}}]      (As a side note, I realize that most of you will probably find my code very sloppy, but I'm just a student and coding isn't really my forte) Above, I establish the Graphic wrapped in Dynamic, and make it so that your mouse position is initialized upon a right-click, the difference between your mouse and the initial click is recorded, and this distance is scaled and changes the two-dimensional center of view. However, when I go to a much more complex manipulate function to allow for several objects that can be toggled on and off, zoom functionality and this panning system, everything works fine until the image is rotated. Following the rotation, my pan system does not work, and I was hoping that someone could tell me how to go about fixing my code. Sorry for this huge chunk of code, but here is the graphic that is not working.                   EventHandler[Dynamic[Manipulate[Show[     {If[x1, obj1, blankobj], If[x2, obj2, blankobj],       If[x3, obj3, blankobj], If[x4, obj4, blankobj],       If[x5, obj5, blankobj]},     RotationAction -> "Clip",      PlotRange -> {{scaling[[1]], -scaling[[1]]}, {scaling[[         2]], -scaling[[2]]}, {-zscaling, zscaling}}, Axes -> False,      ViewCenter -> {{1/2, 1/2,         1/2}, {x = CurrentPosition[[1]] + value[[1]],         y = CurrentPosition[[2]] - value[[2]]}}],      Style["Example Graphic", 22, Bold],     Delimiter, Style["Component Toggle", 16, Bold],     Button["Red Sphere", x1 = Not[x1]],     Button["Blue Cylinder", x2 = Not[x2]],     Button["Black Line", x3 = Not[x3]],     Button["Yellow Polygon", x4 = Not[x4]],     Button["Green Cuboid", x5 = Not[x5]],     Delimiter, Style["Zoom Options", 16, Bold],     {{scaling, {-3, -3}, "Horizontal Zoom"}, {-5, -5}, {-1, -1},      ControlType -> Slider2D},     {{zscaling, -7, "Vertical Zoom"}, -10, -4},     ControlPlacement -> Left,     Initialization :> (value = {0, 0}; CurrentPosition = {1/2, 1/2};      x1 = True; x2 = True; x3 = True; x4 = True; x5 = True;      obj1 = {Graphics3D[{Red, Sphere[{0, 0, 2}]}]};      obj2 = Graphics3D[{Blue, Cylinder[]}];      obj3 =        Graphics3D[{Black, Thick, Dashed,          Line[{{-2, 0, 2}, {2, 0, 2}, {0, 0, 4}, {-2, 0, 2}}]}];      obj4 =        Graphics3D[{Yellow,          Polygon[{{-3, -3, -2}, {-3, 3, -2}, {3,             3, -2}, {3, -3, -2}}]}];      obj5 =        Graphics3D[{Green, Opacity[.3],          Cuboid[{-2, -2, -2}, {2, 2, -1}]}];      blankobj = Plot3D[r, {x, 0, 5}, {y, 0, 5}];      )]], {{"MouseDown", 2} :> (a = CurrentValue[MousePosition];      pt = CurrentValue[ImageSize]), {"MouseDragged",      2} :> {b = CurrentValue[MousePosition], drag = b - a,      val1 = drag[[1]]/(pt[[1]]), val2 = drag[[2]]/(pt[[2]]),      value = {val1, val2}}, {"MouseUp", 2} :> {value = {0, 0},      CurrentPosition[[1]] = x, CurrentPosition[[2]] = y}}]


title: Reduce and Solve unable to solve equation

text: I have the following equation. Why aren't `Solve` and `Reduce` able to find the solution?               Reduce[2 n - Tanh[z] Tanh[2 n z] == 0, z]


title: The i-th element of a permutation

text: I am trying to run something of the form               p = Permutations[Range[1,16]];     result={};     Table[If["p[[i]] satisfies some conditions",result=Append[result,p[[i]]]],{i,1,Length[[p]]}];      and I get an "out of memory error" when defining p. I am trying to find a way around this, especially since I don't really need to store Permutations[Range[1,16]] at any given point. All I want is access the i-th element of it and run some tests (for all i). I understand this might take ages but I can afford to let the program run for months, whereas the memory of the computer I am using is restricted. Any ideas? * * * A "proper" minimal example:               p = Permutations[Range[1,16]];     result={};     Table[If[p[[i]]==Range[1,16],result=Append[result,p[[i]]]],{i,1,Length[p]}];     result      and the expected output would be {1,2,3,4,..,16}.


title: Need to create a function to generate all permutations of Range[$n$]

text: Basically I need a function that takes a list and gives all the possible permutations of it. The reason I can't use `Permutations` is that I have to apply another program that will score each permutation separately, based on certain criteria, and `Permutations[Range[14]]` gives entirely too much data. The function has to work for a list `Range[int]` up to `int = 14`, each permutation has to include all the members of the original list with no repeats, and the function has to produce all possible permutations. I will appreciate any help: I'm very stuck.


title: Extending a grid to avoid line breaks in text

text: I was wondering what the best way is to extend the cells in a `GraphicsGrid` so that my text fits without line breaks. My problem is illustrated by the graphic produced by the code below:               GraphicsGrid[{       {Graphics[{Blue, Rectangle[{1, -1}]}],         Style["Antidisestablishmentarianism", FontSize -> 30],         SpanFromLeft},       {Graphics[{Red, Rectangle[{1, -1}]}],         Style["Pneumonoultramicroscopicsilicovolcanoconiosis", FontSize -> 30],        SpanFromLeft}}]`      ![enter image description here](http://i.stack.imgur.com/nvYrv.png) I've been looking for ways to extend the cells on the right of the `GraphicsGrid` so that the text fits in on one line. In the code above, I've used `SpanFromLeft` to extend the cells a little. I would have to use many `SpanFromLeft` commands in order to fit the word next to the red square. So I was hoping that someone knew of a better way of doing this.


title: How can I differentiate Numerically?

text: Mathematica has two ways to integrate: `Integrate` and `NIntegrate`.   But what about `D`? `D` and `Derivative` are for symbolic differentiation. How can I differentiate _numerically_?


title: Local max/min of Mathematica data sets

text: Is there a way in Mathematica to find the local maxima of a set of points? Suppose you have               points={{xa,ya},{xb,yb},{xc,yc}...}          peakQ[{{x1_,y1_},{x2_,y2_},{x3_,y3_}}] := Abs[y1] > Abs[y2] && Abs[y2] < Abs[y3];     peaks=Map[#[[2]]&, Select[Partition[points,3,1],peakQ[#]&]]      Is it correct because in this way I find points but from plots I can see that I have lost some points.


title: How to store multiple plots to be viewed later

text: I need to be able to import my data and create multiple listlineplots, but my inputs for each plot are very large. I am able to assign variables to each plot and then use GraphicsGrid to view them all, but i have to copy and paste the input for each plot. I am wondering if there is a way to create the plot, store it, then create the next plot and store it along with the first, and so on. This way when i am done creating all plots I can just view them all and compare them together in a grid. I have attempted to use AppendTo, but i am unable to even store two plots, as the first plot is erased in some manner. Here is an example of how I start:                       SetDirectory["Z:\\130709"];             filename = "af.txt";         datafile = Import[filename, "CSV"];             plot = ListLinePlot[datafile]     filename2 ="ai.txt";     datafile2 = Import[filename2,"CSV"];     plot2 = ListLinePlot[datafile2]     AppendTo[plot,plot2]      So I am trying to store the plot, and then my hope is to just change the input filename and continue on to save space. Any help would be appreciated.


title: NDSolve with vectors

text: I'm stumped. I'm trying to write this using vectors, but the 2nd derivative isn't being expanded like I expected it to be. This is a system of equations for a projectile with quadratic drag and gravity (the linear drag is ignored for now). Negative Z is down, X and Y are the horizontal plane. If I write it as 9 equations, one for each coordinate, it works fine, but I'd rather use vectors since it is shorter and (to at least me) more obvious what is going on. Plus since I am new to Mathematica it would be good to learn more/better ways to use it.               gravity = 10;     withDrag[p0_, v0_, drag_] :=       NDSolve[{        p[0] == p0,        p'[0] == v0,        p''[t] == drag * Norm[p'[t]] * p'[t] + {0,0,-gravity}},       {p}, {t, 0, 5}]          withDrag[{0,0,0}, {0,10^4,10}, 0.001]      I get:               NDSolve::ndfdmc: Computed derivatives do not have dimensionality consistent with the initial conditions. >>          NDSolve[{       p[0] == {0, 0, 0},        p'[0] == {0, 10000, 10},        p''[t] == {         0.001 Norm[p'[t]] p'[t],          0.001 Norm[p'[t]] p'[t],          -10 + 0.001 Norm[p'[t]] p'[t]}},       {p}, {t,0,5}]      I formatted the output to make the error more obvious. Each of elements of the p'' vector has all three elements of p'[t]. Each one should really be p'[t][[dim]] (or something like that). Any clues as to what I'm doing wrong?


title: Generate conditions seems to not work

text: I am trying to compute the following integral               Integrate[E^(I*k*Omega*t), {t,0,T}, GenerateConditions->True]      for which Mathematica returns               ((-I)*(-1+E^(I*k*Omega*T)))/(k*Omega)      apparently not recognizing that `k` can be 0. Why `GenerateConditions` doesn't work as expected?