title: Fast Simulations with Compile

text: this post relates to another post that I didn't follow up propely. If I wanted to simulate a system of stochastic proesses like the following, and loop over this run many many times would writing the processes as 'compiled' pure functions speed up the run time? Or, is Nestlist already trying to do this for me?               norTheta[mu_, sigma_] := Random[NormalDistribution[mu, sigma]];     norPi[mu_, sigma_] := Random[NormalDistribution[mu, sigma]];          thetaNext[thetaNow_] :=      thetaNow + (-lambdaTheta*(thetaNow - thetaBar)*deltaT      + sigmaTheta*norTheta[0, 1]*Sqrt[deltaT]);     piNext[piNow_, thetaNow_] := piNow + (-lambdaPi*(piNow - thetaNow)*deltaT +      sigmaPi*norPi[0, 1]*Sqrt[deltaT]);          lambdaTheta = 0.07; sigmaTheta = 1.2; thetaBar = 2; lambdaPi = 1.0;      sigmaPi = 1.25; deltaT = 1/12;     steps = 252;     T = 5;      deltaT = 1/steps; // N      Maturity = T*steps;          simulateRun = Transpose[NestList[{piNext[#[[1]], #[[2]]],                             thetaNext[#[[2]]]} &, {2, 2}, Maturity]];


title: convert long string to integer list

text: at first, i would like to thank all the people here. i'm working with mathematica for half a year now and always found great advice and tricks. now, i came up with a problem i couldn't find a solution for. from a file, i import a string with around 23 mio. characters which is reasonably fast (it acutually is a dna sequence). i then want to split this string into its characters and convert each of them to an integer number. my first, naive approach was the following:               MaxMemoryUsed[]/1024^2//N     AbsoluteTiming[list=Characters[a]/.{"A"->1,"T"->2,"G"->3,"C"->4};]     ByteCount[list]/1024^2//N     MaxMemoryUsed[]/1024^2//N      which creates the following output:               134.286     {13.301206,Null}     702.261     1976.42      as you can see, the timing is quite good but the memory usage during the process is horrible. my next approach was reading from a stream and convert each character to an integer instantly:               MaxMemoryUsed[]/1024^2//N     string=StringReplace[string,{"A"->"1","T"->"2","G"->"3","C"->"4"}];     str=StringToStream[string];     AbsoluteTiming[list=Table[ToExpression[Read[str,Character]],{i,1,StringLength[string]}];]     Close[str];     ByteCount[list]/1024^2//N     MaxMemoryUsed[]/1024^2//N      which results in               134.281     {176.502736,Null}     702.252     813.208      as yo can see, this approach needs way less memory but takes considerably longer. my question now is, if there is another memory efficient way to do this which is faster than my second try? thanks a lot!


title: Calling blank arguments using enclosing functions

text: Is there a way to call a function and have that function use an argument defined in an enclosing function? e.g.,               set = Table@Range@50;          posE[set_] := Select[set, EvenQ]          tform1[mult_,set_] := (#*mult) & /@ set[[posE]];          t1set = tform1[10, set]      which leads to the following message/error, > Part::pspec: Part specification posE is neither an integer nor a list of > integers. >> I would like `posE` to get its argument `set_` from the second argument in `tform1` (also named `set_`). Is this possible? is there a better way to do this? (Note that I do not want to combine the two functions into a single function).


title: Why do all plots open in new windows when I use JavaGraphics?

text: I want to open only one plot in new window. When I use `<<JavaGraphics`` all plots open in new windows. I put `<<JavaGraphics`` before one last plot but it works for all plots. How can I do this?


title: Robust function for manipulation of nested lists

text: I have a nested list of the form:               test = {{"sample1", {"elema", "ppm", 238}, {"elemb", "ppm", 57},                          {"elemc", "w%", 14.23}, {"elemd", "w%", 0.112}},              {"sample2", {"elema", "ppm", 215}, {"elemb", "ppm", 13},                          {"elemc", "w%", 12.13}, {"elemd", "w%", 0.095}},              {"sample3", {"elema", "ppm", 219}, {"elemb", "ppm", 28},                          {"elemc", "w%", 19.11}, {"elemd", "w%", 0.55}}};      I want to be able to select and order rows from this list based on another list:               samples = {"sample3", "sample1"};      and reorder elements based on their label,               order =  {"elemd","elemc","elemb","elema"};      to end up with something like: > {{0.55, 19.11, 28, 219}, {0.112, 14.23, 57, 238}} The main aim is to have a robust re-ordering function of the form               trchem[data_, order_, sample_] := ...      I have played around with the following:               Intersection[sample, #] & /@ test      > {{"sample1"}, {}, {"sample3"}}               Position[#, test[[All, 1]]] & /@ sample      > {{}, {}} Neither of which are quite right.. I'm sure this is really easy but I can't figure it out at the moment. Any suggestions? Thanks.


title: Minimizing a functional takes forever

text: I need help with minimizing a functional in Mathematica. I have a function $V(\xi)=\sum_{i=1}^\infty C_{3_i}J_0(\xi/C_i)+C_{4_i}Y_0(\xi/C_i),~~~\Sigma\leq\xi\leq\xi_1$, and want to find such $\\{C_{3_i}\\}$ and $\\{C_{4_i}\\}$ that $V(\xi)\equiv-1$. Here $\\{C_i\\}$ are known (see below), $J_0(x)$ and $Y_0(x)$ are Bessel functions. To do that, I take $\int\limits_\Sigma^{\xi_1}|V(\xi)+1|d\xi$ and minimize it whit respect to parameters $\\{C_{3_i}\\}$ and $\\{C_{4_i}\\}$. I don't know why, but it takes forever for Mathematica to minimize that functional (at least more than 14 hours). Probably that's because integration increases the number of summands adding some with $C_{3_i}C_{4_i}$ coefficients. Am I doing something wrong or is there a method for getting the $\\{C_{3_i}\\}$ and $\\{C_{4_i}\\}$ faster? **Important note:** I take $V(\xi)\approx\sum_{i=1}^N C_{3_i}J_0(\xi/C_i)+C_{4_i}Y_0(\xi/C_i)$, where $N$ is length of $\\{C_i\\}$, and $\\{C_i\\}$ are eigenvalues of Sturm-Liouville problem (see the code for detailed information). $V(\xi)\equiv-1$ is actually obtained from initial condition for the initial function $F(\xi,\tau)=V(\xi)U(\tau)$.               xi1 = 10;     Sigma = 1;     nn = 1;     f3[z_] = BesselJ[1, nn*xi1/z]*BesselY[0, nn*Sigma/z] -      BesselJ[0, nn*Sigma/z]*BesselY[1, nn*xi1/z];     Plot[f3[z], {z, 0, 10*nn}]     NumberOfRoots = 0;     Timing[roots3 =      Reap[First[       NDSolve[{x'[z] == f3'[z], x[1] == f3[1]}, {x}, {z, 1000, 0.1},         Method -> {"EventLocator", "Event" -> x[z],           "EventAction" :> {Sow[y /. FindRoot[f3[y], {y, z}]],             NumberOfRoots++}}, MaxStepSize -> 0.1,         MaxSteps -> 1000000]]][[2, 1]]];     NumberOfRoots     Min[Abs[f3 /@ roots3]]     Max[Abs[f3 /@ roots3]]     roots3 = Sort[roots3];      The code above finds $\\{C_i\\}$ - roots of equation given by boundary conditions $V(\Sigma)=0$ and $\frac{dV}{d\xi}(\xi_1)=0$ $$J_1(\xi_1/C)Y_0(\Sigma/C)-J_0(\Sigma/C)Y_1(\xi_1/C)=0.$$ I use the function $$f_3(C)=J_1(n\xi_1/C)Y_0(n\Sigma/C)-J_0(n\Sigma/C)Y_1(n\xi_1/C),$$ where $n$ is a scale parameter. Bigger $n$ gives more roots. Thus, for $n=1$ we get 29 roots, $n=5$ - 143, $n=10$ - 286, etc. Then I print maximum and minimum values of $f_3(\\{C_i\\})$ to check if I really get zeros. For $n=1$ $\min f_3(\\{C_i\\})\sim2*10^{-19}$, $\max f_3(\\{C_i\\})\sim 2*10^{-15}$, which is really satisfactory.               Array[CCNew, NumberOfRoots]; (*CCNew=C*)     Array[C3, NumberOfRoots];     Array[C4, NumberOfRoots];     For[i = 0, i < NumberOfRoots, CCNew[i] = roots3[[i]]/nn, i++] (*here we take the scale into account*)     Clear[xi];     InitFunction[xi_] =      Sum[C3[i]*BesselJ[0, xi/CCNew[i]] +      C4[i]*BesselY[0, xi/CCNew[i]], {i, 1, NumberOfRoots}]; (*InitFunction=V*)     C5 = Join[Array[C3, NumberOfRoots], Array[C4, NumberOfRoots]];     Timing[Minimize[Integrate[Abs[InitFunction[xi] + 1], {xi, Sigma, xi1}], C5]]      And here it takes forever to find $\\{C_5\\}=\\{C_3\\}\cup\\{C_4\\}$. Any help with this?


title: Check Specific Connections within Graph

text: Say you have the skeleton of a graph:               fullSkele = PolyhedronData["GreatRhombicosidodecahedron", "SkeletonRules"]      and you've an arbitrary list of some fraction of those nodes, say `extantNodes = {1, 5, 8, 72, 101}`, which you want to turn into the list of all nodes **_connected_** directly to those `extantNodes` (along with the number of `extantNodes` each is connected to). With,               connCheckTool[node1_, node2_] := Count[fullSkele, (node1 -> node2)] + Count[fullSkele,(node2 -> node1)]      The following function achieves this:               DeleteCases[        DeleteCases[         Transpose@{Range[120],             Total /@          Table[connCheckTool[i, extantNodes[[z]]], {i, 1, 120, 1}, {z,            1, Length@extantNodes}]} /. {x_Integer, 0} -> delete, delete], {x_, y_} /;      MemberQ[extantNodes, x] == True];      However, the inner `connCheckTool` is not very efficient, especially with larger graphs. Can anyone think of a way to accomplish this in a better way? I suspect it will involve the `AdjacencyMatrix` of the original, whole graph, as opposed to the list-search mechanism, but can't quite get it...


title: Keyboard issues with Mathematica 9.0.1 for Linux

text: After working for a while with `Manipulate` function and increasing the number of variables to be manipulated, keyboard stops working properly in the Notebook. It gets really crazy, mainly the keys `Backspace`, `Space`, `Delete`, `Ctrl`, `Alt`, `Left`, `Right`, `Up` and `Down`. For example, some times `Backspace` starts behaving as the `Left` Key, some times as `Right`, etc. all this randomly. I am running _Mathematica_ for Linux, and I have had this issue with Ubuntu 13.04 and recently with Ubuntu 13.10 as well. This is not an issue related to my computer since outside _Mathematica_ the keyboard works as usual.


title: Shading area in graphics

text: I want to shade the area between the formula               eqn=(a (Sqrt[a] (-40 + 37 a + 10 a^2 - 3 a^3) + (-1 + a)^2 (32 +        a) ArcTanh[Sqrt[a]]))/(2 (-Sqrt[a] (1 + a) + (-1 + a)^2 ArcTanh[      Sqrt[a]]))      and `-3/2`. To be clearer: `-3/2 < region to be shaded < eqn` I tried with:               Show[{{Plot[{eqn, -3/2}, {a, -2, 1.5}]},        Plot[{eqn, -3/2}, {a, -1.2, 1},         Filling -> {1 -> {-3/2, Automatic}}]}, PlotRange -> {-2, 4}]      but I don't get what I want: it shades also               eqn < region < -3/2      Any ideas? I am sorry but I don't understand how to link a figures, I hope I explained myself... Oh, I am using Mathematica 8.


title: Asynchronous evaluation on EventHandler

text: How can I make this progress bar appears when I press `Enter`? The `Button` Evaluate works just fine, but when `Enter` is pressed it jumps the progress bar. It would be easy if EventHandler could have `Method-> "Queued"`, but is't not the case. Here is my code:               DynamicModule[{output="",slowReport,progress,str,btnEval,enterAction,number,enterEval},              progress=ProgressIndicator[Dynamic[Clock[Infinity]],Indeterminate,ImageSize->280];              enterEval=EventHandler[#,{"ReturnKeyDown":>(output=progress;output=slowReport[])}]&;             btnEval=Button["Evaluate",(output=progress;output=slowReport[]),Method->"Queued"];              Dynamic@Panel@Column[{Row[{InputField[Dynamic[number], String]//enterEval,btnEval}]," ",output," "},Alignment->Center]              ,Initialization:>        (            SetOptions[$FrontEndSession,DynamicEvaluationTimeout->10];            slowReport[]:=(Pause[1];ToExpression@number^2)         )     ]      Here is what happens when Evaluate is pressed: ![enter image description here](http://i.stack.imgur.com/TUPVd.png) ![enter image description here](http://i.stack.imgur.com/F6Dia.png)


title: How can I generate a variable-length list of options in PieChart?

text: I would like to allow a user to manipulate the segments of a pie-chart, which is to be generated from a list of a specific format. The code looks something like the following:               pieChartList = {         {category1, 1},         {category2, 2}     };          generatePieChart[dataList_List, plotLabel_String] :=         Manipulate[             PieChart[                 {category1, category2},                 PlotLabel -> plotLabel             ],             {{category1, 1}, 0, 10}, {{category2, 2}, 0, 10}         ];          generatePieChart[pieChartList, "Test pie chart"]      As you can see, the lists are being written "manually," even though `pieChartList` contains all the information to generate the necessary structures. Is there an elegant way to generate the manipulation list automatically? In other words, if I were to add `{category3, 3}` to `pieChartList`, the function `generatePieChart` should pick up the new value automatically. Thanks in advance for your help.


title: Evaluating terms in series

text: I'm trying to evaluate a simple expression:               Subscript[λ, n] = (2 n - 1) π/(2 L);      And then sum it up:               Sum[Subscript[λ, n], {n, 1, 3}]      The result is: > >     π/(2 L) + Subscript[λ, 2] + Subscript[λ, 3] >   How can i get _Mathematica_ to write the second and third term in the same way as the first?


title: Add Brackets to a string list

text: Hello stackexchange community! I have a stringlist with a value and his error for eg:               {{"12","1"},{"13","2"}}      Now i want to output this as something like this (for a lab-report):               {"12(1)","13(2)"}      Unfortunately I have no idea how to get this working... Thanks in advance   Cx


title: Extracting values from nested rules in JSON data

text: I have been using Mathematica to analyse some data from the StackExchange API. It is conveniently available in JSON form, which Mathematica interprets as replacement rules. However, some of the rules are nested as the right-hand side of an outer rule, as you can see in the case of `badge_counts` here:               Import["http://api.stackexchange.com/2.0/users?page=1&order=desc&sort=reputation&site=mathematica",        "JSON"][[2, 2, 10]]          (* Out[1]=      {"accept_rate" -> 75, "account_id" -> 395497, "age" -> 41,       "badge_counts" -> {"bronze" -> 35, "gold" -> 0, "silver" -> 11},       "creation_date" -> 1326833982, "display_name" -> "Verbeia",       "is_employee" -> False, "last_access_date" -> 1331949804,       "last_modified_date" -> 1330990001,       "link" -> "http://mathematica.stackexchange.com/users/8/verbeia",       "location" -> "Sydney, Australia",       "profile_image" -> "http://www.gravatar.com/avatar/3df2379fc0221bb0281c0d608542bd84?d=\identicon&r=PG",       "reputation" -> 3571, "reputation_change_day" -> 0,       "reputation_change_month" -> 857,       "reputation_change_quarter" -> 3475, "reputation_change_week" -> 605,      "reputation_change_year" -> 3475, "user_id" -> 8,       "user_type" -> "registered",       "website_url" -> "http://www.verbeia.com/mathematica"}     *)      Users without any badges don't have this nested rule. To handle both cases I am doing something like this to get the badge counts in a flattened list, so each row of the final list corresponds to a user of the site:               getUserData[page_Integer] := Module[{ad},       ad = Import[          "http://api.stackexchange.com/2.0/users?page=" <>            IntegerString[page] <>            "&order=desc&sort=reputation&site=mathematica", "JSON"][[2,2]];       If[Length[ad] > 0,        Join[Most[#], {"bronze", "silver", "gold"} /.             Last[#]] & /@ (({"display_name", "creation_date", "reputation",               "reputation_change_week", "is_employee", "last_access_date",               "user_type", "badge_counts"} /. ad) /.            "badge_counts" -> {"bronze" -> 0, "silver" -> 0,              "gold" -> 0}), {}]       ]      Which I can then build up into a list of all users and their stats like this:               Monitor[      pageM = 0;      resultM =        FixedPoint[Join[#, getUserData[++pageM]] &, {}];,       StringForm["Loading page `` ...", pageM]      ]      The final output is list of vectors that look like this:               resultM[[10]]     (*Out[2]= {"Verbeia", 1326833982, 3571, 605, False, 1331949804, "registered", 35, 11, 0} *)      My question is: is there a more concise or elegant way to write the `getUserData` function, without need a `Join` _and_ three separate `ReplaceAll` (`/.`) constructions?


title: Counting radial ridges on an image

text: After happily using the v9 image assistant to crop elliptically an image, and then the drawing tools to put a white disk in the middle, I turned this image: ![](http://i.stack.imgur.com/QDGVy.png) into the following one: ![Mathematica graphics](http://i.stack.imgur.com/NNzNM.png) that can be imported with               im=Import["http://i.stack.imgur.com/NNzNM.png"]      The overall objective is to programatically count the number of those radial lines. Due to the lighting, there are parts of the image in which those lines are darker than its surroundings and others where it is lighter. So far I haven't found a good way worth posting, so any pointer to a good solution would be appreciated. I have the feeling the image processing people will see better ways of dealing with this and I will be grateful to learn something. Thanks a lot **EDIT** A first approach with @RahulNarain's suggestion would be               int = ListInterpolation[        ImageData[ColorConvert[im, "GrayLevel"]], {{-1, 1}, {-1, 1}}];     polInt = Function[t, int[0.95 Cos[2 \[Pi] t], 0.95 Sin[2 \[Pi] t]]];          Plot[polInt[t], {t, 0, 1}, AspectRatio -> 0.2, ImageSize -> Large,       PlotRange -> Full]      ![Mathematica graphics](http://i.stack.imgur.com/sH3mT.png) Now,               ListLinePlot[Abs@Fourier[polInt@Range[0, 1 - 0.001, 0.001]],       PlotRange -> {{0, 500}, {0, 50}}]      ![Mathematica graphics](http://i.stack.imgur.com/07ovO.png) A better zoom shows the maximum at 98 However, manual counting (could be wrong) gave me 96, and nikie's approach is suggesting 97. 1 or 2 off count could be due to the light changes making the real ridge be the local minimum at some places and local maximum at others


title: a problem about simplifing conjugate

text: the situation is as follows               \[Sigma][i_] := PauliMatrix[i];     m := Sum[a[i]*\[Sigma][i], {i, 1, 3}]     $Assumptions = Element[{q, w, e, o}, Reals];     a[1] := q;     a[2] := w;     a[3] := e - o;      what I want is the Conjugate of the eigenvectors,so               Conjugate[Eigenvectors[m]]      and this gives               {{-((-Conjugate[e] +      Conjugate[o + Sqrt[e^2 - 2 e o + o^2 + q^2 + w^2]])/(     Conjugate[q] - I Conjugate[w])),      1}, {-(-Conjugate[e] + Conjugate[o] -        Conjugate[Sqrt[e^2 - 2 e o + o^2 + q^2 + w^2]])/(Conjugate[q] -        I Conjugate[w]), 1}}      now simplify, gives               {{(e - Conjugate[o + Sqrt[e^2 - 2 e o + o^2 + q^2 + w^2]])/(q - I w),      1}, {(e - o + Sqrt[e^2 - 2 e o + o^2 + q^2 + w^2])/(q - I w), 1}}      and here comes the problem, in the second eigenvector, the "conjugate" is totally gone, and this is right. because I have assumed all the variables are real. While in the first eigenvector, there is still one "conjugate" in the expression, But this Conjugate should be simplified too without any problem. If you copy the Cojugate part and simplify, it do simplify.               Simplify[Conjugate[o + Sqrt[e^2 - 2 e o + o^2 + q^2 + w^2]]]      and gives               o + Sqrt[e^2 - 2 e o + o^2 + q^2 + w^2]      > so why mathematica's simplify just don't take a further step in simplifying > first eigenvector as it did in simplifying second eigenvector?? This kind of > asymmetry confused me. So is it a bug or something? Did I missed some step in the simplify procedure? * * * **Edit** It seems that few people are interested in my question. But I do really frequently encounter such anoying simplifing problem. So I choose another example extracted from my real calculation. And expecting more suggections. first, a little prelude               $Assumptions=Element[{x,y},Reals]     Simplify[Conjugate[Sqrt[x^2+y^2]]      result               Sqrt[x^2 + y^2]      This trivial example illustrates that "simplify" is smart enough to deal with Conjugate and it can recognize whether the expression in the Conjugate is real or not. But I encounter an expression which is essentially the same thing only with more variables than the above trivial example. mathematica's simplify function failed to do it correctly. with the global assumptions               $Assumptions = Element[{t1, t2, kx, ky, \[CapitalDelta], \[Phi]}, Reals]          Simplify[Conjugate[Sqrt[     t1^2 (2 Cos[(Sqrt[3] kx)/2] Cos[ky/2] + Cos[ky])^2 +      4 t1^2 (Cos[(Sqrt[3] kx)/2] - Cos[ky/2])^2 Sin[ky/     2]^2 + (\[CapitalDelta] +      4 t2 Cos[(3 ky)/2] Sin[(Sqrt[3] kx)/2] Sin[\[Phi]] -      2 t2 Sin[Sqrt[3] kx] Sin[\[Phi]])^2]]]      the result will still have Conjugate intact. And it shouldn't be like this. It should be smart enough to recognize that the expression under the sqrt is absolutely greater than or equal to zero and throw out the Conjugate Rojo mentioned "MapAll" , But "MapAll" can do nothing more in this situation. And Nasser M. Abbasi proposed to ComplexExpand. Yes, ComplexExpand can tackle this expression. But let me point out the difficulty encountered in real case. In real case, there will be very large expression(even several pages long). And directly ComplexExpand such large expression will cost considerable cpu time (I have tried), because it will transform many expression into Re and Im form which I do not expect. So the most efficient way is still simplify directly first. But as I have showed, there will be several "Conjugate" so obstinate and these Conjugate hides in such long expressions which are difficult to find. I have to find them term by term and ComplexExpand them to test if they are really real. And this is so inconvenient! I hope some one helps me out.


title: CMYK colours in a graph template

text: Hi I'm trying to put together a graphing template. Unfortunately, my arrowheads are a different colour than my functions when the graph is exported to something like a PDF. Is there a way I can manually set the arrowhead colours in CMYK using this setup? I'd also like to change the function arrowheads to lines instead of enclosed arrows. Here's the important parts. The arrowheads come from the last line.               ClearAll["Global`*"];     Interpretation[{f = {  1/(x - 1) + 1, Sin[x], -x, x},        points = {{3, 2}, {-5, -8}}, min = -10, max = 10, size = 0.5,        rmin = -10, rmax = 10, gridx = 1, gridy = 1, hlabel = "x",        vlabel = "y"},       Panel[Grid[{{Style["Plot Characteristics", Bold], SpanFromLeft},         {"Functions:", InputField[Dynamic[f]]}         }]],           Plot[f, {x, min - 0.58*gridx, max + 0.58*gridx},             PlotStyle -> {{AbsoluteThickness[1],            CMYKColor[0, 0, 0, 1]}, {AbsoluteThickness[1],            CMYKColor[0, 0.83, 1, 0]}, {AbsoluteThickness[1],            CMYKColor[1, 0, 0, 0]}, {AbsoluteThickness[1],            CMYKColor[0.36, 1, 0, 0]}, {AbsoluteThickness[1],            CMYKColor[0.63, 0, 1, 0]}, {AbsoluteThickness[1],            CMYKColor[0, 0, 0, 1]}}           ]       /. Line[x__] :> Sequence[Arrowheads[{-.02, .02}], Arrow[x]]      ]


title: How to set the values into some variables from different lists

text: I have a list of Values and a list of variables. I want to set the Values into Variables. Assume the following code:               Values = {{1, 2}, {3, 4}, {5, 6}};     VariableS = {{x1, x2}, {x3, x4}, {x5, x6}};          VariableS[[1]] = Values[[1]];          FIntegrate = Integrate[f[x], {x, x1, x2}]      I want to use `{x1, x2}={1, 2}` and get `x1=1 and x2=2` and finally caculate the definite Integral`FIntegrate` .But I can not set the `x1=1 and x2=2`. How can I to do that ?


title: How to make this code threadsafe?

text: I have the following code, schematically:               $runningLogFile = "data.txt";          If[FileExistsQ[$runningLogFile], Get[$runningLogFile], Export[$runningLogFile, "", "Text"];];          f[x_, y_] := Block[{},         (*do some calculation*)         (*put append result to $runningLogFile*)     ]          LaunchKernels[$ProcessorCount];     DistributeDefinitions[...];      ParallelTable[f[x,y], {x, 1, 10}, {y, 0, 15}];      This code works well, except for the fact that very ocassionally (surprisingly few times in fact, but still annoying) two threads try to write the result out to `$runningLogFile` at the same time, and the results output get spliced together. Is there a way to do this in a thread safe manner? (perhaps similar to `critical` procedure in openmp)


title: How to minimize the sum of squares of deviations from the mean?

text: I am trying to minimize the sum of squares of a deviation from the mean applying the following:               Minimize[Sum[(Subscript[x, i] - \[Mu])^2, {i, 0, n}], x]      It returns the expression, but I was expecting it to return an answer similar to the one below               Sum[Subscript[x, i], {i, 0, n}]/n      which is the sample mean. Is this kind of minimization possible in _Mathematica_?


title: How to add a grid on Plot, ListLinePlot and ListPlot?

text: > **Possible Duplicate:**   >  How to insert guide-lines in graphics without specifying range? When we're using `ArrayPlot`, it's possible to draw a grid by doing:               ArrayPlot[{{1, 0, 0, 0.3}, {1, 1, 0, 0.3}, {1, 0, 1, 0.7}}, Mesh -> True]      But I can't find a way of doing it on `Plot`, `ListPlot` and `ListLinePlot`, can you help me?


title: How to plot multiple horizontal lines?

text: > **Possible Duplicate:**   >  How to insert guide-lines in graphics without specifying range? How to plot multiple horizontal lines? For instance, I want to plot 3 horizontal lines: `y=-1`, `y=0` and `y=1`. Seems to be a pretty simple thing, but I couldn't figure out how; although I've searched all over the documentation center.


title: Speeding up 2D histogram plotting (perhaps via ListDensityPlot)?

text: What would be the fastest way to take an array containing about $n=10^6$ to $10^7$ elements and plot a two-dimensional histogram with A x B bins? ListDensityPlot is taking upwards of half-an-hour. Should I be using compiled code?


title: Symbolic tensor product calculation

text: I am trying to calculate the symbolic tensor product $\langle \nabla f\otimes f,\nabla g\otimes g\rangle ^2+(\langle \nabla f\otimes g,\nabla f\otimes g\rangle +\langle \nabla g\otimes f,\nabla g\otimes f\rangle +\langle \nabla g\otimes f,\nabla g\otimes g\rangle ) \langle \nabla f\otimes f,\nabla g\otimes g\rangle +4 \langle \nabla f\otimes g,\nabla f\otimes g\rangle ^2-\langle \nabla f\otimes f,\nabla f\otimes g\rangle \langle \nabla f\otimes g,\nabla g\otimes g\rangle +8 \langle f\otimes g,g\otimes g\rangle \langle \nabla f\otimes \nabla g,\nabla f\otimes \nabla g\rangle +\langle \nabla f\otimes f,\nabla f\otimes f\rangle \langle \nabla g\otimes g,\nabla g\otimes g\rangle$               \[LeftAngleBracket]\[Del]f\[CircleTimes]f, \[Del]g\[CircleTimes]g\     \[RightAngleBracket]^2 +       4 \[LeftAngleBracket]\[Del]f\[CircleTimes]g, \[Del]f\[CircleTimes]g\     \[RightAngleBracket]^2 - \[LeftAngleBracket]\[Del]f\[CircleTimes]f, \     \[Del]f\[CircleTimes]g\[RightAngleBracket] \[LeftAngleBracket]\[Del]f\     \[CircleTimes]g, \[Del]g\[CircleTimes]g\[RightAngleBracket] + \     \[LeftAngleBracket]\[Del]f\[CircleTimes]f, \[Del]g\[CircleTimes]g\     \[RightAngleBracket] (\[LeftAngleBracket]\[Del]f\[CircleTimes]g, \     \[Del]f\[CircleTimes]g\[RightAngleBracket] + \     \[LeftAngleBracket]\[Del]g\[CircleTimes]f, \[Del]g\[CircleTimes]f\     \[RightAngleBracket] + \[LeftAngleBracket]\[Del]g\[CircleTimes]f, \     \[Del]g\[CircleTimes]g\[RightAngleBracket]) + \[LeftAngleBracket]\     \[Del]f\[CircleTimes]f, \[Del]f\[CircleTimes]f\[RightAngleBracket] \     \[LeftAngleBracket]\[Del]g\[CircleTimes]g, \[Del]g\[CircleTimes]g\     \[RightAngleBracket] +       8 \[LeftAngleBracket]\[Del]f\[CircleTimes]\[Del]g, \[Del]f\     \[CircleTimes]\[Del]g\[RightAngleBracket] \[LeftAngleBracket]f\     \[CircleTimes]g, g\[CircleTimes]g\[RightAngleBracket]      Is there any mathematica package to do this? Welcome to any help


title: How do I make framed plots the same size?

text: Suppose that I have two plots, `plot1` and `plot2`. The plots have different ranges and different axes. Here is a fictitious example that makes no scientific sense, but demonstrates my issue with the size of framed plots:               imgSize = 475;          plot1 = Plot[x^2, {x, 0, 1}, Frame -> True,         FrameLabel -> {"x (nm)", "y (nm)"},         BaseStyle -> {FontFamily -> "Arial", 20}, ImageSize -> imgSize];          plot2 = Plot[x^2, {x, -10, 10}, PlotRange -> {-10, 1000},         Frame -> True,         FrameLabel -> {"\!\(\*SuperscriptBox[SubscriptBox[\"x\", \"a\"], \     \"2\"]\) (\!\(\*SuperscriptBox[\"nm\", \"2\"]\))",           "\!\(\*SuperscriptBox[SubscriptBox[\"y\", \"b\"], \"2\"]\) (\!\(\     \*SuperscriptBox[\"nm\", \"2\"]\))"},         BaseStyle -> {FontFamily -> "Arial", 20}, ImageSize -> imgSize];          Grid[{{plot1, plot2}}]      I get this output: ![plotsize](http://i.stack.imgur.com/ZRD9n.gif) Notice that `plot1` and `plot2` are not really the same size -- in terms of the size of the outer frame of each. In particular, the outer frame of `plot1` has greater height than that of `plot2`. In addition, I think that the outer frame of `plot1` has greater width than that of `plot2`. I think this is because of the different ranges and different axis labels of the two plots. Observed separately, one probably could not discern a difference in size between `plot1` and `plot2`. But when they are next to each other, as in a `Grid`, `plot1` looks noticeably "larger" than `plot2`. This would look rather poor in a publication, like an article in a scientific journal. Is there any way that I can make the outer frames the same size, such that the plots look like they are the same size?


title: Defining a function of a distribution

text: I have a discrete- time and space markov process that I want to evolve given an initial distribution. To that, I defined               TimeP[initial_, state_, 0] := initial[state];     TimeP[initial_, state_, t_] := TimeP[initial, state, t] = TimeP[initial, state, t - 1] + ...      where the initial distribution would be something like this:               initial[state_] := 0     initial[firstState] := 1      and `...` are probabilities to jump from a state to another state. Now, with the above definition of `TimeP`, I can correctly evolve the probabilities. However, when I define another initial distribution, say               Clear[initial]     initial[state_] := 0     initial[firstState1] := 1      The function `TimeP` gets confused because it only stores the name `initial`, and not its definition (i.e. even if `initial` has now a different definition, `TimeP` returns the computed value from `initial`'s definition of `firstState`, and not `firstState1`. So, my question is: is a way of telling `TimeP` that its argument's name doesn't matter, only the actual definition that matters? Or, do you know a better way of implementing this? This is what I would expect: the function `initial` is defining a distribution, and the distribution's definition is on its probabilities. When I change `initial`'s definition to another values, `TimeP` would give another result. (I'm not using Mathematica's `DiscreteMarkovProcess` because the transition matrix is almost diagonal with most entries equal to 0, and the number of states is large).


title: How can I speed up this code？

text: There are 4 variables in this multiple sum, and only 2 are used. This question has the similar scenario as the previous one How can I speed up this code with multiple sum？, but the calculation process is different. This code takes about 1 min 38 sec to obtain the results, but I hope the time can be shortened to several seconds. Any help or suggestion will be highly appreciated! the code is bellow :               data = Table[Exp[-((i + j - 50.)/5)^2] Exp[-((i - j)/5)^2], {i, 50}, {j, 50}];     data = Chop[data, 0.00001];     data = data/Sqrt[Sum[(data[[i, j]])^2, {i, 1, 50}, {j, 1, 50}]];     ListDensityPlot[data, InterpolationOrder -> 0, Mesh -> All,  PlotRange -> All, ColorFunction -> (Blend[{Hue[2/3], Hue[0]}, #] &)]               S1[i_, j_, k_, m_, t_] := (data[[i, k]] data[[j, m]])^2 + (data[[j, k]] data[[i,        m]])^2 - 2 data[[i, k]] data[[j, m]] data[[j, k]] data[[i,       m]] Cos[(2 \[Pi]*(3*10^8)/(1584 - 5 + j*0.1 - 0.05) -          2 \[Pi]*(3*10^8)/(1584 - 5 + i*0.1 - 0.05)) t];     S2[i_, j_, t_] := 1/4*\!\(\*UnderoverscriptBox[\(\[Sum]\), \(k = 1\), \(50\)]\(\*UnderoverscriptBox[\(\[Sum]\), \(m = 1\), \(50\)]S1[i, j, k, m,        t]\)\);     data2 = Table[S2[i, j, 4*0.001], {i, 1, 50}, {j, 1, 50}];     ListDensityPlot[data2, InterpolationOrder -> 0, Mesh -> All, PlotRange -> All, ColorFunction -> (Blend[{Hue[2/3], Hue[0]}, #] &)]      ![enter image description here](http://i.stack.imgur.com/vliPJ.png)


title: Removing clipping masks from exported PDFs

text: I usually export graphics from Mathematica as PDFs which I tweak with Adobe Illustrator. When most plots are exported from Mathematica as PDFs they contain a large number of mostly useless clipping masks. See:               Plot[Sin[x], {x, -Pi, Pi}]      ![Mathematica graphic](http://i.imgur.com/iyZnY.png) https://dl.dropbox.com/u/3730003/pi.pdf All the clipping masks can be removed from this PDF with no effect on the look of the plot. Is there a way to have the PDF exported without clipping masks or somehow remove them automatically after export, ideally with _Mathematica_? Note: in some cases (see below) the clipping masks are needed but I don't need a smart solution, if I can get it of all the clipping masks, useless and useful thats fine.               Plot[Sin[x], {x, -2 Pi, 2 Pi}, PlotRange -> {{-Pi, Pi}, All}]


title: Getting Values From Quaternions

text: I'm using the Quaternion package:               << Quaternions`      Very simply, I would like to be able to get the individual components of the quaternions by themselves. My problem is, if I try               Re[FromQuaternion[Quaternion[1,2,3,4]]]      I get               1+Re[3J+4K]      I would like to isolate the components instead. Then I could get               1      ... or 2 or 3 or 4. How can I do this? **ALSO** Is it possible to convert quaternions into a vector?


title: Why is a bump function making NDSolve take forever to solve?

text: I am attempting to solve a system of relatively complicated elliptic PDEs via a relaxation technique. In particular, I am trying to solve $\textrm{div} LW = S$ where $S$ is some vector and $L$ is the operator $LW_{ij} = \nabla_i W_j + \nabla_j W_i -\frac{2}{n} \textrm{div}W g_{ij}$, essentially on the flat torus. There's a bit more complication here, but there's a function I put in at the beginning that describes the geometry of the problem. Since it's on a flat torus, it needs to be a periodic function. Even fairly complicated trig functions like $\sin(x)\cos^3(y) + \sin (z)$ or something solve in 20 or 30 minutes. However, when I put in a standard bump function, $\exp(\frac{-1}{1 - (x - 2)^2 - (y - 2)^2})$ in a circle around (2,2) and 0 elsewhere (so it's piecewise), it takes forever to solve. I left it open over the weekend and it still hasn't solved it. Any suggestions? For my code, the important bits (I think) are               vectorEquationStart =        Join[vectorEquation, {W1[time, 0, y] == W1[time, 2 π, y],          W1[time, x, 0] == W1[time, x, 2 π], W1[0, x, y] == Sin[x],          W2[0, x, y] == Sin[y], W3[0, x, y] == 0}];      which takes the equations I set up, vectorEquation, and attaches the boundary conditions I use. I am solving for W1, W2 and W3. Then               soln = NDSolve[       vectorEquationStart /. {α ->ξ}, {W1, W2, W3}, {time, 0, 10}, {x, 0, 2π}, {y, 0, 2π},        MaxStepFraction -> 1/25]      is what I try to solve. The `MaxStepFraction` is not necessarily the problem; I had another one running at the same time without it (slightly different problem, but similar) and it also has not given me an answer. The alpha in this code is a simple parameter (ξ=7/8 here). That has given be problems in previous problems if I make it too close to 1 because of how it affects the equations, but 7/8 has not given me problems before. Is there something obvious I don't know or does anyone have any suggestions on how to make this run faster? EDIT: I eventually got an answer from Mathematica, but it within 1.5 sec was up near $10^{50}$ or something. I snooped around and think that the problem may be how mathematica deals with my piecewise function near the boundary of the circle. The function is mathematically smooth, but when I tried to find the min of $1-\frac{4 e^{\frac{2}{7-4x+x^2 - 4y +y^2}} ((x-2)^2+(y-2)^2)}{(7-4x+x^2-4y+y^2)^4}$, which should be positive everywhere for my calculations to work, I got $-1.5\cdot 10^{1123214}$ or so which could account for the observed behavior of the solver. If I look at the min on a slightly smaller circle, say $(x-2)^2+(y-2)^2 <.95$, it gives a reasonable answer, about .37. Here's my code. Warning, it's about 40 lines to get down to where I actually run the NDSolve.               vecNorm[vec_?VectorQ, g_?MatrixQ] := Sqrt[{vec}.g.Transpose[{vec}]][[1, 1]]          Minkowski = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0,0, -1}}          coord = {x, y, z}          f[x_, y_] := Piecewise[{{Exp[-1/(1 - (x - 2)^2 - (y - 2)^2)], (x - 2)^2 + (y - 2)^2 <        1}, {0, (x - 2)^2 + (y - 2)^2 >= 1}}];      t is the parametrization of the graph.               t[x_, y_, z_] := α f[x, y]      X, Y, Z are the three tangent directions               X = {1, 0, 0, D[t[x, y, z], x]}          Y = {0, 1, 0, D[t[x, y, z], y]}          Z = {0, 0, 1, D[t[x, y, z], z]}      A is the normal vector.               A = {D[t[x, y, z], x], D[t[x, y, z], y], D[t[x, y, z], z], 1}          Vect = {X, Y, Z, A}          NA = Simplify[vecNorm[A, -1*Minkowski]]      (The inside of the sqrt in NA MUST be positive or else I picked a bad function t(x,y,z) to start. It SHOULD work for this t(x,y,z), but Mathematica seems to mess up at the boundary of the piecewise parts.) H is the un-normalized 2nd fundamental form, calculated using Weingarter's rule.               H = -Table[Sum[D[A[[k]], coord[[k]]]*Vect[[i, k]]*Vect[[j, k]], {k, 3}], {i, 3}, {j, 3}]      h is the normalized 2nd fundamental form.               h = (1/NA)*H      g is the metric.               g = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}} - Table[D[t[x, y, z], coord[[i]]]*D[t[x, y, z], coord[[j]]], {i, 3}, {j, 3}]      G is the inverse metric.               G = Simplify[Inverse[g]]      τ is the trace of the second fundamental form, i.e. the mean curvature.               τ = Simplify[Tr[h.G]]      dτ is then the gradient of the mean curvature. We call that gradient T               T = Grad[τ, {x, y, z}];          affine := affine = Simplify[Table[(1/2)*Sum[(G[[i, s]])*(D[g[[s, j]], coord[[k]]] + D[g[[s, k]], coord[[j]]] - D[g[[j, k]], coord[[s]]]), {s, 1, 3}], {i, 1, 3}, {j, 1, 3}, {k, 1, 3}]]      This metric Divergence only works if the X, Y, Z are coordinates. (which they are, so no worries)               metricDiv[W_?VectorQ, g_?MatrixQ , coords_?VectorQ] := 1/Sqrt[Det[g]]*Sum[D[W[[i]] Sqrt[Det[g]], coords[[i]]], {i, 3}]          metricL[W_?VectorQ, g_?MatrixQ, Christoffel_, coords_?VectorQ] := Table[Sum[g[[m, j]]*(D[W[[m]], coords[[i]]] + Sum[Christoffel[[m, i, k]]*W[[k]], {k, 3}]), {m, 3}] + Sum[g[[i, m]]*(D[W[[m]], coords[[j]]] + Sum[Christoffel[[m, j, k]]*W[[k]], {k, 3}]), {m, 3}], {i, 3}, {j, 3}] - 2/3 metricDiv[W, g, coord]*g      The trace free part of h is given below as S.               S = Simplify[h - 1/3 g*τ];          DS = Table[metricDiv[S[[i]], g, coord], {i, 3}];      We now define W, LW, etc.               W = {W1[time, x, y], W2[time, x, y], W3[time, x, y]};          testW = {W1, W2, W3};          LW = metricL[W, g, affine, coord];          vectorEquation = Table[Derivative[1, 0, 0][testW[[i]]][time, x, y] ==  metricDiv[LW[[i]], g, coord] - DS[[i]], {i, 3}];          vectorEquationStart = Join[vectorEquation, {W1[time, 0, y] == W1[time, 2 π, y], W1[time, x, 0] == W1[time, x, 2 π], W1[0, x, y] == Sin[x], W2[0, x, y] == Sin[y], W3[0, x, y] == 0}];          We now attempt to solve the PDE we just set up. ξ will be α          ξ = 7/8;          soln = NDSolve[vectorEquationStart /. {α -> ξ}, {W1, W2, W3}, {time, 0, 10}, {x, 0, 2 π}, {y, 0, 2 π}, MaxStepFraction -> 1/25]      And then, for looking at the answers:               RW = W /. soln[[1]];          pics = Table[Labeled[Plot3D[RW[[1]] /. {z -> 1}, {x, 0, 2 π}, {y, 0, 2 π}], Row[{"t = ", Pane[time, {50, 12}]}]], {time, 0, 10, .5}]; ListAnimate[pics]


title: Integrating function can't be epressed?

text: Hi I have a function in a form of * * * $$\frac{a}{x}exp(\frac{b}{\sqrt{3}-x})$$ * * * The code is               Integrate[a/x*E^(b/(3^0.5 - x)), {x, 1, 3^0.5}]      But it can't work currently, even given the value of `a` and `b`. Can it be integrated by `Mathematica`? How can I get the approximation (or if you have the method to get exact integration) and plot the diagram?


title: State "i" goes to state "j"

text: I would like to have a code that given a state "i" in S, it give the set of states "j" which are accessible from "i". Is that possible in mathematica? My state space (S) is               StateSpace = {"1", "2", "3", "4", "5"}      and my transition matrix is               transitionmatrix = {{17/25, 3/25, 5/25, 0, 0}, {5/18, 5/18, 7/18, 1/18, 0}, {4/21,       9/21, 4/21, 0, 4/21}, {0, 0, 3/4, 1/4, 0}, {3/4, 1/4, 0, 0, 0}}       And i know that a state "i" goes to "j" if in the transition matrix the value (i,j) is higher than zero. I would like something like this               If[transitionmatrix {i, j} > 0, t];      And then i will have               transitionmatrix{1,2}     true      (as 1 goes to 2)


title: How to partition a list to make each subset's size equal and mean as close as possible

text: Suppose we have 3 lists each with 18 numbers like this:               list1 = {7.49, 7.56, 7.98, 8.09, 8.16, 8.21,              8.73, 8.64, 8.68, 8.46, 8.57, 8.29, 9.38, 9.43, 8.95, 9.04, 8.9, 9.07};     list2 = {21.08, 21.18, 21.35, 21.79, 21.92, 22.15, 22.38, 22.48, 22.48, 22.51, 22.64, 22.68, 22.75, 22.8, 23.01, 23.28, 23.5, 23.54};     list3 = {36.33, 37.1, 37.19, 37.31, 37.34, 37.61, 37.88, 38.32, 38.42, 38.9, 39.06, 39.12, 39.14, 39.31, 39.39, 39.41, 39.41, 39.43};      I need to partition it into six subsets:   1. Each one with 3 numbers   2. The mean of each one is as close as possible to the others. For an example:               list = {1, 2, 3, 4, 5, 6};      Partition into 3 subsets: 1\. Each one with equal size, it sould be `Length[list]/3=2` 2\. The mean of each subset is as close as possible to the others,it should be `{{1,6},{2,5},{3,4}}` where each subset's mean is `3.5`. My objective is: `Minimize` the `MeanVariance` of all the subsets.


title: Import array indices from Excel

text: In an Excel file, I have some numbers which I will use as the indices of arrays. I want to read those numbers and assign them as the array indices in _Mathematica_. For instance, in Excel I have ![enter image description here](http://i.stack.imgur.com/8BUn4.png) and I want the rows to be imported as follows in _Mathematica_ :               {{x[[1]], x[[1]], x[[10]], x[[12]], x[[1]], x[[2]], x[[11]], x[[3]]},      {x[[1]], x[[1]], x[[12]], x[[14]], x[[1]], x[[3]], x[[13]], x[[4]]},      ... }      Link to download the excel file: http://www.datafilehost.com/d/477a157f


title: How to parse information contained in a file name

text: I have a set of files containing my data, and the file-names contain relevant information that I would like to extract. What I have is:               SetDirectory["c:\\data"]     files = FileNames["201406*.dpt"];     Take[files, 3]      > >     {"20140605_SampleName-C-vert_Polarizer0Deg.dpt", >      "20140605_SampleName-C-vert_Polarizer90Deg-Temp100K.dpt", >      "20140606_SampleName-C-vert_Polarizer0Deg-Temp10K.dpt"} >   I would like to do something like               analysis /@ files      that does something like `"%d_%s_Polarizer%dDeg-Temp%dK.dpt", date, samplestr, angle, temp` and returns `{date, angle, temp}` as in > >     {{{2014, 6, 5, 0, 0, 0.}, 0, Null}, >      {{2014, 6, 5, 0, 0, 0.}, 90, 100}, >      {{2014, 6, 6, 0, 0, 0.}, 0, 10}, ... >


title: Why does Network`GraphPlot`wrapper appear in my GraphPlot?

text: I'm making a `GraphPlot` of data similar to this:               gpd = {{node119->node109,l96},{node158->node148,l88},{node10->0,l1},{node33->node23,l32},{node30->node20,l2},{node19->node09,l91},{node157->node147,l78},{node14->node04,l41},{node15->node05,l51},{node134->node124,l47},{node131->node121,l17},{node159->node149,l98},{node31->node21,l12},{node131->node121,l17},{node92->node82,l25},{node197->node187,l80},{node11->node01,l11},{node57->node47,l73},{node190->node180,l10},{node138->node128,l87}}      When I plot the data, some subset of the labels are preceded by `Network`GraphPlot`wrapper`. Why is this? How can I get rid of it?               GraphPlot[gpd]      ![enter image description here](http://i.stack.imgur.com/05SGe.png)


title: Determination of export video runtime

text: I have a huge simulation and tried to export it as a video file (or .gif). However regardlessly what I specify under the Framerate option the video its just running for 4 seconds (too fast). When I set the framerate to one the video just consists of one picture and if I set it to 100 the video is fluid but still only 4 seconds long. Do I have to set another flag in the animation? While trying to present you some working example I came up with the following short lines:               data = Import["http://pastebin.com/raw.php?i=4Tuv8UKv", {"Data", All, {2, 3}}];     Animate[Graphics[Circle[data[[t]]],           ImageSize -> {500, 200}, PlotRange -> {{0, 100}, {-5, 5}},             Axes -> True], {t, Range[1, 1000]}, AnimationRate -> 1,             AnimationRunning -> False]          Export["test.mov", %, "FrameRate" -> 25]      So I thought that with setting the animation rate to 1 and the framerate to 25 I would get a 1000/25=40 seconds long video. Why is that not happening? Do I have to specify my frames somehow?


title: Elegant way to map a function to only the last element of each sublist

text: Suppose that I have the following list, called `test`:               test = {{{a1}, {a2, a3}}, {{b1}, {b2, b3}}, {{c1}, {c2, c3}}};      Now suppose I have an arbitrary function `g`. I would like to map `g` onto `test` such that I obtain the following list:               {{{a1}, {g[a2], g[a3]}}, {{b1}, {g[b2], g[b3]}}, {{c1}, {g[c2], g[c3]}}}      This code is incorrect:               Map[g, test, {3}]      from which I obtain:               {{{g[a1]}, {g[a2], g[a3]}}, {{g[b1]}, {g[b2], g[b3]}}, {{g[c1]}, {g[c2], g[c3]}}}      Can you please help me? Thank you.


title: Holding Input Windows

text: I am creating a Mathematica document which contains a list of proofs in various fields of Mathematics so that I can easily review whenever I would like. First, I create a large set I call 'proofs' that is of this format:               proofs={       {1, "Analysis Proof", "Hint", "Solution"},       {2, "Algebra Proof",  "Hint", "Solution"}     };      where the number represents the field of Mathematics (so I can later possibly specify the _type_ of review), the next input is the proof statement, the hint is a hint, and the solution is either a reference of where to find the proof or the proof itself. I then wrote the following function (code found below) which picks random problems from 'proofs' and asks you to prove the statement. You can then move on to the next question, ask for a hint, or see the solution. The idea is that when you ask for a hint, you can read the hint and when you click 'Ok', it gives the solution which you can read over, you click 'Okay' then it moves on to the next problem. Similarly, if you chose 'Solution', it would bring up the solution which you could read, then you would click 'Ok' and move on. If you chose 'Next Problem', you get another question. Finally, if you chose 'End Practice', it quits the review and prints how many practice proofs, i.e. the variable _i_ , you did. My question: The code works up to a point. The code I wrote does not force the program to 'wait'. Meaning, if I chose 'Hint', it gives the hint but does not wait for the user to hit 'Okay' before giving the solution and printing the next problem. Or if one chose 'Solution', it does not wait for the person to read it over before creating a new dialog box with the next question. This creates a problem of compiling text boxes that become very irritating and get in the way. What code would you need to add to make Mathematica wait before printing the next question/solution? Of course, my code may be generally very inefficient or non-practical for creating this type of program, so any advice to how I am creating this is of course welcomed!               prob[x_] := Module[{},       i = 1;            Label[begin];       p = RandomInteger[{1, Length[proofs]}];       do = ChoiceDialog[         proofs[[p, 2]], {"Hint" -> 1, "Solution" -> 2,           "Next Problem" -> 3, "End Pracitce" -> 4}];            i++;            If[do == 1, Goto[hint],        If[do == 2, Goto[solution], If[do == 3, Goto[begin], Goto[end]]]];            Label[hint];       CreateDialog[{TextCell[proofs[[p, 3]]], DefaultButton[]}];       MessageDialog[proofs[[p, 4]]];       Goto[begin];            Label[solution];       MessageDialog[proofs[[p, 4]]];       Goto[begin];            Label[end];       Print["You did", i "proof review."];       ]


title: Generating complete lists of polynomials

text: I would like to generate a list of all $3$-variable Laurent polynomials with non-negative integer coefficients using a looping construct so that I can, one-by-one, check them for specific specializations. **Of course, by "all" I mean "all within certain bounds", e.g. on the coefficients, exponents, number of terms... so long as these bounds can be flexibly changed. Any help would be greatly appreciated. **Sample input/output** : Say we want to produce all ordinary (vs. Laurent) polynomials with non-negative integer coefficients in two variables `x`,`y`, subject to: Maximum coefficient is $2$ Maximum `x` and `y` exponents are $1$ Input> `{2,1,1}` Output> `0`, `1`, `2`, `x`, `1+x`, `2+x`, `2x`, `1+2x`, `2+2x`, `y`, `1+y`, `2+y`, `2y`, `1+2y`, `2+2y`, `x+y`, `1+x+y`, `2+x+y`, `2x+y`, `1+2x+y`, `2+2x+y`, `x+2y`, `1+x+2y`, `2+x+2y`, `2x+2y`, `1+2x+2y`, `2+2x+2y`, `xy`, `1+xy`, `2+xy`, `x+xy`, `1+x+xy`, `2+x+xy`, $\ldots$, `2+2x+2xy+2y` for a total of $3^4 = 81$ items in the list. Note that they do not need to be produced in any particular order. Again, the "output" should be produced via a loop or otherwise, so that I can perform some analysis on one item of the list and then either "terminate" or move to the next item on the list. For this simplified example, an input of `{a,b,c}` will produce a list with $(a+1)^{(b+1)(c+1)}$ items.


title: Simple Question: Derivative of a path

text: I have a path `V[t_]:={3t^2,2,6t}`, and I define `F[t_]:=V[t]/Norm[V[t]]`. I simply want the derivative of `F`, which is a 3-vector function of the variable `t`. Somehow I did not manage to find any (simple?) way to calculate it.. Ideas?


title: How to restrict ListContourPlot with two criteria?

text: I use `ListContourPlot` to show exclusions in a physical parameter space. I have restrictions like `A < 5` and `B > 120`. I also have data lists in the form of `{{Input1, Input2, A, B, C, ...}, {Input,....}}`. I create lists of triplets with the inputs as x and y coordinates and the interesting quantity as a third: `AList = {{Input1, Input2, A}, {Input1, Input2, A}, ...}`. Then I simply use `ListContourPlot[AList, Contours -> {5}, ContourShading -> {None, Red}]` to create a red shape that covers the excluded area. I do this e.g. in red and blue for A and B respectively. Then I use `Show[LCP1, LCP2, ...]` to overlay them into a single plot. Now, it would be nice to also show the area that is excluded by A and B in a third color. Is there a possibility to create contours based on two criteria? I manged to get what I want, by creating a list of elements that fulfill criterion A and then plot the exclusion for B the same way as above then doing it once over with a list of elements that fulfill criterion B and plot the exclusion for A. This is cumbersome, however, so I wonder whether it is possible to do it in one step.


title: Tracking FindRoot errors in NestWhileList and Table

text: I'm solving many systems of two equations by varying the initial parameters. I'm running `FindRoot` in a `NestWhileList` where the `NestWhileList` counter allows me to alter parameter values and feed in current solutions as the start point for the next system. My `NestWhileList` index runs up to 5000 and when I run it I get 8 or 9 error messages, so far of two kinds. They are               line search decreased step size to within tolerance...          General::stop: "Further output of FindRoot will be suppressed during this calculation."      Now I'd like to know for which `NestWhileList` index was the error generated. This is a minimal working example similar to the code that I am running. In this example, I start with a start point `sol` and look for solutions. Then the counter increases, the new start point `sol` is the previous solution + the increment from the previous start point: `add`. The list `d` is some vector of parameter values.               d = {0, 0, 0, 0, 0};     sol = {0, 0};     add = {0.5, 0.5}     counter = 5;          data = NestWhileList[{#[[1]] + 1,{x, y} = {x, y} /.FindRoot[{x + y == #[[1]]*#[[1]], x- y == d[[#[[1]]]]}, {x, #[[2]][[1]] + #[[3]]  [[1]]}, {y, \#[[2]][[2]] + #[[3]][[2]]}],{x - #[[2]][[1]], y - #[[2]][[2]]}} &,{1, sol, add},Not[2 < #[[2]][[2]] < #[[2]][[1]] < 3] &, 2, counter]      Of course, this simple example gives no errors. I'd love to be able to figure out which index is (or which all indices are) generating errors so I can go look it up individually in detail and see if the error is because a solution doesn't exist or it does exist but my output is not that solution or maybe everything is fine and I can ignore the messages. I'd love it if you can tell me how this `NestWhileList` error tracker can be extended to a `Table` setting.


title: How to display equations without Mathematica simplifying them?

text: Say I'm trying to make a simple multiplication table and used               Table[i"x"j"="i*j,{i,1,9},{j,1,9}]      I'm trying to make it so that I can get a table of equations, but _Mathematica_ keeps simplifying it so that `1x2 = 2` becomes `4=x`.


title: Why am I not seeing all my graphics?

text: I write a function to simulate a trajectory,code as below:               PlaneSimulation[px_, py_] := Manipulate[     Module[     {L1, L2, θ1, θ2, c2, s2, c1, s1, RobotInverse,      RobotAera, RobotTrajectory},     L1 = 35; L2 = 16;     c2 = (-L1^2 - L2^2 + px^2 + py^2)/(2 L1 L2);           s2 = -Sqrt[1 - (c2^2) ];     c1 = -((-L1 px - c2 L2 px - s2 L2 py)/(px^2 + py^2));      s1 = -((s2 L2 px - L1 py - c2 L2 py)/(px^2 + py^2));     θ2 = ArcTan[c2, s2] // Simplify;     θ1 = ArcTan[c1, s1] // Simplify;     RobotInverse = Graphics[      {Line[{{0, 0}, {L1 Cos[θ1],           L1 Sin[θ1]}, {L1 Cos[θ1] +            L2 Cos[θ1 + θ2],           L1 Sin[θ1] + L2 Sin[θ1 + θ2]}}],       Blue, PointSize[Medium],       Point[{L1 Cos[θ1], L1 Sin[θ1]}],       Green, PointSize[Medium],        Point[{L1 Cos[θ1] + L2 Cos[θ1 + θ2],          L1 Sin[θ1] + L2 Sin[θ1 + θ2]}]},       Axes -> True, PlotRange -> {{-60, 60}, {-60, 60}},       AspectRatio -> Automatic];     RobotAera =      ParametricPlot[{L1 Cos[θ1] + L2 Cos[θ1 + θ2],        L1 Sin[θ1] +         L2 Sin[θ1 + θ2]}, {θ1, -(5/9) \[Pi],        5/9 \[Pi]}, {θ2, -(5/6) \[Pi], 5/6 \[Pi]},       AspectRatio -> Automatic, ImageSize -> 450];     RobotTrajectory =      ParametricPlot[{px /. t -> u, py /. t -> u}, {u, 0.01, t}];     Show[{RobotInverse, RobotAera, RobotTrajectory}]],     {t, 0, 18}]      **_Call the function:_** Circle:               PlaneSimulation[30 + 10 Cos[20 \[Degree] t],      25 + 10 Sin[20 \[Degree] t]]      Sine:               PlaneSimulation[30 + 10 Sin[20 \[Degree] t], t + 10]      **_However,the graphic of`RobotTrajectory` cannot show correctly?_**


title: Units, plotting and empty plots

text: maybe I'm completely newbie but I can't understand the behavior of units and the command plot. I'm doing some easy plotting of the state equation for gasses:               R =  Quantity[0.0831, ("Bars" "Liters")/("Kelvins" "Moles")];     a =  Quantity[3.658, ("Liters")^2]* Quantity[1, ("Bars")/("Moles")^2]       b = Quantity[0.0429, ("Liters")/("Moles")]     PVW[V_, T_, N_] := ((N*R*T)/(V - N*b)) - (+a*(N^2/V^2));      I then test that units are ok:               test = PVW[Quantity[0.6, "Liters"], Quantity[270, "Kelvins"], Quantity[1, "Moles"]];     UnitSimplify[test]      And I get my pressure back :               Quantity[30.1135, "Bars"]      Now I want my plot so I do :               Plot[PVW[V, Quantity[330, "Kelvins"], Quantity[1, "Moles"] ], {V,      Quantity[0.06, "Liters"] , Quantity[0.6, "Liters"]},     Frame -> True,      GridLines -> None,     LabelStyle -> {FontFamily -> "Helvetica", FontSize -> 15},     FrameLabel -> {"Volume", "Pressure"}]      If I evaluate that I get no errors, no nothing but a empty plot: ![enter image description here](http://i.stack.imgur.com/Grcl4.png) What is going on?


title: Export file with semicolon at the end of line

text: Is there a rule that tells Mathematica to set a semicolon at the end of each line (except of the last one)? My MWE is:               Export["..\\Thesis\\Hamiltonian_stark.dat",Table[j + 10 i, {i, 0, 9}, {j, 0, 9}]]      But I want something like               Export["..\\Thesis\\Hamiltonian_stark.dat",Table[j + 10 i, {i, 0, 9}, {j, 0, 9}],{EndOfLine->';/n'}]


title: Why IntegerPart[x/(x/2)]=1?

text: Consider this code               x = 0.109354682484;     IntegerPart[x/(x/2)]     (* 1 *)          Precision[x]     (* MachinePrecision *)      Why does it give 1 ? Version number: 9.0 on Mac 10.9.2 screenshot ![enter image description here](http://i.stack.imgur.com/pimhU.png) **Update:** If we use an undefined variable, `IntegerPart[x0/(x0/2)]` gives 2. Since Mathematica never gives warnings about this `x0`, I'm assuming for any `x0` it is true. If we calculate the same integer part using fortran, we get 2 instead of 1.               program main     implicit none          real(8):: x=0.109354682484     real(8):: y=1.4          write(*,*) int(x/(x/2))     write(*,*) nint(x/(x/2))     write(*,*) int(y)          end program main      compiled with ifort -O0 main.f90 output of above fortran code is                      2            2            1      according to here, int is a fortran intrinsic function that calculate the integer part. Is this a bug?


title: Breaking up combined data into several smaller data sets

text: I have one combined data with first number as the x-value and the remaining as different y-axis values (y1,y2,y3...). How do I break this combined list, data= (x,y1,y2,y3...) into smaller lists, such that data1=(x,y1), data2=(x,y2), data3=(x,y3) and so on. A sample data is provided below. There are 13 different y-values corresponding to each x-value (0.020024338, etc)               data = {{0.020024338, 0.46718468, 0.47932421, 0.4963509, 0.54065813,         0.65672949, 0.90251868, 1.3993448, 2.0366537, 2.7787049, 3.5291491,         4.1795025, 4.7176233, 5.2050893}, {0.022380134, 0.46261264,         0.47904547, 0.48048812, 0.53233204, 0.63802768, 0.87323611,         1.2855847, 1.8349797, 2.4843739, 3.0854011, 3.6431969, 4.0993234,         4.5086694}, {0.024735928, 0.46659667, 0.47086932, 0.48182777,         0.53003113, 0.60881906, 0.82828889, 1.1792591, 1.6458275,         2.1951179, 2.7178107, 3.1922793, 3.6018543,         3.9553359}, {0.027091718, 0.46147435, 0.4661452, 0.47106584,         0.51119942, 0.58587206, 0.77147002, 1.0795141, 1.5085768,         1.9689408, 2.4348231, 2.8437078, 3.2039729,         3.5031466}, {0.029447506, 0.45854677, 0.46537594, 0.4661371,         0.50055295, 0.57566797, 0.72922597, 1.006301, 1.3908136, 1.8015069,         2.2057531, 2.5789405, 2.8856884, 3.136435}, {0.031803289,         0.45134029, 0.45601075, 0.46374043, 0.49128087, 0.55187622,         0.69920774, 0.95526727, 1.2911787, 1.6753659, 2.0387226, 2.3660197,         2.6352631, 2.8969679}, {0.034159069, 0.44936824, 0.45563798,         0.46621482, 0.48637763, 0.54613861, 0.68024646, 0.91613335,         1.2340513, 1.5942974, 1.92385, 2.2354871, 2.5057308, 2.720232}}


title: Using cursors with result sets to reduce memory usage

text: I have a database table with 900,000 rows and 80 columns per row which I'd like to work with in mathematica. My computations are isolated to each row, so I'd like to stream only a single row (or small number of rows) at a time. `SQLSelect` naturally loads the entire results into memory causing a java heap error in my JDBC driver. My initial thought was to use result sets and cursor through them. However, after trying a number of approaches, the JDBC driver (PostgreSQL) and mathematica still try to load the entire results into memory, causing the JDBC driver to run out of memory each attempt. I can use `SQLExecute` to setup a cursor manually, but this loses composability. How can I force Mathematica's `SQLResultSets` to use a cursor and work in a memory efficient way? From reading the documentation I've setup my `Resultset` correctly, the only thing I can think of that might be missing is forcing `Autocommit` off, which I can't figure out how to do. Here's my code.               Needs["DatabaseLink`"];     dbconn = OpenSQLConnection[JDBC["PostgreSQL", "localhost/mydatabase"]]          (* Don't know how to turn off Auto-commit, this may be what is missing here *)     rs = SQLResultSetOpen[SQLSelect[dbconn, "mytable"],        "FetchDirection" -> "Forward", "Mode" -> "ForwardOnly",        "FetchSize" -> 100]          SQLResultSetRead[rs]          SQLResultSetClose[rs]


title: How to use LineLegend and SwatchLegend together

text: I am wondering if one can place on the right of the plot frame a single legend that is a combination of a LineLegend and a SwatchLegend. What I want is to see the line with its label on top of the swatch with its label as if the swatch was the second item of a LineLegend. I have tried                PlotLegends -> {LineLegend[{Blue}, {"first item"},           LabelStyle -> {Bold, 20}],           SwatchLegend[{Opacity[0.3, Blue]}, {"second item"}]}      and some variations with Join[] but I have not succeded to put all these legends on the right of the frame. For instance the code above places one legend on the right and one at the bottom, which is not what I want. Is this merge possible or I should write something from scratch? Thanks for your inputs, Roberto


title: ListPlot[] code for CSV file not working

text: I have a CSV file with $9$ columns. I want to plot them in the following way. Column $1$ will be along the $X$-axis. Any point $(x_i, y_i)$ of $i$-th curve in the plot will have the $x$ value from the corresponding row of column $1$ and the $y$ value from the $x$-th row of the $(i-1)$-th column. So, there will be $8$ curves in the plot. The file could be downloaded from this link. The code is:               data = Import["iso-pair-data.csv", "CSV"]; ListPlot[{data[[All, 2]],     data[[All, 3]], data[[All, 4]]}, Joined -> True, PlotMarkers -> Automatic]      I am not getting the plot as expected. Any help?


title: FindRoot equation-variable mismatch

text: I cannot figure out why `FindRoot` doesn't work and returns this error: _The number of equations does not match the number of variables in ..._ My problem: drawing ground `g`, putting a bigger circle on it.               g = With[{        p = {          {-1.088, -0.395}, {-0.572, 0.235},          {-0.138, -0.28}, {0.404, 0.145},          {0.854, -0.405}, {1.204, -0.07}}},       BSplineFunction[p]]          pr = N@With[{h = 1/GoldenRatio},        {{-1, 1}, {-h, h}}]          perp[{x_?NumericQ, y_?NumericQ}] := Normalize[{-y, x}]          Module[{R = .1, t = .2, p1},      p1 = g[t] + R perp[g'[t]];      Graphics[{        LightGray, Rectangle @@ Transpose@pr,        Gray, Line[g /@ Range[0, 1, .01]],        Black, Circle[p1, R]},       PlotRange -> pr,       ImageSize -> 300]]      ![pic1](http://i.stack.imgur.com/YS0pU.png) Now I would like to draw a smaller circle which touches the ground and the bigger circle to its left. But this produces the error:               FindRoot[      EuclideanDistance[        g[.2] + .1 perp[g'[.2]],        g[u] + .05 perp[g'[u]]] == .1 + .05, {u, .1}]


title: Generating dynamic Inputfields

text: I want to create a bunch of input fields, four in this case, one for each element of the list "x", but since `Dynamic` has `HoldFirst` it is not evaluated. Is there any way to get around this, except for declaring it by hand, or messing with strings, I played a bit with `Evaluate , and`RelaseHold`, but without success.               DynamicModule[{x = Table[0, {4}]},      Column[{        Row[Table[          InputField[Dynamic[x[[i]]], Number, FieldSize -> Tiny],          {i, 1, 4}]],        Norm[x]}       ]      ]


title: Symbolic Output after numerical computation

text: I have a small question about the symbolic output. I started to write a program that generates the coordinates of n-dimensional polytopes by Wythoff construction. For crystallographic groups, all is well, but for non- crystallographic groups, H2, H3 and H4 (5-fold symmetry) I have to use the golden ratio. The calculation operates. However, I would like the output of the golden ratio and its multiples is done by a symbol, for exemple $\tau$. There he has a way to do this without losing too much computational efficiency?               (*General setting*)     $RecursionLimit = Infinity;         SetOptions[EvaluationNotebook[],          CellEvaluationFunction ->           (ToExpression[#, StandardForm,              Function[               Null,               Module[{aborted = $Aborted},                Internal`WithLocalSettings[                 Null,                 aborted = (ReleaseHold[Most[Hold[##]]]; Last[Hold[##]]),                 AbortProtect[                  If[aborted === $Aborted,               Print["General Abort"]; Abort[]               ]]]],           HoldAll]] &)]          (*Constants*)     τ = (1 + Sqrt[5])/2;          (*Cartan Matrices*)     An[n_] :=        Which[n == 1, {2}, n > 1,         Normal[SparseArray[{Band[{1, 1}] -> 2, Band[{2, 1}] -> -1,            Band[{1, 2}] -> -1}, n]]];     Bn[n_] :=        Which[n == 1, {2}, n == 2, Normal[{{2, -1}, {-1, 2}}], n >= 3,         Normal[SparseArray[{Band[{1, 1}] -> 2, Band[{2, 1}] -> -1,            Band[{1, 2}, {n - 2, n - 1}] -> -1, {n - 1, n} -> -2}, n]]];     Cn[n_] :=        Which[n == 1, {2}, n == 2, Normal[{{2, -1}, {-1, 2}}], n >= 3,         Normal[         SparseArray[{Band[{1, 1}] -> 2, Band[{1, 2}] -> -1,            Band[{2, 1}, {n - 1, n - 1}] -> -1, {n, n - 1} -> -2}, n]]];     Dn[n_] :=        Which[n == 1, {2}, 1 < n < 4,         Normal[SparseArray[{Band[{1, 1}] -> 2, Band[{2, 1}] -> -1,            Band[{1, 2}] -> -1}, n]], n >= 4,         Normal[SparseArray[{Band[{1, 1}] -> 2,            Band[{1, 2}, {n - 3, n - 2}] -> -1,            Band[{2, 1}, {n - 1, n}] -> -1,            Band[{n - 2, n - 2}] -> {{2, -1, -1}, {-1, 2, 0}, {-1, 0, 2}}},           n]]];     En[n_] :=        If[6 <= n <= 8,         Normal[SparseArray[{Band[{1, 1}] -> {{2, 0, -1, 0}, {0, 2,               0, -1}, {-1, 0, 2, -1}, {0, -1, -1, 2}}, Band[{4, 3}] -> -1,            Band[{3, 4}] -> -1, Band[{5, 5}] -> 2}, n]],         Print["This group doesn' t exist."] && Abort[]];     Fn[n_] :=        If[n == 4,         Normal[{{2, -1, 0, 0}, {-1, 2, -2, 0}, {0, -1, 2, -1}, {0, 0, -1,            2}}], Print["This group doesn't exist. n = 4"] && Abort[]];     Gn[n_] :=        If[n == 2, Normal[{{2, -3}, {-1, 2}}],         Print["This group doesn't exist. n = 2"] && Abort[]];     Hn[n_] :=       Which[n == 2, Normal[{{2, -τ}, {-τ, 2}}], n == 3,        Normal[{{2, -1, 0}, {-1, 2, -τ}, {0, -τ, 2}}], n == 4,        Normal[{{2, -1, 0, 0}, {-1, 2, -1, 0}, {0, -1, 2, -τ}, {0,           0, -τ, 2}}], n == 1 || n > 4,        Print["This group doesn't exist."] && Abort[]]          (*Group selection function*)     selectGr[group_, dim_] :=        Which[group == "An", An[dim], group == "Bn", Bn[dim], group == "Cn",         Cn[dim], group == "Dn", Dn[dim], group == "En", En[dim],         group == "Fn", Fn[dim], group == "Gn", Gn[dim], group == "Hn",         Hn[dim]];          (*Reflection*)     reflect[vect_, group_] := Module[{dim, Gr, vectTemp},        dim = Length[vect];        Gr = selectGr[group, dim];        For[i = 1, i <= dim, i++,         vectTemp[i] =            If[vect[[i]] > 0,             FullSimplify[vect - vect[[i]]*Gr[[i]]], ## &[]];         ];        Return[Table[vectTemp[k], {k, 1, dim}]];        ];     reflectAll[vect_, group_] :=        DeleteDuplicates[        Flatten[{vect, Flatten[reflect[#, group] & /@ vect, 1]},          1], #1 == #2 &];               (*Positive elements*)     elemPos[vect_] := Positive@Max@vect;     (*elemAllPos[vect_]:=elemPos/@vect;     testPos[list1_,list2_]:=If[MemberQ[elemAllPos[Complement[list1,list2]]\     ,True]\[Equal]True,True,False];*)               (*ω-basis coordinates*)          omegaCoor[vect_, group_] := (i = 2; j = 1; vtmp[1] = vect;        While[True,         vtmp[i] = reflectAll[vtmp[i - 1], group];         If[elemPos[Last[vtmp[i]]] == False, Break[]]; i++; j++         ];         Return[{vtmp[i], group}]);          (*===============================================================================*)     (*Crash Test Dummies Zone*)     seed = {{0, 0, 1}};     coordinates = omegaCoor[seed, "Hn"];     Print[Length[coordinates[[1]]] "vertices"]     Print[coordinates[[1]]]     (*===============================================================================*)      The output will be :               (* 20 vertices *)     {{0,0,1},{0,1/2 (1+Sqrt[5]),-1},{1/2 (1+Sqrt[5]),1/2 (-1-Sqrt[5]),1/2 (1+Sqrt[5])},{1/2 (-1-Sqrt[5]),0,1/2 (1+Sqrt[5])},{1/2 (1+Sqrt[5]),1,1/2 (-1-Sqrt[5])},{1/2 (-1-Sqrt[5]),1/2 (3+Sqrt[5]),1/2 (-1-Sqrt[5])},{1/2 (3+Sqrt[5]),-1,0},{1,1/2 (-3-Sqrt[5]),1/2 (3+Sqrt[5])},{1/2 (-3-Sqrt[5]),1/2 (1+Sqrt[5]),0},{-1,1/2 (-1-Sqrt[5]),1/2 (3+Sqrt[5])},{1,1/2 (1+Sqrt[5]),1/2 (-3-Sqrt[5])},{-1,1/2 (3+Sqrt[5]),1/2 (-3-Sqrt[5])},{1/2 (3+Sqrt[5]),1/2 (-1-Sqrt[5]),0},{1/2 (1+Sqrt[5]),1/2 (-3-Sqrt[5]),1/2 (1+Sqrt[5])},{1/2 (-3-Sqrt[5]),1,0},{1/2 (-1-Sqrt[5]),-1,1/2 (1+Sqrt[5])},{1/2 (1+Sqrt[5]),0,1/2 (-1-Sqrt[5])},{1/2 (-1-Sqrt[5]),1/2 (1+Sqrt[5]),1/2 (-1-Sqrt[5])},{0,1/2 (-1-Sqrt[5]),1},{0,0,-1}}


title: How to insert a function into OptionsPattern?

text: I’ve written a function TableauForm to draw a standard Young Tableau. This problem is related to this one, however, the difficulty is that, a _function_ has to be applied to the list in my case. This is my first version code:               TableauForm [l : {{__} ..}, opts : OptionsPattern[{Alignment -> {Center, Center},FrameStyle -> Thin, Grid}]] :=        Grid[l,        Frame -> {None, None,          Thread@Rule[Flatten[Function[{a, b}, {a, #} & /@ b] @@@ Transpose[{Range@Length@l, Range /@ Length /@ l}], 1], True]},        Alignment -> OptionValue[Alignment], FrameStyle -> OptionValue[FrameStyle]];      The function works well when evaluate this:               youngTableau = {{1, 2, 3}, {4}};     TableauForm [youngTableau]      ![first output](http://i.stack.imgur.com/XB9AP.jpg) Or even this:               TableauForm [youngTableau, FrameStyle -> {Red, Thin}]      ![second output](http://i.stack.imgur.com/ggLRg.jpg) But the flaw is that if someone _doesn’t wants to show the lines_ (regardless of such a strange usage of this function) and evaluate this               TableauForm [youngTableau, Frame->None]      The output will still draw up the lines just like the first one. ![first output](http://i.stack.imgur.com/XB9AP.jpg) I’ve put the drawing function into the `OptionsPattern`, but only make it worse               TableauForm [l : {{__} ..}, opts : OptionsPattern[{Alignment -> {Center, Center},          Frame -> {None, None, (Thread@ Rule[Flatten[Function[{a, b}, {a, #} & /@ b] @@@ Transpose[{Range@Length@#, Range /@ Length /@ #}], 1], True] &)},FrameStyle -> Thin, Grid}]] :=        Grid[l, Frame -> OptionValue[Frame],Alignment -> OptionValue[Alignment],FrameStyle -> OptionValue[FrameStyle]];      Now evaluating `TableauForm[youngTableau]` will give a table with empty frame. ![](http://i.stack.imgur.com/rSK2T.jpg) To sum up and put the problem into another way, how to write a function sharing the same `OptionsPattern` with `Grid` only changing some default settings? (Note that some default settings may be a function of the parameters.) Is it possible to put a function into `OptionsPattern`, or are there any other ways to do this(plot a Young Tableau)?


title: Why do I have to perform a second ReplaceAll in this InterpolatingFunction?

text:
I have an InterpolatingFunction that I'd like to plot, and I wonder why I have to perform a `ReplaceAll` on the following function:               Plot[Evaluate[IIz[r, t] /. soln] /. t -> 5, {r, 0, 490}, PlotRange -> {{0,       490}, {.000015, -.00035}}, AxesLabel -> Automatic]`      `soln` is the solution to a differential diffusion equation given by Mathematica (v. 9.0.1) as               {{IIz[r,t]->InterpolatingFunction[{{1.*10^-8,490.5},{0.,10.}},<>][r,t]}}[r,       t]}}       When I plot the 3D solution, there is no problem in using               Plot3D[Evaluate[IIz[r, t] /. soln], {r, 0, 490}, {t, 0, 10},
 PlotRange ->       {{0, 490}, {0, 10}, {.000015, -.00035}},
 AxesLabel -> Automatic]       and I would think that all I'd need to do to plot this in terms of a fixed `t` would be to replace `t` with a constant like so:               Plot[Evaluate[IIz[r, 5] /. soln] , {r, 0, 490},
 PlotRange -> {{0, 490},       {.000015, -.00035}}, AxesLabel -> Automatic]`      However, when I input that, I get a blank plot… What gives? For the original differential equation, see this question.


title: How to declare a 3D vector variable?

text: How can I do vector calculations without telling Mathematica the vector entries? I have very many arbitrary linear combinations in $\mathbb{R}^3$ which I want to perform some general calculations on (scalar and vector products) and want to use Mathematica to do this ( _especially for simplifying stuff like very long equations with scalar prodcuts of vector products_ ). So, I don't want to write for all my vectors stuff like `v1={a1,b1,c1} ... vN={aN,bN,cN}` and so on, but just want to say `v1 ... vN` are vectors. How is this possible?


title: Sort a multidimensional list row-wise

text: Suppose I have a multidimensional list as shown below:               RandomInteger[{1,10},{3,7}]      I obtain the results: $$ \left( \begin{array}{ccccccc} 3 & 8 & 3 & 1 & 1 & 2 & 6 \\\ 9 & 1 & 9 & 4 & 2 & 3 & 5 \\\ 8 & 10 & 9 & 9 & 2 & 1 & 8 \\\ \end{array} \right)$$               I applied the function Sort[%]:      $$ \left( \begin{array}{ccccccc} 3 & 8 & 3 & 1 & 1 & 2 & 6 \\\ 8 & 10 & 9 & 9 & 2 & 1 & 8 \\\ 9 & 1 & 9 & 4 & 2 & 3 & 5 \\\ \end{array} \right)$$ But the problem is, I'm trying to sort **row-wise**. I've played around with other functions but I'm not quite getting what I want. Can someone guide me please?


title: What's the differences between the shift-enter and MakeBoxes running?

text: I know the example usages of MakeBoxes in the Tutorial like this. but I want to know a subtle distinction between (1) and (3)               gplus /: MakeBoxes[gplus[x_, y_, n_], StandardForm] :=       RowBox[{MakeBoxes[x, StandardForm],         SubscriptBox["\[CirclePlus]", MakeBoxes[n, StandardForm]],         MakeBoxes[y, StandardForm]}]      In(1)               MakeBoxes[gplus[a, b, m + n], StandardForm]      Out(1) > RowBox[{"a", SubscriptBox["[CirclePlus]", RowBox[{"m", "+", "n"}]], "b"}] In(2)               MakeBoxes[gplus[a, b, m + n], StandardForm] // RawBoxes      Out(2) > ![enter image description here](http://i.stack.imgur.com/uyfK2.png) In(3)               gplus[a, b, m + n]      Out(3) > ![enter image description here](http://i.stack.imgur.com/Nz6td.png) I had thought that if I type the In(1) then it will be like to Out(3). I want to know the diffenrences after In(1) enter typing and In(3) enter typing. When I type the shift-enter keys. what the front end mechanism does like RawBoxes to do.


title: Prepend 0 to sublists

text: My question is similar to this one, but my goal is to prepend a _single_ 0 the each sublist, not incrementally many 0's. The file I'm working is a CSV containing around 50K sublists of length 35. I've tried to `Riffle` my `Flatten[list,1]` and then `Partition` it into properly sized sublists, but the result isn't pretty - I might have to add an offset parameter. Also, I'm trying to learn how to use pure functions, so any suggestion using them will be of help!


title: How to append to a list of lists elegantly

text: I have have list of lists and I would like to be able to append an element to the start of each list. I am sure there must be an elegant solution. EG: `a` and `{{b,c},{d,e,f}}` -> `{{a,b,c},{a,d,e,f}}` If I want to apply a function to a list of lists I normally use `@@@` however I don't know how to modify this so that it gets feed into the second argument or `AppendTo`. Can someone please explain how I could achieve this?


title: Legend in a Show

text: I am trying to put some legends on a graph but I am not able to do that. This is my code:               k = 1;   (* J/K *)     T = 1;  (* K *)     nlm =       NonlinearModelFit[data, V, {M, n}, λ];     nlm["BestFitParameters"]     Show[ListPlot[data],       Plot[Normal[nlm], {λ, 0, 8}, PlotStyle -> Red],      Frame -> True, GridLines -> Automatic,       GridLinesStyle -> Directive[Gray, Dashed], AspectRatio -> 1.6,       ImageSize -> Large,      FrameLabel -> {"λ", "σ [MPa]"},       LabelStyle -> {FontFamily -> "Helvetica", 14}]      I tried to look on the internet already but I don´t understand how to do it. For example there is this discussion: Dynamic legends involving show In which it looks like the same problem of mine, but I am not able to fully understand it. I am really new with _Mathematica_ , so please consider it. Thanks, Fab. EDIT: After discussing here, this is the new code which works for me. Of course as someone told me, it is not running this piece of code because you need the data but it can be really useful to understand how to have such a picture: ![I still need to understand how to enlarge the font of the legend, but this is another problem](http://i.stack.imgur.com/nnlnx.jpg)               k = 1;   (* J/K *)     T = 1;  (* K *)          nlm = NonlinearModelFit[data, V, {M, n}, \[Lambda]];     nlm["BestFitParameters"]     lgnd = Framed[        Column[{LineLegend[{Red}, {"data"}],           PointLegend[{Blue}, {Row[{"Experiment Data"}]}]}],         Background -> LightGray];     Legended[Show[ListPlot[data],        Plot[Normal[nlm], {\[Lambda], 0, 8}, PlotStyle -> Red],       Frame -> True, GridLines -> Automatic,        GridLinesStyle -> Directive[Gray, Dashed], AspectRatio -> 1.,        ImageSize -> Large,       FrameLabel -> {"\[Lambda]", "\[Sigma] [MPa]"},        LabelStyle -> {FontFamily -> "Helvetica", 22}],       Placed[lgnd, {0.82, 0.2}]]


title: Expansion of functions in the real domain

text: When I try               FullSimplify[FunctionExpand[x^(1/12)(1/12) LerchPhi[x,1,1/12]]]      I have a nice answer with many complex numbers. Is there any way to have the expression with just real terms ? As an example, changing (1/12) by (1/4) leads to beautiful results.the argument "x" is real and (value between 0 and 1). Thanks for your help


title: An issue regarding Eigenvalues function

text: Can anybody please kindly explain to me why the members of the output vector produced by the following example are not equal to zero?               mm = 1000;     Clear[i, j, ss, EIG];     ss = ConstantArray[0, {mm, mm}];     %%% "Generating a random sparse matrix (ss)";     For[i = 1, i < (mm) + 1, i++,       For[j = 1, j < (mm) + 1, j++,         If[i == j,          ss[[i,j]] = (RandomReal[{-Mod[{i + j}, 2][[1]],Mod[{i + j}, 3][[1]]}, 1])[[1]];          ];         If[Abs[i - j] == 1,          ss[[i,j]] = (RandomReal[{-Mod[{i + j}, 2][[1]],Mod[{i + j}, 3][[1]]}, 1])[[1]]+0.2;          ];         If[Abs[i - j] == 2,          ss[[i,j]] = (RandomReal[{-Mod[{i + j}, 2][[1]],Mod[{i + j}, 3][[1]]}, 1])[[1]]-0.1;          ];         If[Abs[i - j] == 3,          ss[[i,j]] = (RandomReal[{-Mod[{i + j}, 2][[1]],Mod[{i + j}, 2][[1]]}, 1])[[1]]+0.1;          ];         ];       ];          EIG = Sort[(Select[Cases[(Eigenvalues[ss, -10]), _Real], # > 0 &]),Less];     EIG - Sort[(Select[Cases[(Eigenvalues[ss, -10]), _Real], # > 0 &]),Less]      For instance, one run of this example leaded to this vector:               {8.41341*10^-16, -2.57433*10^-15, -1.9082*10^-16, -8.32667*10^-17}      I am wondering why the output vector members are not zero! You can test this example on your PC. THNAKS.


title: Is there such a command like FindZero[f[x],{x,1}]?

text: I´d like to find the zeros of a function. I know I could find them by               Solve[f[x] == 0, x]       but that gives me only the x-coordinates. I want to get both the value of the maximum and the x-coordinate at which it occurs in the same form as the output from               FindMaximum[f[x], {x, 1}]      which returns both; e.g.,               {2, {x->3}}      Is there such a command? I´d like to use it later on to connect the zero of a derivative with the maximum of its antiderivative. Like this               Plot[{f[x], f´[x]},        Epilog->{Line[{{x /. FindZero[f´[x], {x, 1}][[2]],                       FindZero[f´[x], {x, 1}][[1]]},                      {x /. FindMaximum[f[x], {x, 1}][[2]],                       FindMaximum[f[x], {x, 1}][[1]]}}]      Well, since it´s not valid code, it doesn´t work, and I'm not sure how to write something like it that could work. I just wondered if there´s a built-in function or easily-written function to do what I label with `FindZero`? Currently, I'm using               Plot[{f[x], f´[x]},        Epilog->{Line[{{x/.FindMaximum[f[x], {x, 1}][[2]], 0},                      {x/.FindMaximum[f[x], {x, 1}][[2]],                       FindMaximum[f[x], {x, 1}][[1]]}}]      but I would be happier using the zero of the derivative. (What I do right now seems like cheating because I want to show the maxima occur at the zeros.)


title: ErrorListLogPlot gives wrong error bars on log scale

text: From this and this post I learned how to use `ErrorListLogPlot` and its family to add error bars on top of a list of mean values. However, consider this simple example:               Needs["ErrorBarLogPlots`"]          ErrorListLogPlot[{{1, 0.6}, {2, 0.5}, {3, 1.5}}, Joined -> True,      PlotRange -> {{0, 4}, {0.1, 5}},      GridLines -> {{}, {0.4, 1.5, 1.6, 2.5, 4.5}}]      ![output](http://i.stack.imgur.com/88ceX.png) where `{1, 2, 3}` are mean values and `{0.6, 0.5, 1.5}` are the associated standard errors. I added `GridLines` to indicate the positions where the end points of error bars are supposed to be located. It is clear from the plot above that the gridlines and end points do not intersect (on Mathematica 9), so the error bars must be wrong. I wonder whether something can be fixed in the `ErrorBarLogPlots` package. Note that the following examples, including built-in `ErrorListPlot`, give correct error bars (either on linear or log scale):               ErrorListPlot[{{1, 0.6}, {2, 0.5}, {3, 1.5}}, Joined -> True,      PlotRange -> {{0, 4}, {0.1, 5}},      GridLines -> {{}, {0.4, 1.5, 1.6, 2.5, 4.5}}]           ListPlot[{{1, 2, 3}, {0.4, 1.5, 1.5}, {1.6, 2.5, 4.5}},      Joined -> {False, True, True}, PlotRange -> {{0, 4}, {0.1, 5}},      GridLines -> {{}, {0.4, 1.5, 1.6, 2.5, 4.5}},      Filling -> {2 -> {3}}]          ListLogPlot[{{1, 2, 3}, {0.4, 1.5, 1.5}, {1.6, 2.5, 4.5}},      Joined -> {False, True, True}, PlotRange -> {{0, 4}, {0.1, 5}},      GridLines -> {{}, {0.4, 1.5, 1.6, 2.5, 4.5}},      Filling -> {2 -> {3}}]


title: Can I use Geronimo instead of Apache Tomcat for deploying?

text: I am using Apache Tomcat for deploying Web-Applications. I want to deploy Apps in Geronimo (also built by Apache), because it's open source and provides more features (clustering, JMS, Application Server) than Tomcat. Before installing Geronimo, I'd like to know if `webMathematica` will work with Geronimo. Has anybody tried this? Thanks * * * @All, I placed my Application folder under web-apps folder of `Apache Geronimo`,it's working great.But here I faced one problem. I made `.war` file of my Application and I tried to deploy `.war` file into `Apache Geronimo`,it shows `deployed successfully`. I open my application in browser,it's not working.I will figure out.finally webMathematica applications are working in `Apache Geronimo`.


title: Slow CreateDialog when passing image sequence

text: I'm attempting to display an image sequence of 40 images inside of a `Manipulate` that cycles through each frame with a slider. I would like the `Manipulate` to appear in a separate `DialogBox`. I see a significant performance difference if I try to encapsulate this functionality inside its own function. This code displays the dialog nearly instantaneously:               CreateDialog[       Manipulate[         imageSequence[[frame]], {frame, 1, Length[imageSequence], 1}]]      However the code below takes around 10 seconds for the dialog to appear:               showit[imageSequence_] :=        CreateDialog[         Manipulate[           imageSequence[[frame]], {frame, 1, Length[imageSequence], 1}]]          showit[imageSequence]      It does not seem to matter if the function definition is surrounded by `DynamicModule` or not. Any ideas what is going on and what I can do to improve performance while maintaining encapsulation? Thanks!


title: How does one set a logarithmic scale in a ContourPlot?

text: How does one set a logarithmic scale for both `x` and `y` axes in `ContourPlot` in _Mathematica_?


title: Customize TableForm behavior for a single function

text: I have a function of this form                   Garch[a,b,c....]       that gives me a list as an output,where the first column collects names of output variables.   Is it possible to customize `TableForm` so that when I evaluate:                   Garch[a,b,c...]//TableForm      it takes that first column and displays it as a column table heading, and the rest columns as data?   I don't want to make another function for this because I want to make it as simple as possible. The function should look something like this:                   TableForm[ Garch[a_, b_, c_, ___]] :=            TableForm[ Garch[a, b, c][[All, 2 ;; -1]],             TableHeadings -> {ToString /@ Garch[a, b, c][[All, 1]], None}]      So,I'll try to be more precise.The reason I don't want to define a new function is because in the end I want to create a compact mathematica package(this is part of my master thesis) that other students would use without learning another function. If you are familiar with RLink and the mathematica representation of data.frame object you'll understand what I mean.For example evaluate the next code:                   Needs["RLink`"]         InstallR[]         REvaluate["data.frame(a=c(1,2,3),b=c(4,5,6))"]      Now when we do                   REvaluate["data.frame(a=c(1,2,3),b=c(4,5,6))"]//TableForm      we should get the table with row names 1,2,3 and column names a,b.So I'm guessing that TableForm is somehow modified to recognize the functions in first output and show them like in the second case. Analogically to this I would like to modify the TableForm function to recognize my Garch function and do the operations you suggested.


title: Force size in pixels of plot area excluding axes and labels

text: I have a matrix where each element represents a pixel. I want to plot the matrix (possibly with `ArrayPlot`). To suppress aliasing in the final graphic (which I will then export as a png), I am currently disabling any axis, caption and so on, and I'm forcing the size of the image to match the dimension of the matrix with `ImageSize`. I get the desired result, but I need to show the axes. Is there a way to do it?


title: Graphics // Triangle // Manipulation

text: ![What I am trying to do:](http://i.stack.imgur.com/fw1Yu.jpg) I have been Mathematica user for a considerably short while. I have learned some of its functionality using wolfram how-to resources and the documentation. I am having difficulties constructing something similar as shown above. I was wondering if anyone could give me pointers to resources that would allow me to achieve visuals as presented in the image attached with this question. My objective is to use a slider to manipulate triangles height and as the slider moves text appears, color changes and values at milestones become visible. Many thanks in advance!


title: Importing Excel Spreadsheet containing Array Formulas

text: Has anyone had any success with importing an Excel Spreadsheet holding an array formula into Mathematica? The Syntax I'm using is `Import["test.xlsx", {"Sheets", "SheetWithArrayFormula"}]` The error that is returned is: Import::fmterr: Cannot import data as XLSX format. >> EDIT A sample excel file can be found here: http://temp-share.com/show/gFHKQZS0Y


title: Why selecting text in my notebook become abnormal?

text: Selecting text in one of my Notebooks becomes abnormal. Here is the unselected text: ![enter image description here](http://i.stack.imgur.com/5GvcI.png) and here is the partly selected text: ![enter image description here](http://i.stack.imgur.com/NR6Ce.png) When the text being selected, it should be like this: ![enter image description here](http://i.stack.imgur.com/I1mcr.png) What is wrong with this Notebook? my other Notebook is OK! Here is my abnormal Notebook.


title: Logical AND operation over several comparisons

text: Let x and y be arrays defined as `Array[x, m], Array[y,n]` respectively. How to generate the following function of $x$ and $y$ for variable $k$:               x[1]<y[n-k+1] && x[2]<y[n-k+2] && ... && x[k]<y[n]      Assume that $k<n$ and $k<m$.


title: Degeneracy problem at the start of a series expansion

text: I am facing the following problem : I have an equation which could write $$ F(x_1(Y))-F(x_2(Y)) = 0 $$ $x_1$ and $x_2$ are the largest and smallest roots of a cubic equation; their definition involves a function $Y$ I do not know and for which I try to have a Taylor expansion at $Y=0$. The problem is that, at $Y=0$, $x_1=x_2$ and I am stuck; no way to get anything. Any idea and suggestion will be welcomed. Thank you very much.


title: Solving a system of equations using subscripted variables

text: I want to solve this equation:               X(i, j) + C*Y(i, j) = Z(i, j)      Where               i = 2         j = 2     C = 5     X(i, j) = {{1, 1}, {1, 1}}     Y(i, j) = {{2, 2}, {2, 2}}      How can I get _Mathematica_ to solve for values of `Z(1, 1)`, `Z(2, 1)`, `Z(1, 2)`, `Z(2, 2)`? I’m relatively new the _Mathematica_ , and I’d like to solve these 4 equations, but I’d also like to be able to scale up i and j (to say, 10) without rewriting the code. Any syntax help would be very helpful. My code looks like this, but I can’t get _Mathematica_ to find the solution.               Solve[       Table[Subscript[X, i, j] - (C*Subscript[Y, i, j]), {i, 2}, {j, 2}] ==         Table[Subscript[Z, i, j], {i, 2}, {j, 2}], {X, Y, Z}]


title: How to replace a string within a selected region in a notebook?

text: I want to replace a string in a selected region/cell in mathematica notebook/package. I searched but didn' t get any result. I think it' s a quite common feature for editors/programming environments. I guess workbench has this but I don' t have access to a copy. Maybe now the best option is to use some other editor to do this, is it?


title: Issues with ColorFunction Scaling when using RegionFunction in VectorPlot

text: I was plotting a `VectorPlot` and restricting it to the physically meaningful region using `RegionFunction`. To my surprise, the result for the following code was an empty plot.               tempa = 0.2;     vectorfield = {(0.02*x y)/(x^2 + y^2)^(5/2),        1/(x^2 + y^2) (x^2 (1 - 0.008/(x^2 + y^2)^(3/2)) + y^2 (1 + 0.016/(x^2 + y^2)^(3/2)))}     VectorPlot[vectorfield, {x, -1, 1}, {y, -1, 1},       RegionFunction -> ((tempa^2 < (#1^2 + #2^2 ) < 1 && #2 < 0) &),       VectorColorFunction -> "Rainbow"]      Investigating the problem further by removing the `RegionFunction`, I realized that the probem was with the vector's value at the origin, which is very large. In fact, the following code with the RegionFunction option removed returns the following image.               VectorPlot[vectorfield, {x, -1, 1}, {y, -1, 1},       VectorColorFunction -> "Rainbow"]      ![VectorPlot with one visible arrow](http://i.stack.imgur.com/1lrvU.png) By adding the options of `VectorPoints` and `VectorScale`, I was able to display some meaningful information, as shown below.                VectorPlot[vectorfield, {x, -1, 1}, {y, -1, 1},         VectorPoints -> {20, 20}, VectorScale -> 0.5,         RegionFunction -> ((tempa^2 < (#1^2 + #2^2 ) < 1 && #2 < 0) &),         VectorColorFunction -> "Rainbow"]      ![Modified VectorPlot](http://i.stack.imgur.com/F03nP.png) Alternatively, using `VectorScale` as follows                VectorPlot[vectorfield, {x, -1, 1}, {y, -1, 1},         VectorPoints -> {20, 20}, VectorScale -> {Automatic, Automatic, If[#5 > 3, 0, #5] &},         RegionFunction -> ((tempa^2 < (#1^2 + #2^2 ) < 1 && #2 < 0) &),         VectorColorFunction -> "Rainbow"]      seems to be a better way to scale the length of the vectors, but it still doesn't help with the `ColorFunction`. ![enter image description here](http://i.stack.imgur.com/J8aXw.png) > I would expect Mathematica to scale the colors of the vectors based on the > range of norms in the `RegionFunction`. Is this not the case, or is there > something wrong with my code?


title: scatterplot from 3d table

text: I am using this code:               L = {1.5, 2.0, 2.5, 3.0, 3.5};     R = {0.0001, 0.001, 0.01, 0.1, 1, 10};     Y[a_, b_] = Exp[-b/a]/a;     ris = Table[{L[[i]], R[[j]],         NIntegrate[Y[Abs[x - 7.6], L[[i]]], {x, 0, R[[j]]}]}, {i,         Length[L]}, {j, Length[R]}]       to build a 3D table: the result of the numerical integration as a function of two parameters (L;R). Now I need to plot this with a scatter plot: the integral as a function of R, for different values of L, so, on the same plot, I need a different curve, one for each value of L. Doing:               A = ris[[1, All]]     B = A[[All, 3]]      I have the integral for L=1.5, with `A = ris[[2, All]]`, in B I have the integral for L=2, and so on: in this way I built 5 different list, and plotted them on the same graphic. How can I make this last part "automatic" and smarter? I tried a `Do` loop, but I cannot make the different curves on the same plot.


title: Move selection to next Output and export to CDF

text: In my quest to a custom "Save as HTML" (please see context here) I am now able to iterate through the notebook, grab Input cells decorated with a CellTag that, by convention, is going to be a file name of a CDF file. The CDF needs to come from the corresponding Output cell if that Input cell. For simplicity, I am assuming it is the next one. So, I am trying to `SelectionMove[nb, Next, Cell]` (* 1 *) but my debugging in (* 2 *) doesn't work and the actual export in (* 3 *) fails. See below               PaletteNotebook[      Button[Style["Blog it", 12, FontFamily -> "Times"],       Block[{         nb = InputNotebook[],         out = NotebookCreate[],         fpath = NotebookDirectory[InputNotebook[]],         generateCDF,         generateCDFs,         exportHTML         },        generateCDF[nb_, name_] := Module[{sel},          sel = SelectionMove[nb, Next, Cell]; (* 1 *)               Message[generateCDF::info, name];          NotebookWrite[out, CurrentValue[{sel, Cell}]]; (* 2 *)               Export[           FileNameJoin[{fpath, name}],           CurrentValue[sel, Cell],           "CDF"]; (* 3 *)               SelectionMove[nb, "Input", Next, CellStyle]          ];        generateCDF::info = "Generating CDF `1`";        generateCDFs[nb_] := Module[{sel, curID},          SelectionMove[nb, Before, Notebook];          sel = NotebookFind[nb, "Input", Next, CellStyle];          While[ MatchQ[sel, _NotebookSelection],           curID = CurrentValue[sel, CellID];           sel = Switch[CurrentValue[sel, CellTags],             _String, generateCDF[nb, CurrentValue[sel, CellTags]],             _, NotebookFind[nb, "Input", Next, CellStyle]             ];           ];          ];        exportHTML[nb_] := False; (* yet to be done, ignore for now *)             generateCDFs[nb];        exportHTML[nb];        ],       Appearance -> "Palette"]      ]      The Message is printing properly in the message window.