title: More stream lines in a ListStreamPlot

text: To provide a bit of background, I have a set of wind flow data from a two- dimensional computational fluid dynamics simulation in an urban environment. The data that are returned from the simulation are two matrices, u and v, that highlight the wind flow velocity in the horizontal and vertical directions of the plane: ![A false-color image of the u matrix: the wind flow in the horizontal direction.](http://i.stack.imgur.com/Sasco.png) ![A false-color image of the v matrix: the wind flow in the vertical direction.](http://i.stack.imgur.com/TNxo7.png) To briefly go over the above images, the first is a false-color plot of the u matrix. In this case, warm colors correspond to regions of high wind flow velocities in the horizontal direction (going from right to left) while cooler colors correspond to either regions with low wind flow velocities or those velocities going in the opposite direction. The light blue polygons in the image are the buildings, which have no horizontal wind flow velocity. The second image is a false-color plot of the v matrix. In a similar fashion as before, warm colors correspond to regions of high wind flow velocities in the vertical direction (going from top to bottom) while cooler colors correspond to either regions with low wind flow velocities or those velocities going in the opposite direction. The yellow-green polygons in the image are the buildings, which have no vertical wind flow velocity. As I have done in the past for my computational fluid dynamics plots, I combined both of these matrices into a form that could be understood by Mathemtica as a ListStreamPlot. That is, for each spatial location in my u and v matrix, I pass out an array of values: `{{{x_location,y_location},{u_value,v_value}},...}`. For this particular simulation, I only considered rows of u and v that were sandwiched between the buildings; a copy of the data contained within a Mathematica notebook can be obtained from here. When I went to go and make a ListStreamPlot,               ListStreamPlot[data, AspectRatio -> 0.5, StreamPoints -> Fine, PerformanceGoal -> "Quality", StreamColorFunction -> "Rainbow"]      however, I ended up with far fewer stream lines than I have been accustomed to seeing: ![A streamline plot of the wind flow data](http://i.stack.imgur.com/fR5Iw.png) Consequently, my question is this: how can I ensure that Mathematica includes more streamlines in the plot? (It is apparent, from the above images of u and v, that there should be more streamlines that could be generated.) Moreover, I would like to ensure that the arrows on the ListStreamPlot are included in the final visualization along with the chosen color scheme; the latter of these desires seems to be ignored in my ListStreamPlot, which leads me to believe that there might need to be some post-processing done to the data. Also, as a final note, I have already looked at the discussion here and the highest rated response from Jens has not worked in the context of my data.


title: How to assign special colors to the output of DensityPlot?

text: I have created the following function for plotting               plotDynamical[iterMethod_, points_] :=       DensityPlot[       iterAlgorithm[iterMethod], {t, xxMin, xxMax}, {s, yyMin,yyMax},        PlotRange -> {1,4}, ColorFunction -> {Orange, Blue, Black, Green},        PlotPoints -> points]      The possible results of " `iterAlgorithm[iterMethod]` " are 1 , 2, 3 or 4. I would like to assigning colours to numbers like so: Orange to 1,Blue to 2,Black to 3 and Green to 4. How can I do this? complete my Algorithm is:               F = Compile[{{t, _Real}, {s, _Real}}, {t^2 + s^2 - 4, -Exp[t] + s -           1}];     dF = Compile[{{t, _Real}, {s, _Real}}, {{2 t, 2 s}, {-E^t, 1}}];     invdF = Compile[{{t, _Real}, {s, _Real}}, {{1/(          2 E^t s + 2 t), -((2 s)/(2 E^t s + 2 t))}, {E^t/(          2 E^t s + 2 t), (2 t)/(2 E^t s + 2 t)}}];          rootF[1] = {-1.59832066552612835, 1.202235854627582} ;     rootF[2] = {0, 2} ;               rootPosition =       Compile[{{t, _Real}, {s, _Real}},        Which[Norm[{t, s} - rootF[1]] < 10.0^(-10), 3,        Norm[{t, s} - rootF[2]] < 10.0^(-10), 2, True,         1], {{rootF[_, _], _Real, _Real}}];          iterPsM10 = Compile[{{t, _Real}, {s, _Real}},       Block[{v = F[t, s], w = dF[t, s], u = invdF[t, s], x, y, z, dFz, Q,          uu, vv, Fu, vu, invdFvu},        x = {t, s};        y = x - (1/2 ) u.v;        z = 1/3 (4 y - x);        dFz = dF @@ ({z[[1]], z[[2]]});        Q = Inverse[w - 3 dFz];        uu = y + Q.v;        Fu = F @@ ({uu[[1]], uu[[2]]});        vv = uu + 2 Q.Fu;        vu = 1/2 (vv + uu);        invdFvu = invdF @@ ({vu[[1]], vu[[2]]});        uu - invdFvu.Fu]];          iterAlgorithm[iterMethod_, lim_] :=       Block[{ct, r}, ct = 0; r = rootPosition[t, s];       While[(r == 1) && (ct < lim), ++ct; {t, s} = iterMethod[t, s];         r = rootPosition[t, s]];       If[Head[r] == Which, r = 0];(*"Which" unevaluated*)Return[r]];          limIterations = 1000;     xxMin = -5; xxMax = 5; yyMin = -5; yyMax = 5;          plotDynamical[iterMethod_, points_] :=       DensityPlot[iterAlgorithm[iterMethod, limIterations],       {t, xxMin, xxMax}, {s, yyMin, yyMax}, PlotRange -> {0, 3},        ColorFunction -> {Green, Black, Orange, Blue},       PlotPoints -> points,        Epilog -> {White, PointSize[.02], Point[rootF[1]], Point[rootF[2]]}];               plotDynamical[iterPsM10, 56]


title: Some windows go off display

text: (I'm navigated from stackoverflow.com where I asked almost the same question) When I want to use additional windows, let's say for example "Basic Math Input", I feel reluctant to find visually where they are in the display. So I tend to "re-open" them by clicking "Palette" -> their name. However, when I do so, the window rearranges its position and goes up too high so that its bar (and often even some region of it that contains function panes) doesn't appear like this figure. !["Basic Math Input" windows lies left.](http://i.stack.imgur.com/bh8ll.jpg) "Basic Math Input" windows lies left. With this, I have no way to move this window. Luckily all function panes are shown so it still provides all functionality but like I said earlier some panes hide often. Tedious workaround on Mac is to arrange the displays (I'm using multiple displays) whatever. Then window's bar appears like this: ![After arranging displays' position, the bar of the window appears.](http://i.stack.imgur.com/CeWs1.jpg) Is there any easier way to resolve this? I've seen this happens to many other additional windows that are available in "Palette" section. ( **Environment** ) Mac OSX 10.7, Mathematica 8.0.4 Student Edition I've tested Ubuntu linux 11.10 with 2 displays, and it doesn't give the same issue.


title: bar and hat only apply to certain letters

text: (I'm navigated from stackoverflow.com where I asked almost the same question) I'm a beginner in `Mathematica`. Like shown in the image below, I'm trying to put hat and bar to some letters in a statement (I basically want to write vector notation) but only some letters can have them. What's wrong with how I do? ![enter image description here](http://i.stack.imgur.com/ehy3H.jpg) In the stackoverflow.com page I cited above, someone suggested functions `OverHat/OverBar`. These could do the similar work when I only want a letter in a line. But as I described, I want to write a `statement`, which consists of left-hand & right-hand sides, where those functions might not work as it seems. If you could provide online resource that covers these syntax, that would be more appreciable. Thank you. ( **Environment** ) { Mac OSX 10.7, Ubuntu 11.10, Ubuntu 10.10}, Mathematica 8.0.4 Student Edition


title: How to create Line Chart with real third coordinates?

text: I would like to generate something like 3D Line Chart in Excel. Like the following figure ![enter image description here](http://i.stack.imgur.com/MR5GG.png) but including third coordinates. **Example** I have a set of 2D data combied with 1D spatial data.               dxy = {{{0, 5.5`, 71.53`}, {0, 7.5`, 42.25`}, {0, 11.5`, 15.85`}, {0,           15.5`, 20.33`}, {0, 18.`, 43.555200000000006`}, {0,           22.833333333333332`, 24.47`}}, {{10.`, 5.5`, 48.5`}, {10.`, 7.5`,           40.44`}, {10.`, 11.5`, 14.69`}, {10.`, 15.5`, 14.65`}, {10.`,           18.`, 42.9104`}, {10.`, 22.833333333333332`, 24.16`}}, {{425.`,           5.5`, 44.46`}, {425.`, 7.5`, 83.82`}, {425.`, 11.5`,           21.88`}, {425.`, 15.5`, 71.99`}, {425.`, 18.`, 63.65`}, {425.`,           22.833333333333332`, 45.32`}}, {{650, 5.5`, 64.52`}, {650, 7.5`,           65.36`}, {650, 11.5`, 20.0512`}, {650, 15.5`, 66.8`}, {650, 18.`,           38.6984`}, {650, 22.833333333333332`, 30.3`}}, {{700, 5.5`,           105.49`}, {700, 7.5`, 118.6`}, {700, 11.5`, 17.1288`}, {700,           15.5`, 43.39`}, {700, 18.`, 29.276`}, {700, 22.833333333333332`,           23.18`}}, {{1300, 5.5`, 35.98`}, {1300, 7.5`,           59.976800000000004`}, {1300, 11.5`, 35.2768`}, {1300, 15.5`,           45.09`}, {1300, 18.`, 7.872800000000001`}, {1300,           22.833333333333332`, 7.86`}}};          ListPointPlot3D[dxy, Filling -> Bottom,       AxesLabel -> {"Distance", "Time", "Value"},       LabelStyle -> Directive[Bold]]      > ![enter image description here](http://i.stack.imgur.com/5zIeK.png) Almost does what I wanted, but I cannot connect the dots by options. If I use `Line`, I have to do the coloring manually. I plan to apply the code for more different size datasets.               ListPlot3D[dxy]      Gives an empty graph. Surprisingly, if I change the order of coordinates it works.               xyd = dxy /. {a_, b_, c_} -> {b, c, a}      > >     {{{5.5, 71.53, 0}, {7.5, 42.25, 0}, {11.5, 15.85, 0}, {15.5, >      20.33, 0}, {18., 43.5552, 0}, {22.8333, 24.47, 0}}, {{5.5, 48.5, >      10.}, {7.5, 40.44, 10.}, {11.5, 14.69, 10.}, {15.5, 14.65, >      10.}, {18., 42.9104, 10.}, {22.8333, 24.16, 10.}}, {{5.5, 44.46, >      425.}, {7.5, 83.82, 425.}, {11.5, 21.88, 425.}, {15.5, 71.99, >      425.}, {18., 63.65, 425.}, {22.8333, 45.32, 425.}}, {{5.5, 64.52, >      650}, {7.5, 65.36, 650}, {11.5, 20.0512, 650}, {15.5, 66.8, >      650}, {18., 38.6984, 650}, {22.8333, 30.3, 650}}, {{5.5, 105.49, >      700}, {7.5, 118.6, 700}, {11.5, 17.1288, 700}, {15.5, 43.39, >      700}, {18., 29.276, 700}, {22.8333, 23.18, 700}}, {{5.5, 35.98, >      1300}, {7.5, 59.9768, 1300}, {11.5, 35.2768, 1300}, {15.5, 45.09, >      1300}, {18., 7.8728, 1300}, {22.8333, 7.86, 1300}}} >                 ListPlot3D[xyd]      > ![enter image description here](http://i.stack.imgur.com/TJKpP.png) Works, but -of course - with wrong connections. `Dimensions[dxy] == Dimensions[xyd]` is obviously `True`, `Options[]` of the outputs are similar. I do not understand the difference.


title: NIntegrate: Catastrophic loss of precision

text: Below is a simplified code that I am trying to evaluate. I am basically getting the rms value of a Wakefield function. When I finally try to evaluate the rms, I get an error. Any help would be greatly appreciated.               sigmaS = 50*10^-6;          gaussian2[s_?NumericQ] := 1/(Sqrt[2 Pi] sigmaS) Exp[-(s^2/(2 sigmaS^2))]          fo2[s_?NumericQ] :=       NIntegrate[gaussian2'[sprime]/(s - sprime)^(1/3), {sprime, -Infinity, s}]          rms2 = Sqrt[       NIntegrate[         gaussian2[x] (fo2[x])^2, {x, -Infinity, Infinity}] - (NIntegrate[          gaussian2[x] fo2[x], {x, -Infinity, Infinity}])^2]


title: How would one minimize with respect to an unknown number of variables?

text: Say I had a function like the following:               f[n_] := Sum[a + Subscript[b, k], {k, 0, n}]      Such that `f[5] == 6 a + Subscript[b, 0] + Subscript[b, 1] + Subscript[b, 2] + Subscript[b, 3] + Subscript[b, 4] + Subscript[b, 5]` How would I go about minimizing `f` with respect to both a and all of the subscripted bs? How would I go about minimizing `f[5]` without manually supplying `{a, Subscript[b, 0], Subscript[b, 1], Subscript[b, 2], Subscript[b, 3], Subscript[b, 4], Subscript[b, 5]}` as the vars param? I'm asking about a specific simplified case here, but hopefully answers will be applicable in the general case and to other functions that take a vars param other than Minimize[]


title: efficient way to count the number of zeros at the (right) end of a very large number

text: If I want to count the number of zeros at the (right) end of a large number, like $12345!$, I can use something like:               Length[Last[Split[IntegerDigits[12345!]]]]      But this seems clumsy, since it's potentially doing the full work of `Split[]` to the whole list of digits when all I need is the length of the run of $0$s at the end of the list. Is there a more efficient (and particularly more Mathematica-elegant) way to do this? ( _edit_ : the answer for the example should be 3082)


title: Any way I can solve this integral?

text: So, _Mathematica_ can't solve it. Any workaround? \begin{equation*} \int_0^\pi \frac{1}{\sin\left(\frac{\theta}{2}\right)^\beta + 1} \mathrm{d}\theta \end{equation*} The code is:               Integrate[1/(Sin[θ/2]^β + 1), {θ, 0, π}]


title: Global vs local adaptive integration: lattice propagator

text: I was doing the first exercise in the paper Lattice QCD for Novices. This is the expected result: ![enter image description here](http://i.stack.imgur.com/Lo3sD.png) With the default "GlobalAdaptive" method for NIntegrate it threw errors saying that the error had increased more than 2000 times, so I switched to "LocalAdaptive". The result had some jitters, but was recognizable. ![enter image description here](http://i.stack.imgur.com/GnEwt.png) I decided to go back to "GlobalAdaptive" despite the warnings and slower time, and it actually looks really good despite the warnings. ![enter image description here](http://i.stack.imgur.com/RXlEw.png) However, the documentation says global adaptive is generally faster for multidimensional integrals. I'm looking for insight for why it is not true in this case, and in general, any settings that would give a better and faster result. I'm just getting into the options for the Monte Carlo methods. Here's the code:               stepSize = 1/2; stepCount = 8; potential[x_] := x^2/2; mass = 1;          action[x_List] :=       Sum[mass/(2 stepSize) (x[[j + 1]] - x[[j]])^2 +         stepSize potential[x[[j]]], {j, stepCount}]          ListLinePlot@      ParallelTable[       NIntegrate @@         Join[{E^-action[Join[{b}, Table[x[i], {i, stepCount - 1}], {b}]]},          Table[{x[i], -5, 5}, {i, stepCount - 1}], {Method ->            "LocalAdaptive"}], {b, 0, 2, .2}]          ListLinePlot@      ParallelTable[       Quiet[NIntegrate @@          Join[{E^-action[Join[{b}, Table[x[i], {i, stepCount - 1}], {b}]]},           Table[{x[i], -5, 5}, {i, stepCount - 1}]]], {b, 0, 2, .2}]


title: Question about Map and Total

text: Suppose I have a list and I want to generate a new list, such that $$ NewList[index] = \sum_{index \neq j}^{NumOfElts} \frac {1}{ \lvert OldList[index]-OldList[j] \rvert ^2 } $$ Can I do it using Map and Total on $OldList$? ### Edit Given `OldList = {a, b, c}`, I want `NewList` to be > >     {1/Abs[a - b]^2 + 1/Abs[a - c]^2, >      1/Abs[-a + b]^2 + 1/Abs[b - c]^2, >      1/Abs[-a + c]^2 + 1/Abs[-b + c]^2} >


title: How to open directly the help/reference window from a notebook

text: I'm used to do > ??symbol when I want the reference for a given symbol, then I click on the `>>` arrows to open the help window. Would it be possible to redefine the meaning of `??` in order to open the reference window directly ?


title: How can I iterate my code a 1000 times?

text: this is my solution to Exercise 5 of http://work.caltech.edu/homework/hw2.pdf Please help me make this more elegant. The exercise is about classifying random Points by a (randomly generated) target function to 2 classes (-1 and +1), build a new target function by linear Regression and compare where they don't classify to the same value. first I generate two Random Points to build the target function               funktionsPunkte = RandomReal[{-1, 1}, {2, 2}]      then generate the target function from it (to classify the data points)               targetFct[{x1_, x2_}] :=      With[{targetFunction = LinearModelFit[funktionsPunkte, {1, t}, t]},      x2 - targetFunction[x1]];      then I generate 100 data Points and classify them to either +1 or -1 ,depending if they are above or below the target function               data = With[{points = RandomReal[{-1, 1}, {100, 2}]},      Map[{Prepend[#, 1], If[targetFct[#] < 0, -1, 1]} &, points]];      one data Point is of the form {{1,x1,x2},y} where y is either +1 or -1. now Comes the ugly part. I Need the weight vector w = PseudoInverse[{1,x1,x2}].y               w = (PseudoInverse[#[[1]] & /@ data]).(#[[2]] & /@ data)      only {1,x1,x2} :               xlist = (#[[1]] &) /@ data;      the sign of each element w.x (-1 or 1 depending on which class we classify it)                sig = Sign /@ (w.# &) /@ xlist ;      only the y of our data Points               datasig = #[[2]] & /@ data;      now we Count the "misclassified" elements               Length[Select[      Table[sig[[i]] != datasig[[i]], {i, 100}], # == True &]]      now I Need to repeat this Experiment a 1000 times and take the mean. But how do I do that. I'm coming from an imperative Point of view and this would be trivial there. I'm also welcoming more elegant Solutions that more use functional and mathematica specific elements. edit: thanks to the comments, I made this               f := Module[{}, funktionsPunkte = RandomReal[{-1, 1}, {2, 2}];      targetFct[{x1_, x2_}] :=       With[{targetFunction = LinearModelFit[funktionsPunkte, {1, t}, t]},      x2 - targetFunction[x1]];      data = With[{points = RandomReal[{-1, 1}, {100, 2}]},       Map[{Prepend[#, 1], If[targetFct[#] < 0, -1, 1]} &, points]];      w = (PseudoInverse[#[[1]] & /@ data]).(#[[2]] & /@ data);      xlist = (#[[1]] &) /@ data;      sig = Sign /@ (w.# &) /@ xlist;      datasig = #[[2]] & /@ data;      Length[Select[      Table[sig[[i]] != datasig[[i]], {i, 100}], # == True &]]]      and then               f & /@ Range[1000]      it's awfully slow but it works (have not implemented the other suggestions yet)


title: Backslash commands in strings?

text: I discovered by playing around that               Text[DisplayForm@SubscriptBox["\[Lambda]", "k"]]      produces the same result as               Text["\*SubscriptBox[\"\[Lambda]\", \"k\"]"]      and, further, that the `\\*` is essential. This finding suggests that `\\*` means `DisplayForm` when inside a string. After more playing around, I found that               Text["\!\(\*SubscriptBox[\"\[Lambda]\", \"k\"]\)"]      produces the same result, but only if you have the bang _and_ the parens, that is, that `\\!` and `\\(`+`\\)` are _both_ necessary; either construct alone will not work. Where can I find the documentation for this magic? I don't know what to search for because I don't know what these kinds of constructs are called.


title: How would you efficiently implement BinListsBy?

text: Let's say I have a list like this:               data = {{21, "Alice"}, {27, "Bob"}, {22, "Charles"}, {34, "Dora"}, {75, "Eliza"}}      containing ages and names of persons. What I would like is a list of e.g. 10-year age brackets, containing a list of _{age,name}_ -pairs:               {       {{21, "Alice"}, {27, "Bob"}, {22, "Charles"}}, (* 20-30 years *)       {{34, "Dora"}}, (* 30-40 years *)       {}, (* 40-50 years *)       {}, (* 50-60 years *)       {}, (* 60-70 years *)       {{75, "Eliza"}} (* 70-80 years *)     }      `GatherBy[data, Floor[First[#]/10]&]` is close, but it leaves out empty bins. `BinLists[data[[All, 1]], 10]` is also similar, but it only returns the list of ages, I can't get it to include the names as well. Ideally, I'd like to have a function with similar syntax and performance to `BinLists`, i.e.: `binListsBy[data, {10,70,10}, First]`. And the function should be fast, because I'm going to use it on millions of entries (pixels of an image, in fact). (Following Mr.Wizard's meta discussion, I'm not going to add "what have I tried" in my question - I'm really looking for better ideas, or maybe even a built-in function I haven't noticed. Instead I'll post my attempts as an answer.)


title: How to create breathing wall effect?

text: I would like to recreate the effect of the one in this video: Breathing walls ![enter image description here](http://i.stack.imgur.com/8Pgul.gif) This is my first time manipulating images, and because of that, I don't even have a clue where to start. But I think the way to do this must be transforming the geometry of the image with sine waves, correct me if I'm wrong.


title: Combining key pivoting and lookup operators in Dataset

text: This question is related to this one re pivoting on keys. Because of the nesting, using Leonid's method as starting point - single key:               pivotUp[key_] := Query[GroupBy[Key@key], KeyDrop[key]]      How to extend the operation iteratively - but partially - to create hierarhical Datasets from tabular data. Interesting cases include duplicate values, which are pivoted to duplicate keys. Consider:               pivotUp[keys_List] :=       Sequence @@ (Flatten@{GroupBy[Key@#] & /@ keys, KeyDrop@keys})      Given:               data = AssociationThread[{"key1", "key2", "key3"} -> #] & /@  {{1,           "a", 10}, {1, "b", 20}, {2, "c", 30}} // Dataset      ![enter image description here](http://i.stack.imgur.com/aoo6T.png) One way to use pivotUp is this:                 data[pivotUp[Key@"key1"]][All, pivotUp[Key@"key2"]]       This is more compact:               data[pivotUp[{"key1", "key2"}]]                 <|1 -> <|"a" -> {<|"key3" -> 10|>}, "b" -> {<|"key3" -> 20|>}|>,           2 -> <|"c" -> {<|"key3" -> 30|>}|>|> (* normal form *)      But how can "key3" be accessed, either with given pivotUp or alternatives? These don't work:               data[pivotUp[{"key1", "key2"}], "key3"]      ![enter image description here](http://i.stack.imgur.com/DqFVg.png) The desired output is:               data[pivotUp[{"key1", "key2"}]][All, All, All, "key3"] // Normal          <|1 -> <|"a" -> {10}, "b" -> {20}|>, 2 -> <|"c" -> {30}|>|>      Ideally, these partial pivots should handle {__Association} structures.


title: Nested Sums to multiple sum

text: I would like to automatically "move nested sums to the left". I mean, just take out of an expression all the summations and go from a nested Sum to a multiple sum. Something like starting with:               Sum[f[y] Sum[g[x],x],y]      And changing it into:               Sum[ f[y] g[x],y,x]      But I can't think of a way to do it. Thanks!


title: Smarter way of manipulating plot style?

text: Say, I have a colorlist               listColor={Black,Brown,Red,Cyan}      Now, I have some Plot function that I can use this list:               Plot[{Sin[x],Cos[x],x,x^2},{x,1,100},PlotStyle->listColor]      Everything went fine. Now, I wanted to make the plot style "thick" But when I add:               Plot[{Sin[x],Cos[x],x,x^2},{x,1,100},PlotStyle->{Thick,listColor}]      The listColor breaks down. I understand I actually need               listColor={{Thick, Black},{Thick, Brown},{Thick, Red},{Thick, Cyan}}      But adding {Thick} to each entry of listColor is too hard. Is there anyway that I can append {Thick, } to each entry of the list elegantly? I notice that using               Transpose[{Table[Thick,{i,1,4}],listColor}]      might work but it looks unnecessary...


title: Am I entering this 2-variable recurrence correctly?

text: I'm trying to solve this recurrence with two variables.               RSolve[g[d, n] == 1 + g[d - 1, n] + g[d - 1, n - 1] &&        g[d, 0] == g[0, n] == 0, g[d, n], {d, n}]      My boundary conditions are that `g[d, 0] == g[0, n] == 0` for all `d,n` . But when I plug this in, I get the same input back with no error message. Am I inputting the recurrence incorrectly? Or is _Mathematica_ simply unable to find a closed form?


title: How to transpose x and y axes on a LogPlot?

text: Consider the following simple LogPlot:               LogPlot[Exp[x],{x,0,5}]      ![LogPlot of Exp\[x\]](http://i.stack.imgur.com/Rn3Er.png) Is there a nice way to switch the axes of a LogPlot? I'm aware that plotting the inverse function as follows               LogLinearPlot[Log[y],{y,Exp[0],Exp[5]}]      will do the job. The actual function I'm using is more complicated so I want to avoid using the inverse if possible. I've tried the various methods here How can I transpose x and y axis on a Plot? but they would seem to require some modification in order to work.


title: Different colors when comparing Plot3D V9 and V10

text: I am trying to create Plot3D with same color as we used to get in V9 but without success. I used `PlotTheme -> "Classic"` in V10 but the results looks like somehow not the same as V9. I have also copied the FullForm between V9 and V10 and again the plots are different. does anyone know the reason behind this? V9: ![enter image description here](http://i.stack.imgur.com/F4qSe.jpg) V10: ![enter image description here](http://i.stack.imgur.com/QG3LQ.jpg)


title: Problem about Solve

text: See this example :               Solve[x^2 == (a - b)^2, x]   (* {{x -> a - b}, {x -> -a + b}} *)          Solve[x^2 == 4 (a - b)^2, x]      (*{{x -> -2 Sqrt[a^2 - 2 a b + b^2]}, {x -> 2 Sqrt[a^2 - 2 a b + b^2]}}*)          Reduce[x^2 == 4 (a - b)^2, x]     (*x == 2 a - 2 b || x == -2 a + 2 b*)      More complicated,               Solve[{(x - x1)^2 + (y - y1)^2 == (x1 - x2)^2 + (y1 - y2)^2,       (x - x2)^2 + (y - y2)^2 == (x1 - x2)^2 + (y1 - y2)^2}, {x,  y}] // FullSimplify      gives $\left\{\left\{x\to \frac{1}{2} \left(\text{x1}+\text{x2}-\sqrt{3} \sqrt{(\text{y1}-\text{y2})^2}\right),y\to \frac{\sqrt{3} (\text{x1}-\text{x2}) \sqrt{(\text{y1}-\text{y2})^2}+\text{y1}^2-\text{y2}^2}{2 (\text{y1}-\text{y2})}\right\},\left\{x\to \frac{1}{2} \left(\text{x1}+\text{x2}+\sqrt{3} \sqrt{(\text{y1}-\text{y2})^2}\right),y\to \frac{\sqrt{3} (\text{x2}-\text{x1}) \sqrt{(\text{y1}-\text{y2})^2}+\text{y1}^2-\text{y2}^2}{2 (\text{y1}-\text{y2})}\right\}\right\}$ but I excepted result is $\left\{\left\{x\to \frac{\text{x1}}{2}+\frac{\text{x2}}{2}-\frac{\sqrt{3} \text{y1}}{2}+\frac{\sqrt{3} \text{y2}}{2},y\to \frac{\sqrt{3} \text{x1}}{2}-\frac{\sqrt{3} \text{x2}}{2}+\frac{\text{y1}}{2}+\frac{\text{y2}}{2}\right\},\left\{x\to \frac{\text{x1}}{2}+\frac{\text{x2}}{2}+\frac{\sqrt{3} \text{y1}}{2}-\frac{\sqrt{3} \text{y2}}{2},y\to -\frac{\sqrt{3} \text{x1}}{2}+\frac{\sqrt{3} \text{x2}}{2}+\frac{\text{y1}}{2}+\frac{\text{y2}}{2}\right\}\right\}$ both `Reduce` and `FullSimplify` can't gives a better result, How can I get the result as I want?


title: How to change the LabelStyle only for one axis?

text: I want to modify the style of just one axis, but I'm stuck with something like               Plot[x^2, {x, 0, 3}, LabelStyle -> Red]      which of course modifies both axes. How do I solve this problem?


title: plot probability

text: Hi I just want to flatten a function, I tied it with Joined->True, but it did not work, hope somebody of you can help me. This is my code:               Remove["Global`*"]     m = 30; (*number of banks*)     n = 5;(*number of defaults*)     AssetV = 100;(*asset value at T*)     DebtV = 80;(*debt value at T*)     μ = 0.2;(*annual drift*)     σ = 0.3;(*annual volatility*)     T = 5;(*years*)     ρ = 0.8;      Since I want to use a BinomialDistribution I calculated the individual probabilities through:               P = (CDF[NormalDistribution[], -(Log[             AssetV/DebtV] + (μ - 0.5*σ^2)*T)/(σ*Sqrt[           T])])      In the following I generated a table where I wanted to see the probabilities where k=n1, varies from 0 to 30 since n=30, and this is given by:               data1 = Table[       Probability[x >= n1,         x \[Distributed] BinomialDistribution[30, P]], {n1, 0, 30, 1}]      In order to plot the probabilities I entered:               Plot[Probability[x >= n1,        x \[Distributed] BinomialDistribution[30, P]], {n1, 0, 30},       PlotRange -> All, AxesLabel -> {"# of Defaults", "PD"},       Filling -> Axis]      and now I just want to flatten this function. I tried it with Joined-True, which did not work out. I want also to show the density by:               DiscretePlot[PDF[BinomialDistribution[30, P], n1], {n1, 0, 30},       PlotRange -> All, AxesLabel -> {"# of Defaults", "PD"},       Joined -> True]      However, is there the possibility to implement data1=Table[...] into the two functions, would it be then possible to generate the plot by the ListLinePlot function? thank you for your help.


title: Problem with plotting legends using the PlotLegends package

text: Here is my problem : I have a table composed of 3 "under"-Lists and I'd like to plot it with legends, but I can't find a way to do it.               DistSpat20084D = {        {7, 7, 44, 79, 121, 148, 152, 158, 153, 165, 182, 160, 163, 164, 169, 177, 198, 190, 177,         173, 159, 155, 147, 126, 142, 127, 129, 117, 13},         {7, 2, 10, 36, 53, 93, 108, 116, 134, 117, 115, 123, 84, 123, 127, 126, 153, 119, 147, 50,         43, 27, 23, 26, 21, 22, 28, 16, 18, 12,, 4, 5, 4, 3, 4, 1, 3, 0, 2, 4, 3, 4, 2, 5, 4,  0},         {7, 1, 6, 12, 3, 3, 2, 5, 4, 1, 3, 2, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0}};       My command to plot and add legends :               ListLinePlot[Table[{km/10, DistSpat20084D[[j, km]]}, {j, 3},        {km, Length[DistSpat20084D[[j]]]}],PlotLegend ->        {{"Speed1", "Speed2", "Speed3"}}, AxesOrigin -> {0, 0}]


title: ToBoxes Respect Spaces Code

text: Is there a way to force either `ToBoxes` or `MakeBoxes` to respect the spacing that occurs in the code? For example is there a way to force the following to print the code like so.               CellPrint@Cell[       BoxData@MakeBoxes[         f[          y          ]         ], "Input"]      would output               f[      y     ]


title: Combinatorica: Girth[] and FindCycle[] disagreement

text: Warning: run the following code in a fresh Mma session, as some symbols could be shadowed (depending on your Mma version) While trying to answer this question, I fell into the following:                (* Let's load a large Directed Graph and convert it to Combinatorica *)     g = Graph@Union@Flatten[          Thread[DirectedEdge @@ ##] & /@ Select[{#, IsotopeData[#, "DaughterNuclides"]} & /@              IsotopeData[], #[[2]] != {} &]];     Needs["GraphUtilities`"]     << Combinatorica`     cg = ToCombinatoricaGraph[g];      > Girth[cg] gives the length of a shortest cycle in a simple graph g. So, let's check if `cg` is Simple and calculate its Girth:               {SimpleQ@cg, Girth@cg}     (*     -> {True, 3}     *)      So there is at least one Cycle in `cg` of length 3. But look what happens when we try to find it by the two available methods in `Combinatorica`:               {ExtractCycles@cg, FindCycle@cg}     (*     -> {{},{}}     *)      So, two questions:   1. Is this a bug?   2. What is the easiest way to find all cycles in `g` without using Combinatorica? **Edit** BTW, the (now) standard Graph functionality also detects cycles:               AcyclicGraphQ[g]     (* -> False *)


title: How to Manipulate a ListLinePlot[Transpose[{T,B}]] if T is a Table and B is a list of minima built by using FindMinimum?

text: I need to Manipulate a ListLinePlot using a parameter P. The problem is that this Curve is a ListLinePlot of a Transpose[{T,B}], in which T is a normal table and B is a list of minima got using FindMinimum in f[x]. This is a simplified code that contains my concern:               f[x_] := (b/a)*x^2 + (x^2/b)     Quiet[Xmin = Table[        FindMinimum[{f[x], a >= 1, b >= 1}, {a, b}], {x, 250, 310, 20}]];          T = Table[T, {T, 250, 310, 20}];     B = b /. Take[Xmin, All, {2}] // Flatten;     Transpose[{T, B}];          ListLinePlot[Transpose[{T, B}]]      I'm able to plot this ListLinePlot as it is presented in the code but the idea is to insert a parameter P, multiplying the constant "a", inside of f[x] (P varies from 1 - 50). When I just put this ListLinePlot correctly inside the Manipulate expression, setting P as a changeable parameter and also insert the parameter P, multiplying the constant "a", the routine is not able to output B and I get a list of errors. I really need B, so, is there any way to Manipulate it? The Manipulate code that is not working is this:               Manipulate[ListLinePlot[Transpose[{T, B}]], {P, 1, 50}]      But with this Manipulate code above is evaluated only if I change "a" for "a*P" in the f[x]. Thanks a lot!


title: How to guarantee that NDSolve correctly detects abrupt changes in parameters?

text: When using `NDSolve`, I often have parameters that, in most of their domain, have a constant or null variation, but that suffer from abrupt variations on a very small interval. Mathematica variable step algorithm is unable to detect these singularities. On the following example, it misses the 15.0 to 15.1 abrupt rise:               variation[x_?NumericQ] := Which[       x < 10, 1,       x < 15, 0,       x < 15.1, 10,       x < 20, 0,       x < 30, 1,       True, 0]     points = {};     ans = accumulation /.         Flatten[NDSolve[{accumulation'[x] == variation[x],            accumulation[0] == 0}, accumulation, {x, 0, 40},             StepMonitor :> AppendTo[points, {x, accumulation[x]}]]];      ![plot of wrong integral](http://i.stack.imgur.com/Z71QK.jpg) What I do to guarantee a correct integration, is to define a `MaxStepSize`. In the following example `MaxStepSize -> 0.01`: ![plow with decreased MaxStepSize](http://i.stack.imgur.com/xzxdZ.jpg) But as you can see, this can cost me a lot of computation time. Since I know where exactly are the abrupt variations of my parameters, is there another way to guarantee the correct integration, without raising so high the number of steps? Something like listing to Mathematica points in the integration domain that have to be "seen"?


title: Custom Mathematica Shortcut: Copy as $\LaTeX$

text: If you edit the > `Wolfram > Research\Mathematica\8.0\SystemFiles\FrontEnd\TextResources\Windows\MenuSetup.tr` file you can make Ctrl+Shift+C copy not plain but in $\LaTeX$ format. Very useful. Look for the line in the file that says "&LaTeX" and the one that says "Plain &Text". The & sign gives the underscore letter in the menu. Then replace them with the following:               MenuItem["Plain &Text", FrontEnd`CopySpecial["PlainText"]],              MenuItem["&LaTeX", KernelExecute[ToExpression["FrontEnd`CopyAsTeX[]"]],              MenuKey["C", Modifiers->{"Control", "Shift"}],              MenuEvaluator -> Automatic],      Restart Mathematica and you are done. The question I have is if anyone knows what `MenuEvaluator` does, or if you know how to do this modification from a notebook in Mathematica rather than modifying the config file.


title: Z-Transforms and Floor Functions

text: When I take the $Z$-Transform of the `Floor` function:               ZTransform[ Floor[x], x, z]      I get > >     z/(-1 + z)^2 >   But when I do:               InverseZTransform[ z/(-1 + z)^2, z, x]      > >     x >   ... rather than `Floor[x]`... Is this an error in _Mathematica_ or is my understanding wrong? Is there a way to take the discrete-time $Z$-transform on a list, say: `{ 1, 2, 3, 4, 5, 6, 7, 8, 9}`... and then the inverse $Z$-transform?


title: Defining an anonymous function using another function but with fewer arguments

text: In MATLAB you can use an anonymous function with another function to define a new function with fewer arguments as long you define the excluded argument before, e.g.               z=1          f1=@(x,y) f(x,y,z)          x=2          y=3          f1(x,y)      Can you do that in Mathematica?


title: NSolve stalls when given an equation containing Log

text: Why does `NSolve` not work for this type of equation?               2.01224 == (0.954875 - 0.0084496 a) Log[         9 (0.954875 - 0.0084496 a)] + (0.0113946 - 0.00295146 a) Log[         9/4 (0.0113946 - 0.00295146 a)]      Here is my full script, where I solve got `a`, it just hangs there:               NSolve[2.01224 == (0.954875 - 0.0084496 a) Log[         9 (0.954875 - 0.0084496 a)] + (0.0113946 - 0.00295146 a) Log[         9/4 (0.0113946 - 0.00295146 a), ], a]


title: Fastest square number test

text: What is the fastest possible square number test in _Mathematica_ 7, both for machine size and big integers? I presume in version 8 the fastest will be a dedicated C LibraryLink function.


title: Can a Trie be implemented efficiently?

text: What is the most space and time efficient way to implement a Trie in _Mathematica_? Will it be practically faster than what is natively available in appropriate cases?


title: Understanding of method for NDSolve

text: I used automatic method for NDSolve. Then I asked myself - which method Mathemathica prefered? I got an answer for this question on this forum, that I need to use:               Select[Flatten[       Trace[NDSolve[{g[a[t]]*a''[t] + 0.5*dg[a[t]]*(a'[t])^2 + dV[a[t]] ==            0, a[0] == a0, a'[0] == -u}, a, {t, 0, t0}],         TraceInternal -> True]], ! FreeQ[#, Method | NDSolve`MethodData] &]      I got a long answer from Mathematica, from which I show you only two main unique strings:               NDSolve`InitializeMethod[NDSolve'LSODA,{Automatic, Automatic} ...     NDSolve`LSODA[NDSolve`MethodData[4, 22, {{}, False, 12, {NDSolve`Newton,{Automatic}}, None, False}]]      I understood, that Mathematica has chosen for method: LSODA and it's submethod: Newton. Whether I'm correct or this methods have another name? And what does LSODA stand for?


title: Mathematica 9 cannot solve a difference equation that Mathematica 8 can

text: Consider               RSolve[{a[n + 1] == 2 a[n] + n (1 + 2^n), a[1] == 1}, a[n], n]      _Mathematica_ 8 can solve this quickly, but _Mathematica_ 9, even after being allowed to run for a long time, cannot giva a result.


title: Background image in a polygon / CountryData

text: Is it possible to use a background image in a polygon without rasterizing the polygon? I tried with textures, but they seem to be viable only for simple polygons. I want to put a flag as the background of the polygon that represents a country shape. I can do this for one country by rasterizing the polygon:               ImageAdd[         Graphics[CountryData["Monaco", "Polygon"]],          CountryData["Monaco", "Flag"]     ]      ![monaco](http://i.stack.imgur.com/gQrkk.png) But by rasterizing the polygon, I make it difficult to apply this procedure to several neigboring countries and assemble them together. I would like to put each country flag in the background of, for example:               Graphics[         {EdgeForm[White],           CountryData[#, "Polygon"] & /@ {"Venezuela", "Colombia"}}]        ![colombia and venezuela](http://i.stack.imgur.com/6tCtL.png) * * * ## Solution After seeing cormullion answer, I was able to do what I wanted:               Graphics[      {EdgeForm[Black],       {{Texture[ImageReflect[CountryData[#, "Flag"], Top -> Right]],          CountryData[#, "Polygon"] /.            {Polygon[a_] :> Polygon[First[a], VertexTextureCoordinates ->             Transpose[Rescale /@ Transpose[First[CountryData[#, "Coordinates"]]]]]}} & /@      CountryData["SouthAmerica"]}}]      ![southamerica](http://i.stack.imgur.com/T2jnb.png) The key part is the use of Rescale[]. Thank you!


title: Mobius transformations revealed

text: Mobius Transformations Revealed is a short video that vividly illustrates the simplicity of Mobius transformations when viewed as rigid motions of the Riemann sphere. It was one of the winners in the 2007 Science and Engineering Visualization Challenge and the various YouTube versions have been viewed some 2,000,000 times. In the still image below, the colored portion corresponds to a simple square in the plane. The colored portion on the sphere is the image of the square in the plane under (inverse) stereographic projection; the sphere is then rotated into the position shown and finally projected back to the plane. The colored portion on the plane is the image of the original square under a Mobius transformation. ![enter image description here](http://i.stack.imgur.com/WzDfq.jpg) How can we implement this in Mathematica? Is it possible to create a dynamic version with `Manipulate` that allows us to interact with the image? Can we recreate a portion of the movie? Obviously, we can't create images of the quality of the original (which was produced with POV-Ray) but how close can we get? Can we generate color or should we stick with simple graphics primitives?


title: Pick bug: level 0 matching

text: A previous discussion of this issue (Is there a bug in Pick?) accepted that matching at level 0 is not a bug in `Pick`. Was that correct? I am not yet persuaded. Here is the documentation (http://reference.wolfram.com/language/ref/Pick.html): "`Pick[list,sel,patt]` picks out those elements of `list` for which the corresponding element of `sel` matches `patt`." This clearly speaks of _corresponding_ elements. It seems to me that either there is a documentation bug or there is an implementation bug. Why am I wrong? Furthermore, the documentation gives the obvious statement of intent, so I suspect an implementation bug. Here is (yet) another example that illustrates how bizarrely unexpected is the current behavior:               x = Range[20]     Pick[x, x/2, _Integer]  (* works as expected *)     Pick[x, x/2, Except[_Integer]]  (* does not work as expected *)      I find it almost impossible to believe that `Pick` was intended to cause this simple use of `Except` to fail by matching the entire list `x/2` rather than, as the documentation states, checking for a match in the _corresponding element_. Note that I am not asking how to get the intended match; I realize that `Except[_Integer|_List]` will accomplish that in this case. Also, I am using Mma 9.


title: Fast Trial Division

text: I'm going to write a custom Trial Division primality test. I know that `PrimeQ` will first try trial division and then switches to `PowerMod`.               TrialFactorFreeQ[N_, Max_] :=      (For[j = 1, j < Max && Divisible[N, Prime[j]] == False, j++];       Return[j == Max])      For example for testing a 300K digits number with first 100,000 primes, it took 4 seconds which is very slow since a real testing is applied for billions of primes.               In[179]:= Timing[TrialFactorFreeQ[3^1000000 + 2, 100000]]          Out[179]= {4.031, True}      Can it be optimized? * * * I wrote the parallel version and its timing seems good but when I wrap it in a function, the timing goes to sky:               p = 3^1000000 + 2;     max = Prime[100000];          In[85]:= ParallelTrialFactorFreeQ[Num_, Maxi_] := (IsFree = True;        ParallelDo[         If[Divisible[Num, i], IsFree = False; Break[]], {i,           Prime[Range[1, PrimePi[Maxi]]]}] If[! IsFree, AbortKernels[]];        Return[IsFree])          In[82]:= AbsoluteTiming[ParallelTrialFactorFreeQ[p, max]]          Out[82]= {18.2821829, True}          In[84]:= Timing[Num = p; Maxi = max;          IsFree = True;           ParallelDo[            If[Divisible[Num, i], IsFree = False; Break[]],             {i,Prime[Range[1, PrimePi[Maxi]]]}];            If[! IsFree, AbortKernels[]]; IsFree]          Out[84]= {0.609, True}      * * * **Updated** Based on the Daniel Lichtblau answer to my Fast Sieve Implementation question, I wrote a very fast Trial Division function which can be used for numbers that are larger than products of primes in the given range:               prod = Product[i, {i, Prime[Range[10^5]]}];          TrialFactorFreeQ2[n_] := GCD[n, prod] == 1      And a **10x** speedup               n = 3^1000000 + 2;          Timing[TrialFactorFreeQ2[n]]      > {0.375, True}


title: Manipulating a catenary in Mathematica

text: I have a catenary curve in Mathematica, and I wanted to add a variator (dimmer) with `Manipulate`, so that the user can modify the value of the x/y-coordinate of the hanging-points `A`, `B` and the point `C` on the curve. With my current code, I can just modify these values with the locator, but I can't see the current value and cannot set one directly. Is there a solution, so that I delete the rest of the curve, the part above the hanging-points `A` and `B`? Here is my code till now:               catenary[x_] := a*Cosh[(x - c)/a] + y          m = Manipulate[Module[{root},          (root = FindRoot[catenary[#[[1]]] == #[[2]] & /@ pt, {{y, 0}, {c, 0}, {a, 1}}];          Show[             Plot[catenary[x] /. root, {x, -2, 2}, PlotRange -> {-3, 3}, AspectRatio -> 3/2],              Graphics[{Red, Point[pt]}]])         ],          {{pt, {{-1, 1}, {1, 1}, {0, 0}}}, Locator}     ]


title: How To Track the Cursor Position?

text: I have 2 `InputFields` and 2 `Buttons`. I would like that when the user clicks the Pi `Button` or -Pi `Button`, that value will be assigned to that `InputField` only where the cursor was (either the first input field or the second).               Button["Range", (DialogInput[{range1 = 0, range2 = 0},      Column[{"Enter the Range",       Panel[Column[{InputField[Dynamic[range1], Number],          InputField[Dynamic[range2], Number],          Button["-Pi", (range2 = -3.14159;)],          Button["Pi", (range1 = 3.14159;)]}]]}]]), Method -> "Queued"]      ![Mathematica graphics](http://i.stack.imgur.com/ofOzG.png)


title: Mathematica package manager

text: I want to bundle up a Mathematica package that I've written and distribute it as open source. It has a couple of dependencies that I'd like to automatically download independently from my package as well. Is there any sort of established Mathematica package manager and package distribution site? (I'm thinking along the lines of pip for Python, gem for Ruby, nuget for .NET, hackage for Haskell, that sort of thing.) I've seen Wolfram MathSource, and as near as I can tell its aim seems to be to collect various contributed packages from around the web into a central place, but it doesn't feel very active (maybe I'm wrong?).


title: Tick marks on curves

text: I would like to put tick marks on a curve. In this trivial example I have managed to put some ticks.               ClearAll[fx, fy];     fx[t_] := 20 t - 0.1 t^2;     fy[t_] := 70 t - 5 t^2;     ParametricPlot[{fx[t], fy[t]}, {t, 0, 15}, AspectRatio -> Automatic,      Frame -> True, Axes -> False,      Epilog -> {Table[     Line[{{fx[t], fy[t]} + 3 #/Sqrt[#.#] &[{-fy'[t],          fx'[t]}], {fx[t], fy[t]} - 3 #/Sqrt[#.#] &[{-fy'[t],          fx'[t]}]}], {t, 0, 15, 0.5}]}]      ![Mathematica graphics](http://i.stack.imgur.com/I0Kcb.png) I began to write a module but then wondered if it had been done properly before but looked and could not find. My idea of a module is that it should enable the Epilog statement to look something like               Epilog -> {curveTicks[{fx, fy}, {t, tmin, tmax, tinc}]}      (Do I have to input the curve again?) My suggestion for a specification is as follows: The process will involve taking the derivative to get the tangent and then turning through 90 degrees. This could be done by taking the derivative of the function (as I have begun to do) or by using the lines that make up the curve. Alternatively, there may be a method using Mesh. Taking the derivative for each tick mark seems expensive (above is a trivial example). The length of the tick mark should be default or input. The tick line should stick out equally on both sides of the curve. If the aspect ratio of the plot is not automatic the line should be rotated so that it is still perpendicular to the curve. There should be a method of labeling some tick marks. Has this been done already somewhere? Thanks.


title: Internal Representation of ?name and ??name

text: ## Code               FullForm[Hold[?name]]          Syntax::bktmcp: Expression "Hold[?name]]" has no closing "]".          Syntax::sntxi: Incomplete expression; more input is needed .      ## Question This is exercise 3.2 (page 47) of Power Programming w/ Mathematica The task is: "determine the internal representation of the expressions ?name and ??name" The above is what I tried. It failed. How do I win?


title: Support for Multidimensional Scaling (MDS)?

text: Does mathematica support MDS? Or, are there any libraries that support it? Basically, I have points and a distance function defined between them, and I want to plot them in 2D space, trying to minimize the error (stress) in the distance. This is what MDS does. R has support for MDS, but I can't find similar methods in Mathematica, which I think is strange because this seems like a really common thing to want to do...


title: Code Readability and Object-Oriented Code

text: The basic problem I have been running into is making readable code, where in other languages I am more familiar with I might have been using class or struct like objects. For example, you can imagine I might want to create a circle object, which would, at the very least, store the radius and position of the circle. In an object-oriented language, I might access the $x$-coordinate of the center of the circle using something like `circ.pos.x`. In Mathematica, however, I find myself using nothing more than nested lists, and as a result, wind up with code looking something like `circ[[2]][[1]]` (`circ[[1]]` is the radius and `circ[[2]]` is the position vector, say). You can imagine how code like this could become very unreadable very fast. Presumably, this is because I'm not 'doing it right'. So, then, what is the 'right' way to implement something like this? Does Mathematica support built- in object-oriented features I'm not aware of?


title: Counting number of inversions

text: Is there an inbuilt method to find the number of inversions in a set of numbers? I found `Inversions` in `Combinatorica` but when I tried to use it as `Inversions[{1,4,2,5,2,3,2}]` it doesn't return a number as a result. How are you supposed to use the function?


title: Question about VertexTextureCoordinates

text: Background: consider the following snippet:                gp := Graphics      bill = Import["http://i.stack.imgur.com/FyojA.jpg"];      poly1 = {{1, 0}, {.5, .86}, {-.5, .86}, {-1, 0}, {-.5, -.86}, {.5, -.86}};      g1 = {Texture[bill], Polygon[poly1, VertexTextureCoordinates -> poly1]};      poly2 = {{0, 0}, {1, 0}, {1, 1}, {0, 1}};      g2 = {Texture[bill], Polygon[poly2, VertexTextureCoordinates -> poly2]};      g1 // gp      g2 // gp      ![example of output](http://i.stack.imgur.com/hywwS.jpg) The option `VertexTextureCoordinates` isn't entirely clear to me. I want to put an image with the correct ratios in the hexagon left. So for example on {{-.5,-.5},{.5,-.5},{.5,5},{-.5,.5}}. (I have not been able to get this to work although I have tried all sort of possibilities) However with the restriction that if I rescale the (coordinates of the) hexagon the image should be scaled accordingly. EDIT-1: ![enter image description here](http://i.stack.imgur.com/FyojA.jpg) Image as requested. EDIT-2: This nicely sums up and demonstrates the answer by Heike:                rescale1[poly_, p1_, p2_] :=        Transpose[{Rescale[poly[[All, 1]], {p1[[1]], p2[[1]]}, {0, 1}],          Rescale[poly[[All, 2]], {p1[[2]], p2[[2]]}, {0, 1}]}]      Manipulate[       g = {Texture[bill],           Polygon[poly,            VertexTextureCoordinates -> rescale1[poly, leftbot, righttop]]} //          Graphics,       {leftbot, {0, 0}, {1, 1}}, {righttop, {0, 0}, {1, 1}},        Initialization :> {righttop = {1, 1}}, ControlPlacement -> Bottom]      Key is the mapping between the image and vertextexture coordinates.


title: Delete Missing data from coordinate sets

text: I have a list of pairs of coordinates, where some are missing.               coordinates = {       {{1, 1}, {1, 2}},       {{3, 4}, {5, 5}},       {{1, 2}, Missing[]},       {{9, 8}, {7, 7}},       {Missing[], {2, 3}}     }      I am trying to remove the pairs containing missing coordinates, to get               coordinates = {       {{1, 1}, {1, 2}},       {{3, 4}, {5, 5}},       {{9, 8}, {7, 7}},     }      I tried               coordinates = DeleteCases[coordinates, MemberQ[#, _Missing] &]      but that did not work. But the function `MemberQ` works on pairs directly:               MemberQ[coordinates[[1]], _Missing] (* returns False *)     MemberQ[coordinates[[3]], _Missing] (* returns True *)      What did I do wrong?


title: Mathlink and Parallelization

text: > **Possible Duplicate:**   >  How to run mathlink external commands in parallel? # Abstract I have a binary file compiled to work with MathLink. I can install the file and run the component functions from within Mathematica without any problems. But, when I try to use Mathematica's inbuilt parallelization with calls to my binary, I get an error that says               LinkObject::linkn: Argument LinkObject[/path/to/binary/file.binary,14,8] in      LinkWrite[LinkObject[/path/to/binary/file.binary,14,8],CallPacket[1,{1,2066455,5.,200000}]]      has an invalid LinkObject number; the link may be closed.      I understand this to mean that MathLink cannot set up links to my binary for some reason? How does one get this to work? # System Details I am on a system with 8 cores running x86_64-redhat-linux-gnu. # Mathematica Code that Produces the Error Assume `SwitchTimes` is a function defined inside my binary. It takes a number of inputs, but I want to loop over values for one particular input.               f[x_] := Module[{A, ma},         A = SwitchTimes[x, RandomInteger[10000000], 5.0, 200000];        ma = Mean[A];        ma        ];          B = ParallelMap[f, Table[i, {i, 1, 100, 2}]];      # Code that runs fine               f[x_] := Module[{A, ma},         A = SwitchTimes[x, RandomInteger[10000000], 5.0, 200000];        ma = Mean[A];        ma        ];          B = Map[f, Table[i, {i, 1, 100, 2}]];


title: Incorrect value of infinite sum

text: Wolfram Alpha and _Mathematica_ give an incorrect result (numerically) for the following infinite sum:               N[Sum[((-1)^n)/(n - (-1)^n), {n, 1, Infinity}]]     (* 0.700059 *)      Here's the result on Wolfram Alpha. Why the series isn't correctly evaluated?   The answer should be $\log(2)$.


title: File-backed lists/variables for handling large data

text: **Background** Currently I am working with some large data (most of it generated by Mathematica itself). I usually find it a hassle to do this. For example, I just exported a large amount of data to WDX on a machine with a lot of memory, just to find that I can't read it on my own machine (with little memory) because the file can only be read as a whole. It is also extremely slow to import (but using MX was not an option due to different architectures) Mathematica is excellent when working with in-memory data, as it's paradigms of operating on data as a whole (`Map`, `Outer`, `Table`, etc.) are very convenient. But it is not great at working with data that is too large to fit into memory, and it is not good at sequential processing of on-disk data. There have been discussions about this (see the comment discussions on this and this question), and the following idea came up more than once: it would be great to be able to use Mathematica's native paradigms to work on large on- disk data. The data would be loaded on-demand from disk, and discarded when not needed any more. I'd love to hear some ideas on how to implement a framework that does this, but read the next section for a more practical question. **Question** How can I conveniently work with data that doesn't fit in memory? Can we implement a list-like structure which fetches the data from disk as needed? (For example, when indexed, it would load only the requested list-item directly from disk. As processing of this item has finished, the memory it took up would be freed.) Alternatively could we implement variable which are loaded from disk on demand, but can be unloaded from memory? I'd prefer not to have to deal with things like file names (if this is backed my multiple files). I'm hoping to be able to have a nice abstraction, where I never need to do explicit reading from disk. I'd like to work with an object which acts and works similar to an in-memory list. **Ideas**   * This could be backed by the MX format, which is very fast to read and can store any expression. Unfortunately it's not portable between machines. For machine numbers, a flat binary file and `BinaryReadList` could be useful.   * `Stub` might or might not be useful.   * Are databases the right way to go? I'm not familiar with them.


title: Functional programming Style & Performance

text: Hello i have been spending time to convert my R tools into Mathematica Packages mainly because i like the functional programming style in Mathematica. In doing so it seems that i run into one conundrum. On one had functional programming suggests to avoid intermediate variables on the other side, a simple example like below clearly shows the potentially significant performance difference when avoiding intermediate (pre-calculated) steps. do i miss any better solution, or is this really a case where functional style, just looses out ?   * `dfm` is simply a List of Lists with some syntactic sugar   * `dfm["SER"]` is a vector of 25k real numbers   * `dfm["serial"]` is a vector of 25k string factors  * * *               (* check out the add variation as function of model *)     uSerial  = DeleteDuplicates[dfm["serial"]];     tt       = Transpose@{dfm["SER"], dfm["serial"]};     foo[z_] := Select[tt, (Last[#] == z) &][[All, 1]];     serMhdd = Mean /@ Map[foo[#] &, dfm["serial"]] // N; // AbsoluteTiming          uSerial = DeleteDuplicates[dfm["serial"]];     foo[z_] := Select[Transpose@{dfm["detSER"],                      dfm["serial"]}, (Last[#] == z) &][[All, 1]];     serMhdd = Mean /@ Map[foo[#] &, dfm["serial"]] // N; // AbsoluteTiming      happy holidays, Bernd


title: Center Manifolds

text: a[x_, y_] := -1     b[x_, y_] := x     c[x_, y_] := x     d[x_, y_] := -(1/2)          h[x_] = c1*x^2 + c2*x^3 + O[x]^4;          h[0] = 0;          D[h[x], x] = 0 /. {x -> 0};          cz3 = Solve[ h[a[x, y]*x + b[x, h[x]]] == c[x, h[x]]*h[x] + d[x, y], {c1, c2}]      I am using Implicit Function Theorem/center Manifold to determine stability of the fixed point give me P(x*)=1. But for the above `h`, I need to determine `c1` and `c2` but my programme gives me nothing. I know I think simple but I have recently started to use _Mathematica_. Please help me! I don't know what to use in here.


title: Control over the way matrix is displayed

text: I am wondering how to change the output format in _Mathematica_. For example, I have $x=\binom{3}{1}$ and $y=\binom{2}{5}$, and I want to find what linear combination of $x$ and $y$ produces $\binom{7}{11}$. What do I have to do to make _Mathematica_ display the output $x+2y$ ? I tried using `Solve`, but _Mathematica_ just returns the coefficients. I also tried to use the augmented matrix, but again _Mathematica_ still did not give me the output I want. P.S. I am working with a 16 by 16 matrix with 16 variables, so it's not very convenient to read off the coefficients for each variable.


title: How to extract phase angle from sinusoid

text: I'm doing some electric circuit calcualtions and I'm trying to get the phasor representation of some arbitrary function of Sin or Cos. Could be complex like:               (0. - 10. I) Sin[1000 t]      For instance, if I have:               Vin = 10Cos[1000t- 90Degree]      which is:               Vin = 10Re[Exp[-I*90Degree]*Exp[I*1000t]]      I want to get the magnitude angle form. i.e $10\angle-90^\circ$ I can get the magnitude with:               MaxValue[Abs[Vin], t]      but I can't get the phase angle correctly. I've tried:               Re[N[ArcCos[(Vin/MaxValue[Vin, t]) /. t -> 0]/Degree]]      but that gives $90^\circ$ not $-90^\circ$ So I have 2 questions actually:   1. Can I force mathematica to keep my function in $\cos\left(something - 90^\circ\right)$ form instead of changing it to $\sin\left(something + 0^\circ\right)$?   2. And how can I correctly obtain the phase angle


title: Bug in GeneratingFunction?

text: According to the documentation               GeneratingFunction[a[n],n,x]==Sum[a[n]x^n,{n,0,Infinity}]      However, for $a_n=1/(n+2)$ I obtain               {Sum[1/(n + 2) x^n, {n, 0, Infinity}], GeneratingFunction[1/(n + 2), n, x]} // FullSimplify     % /. x -> .2     (*{-((x + Log[1 - x])/x^2), PolyLog[2, x]/x}*)     (*{0.578589, 1.05502}*)      Thanks **Edit:** I'm using Mathematica 8.0.0.0 on a Linux x86 (32-bit)


title: Problem with NonlinearModelFit: "The function value... is not a list of real numbers..."

text: I'm trying to use NonlinearModelFit to fit the data:               Data = {{2.046204620462046`, 1.274347668`}, {2.012987012987013`,          1.131369542`}, {1.984`, 0.939944276`}, {1.952755905511811`,          0.721156437`}, {1.9224806201550388`,          0.614591638`}, {1.8931297709923665`,          0.572324748`}, {1.8674698795180722`,          0.536605273`}, {1.8397626112759644`,          0.49948005`}, {1.8128654970760234`,          0.478452409`}, {1.7867435158501441`,          0.455583518`}, {1.7613636363636365`,          0.439702881`}, {1.7342657342657342`,          0.411870668`}, {1.712707182320442`,          0.365204419`}, {1.6870748299319729`,          0.303633546`}, {1.6666666666666667`,          0.232056102`}, {1.6445623342175066`,          0.140710942`}, {1.6230366492146597`,          0.070744185`}, {1.6020671834625324`,          0.035633753`}, {1.597938144329897`, 0.044761696`}};          fit = NonlinearModelFit[Data, B/(       1 + g (x - (1.42 + Ea))^(-3/2)), {B, g, Ea}, x]      which gives: > NonlinearModelFit::nrlnum: "The function value {-1.22471-0.217191\ > I,-1.0682-0.243262\ I,-0.863406-0.265857\ I,-0.628591-0.289822\ > I,<<12>>,0.26533 -0.472365\ I,0.318041 -0.47811\ I,0.312374 -0.479155\ I}\n > is not a list of real numbers with dimensions {19} at {B,g,Ea} = > {1.,1.,1.}." The function I am using to fit my data gets imaginary values for some values of the parameters. But how can I force Mathematica to avoid these values?


title: How to resolve the duplicate error during interpolation

text: I have few hundred data points corresponding to an irregular shape closed curve. As the result I have data points that have the same value of y but different values of x. I want to create an interpolation curve and find the intersection of the curve with a straight line. When I try to interpolate the data _Mathematica_ tells me that there are duplicates. Is there any way of finding the intersection of the curve with a straight line? Here is how I was trying to do it               aa = Interpolation[Data, InterpolationOrder -> 1];     Interpolation::inddp: "The point -6.72 in dimension 1 is duplicated"          FindRoot[aa[x] - x, {x, bestguess}]      Thank you in advance.


title: is there a method to send different cell evaluation to different core

text: I am running _Mathematica_ on a computer with mulicpu and every cpu has multicore. I am wondering if there exist a method to send different cell evaluation to different core? So if I already have a cell being evaluating for a long time, I can still add other cells into evaluation at the same time, while won't have to stop the current evaluation or wait until the current evaluation to be done.


title: Detect when InputField gets keyboard focus

text: How might I detect when an `InputField` comes into focus? For example ideally something like this would work.               EventHandler[      InputField["default", String], {       "FocusGained" :> (MessageDialog["Focus"]),       "FocusLost" :> (MessageDialog["unFocus"]),       "Focus" :> (MessageDialog["Focus"])       }      ]      After reading this question I assumed "FocusGained,FocusLost or Focus" would do something but I haven't had any luck just yet.


title: Determine appropriate initial conditions for exit time

text: These are some constants:               b1b = 0.9;     b3b = .8;     a1b = 0.1;     a3b = 0.2;     eps = 0.1;     G = (1/eps^2)*b1b ; a1 = (1/eps^2)*a1b; a3 = (1/eps^2)*a3b;     xc = Sqrt[a1/a3];     Uc = a1*xc^2/2 - a3*xc^4/4      I have the following constraint for my system --> this was to find exit time:               const[x_, y_] := And[10^-8 <= y <= 10^-3, 0.9*(Uc) <= a1*x^2 - a3*x^4/4 <= 1.1*(Uc)]      Define the process (thanks to b.gatessucks):               x0 =    (* starting point for x[t] *)     y0 =    (* starting point for y[t] *)          proc = ItoProcess[      {\[DifferentialD]x[t] == y[t] \[DifferentialD]t,        \[DifferentialD]y[t] == (-G*y[t] - (a1*x[t] + a3*x[t]^3) - eps*b3b*y[t]^3) \[DifferentialD]t + Sqrt[2*eps*G] \[DifferentialD]w[t]},        {t, x[t], y[t], Boole[const[x[t], y[t]]]},        {{x, y}, {x0, y0}}, {t, 0}, w \[Distributed] WienerProcess[]]      Find exit time (output as **{t, x[t], y[t], Boole[const[x[t], y[t]]]}** ):               SeedRandom[3]     sim = RandomFunction[proc, {0, 1, 0.001}];     First@Select[sim[[2, 1, 1]], #[[4]] == 0 &]      I need help on how to choose the initial conditions: **(x0,y0)** so that I can find exit times that are non-zero. I need to find about 100 of these for every `eps`. `eps` is varying. Also, can someone kindly explain as to what:               SeedRandom[3]     sim = RandomFunction[proc, {0, 1, 0.001}];     First@Select[sim[[2, 1, 1]], #[[4]] == 0 &]      mean? Finally, the `const[x_, y_]` function need not be defined if there is some other way (algorithms) as to how I can find exit time for my dynamical system. If an answer is hard to come by then I would sincerely appreciate any leads or thoughts on this matter. Thanks!


title: Can I automatically stop operation that is too slow?

text: I need to write code like this: Do operation 1, but if it takes more that 5 seconds then stop it and do operation 2. Is it possible to do this somehow without manual interruption?


title: Can someone explain this code for joining two lists by the first element of each sublist?

text: **Background** (which may be skipped, unless context is needed) I've recently begun learning Mathematica (and only up to chapter 3 of Wellin), but wanted to write some code to get a better feel for syntax before reading on. I decided a good exercise would be to obtain a list of daily prices and volumes for a stock, _i.e._               P = FinancialData["QCOM", All];     V = FinancialData["QCOM", "Volume", All];      These returned, respectively,               {{{1991,12,16},0.47},{{1991,12,17},0.46},{{1991,12,18},0.48},{{1991,12,19},0.46},{{1991,12,20},0.47},{{1991,12,23},0.47},<<5447>>,{{2013,8,16},66.9},{{2013,8,19},66.33},{{2013,8,20},66.71},{{2013,8,21},66.57},{{2013,8,22},67.13},{{2013,8,23},67.15}}      and               {{{1991,12,16},143667200},{{1991,12,17},16176000},{{1991,12,18},10899200},{{1991,12,19},7299200},{{1991,12,20},5235200},{{1991,12,23},7894400},<<5448>>,{{2013,8,19},9063600},{{2013,8,20},9064900},{{2013,8,21},8471500},{{2013,8,22},6694200},{{2013,8,23},8335800}}      Probably all the dates would line up, but for sake of learning, I wanted to intersect the two lists by date. That is, obtain a list like               {{{1991,12,16},{0.47,143667200}},{{1991,12,17},{0.46,16176000}}, ... }      * * * **Problem** The canonical answer for combining lists seemed to be How do I obtain an intersection of two or more list of lists conditioned on the first element of each sub-list?, answered in main by @Mr.Wizard. But even after an hour of investigation, I cannot seem to wrap my mind around the following:               f1[a_List, b_List] :=         Reap[Sow[#2, #] & @@@ a ~Join~ b, a[[All, 1]] ⋂ b[[All, 1]], List][[2, All, 1]]      Here's where I've gotten:   1. `a ~Join~ b` is using the infix form to join the price and volume lists.   2. `Sow[#2, #] &` is a "pure function" (which confuses me, because they seem more like "anonymous" functions, distinct from "pure [virtual] functions" in C++), swapping the first and second parameters.   3. `@@@` is shorthand for `Apply`-at-level-1, so in other words, it's executing `Sow[{1991,12,16}, 0.47]; Sow[{1991,12,17}, 0.46]; ...` for all the prices, and then all the volumes. The prices (and volumes) are what's being "sowed", and each sowing is "tagged" by the date.   4. The intersection, `a[[All, 1]] ⋂ b[[All, 1]]`, simply returns all the "keys" (dates) that are common between the two lists. But, beyond that, **I don't understand how`Reap` brings it all together. Would someone explain the rest in simpler terms?** I'm a C++ developer, so I'm comfortable with programming terms. Either I'm not interpreting the documentation correctly, or my brain is fried from figuring out the rest. Thanks very much in advance.


title: Chi square: compare two different distribution

text: I try to compare two file with two different distribution of numbers. So i have random1.dat and random2.dat each one are vectors of more then 1000 rows. I saw from this question Doing a chi-square independence test in Mathematica that is it possible to make the comparison with Chi-square or Poisson but they attach the two files. How can i do that if my files are so long (or longer then 1000 rows)? Here my files: http://www.filedropper.com/random1_1: random1.dat http://www.filedropper.com/random2 : random2.dat Than I like, having in the same directory for instance 100 of this different files: random*.dat to compare all of them with a particular one (for instance random1.dat) is that possible in Mathematica? Thanks a lot !


title: NMinimize to optimize function Module

text: I am using `Nminimize` for simulation based optimization. I define the objective function (simulation with a variable "a") as a module to be used in the minimization. What I have found is if I do not print the function value (f[a]) using the EvaluationMonitor, NMinimize outputs 1000s of iterations of possible values for "a" extremely quickly without running the corresponding simulation run (because if it runs simulations, it will need few seconds for each simulation run and can not do 1000s of simulations in no time). However, when I include "f[a]" in the evaluation monitor, NMinimize runs the simulation for each possible value of "a" it outputs, but is disconnected to the optimization process. This is evident because NMinimize does not converge even after 1000s of iterations, when there are only 10 possible values "a" can take and I know the minimum occurs at "a"=10. Will someone help me understand what I am missing?               demand[n_,k_]:=Min[k Vf,n capacity];     supply[n_,k_]:=Min[(n Kj-k) w,n capacity];     flo[n_,Ku_,Kd_]:=Min[demand[n,Ku],supply[n,Kd]];     dx=Vf*dt;capacity=w*Vf*Kj/(Vf+w);Kj=150.;w=20.;Vf=100.;     n=Round[Flen/dx];m=Round[SimTime/dt];p=Round[Rlen/dx];RMLocation=Round[(2/3) p];     \[Alpha][a1_]:=1800.;\[Beta][a2_]:=0.1;L=1.;Flen=4.;Rlen=3.;delta = 1.;SimTime=15./60.;dt=6./3600.;     f[a_]:=Module[{k0=ConstantArray[0,n],kr=Table[Table[0,{i1,1,p}],{i2,1,n}],\[Gamma]=ConstantArray[1,n],\[Phi]},     Clear[j];j=0;RM[x_,t_]:=100 a;k=k0;     For[i=2,i<n,i++,kr[[i,1]]=\[Alpha][i dx] delta/Vf];     NtwrkTT=TT=Plus@@(Plus@@kr);     While[TT>0,      For[i=2,i<n,i++,       FQin=If[i==2,Min[demand[L,k0[[i-1]]],supply[L,k0[[i]]]],FQout];       dem=demand[L,k0[[i]]];dem=If[dem==0,0.001,dem];       \[Gamma][[i]]=Min[1,supply[L,k0[[i+1]]]/dem];       \[Phi]=\[Gamma][[i]] demand[1,kr[[i,p]]]/delta;       Qr=(\[Phi]-\[Beta][i dx] FQin) dx;       FQout=Min[demand[L,k0[[i]]],supply[L,k0[[i+1]]]];       k[[i]]=k0[[i]]+(FQin-FQout+Qr)/Vf;kr0=kr[[i]];       For[ir=2,ir<=p,ir++,        MR=If[ir==RMLocation+1,RM[i dx,j dt],capacity];        RQin=Min[MR,If[ir==2,flo[1,kr0[[ir-1]],kr0[[ir]]],RQout]];        MR=If[ir==RMLocation,RM[i dx,j dt],capacity];        RQout=Min[MR,If[ir<p,flo[1,kr0[[ir]],kr0[[ir+1]]],\[Phi] delta]];        kr[[i,ir]]=kr0[[ir]]+(RQin-RQout)/Vf];       kr[[i,1]]=If[j<=m,\[Alpha][i dx] delta/Vf,0]];      TT=Plus@@(Plus@@kr);      TT+=Plus@@k;      k0=k;NtwrkTT+=TT;j++];     NtwrkTT dt]     NMinimize[{f[a],3<=a<=12&&Element[a,Integers]},a,Method->"SimulatedAnnealing",EvaluationMonitor:>Print["a = ",a]]      **edit** : I edited this post extensively to make it clear. Apologize for any confusion.


title: GUI of a Karnaugh Map

text: I intend to implement a three-variables Karnaugh map with the following code. There are two points I failed to figure out. How to remove the outer double- line border? How to change the toggling into "1" and blank instead of black and white? Please help.               labels = {"00", "01", "11", "10"};     frame = Graphics[{         Line@Table[{{i, 0}, {i, 4}}, {i, 0, 2, 1}],         Line@Table[{{0, i}, {2, i}}, {i, 0, 4, 1}],          Table[Text[           labels[[3 - i + 1]], {-0.3, i + 0.3}], {i, {0, 1, 3, 2}}],          Table[Text[labels[[i + 1]], {i + 0.75, 4.25}], {i, {0, 1, 0, 1}}],          Line[{{0, 4}, {-0.75, 4.75}}],          Text[Style[ "A B" , 12], {-0.5, 4.}],          Text[Style["C", 12], {0., 4.5}]}, ImageSize -> {100, 200}];          Manipulate[       arrX = ConstantArray[0, {2, 4}];       EventHandler[       Dynamic[        mat = Reverse[ Transpose[arrX]] ;        Show[frame,         MatrixPlot[          mat,          Mesh -> All,          ImageSize -> {100, 200},          PlotRangePadding -> 0,          FrameTicks -> None,          ColorRules -> {1 -> Black, 0 -> None}]         ]],       {        "MouseClicked" :> (pos = Ceiling[MousePosition["Graphics"]];          arrX = ReplacePart[arrX, pos -> 1 - arrX[[Sequence @@ pos]]];          )        }],       AppearanceElements -> None,      FrameMargins -> 0      ]      ![enter image description here](http://i.stack.imgur.com/vlm1V.gif)


title: Wrong font selection for some characters in Mathematica 10 for Linux

text: I've just started using _Mathematica_ 10 on Linux and have immediately run into problems with the fonts. Fonts on Linux are always a headache, but I had managed to find a reasonable one in "Century Schoolbook L". However, in _Mathematica_ 10, this font and many others are being displayed with incorrect special characters and punctuation. It seems like _Mathematica_ is trying to assign sans-serif default (that is, not appearing in the font specified) characters when it needs to be using serif. I have tried messing with "OperatorSubstitution" and "FontSerifed". The former can change the parentheses, but neither affects the Greek. My only current recourse is to select one of the fonts that (seemingly randomly) does not suffer this problem; "Linux Libertine O", for example. Is this a bug? Is there a workaround? ![Example of problematic text; note the Greek and parentheses](http://i.stack.imgur.com/oCoPi.png)


title: Control formatting of a Text element in a plot?

text: Is it possible to define the format for a part of `Text` in a plot? For instance, is it possible to have `v` bold and `(a)` italic:               Show[Graphics3D[Line[{{0, 0, 0}, {1, 1, 1}}]],      Graphics3D[Text["v(a)", {1.1, 1.1, 1.1}, BaseStyle -> Large]],      PlotRange -> {{0, 2}, {0, 2}, {0, 2}}]      ![enter image description here](http://i.stack.imgur.com/50kbE.png)


title: Replacing values of a function

text: I have recently starting using _Mathematica_ and have recently come to what seems as an impasse in my understanding of the language. If this is too "tell me how to do it" I would certainly understand. I have written a program that applies commutator logic to a sequence of creation and annihilation operators to produce a string of Kronecker deltas. I then need to apply the Kronecker delta restrictions to my operators. This is purely symbolic algebra, no real numbers need be produced at the end of the day. For example,               (* KD[a,b] is a Kronecker delta with indices a and b. *)     (* KD Attributes: Orderless,NumericFunction *)     (* A[{x},{y}] is an operator with creation indices x and annihilation indices y*)          In:     A[{x},{y}] (KD[x,a1]*KD[y,a2]-KD[x,b1]*KD[y,b2])          Out:     A[{a1},{a2}]-A[{b1},{b2}]      What I have so far:               In:     rules=torules[(KD[x,a1]*KD[y,a2]]     A[{x},{y}]/.rules          Out:     {x->a1,y->a2}     A[{a1},{a2}]      This, however, is not quite what I need and converting from KD's to the rules list seems overly complicated. The main issues with this is that I cannot generate operator expressions that have plus within them. The structure of KD is not easily changed, but the input of the operator expressions is quite flexible. Another take on this, I am not sure if it will help, but its my current direction.               In:     SetAttributes[A, NumericFunciton]     A[{x},{y}] (KD[x,a1]*KD[y,a2]-KD[x,b1]*KD[y,b2])          Out:     A[{x},{y}]*KD[x,a1]*KD[y,a2]- A[{x},{y}]*KD[x,b1]*KD[y,b2]      This should be a fairly simple replacement pattern, but I cannot get any further.


title: How can I find the points of B Spline functions for a specific range?

text: Based on this question: I have a list of bspline functions (nearly 1000) provided by applying `BSplineFunction` to a list of points. I want to get the points each of bspline function for `Range[0, 1, .1]`. For instance:               functions = {bsplinefunc1, bsplinefunc2, bsplinefunc3};      The desired result is:               result =       {bsplinefunc1[0], bsplinefunc1[.1], bsplinefunc1[.2], ..., bsplinefunc1[1]},        {bsplinefunc2[0], bsplinefunc2[.1], bsplinefunc2[.2], ..., bsplinefunc2[1]},       {bsplinefunc3[0], bsplinefunc3[.1], bsplinefunc3[.2], ..., bsplinefunc3[1]}}      I tried to use the solutions of this question, mainly István Zachar's answer; however, I couldn't make it work. Any help is appreciated.


title: Create formatting wrapper for use with ToString

text: I'd like to create a custom number format for use with `ToString`. However if I do the obvious and create a function that calls `NumberForm` with modified options:               numberform =        NumberForm[#,          ExponentFunction -> (If[-5 < # < 5, Null, #]&),          NumberFormat -> (If[#3 != "", SequenceForm[#1, "E", #3],#1]&)]&        > >     Slot[1]& >   It works fine as a function:               numberform[1234567890.]        > >     1.23457E9 >   but not with `ToString`:               ToString[1234567890., numberform]        > >     ToString[1.23457*10^9, Slot[1]&] >   Is there some attribute I have to set to make it behave like the built-in forms? Is that even possible? Is there a workaround?


title: Defining an operator

text: Let `s` be a positive integer and let `DifferenceDelta` be this function with `step = 1`. Define `DifferenceDelta^s` to be an operator that applies `DifferenceDelta` `s`-times to any function `f[x]`. What _Mathematica_ syntax will give me the result of `(1 + DifferenceDelta)^s f[x]`? It seems that _Mathematica_ does not support operations with "pure" operators.


title: Test if a list is a permutation of another list

text: This question may have a simple answer, but I can't find it anywhere in the documentation. I'm trying to find a function that tells me whether a list is a permutation of another list. So the function should behave like this:               TestPermutation[{1, 2, 3, 4}, {1, 3, 2, 4}] (* Should return True *)          TestPermutation[{1, 2, 3, 4}, {1, 1, 2, 4}] (* Should return False *)      What sort of works is to use `FindPermutation[list1, list2]`, and then catch the error that says e.g.:               FindPermutation::norel: Expressions {1,2,3} and {2,1,2} cannot be related by a permutation. >>      But that isn't a very nice solution. Is there a neat way do do this?


title: Caching RecursionLimit::reclim error

text: I am learning how to catch exceptions, RecursionLimit::reclim in particular. To see how it works, I came up with the following example:               Clear[a]     a = 1     test[] :=      Check[If[a > 100, a, If[RandomReal[1000] < 1, Print["yupeee"];Print[a], test[]]],        a += 1; test[]]     test[]      With variable `a` I would like to count not how many times `Test[]` has been called, but how many times recursion limit has been exceeded. When I run it, I either get the output               "yupeee"      1      or               $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >>     $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >>     $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >>     General::stop: Further output of $RecursionLimit::reclim will be suppressed during this calculation. >>     1117      I expected something like               "yupeee"     45      or               101      but definitly not               1117      Could someone please explain this strange number? Any idea how can I control the number of exceeded recursion limit? And since I am a beginner, PLEASE, try to make it simple. Thanks


title: Print prints into the Messages notebook rather than into the evaluation notebook

text: Some time ago I noticed that the results of the evaluating the function `Print[something]` does not emerge in a new cell created in the notebook where the operation was evaluated. Instead it appears in the Messages notebook. Evidently some global option has been involuntarily switched. Do you know, which one? What should I do to return the behavior of `Print` back to normal?


title: NIntegrate doesn't work

text: I have a function, `Dx[s]` (defined in a module) which I can plot:               Plot[Dx[s], {s, 0, GetLatticeLength[]}]      ![enter image description here](http://i.stack.imgur.com/GqfJM.jpg) However if I try to integrate it, I get nothing:               NIntegrate[Dx[s], {s, 2, 3}]      > > >>     NIntegrate[Dx[s], {s, 2, 3}] >>   Note that the function has quite complicated form with many `If`-statements, hence can't be easily represented symbolically (e.g. `Dx[a]`). Still, for any numerical value I tried it gives a definite answer. Also, it seems from the plot that there are no wild singularities etc. Why doesn't `NIntegrate` work? Shouldn't it be just numerical evaluation of the integrand? I mean, the plot works, why shouldn't `NIntegrate` work as well?


title: GraphEdit making edges straight

text: When using a GraphEdit to alter a graph, is there a way to make the edges straight from one vertex to another? Thanks Here is my code:                 GraphEdit[      LayeredGraphPlot[{"C1.4.4" -> "T1.5.7", "1.23" -> "L1.5.4",         "P1.4.3" -> "C1.4.4", "P1.4.3" -> "C1.1.4", "P1.1.9" -> "P1.5.2",         "P1.1.9" -> "L1.5.3", "P1.5.2" -> "T1.5.7", "L1.5.3" -> "T1.5.7",         "L1.5.4" -> "T1.5.7", "P1.5.5" -> "T1.5.7", "L1.4.6" -> "L1.4.7",         "L1.4.8" -> "P1.4.20", "L1.4.8" -> "P1.4.19", "L1.5.6" -> "T1.5.7",         "L1.4.8" -> "P1.4.9", "T1.5.7" -> "C1.5.8", "P1.4.9" -> "C1.4.10",         "C1.5.8" -> "T1.5.9", "L1.1.15" -> "R1.4.11",         "P1.1.5" -> "R1.4.11", "P1.1.26" -> "P1.5.11",         "P1.1.26" -> "T1.5.9", "P1.2.14" -> "P1.4.12",         "P1.4.13" -> "P1.4.13", "T1.5.9" -> "R1.5.10",         "T1.5.9" -> "P1.5.11", "L1.4.14" -> "P1.5.2",         "C1.4.18" -> "P1.5.5", "C1.4.18" -> "R1.5.10",         "C1.4.18" -> "P1.5.5", "C1.4.18" -> "L1.5.6", "P1.4.5" -> "P1.4.5",         "C1.4.17" -> "P1.4.20", "R1.5.12" -> "R1.5.11",         "D1.20" -> "P1.4.16", "L1.4.8" -> "P1.4.16",         "L1.4.14" -> "P1.4.16", "P1.2.11" -> "T1.5.9",         "R1.5.12" -> "C1.5.13", "1.5.11" -> "C1.5.13",         "P1.5.14" -> "C1.5.15", "T1.5.9" -> "T1.5.17",         "P1.5.14" -> "T1.5.17", "C1.5.15" -> "T1.5.17",         "P1.2.5" -> "P1.5.19", "P1.1.9" -> "P1.5.19",         "P1.1.11" -> "P1.5.19", "P1.1.12" -> "P1.5.19",         "T1.5.17" -> "P1.5.19", "P1.5.20" -> "P1.5.20",         "L1.5.21" -> "L1.5.23", "R1.5.24" -> "R1.5.27",         "L1.1.4" -> "L1.6.1", "L1.6.1" -> "C1.6.2", "R1.6.14" -> "R1.6.14",         "P1.4.19" -> "P1.6.5", "P1.5.11" -> "P1.6.5",         "P1.5.25" -> "P1.6.5", "P1.4.19" -> "P1.6.7",         "P1.5.11" -> "P1.6.7", "P1.5.25" -> "P1.6.7", "P1.6.8" -> "P1.6.8",         "P1.4.20" -> "P1.6.9", "P1.5.11" -> "P1.6.9",         "P1.5.25" -> "P1.6.9", "P1.6.10" -> "P1.6.10",         "L1.6.11" -> "L1.6.11", "P1.6.12" -> "C1.6.13",         "P1.6.6" -> "L1.6.14", "C1.4.4" -> "L1.6.14",         "P1.6.6" -> "L1.6.14", "C1.6.13" -> "L1.6.14",         "P1.4.9" -> "P1.6.16", "L1.6.14" -> "P1.6.16",         "L1.6.17" -> "P1.6.16", "L1.6.17" -> "P1.6.16",         "P1.6.16" -> "R1.6.18", "L1.6.14" -> "T1.6.19",         "P1.6.16" -> "T1.6.19", "L1.6.14" -> "T1.6.19",         "L1.6.1" -> "P1.6.20", "P1.6.6" -> "P1.6.20",         "C1.6.2" -> "P1.6.20", "L1.6.1" -> "C1.6.21",         "P1.6.20" -> "C1.6.21", "L1.6.1" -> "P1.6.22",         "P1.6.22" -> "C1.6.23", "L1.6.1" -> "C1.6.23",         "L1.6.1" -> "P1.6.24", "P1.6.9" -> "P1.6.24",         "P1.6.24" -> "C1.6.25", "L1.6.1" -> "C1.6.25",         "L1.6.1" -> "P1.6.26", "P1.6.26" -> "C1.627",         "L1.6.1" -> "C1.6.27", "T1.6.19" -> "P1.6.28",         "P1.6.12" -> "P1.6.28", "L1.6.30" -> "T1.6.29",         "C1.6.2" -> "L1.6.30", "T1.6.19" -> "L1.6.30",         "P1.4.20" -> "L1.6.30", "L1.6.17" -> "L1.6.30",         "P1.6.24" -> "L1.6.32", "L1.6.31" -> "L1.6.32",         "P1.6.24" -> "L1.6.32", "P1.4.9" -> "L1.6.32",         "P1.6.22" -> "L1.6.32", "T1.6.33" -> "C1.6.34",         "C1.6.34" -> "C1.6.35", "P1.6.20" -> "C1.6.35",         "P1.5.19" -> "P1.6.36", "P1.6.36" -> "P1.6.38",         "T1.5.9" -> "P1.6.38", "C1.6.21" -> "P1.6.38",         "P1.5.11" -> "P1.6.38", "T1.5.18" -> "P1.6.38",         "P1.6.40" -> "P1.6.39", "C1.6.25" -> "P1.6.40",         "P1.6.36" -> "P1.6.40", "C1.6.35" -> "P1.6.40",         "T1.3.1" -> "P1.6.42", "P1.6.36" -> "P1.6.43",         "P1.6.38" -> "P1.6.43", "P1.6.42" -> "P1.6.43",         "P1.6.41" -> "P1.6.43", "P1.6.40" -> "P1.6.44",         "P1.6.41" -> "P1.6.44", "P1.6.36" -> "P1.6.44",         "P1.4.15" -> "P1.6.46", "P1.5.19" -> "P1.6.46",         "P1.6.39" -> "P1.6.47", "P1.4.15" -> "P1.6.47",         "P1.5.19" -> "P1.6.47", "P1.2.14" -> "P1.6.47",         "P1.6.36" -> "P1.6.47", "R1.7.2" -> "R1.7.2", "P1.7.3" -> "P1.7.3",         "C1.7.4" -> "C1.7.4", "P1.7.5" -> "P1.7.6", "P1.7.7" -> "P1.7.8",         "P1.1.17" -> "P1.7.10", "P1.7.10" -> "R1.7.11",         "P1.1.17" -> "P1.7.12", "P1.7.10" -> "P1.7.12",         "P1.7.12" -> "C1.7.13", "P1.7.10" -> "C1.7.13",         "C1.7.13" -> "C1.7.14", "L1.7.15" -> "P1.7.16",         "T1.7.17" -> "C1.7.18", "P1.7.7" -> "C.7.18",         "C1.7.18" -> "R1.7.19" }, VertexLabeling -> True,        PlotStyle -> {Arrowheads[{{0.008, 0.6}}]},        PlotRangePadding -> Automatic]]      If I move a vertex, the edge becomes very irregular if it had any curvature in it. I would like to make edges straight without moving all the active points on an edge.


title: Dynamic panel crashes Mathematica 10.0.0.0

text: This answer by @paw have revealed a bug that causes Mathematica v 10.0.0.0 to crash the GUI and kernel. So far the offending code is this:               Needs["QuantityUnits`"]     table = Keys[QuantityUnits`Private`$UnitReplacementRules];          Panel[DynamicModule[{f = ""},        Column[{Text[Style["Mathematica Unit Search:", Bold]],          InputField[Dynamic[f], String, ContinuousAction -> True],          Dynamic[Union@Flatten[StringCases[#, f ~~ ___] & /@ table] //            TableForm]}]]]      This creates a dynamic panel and the crash happens when pressing "panel format" in the suggestion bar. The bug has been confirmed so far only on M10 under Windows 7 64 bits. My skills are not enough to reduce that code to a minimum working example that reproduces the crash, nor I have available Mathematica under other OS. So I'm both reporting the bug and asking:   1. What would be a minimum working example of the crash?   2. Does this crash also in other platforms? The Wolfram Technical Support identification code is: CASE:1566616


title: Printing the base 'b' value of an integer as a string (without the subscript base indication)

text: Is there a simple one-liner to convert a given base 10 integer to a string representation of this integer in some desired base 'b'? Is there a way to do this avoiding the subscript indicating the base, for example the small 2 if we ask for a binary string? The best thing for my purpose, despite the danger, would be have a function that takes a decimal integer and returns what appears to be the binary, ternary, etc. representation of this integer, but which Mathematica still treats as a decimal integer value.


title: Legends for multiple curves

text: Dear users I am a new member here and I would like to ask a question about `PlotLegends`. I have multiple curves and want to make their legends bit more _visible_. Here is a sample code:               Plot[{Sin[h], Cos[h], Tan[h]}, {h, 5, 10},        PlotStyle -> {{GrayLevel[0], Dashing[None],Thickness[0.005]},                      {GrayLevel[0], Dashing[0.01],Thickness[0.005]},                      {GrayLevel[0], Dashing[0.02],Thickness[0.005]},                      {GrayLevel[0], Dashing[0.03],Thickness[0.005]}},        Axes -> False, Frame -> True,       PlotLegends -> Placed[{"sin", "cos", "tan"}, Top]]      I assume that the problem comes from the `Dashing[]` specifications making the legends line not _visible_ enough.I may have up to 7 curves so i need and alternative to `Dashing[]` or any other way to increase lengths of legends and make them more _visible_.


title: xCoba: evaluate tensor quantities, given an explicit metric

text: I am new to _xAct_ packages and I'm having some problems to compute tensor quantities with _xCoba_. I defined a manifold and a metric. I computed All quantities of `MetricCompute`. What I need now is to calculare things like:               DefTensor[ G[d],M]     IndexSet[ G[h_] RiemannCd[h, a, b, c] Cd[-a][F[-b, -c]]      where `F` is antoher defined tensor. I know how to select components of a tensor, so for example, let's say that I would like to compute explicitly `G[{1,B}]` in my Chart `B`. I tried with things like:               ToBasis[B]//TraceBasisDummy//ToValues      but they don't work. I imagine that there is a simple solution to my problem, but I cannot find it. I hope that someone can help me.


title: How can I define a function taking two distinguishable sets of options?

text: It commonly happens that one wants to define some function `foo` which in turn calls some other function (e.g., `Plot`) that can take a vast variety of optional arguments, and one would like to arrange things so that the caller of `foo` can pass optional parameters intended for the second function (e.g., `Plot`) among the arguments to `foo`. The latter is expected to simply pass those arguments right through. The pattern for doing this, according to the documentation, is something like:               foo[x_, y_, z_, opts:OptionsPattern[]] :=         Plot[..., Evaluate[FilterRules[{opts}, Options[Plot]]]]      But now suppose that `foo` in fact makes _two_ calls to `Plot` (for example), and that one wants to provide the caller the opportunity to pass separate sets of optional parameters for the two calls to `Plot`. (In general, these two parameter sets would differ.) How can one retool `foo` so that it can accept 2 sets of optional parameters? Also, how would one actually _invoke_ the function thus defined, with two different, non-empty sets of optional parameters?


title: Counter assignments

text: I'm trying to create a specific outline format to match some course materials I am required to submit in a particular way. I know how to create auto-numbered cells using `Automatic` numbering. The structure I am looking for is something like   * Section 1     * Subsection 1     * Subsection 2     * Subsection 3   * Section 2     * Subsection 4     * Subsection 5   * Section 3     * Subsection 6 etc. I know these is a way to NOT have the `Subsection` cells go back to one at each `Section` heading, but I can't find the way to make that happen. I'd like to be able to move the `Section` cells if necessary but have the `Subsection` cells number from $1$ - whatever and not reset in each section. Is this possible? Any help is appreciated.


title: GIF file breaking Import

text: I'm working with a large number of historical image files and am playing around with extracting dominant colours, faces, etc. with _Mathematica 10_. Occasionally, however, I am running into files that just plain out break the language - i.e. even `Import[file,"Elements"]` leads me to have to quit the kernel to get things going again. Here's the workflow. Often `Import[file]` will return > > Import::fmterr : Cannot import data as GIF format.>> So far so good. But if you run it _again_ , the whole kernel comes crashing down. Even if I decide not to run it again, things become unstable and the program begins to hang. The same context happens with `Import[file,"Elements"]` so I'm at a loss of how to debug it. Is there any way to get _Mathematica_ to skip these files - or any clue of what might be happening? File here: https://www.dropbox.com/s/7x5qxlp6ybiqbxu/broken-image.gif Screenshot of file in OS X preview: ![enter image description here](http://i.stack.imgur.com/TS7xI.png) In case it helps, here's the overall context of what I'm doing:               SetDirectory["/volumes/lacie/geocities-images/athens/"];     files = FileNames["*.*"];     hue = Reap[        Do[input = Import[files[[x]]];          Sow[If[Length[input] == 0, ImageMeasurements[input, "Mean"],            ImageMeasurements[input[[1]], "Mean"]]], {x, 1,           Length[files]}]];      This crashes when it hits the 'broken-image' GIF and needs to be restarted.