title: Bounded Voronoi Diagram

text: I am trying to compute a Voronoi diagram bounded by a box. In some cases, the points used to compute the diagram form a diagram such that at least two boundary points are within the same polygon. For Example:               centres = {{0, 1250}, {4750, 2000}, {-2500, -2500}, {500, 750}};     boundaries = {{10000, 10000}, {-10000,          10000}, {-10000, -10000}, {10000, -10000}};     {diagvert, diagval} = BoundedDiagram[boundaries, centres];      With the Voronoi diagram: ![enter image description here](http://i.stack.imgur.com/Hbg4q.jpg) This leads to the error: > BoundedDiagram::notuniq: BoundedDiagram requires that boundary vertices lie > in unique Voronoi polygons. Since I am trying to generalize the scenario, I can't design a specific boundary for the points, and I would like to use a general big enough boundary. Is there any way to allow multiple boundary points within the same polygon? Or perhaps a different approach?


title: PaneSelector and options in a Module

text: Consider the following snippet of code:                 Module[{pr, ps, var, option},        option = 1;        var = 0;        pr[] := Module[{}, var++; Print[var]];        ps[] := Print["Test..."];             PaneSelector[         {1 ->           Button["Defaults 1",           option = 2,           ImageSize -> 100],          2 ->           Button["Defaults 2",           option = 1;           pr[],           ImageSize -> 100]},          Dynamic[option]]       ]      Note that pr[] is executed when the button "Defaults 2" is clicked. **Question: I want to execute a function immediately after a Pane is selected in a PaneSelector construction. How should this be implemented?** ( Question translated to the context of the above snippet: how to execute either ps[] or pr[] immediately after setting option to 1 or 2?)


title: How to create blurred Graphics3D objects?

text: Initially I was interested in renderring a 3D analog of a blurred disk like this               DensityPlot[1 - HeavisideLambda[(x^2 + y^2)/8]/2, {x, -4, 4}, {y, -4, 4},       FrameTicks -> False, ColorFunctionScaling -> False,       ColorFunction -> "SunsetColors", PlotRange -> {0, 1},       PlotPoints -> 50]      ![enter image description here](http://i.stack.imgur.com/oxsud.png) The only idea that came to my mind was playing with `Opacity`, which gives hardly an impressive result:               Graphics3D[{Orange}~Join~        Table[{Opacity[i], Sphere[{0, 0, 0}, 1 - i]}, {i, 0.1, 1, 0.1}] //        Flatten]      ![enter image description here](http://i.stack.imgur.com/7PgYj.png) So, **1) is it possible to get "true" blurred ball and 2) how to extrapolate this idea to other 3D objects?**


title: Construct 3D image from multiple 2D images

text: My goal: How to (1) construct 3D image for visualization. (2) how to write 3D array or image into binary raw file. Is there a way to accomplish this in Mathematica? Alternative_Answer for: (1)               slices={1,2,3,4,5};     ss = Map[ImageData, slices];     ListContourPlot3D[ss, Mesh -> None, Contours -> Automatic]


title: Is it possible to simplify a trigonometric expression only in terms of $\cos (u)$ OR $\sin (u)$?

text: I want to expand the following expression into powers of $\cos(u)$ only:               a1 + a2 Cos[2 u] + a3 Cos[4 u] + a4 Cos[6 u]      The answer that I want (and which I found by hand) is :               (a1 + a3 - a2 - a4) + (2 a2 - 8 a3 + 18 a4) Cos[u]^2 + (8 a3 - 48 a4) Cos[u]^4 + (32 a4) Cos[u]^6      As you see it contains only powers of $\cos (u)$. But when I use the `TrigExpand`, which is supposed to simplify the expression into powers of trigonometric functions, it gives this:               1 + a2 Cos[u]^2 + a3 Cos[u]^4 + a4 Cos[u]^6 - a2 Sin[u]^2 - 6 a3 Cos[u]^2 Sin[u]^2      - 15 a4 Cos[u]^4 Sin[u]^2 + a3 Sin[u]^4 + 15 a4 Cos[u]^2 Sin[u]^4 - a4 Sin[u]^6      Is it possible to make `TrigExpand` to simplify only in terms of $\cos (u)$ or $\sin (u)$? (or maybe using another command instead of `TrigExpand`) By the way, It is my first _work_ done in Mathematica.


I would like to typeset the following in a _Mathematica_ notebook: $$\langle P \rangle$$ Is it possible to typeset left and right angle brackets? In $\LaTeX$, they are given by `\langle` and `\rangle`. I do not see such symbols in the documentation, but I may be overlooking them.


title: How to know at which point of a calculation I am while using Table

text: If I use a code of this type:               Table[foo[i], {i, 0, 10}]      _Mathematica_ won't output anything until it is done: is it possible to know at which point of the calculations I am, without using some slow `For` loop (in this way it would be easy to print something like `i=1`, `i=2`...)? I want to check if everything is OK at each step.


title: Cannot save array to CSV file from EvaluationMonitor[]

text: Here is my Mathematica function.               fourVertEnrgy[x11_, x12_,x13_, x14_, x21_, x22_, x23_, x24_, x31_, x32_, x33_, x34_, x41_, x42_, x43_, x44_]:=     1 + 2x11 x12 + 2x11 x13+ 2x11 x14+2x12 x13 + 2 x12 x14+ 2x13 x14 -x11 -x12 -x13 - x14 +     1+2x21 x22+2x21 x23+2x21 x24+ 2x22 x23+ 2x22 x24+ 2x23 x24 - x21 -x22 -x23-x24 +      1 + 2x31 x32 + 2x31 x33 + 2x31 x34 + 2x32 x33 + 2 x32 x34 + 2 x33 x34 -x31 -x32- x33-x34 +      1+2x41 x42 + 2x41 x43 +2 x41 x44 + 2x42 x43 + 2x42 x44 + 2x43 x44 - x41-x42 -x43 -x44 +      1 + 2x11 x21 + 2x11 x31 + 2x11 x41 + 2x21 x31 + 2x21 x41 +2x31 x41 -x11-x21-x31-x41+     1+2x12 x22 + 2x12 x32 + 2x12 x42 + 2x22 x32 + 2x22 x42 + 2x32 x42 -x12 -x22-x32-x42 +      1+2x13 x23 + 2x13 x33 + 2x13 x43 + 2x23 x33 + 2x23 x43 + 2x33 x43 -x13-x23-x33-x43+     1+2x14 x24 + 2x14 x34 + 2x14 x44+ 2x24 x34 + 2x24 x44 + 2x34 x44 -x14-x24 -x34 -x44;      I am trying to find the minima using Simulated Annealing.               destFile=OpenWrite["/home/shehab/Documents/shehab-isi/quantum-shehab/docs/presentations/lucas-gi-algo/values-"<>DateString[]]     i=0; list={{0,9999999}};      NMinimize[{fourVertEnrgy[x11, x12,x13, x14, x21, x22, x23, x24, x31, x32, x33, x34, x41, x42, x43,x44],     x11\[Element]Integers,x12\[Element]Integers,x13\[Element]Integers, x14\[Element]Integers,x21\[Element]Integers, x22\[Element]Integers, x23\[Element]Integers,x24\[Element]Integers, x31\[Element]Integers, x32\[Element]Integers,x33\[Element]Integers, x34\[Element]Integers, x41\[Element]Integers, x42\[Element]Integers, x43\[Element]Integers,x44\[Element]Integers,     0<=x11<=1,0<=x12<=1,0<=x13<=1,0<=x14<=1,0<=x21<=1,0<=x22<=1,0<=x23<=1,0<=x24<=1,0<=x31<=1,0<=x32<=1,0<=x33<=1,0<=x34<=1, 0<=x41<=1, 0<=x42<=1,0<=x43<=1,0<=x44<=1},{x11, x12,x13, x14, x21, x22, x23, x24, x31, x32, x33, x34, x41, x42, x43, x44},     Method->"SimulatedAnnealing",EvaluationMonitor:>Join[list,{{i++,fourVertEnrgy[x11, x12,x13, x14, x21, x22, x23, x24, x31, x32, x33, x34, x41, x42, x43, x44]}}]]     Export[destFile,list,"CSV"]      Close[destFile]      I am using EvaluationMonitor[] to store the function value against the step number for all the steps in a CSV file. But the file only has $0, 9999999$ when the computation is done. Did I do anything wrong?


title: How to arrange elements of a list

text: A file consists out of (x,y,z) data and I need the z-values arranged like this: `{{z[1],z[2],...z[idimx]},{z[idimx+1],z[idimx+2],...z[idimx*2]},{....}}` With               y=data[[All,2]]; z = data[[All, 3]];     iall=Length[z];     idimy=Length@Position[y,0];     idimx=iall/iy;      I get the dimensions of the array: {idimx,idimy}. But how can I now arrange it's elements? Thanks a lot.


title: Using EdgeList on a once empty Graph crashes the kernel

text: Note: this is fixed in version 9. * * * Calling `EdgeList` on a non-empty graph which was previously empty causes the math kernel to crash. For example,               EdgeList[       EdgeAdd[         VertexAdd[           Graph[{}],           {x, y}],         DirectedEdge[x, y]       ]     ]      and               EdgeList[       EdgeAdd[         VertexAdd[           VertexDelete[             Graph[{DirectedEdge[x,y]}],             {x, y}],           {x, y}],         DirectedEdge[x, y]       ]     ]      both will crash the kernel. I've recently posted this issue to the Mathematica Bug List but haven't received any response. Is this the correct place to report bugs, or should I use the contact page for WRI instead. Can other people reproduce this? Also, how could WRI possibly mess this up / not notice this? Edit: fixed second example.


title: How to construct a polyhedron from its vertex graph?

text: Consider the graph given by               graph = Graph[{2 <-> 1, 3 <-> 1, 7 <-> 1, 5 <-> 1, 6 <-> 1, 3 <-> 2, 4 <-> 3,         4 <-> 7, 4 <-> 5, 7 <-> 5, 6 <-> 5, 2 <-> 6}]      ![enter image description here](http://i.stack.imgur.com/YSTlc.png) Via Steinitz's theorem, this is the vertex graph of a convex polyhedron:               KVertexConnectedGraphQ[graph, 3] && PlanarGraphQ[graph]     -> True      **How can one construct that polyhedron (i.e. a spatial representation of it) from the graph?** Embedding the graph in 3-space using `GraphPlot3D` comes close, but does not actually build a polyhedron as the side view reveals:               GraphPlot3D[graph, Boxed -> False,          EdgeRenderingFunction -> (Cylinder[#1, .05] &),          VertexRenderingFunction -> (Sphere[#1, .1] &)]      ![enter image description here](http://i.stack.imgur.com/G8FKC.png) (Note how the quadrilateral face is "bent".) I have experimented with various embeddings such as `"SpringEmbedding"`, `"SpringElectricalEmbedding"` etc. but none of them seem to produce a true polyhedron even from this simple graph. I am aware that the polyhedron representation of a polyhedral graph is not unique (maybe not even _topologically_ unique(?)) but any embedding that is a polyhedron would suffice. The polyhedral graphs supplied in Mathematica's graph database all come with such embeddings, so I am confident this must be possible.


title: Emulating R data frame getters with UpValues

text: What's the best way to emulate R's data frames functionality? This includes the ability to select rows and columns in a 2-dimensional table by the string identifiers positioned typically in the first row or column, see this related question, (and thanks to Leonid Shifrin for cluing me to the term 'data frame.') Wrapping a 2D array in the symbol `DF` enables leveraging upvalues to essentially overload `Part` for the getters, here defined separately for singleton and list string arguments; matching uses Position. To select rows at level 1 of the array:               Part[DF[expr_], r_String, rest___] ^:=       expr[[Position[expr, r][[1, 1]], rest]]          Part[DF[expr_], r_List /; And @@ StringQ /@ r, rest___] ^:=       expr[[Position[expr, #][[1, 1]] & /@ r, rest]]      Similarly to get columns at level 2 of the array:               Part[DF[expr_], All, c_String] ^:=       Transpose[expr][[Position[Transpose@expr, c][[1, 1]]]]          Part[DF[expr_], All, c_List /; And @@ StringQ /@ c] ^:=       Transpose[expr][[Position[Transpose@expr, #][[1, 1]] & /@ c]]      These seem to work correctly (though I've not implemented preconditions checks that the header strings are at the correct level or that the array Dimension length is 2), eg given data:               data = {{"ID", "COL1", "COL2", "COL3"}, {"ROW1", 1, 2, 3}, {"ROW2", 4,          5, 6}, {"ROW3", 7, 8, 9}};      yields:               DF[data][[{"ID", "ROW1", "ROW3"}]]          (* {{"ID", "COL1", "COL2", "COL3"}, {"ROW1", 1, 2, 3}, {"ROW3", 7, 8, 9}}*)      and               DF[data][[All, {"ID", "COL2"}]]          (* {{"ID", "ROW1", "ROW2", "ROW3"}, {"COL2", 2, 5, 8}} *)      Note that this mechanism is somewhat more elegant than R, where the string arguments are wrapped in the 'c' function. Several related questions: First, these definitions raise similar errors - why?               UpSetDelayed::write: "Tag String in DF[expr_][[r_String,rest___]] is Protected."      Second - key question - how to define general getter passing row & column arguments to return a subarray, eg `DF[data][[{"ID","ROW1"},{"ID","COL2"}]]` but avoiding replicating the list and singleton combinations above? Is there an implementation of the general case that avoids the special cases?   * Arguments need not include the "ID" row or column, composing the row getter followed by column getter, or vice versa, won't work directly.   * Note the asymmetry and limitation between the methods to access rows and columns: the row accessor is more general since All can be passed as a special case, but also numeric parameters and Spans. Finally, can the UpValues mechanism be used to emulate other data frames functionality? Would it be possible to use as setters? Also, Apparently in R data frames are used to query the data with conditionals. **EDIT** Note, given the comments on computational complexity and scalability, I would like to stress that the primary purpose of this approach is to deal with small to medium datasets imported from Excel, where string headers, unlike RDBMS, are not separated as metadata. In many data analysis applications, for example biomedicine and healthcare, Excel-based workflows are the norm (for input data, intermediates and output). Moreover, query (and statistical) development time dominates execution time. So syntax and modular approaches to data frames outweigh computational complexity considerations.


title: Creating multicolored meshed plots (connected scatter plots) using ListPlot

text: I would like to make colored scatter plots where the dots are connected by lines. I have tried the following, using `Joined->True` to connect the dots and `Mesh->Full` to actually show the dots. I have tried using both `PlotStyle` and `MeshStyle` to color the lines and dots, respectively:               data1 = {{0, 1}, {1, 2}, {2, 3}};     data2 = {{0, 2}, {1, 3}, {2, 4}};     data3 = {{0, 3}, {1, 4}, {2, 5}};          ListPlot[{data1, data2, data3}, PlotRange -> All, Joined -> True,       Mesh -> Full, PlotStyle -> {Red, Green, Blue}, MeshStyle -> {Red, Green, Blue}]      which gives ![ListPlot](http://i.stack.imgur.com/6qaEZ.gif) Why are _all_ of the dots blue? I would like their colors to match those of the lines (`data1` should be red, `data2` should be green, and `data3` should be blue). Is this possible? Thank you!


title: Problems with setting style options

text: Consider the following:               FirstOutput=Style["Test", FontSize -> 20]          SetOptions[Style, FontSize -> 20];     SecondOutput=Style["Test"]      I would like the string `"Test"` to appear in `SecondOutput` as in `FirstOutput`. Why does `SetOptions[Style, FontSize -> 20]` not apply to `SecondOutput`? Does anyone have an idea?


title: Automatically sending to Print (using CutePDF Writer)

text: I use CutePDF for creating PDF output, but this requires manually selecting Print (Ctrl+P), with CutePDF Writer as the printer, and pressing OK. Can this be automated?


title: Why does Mathematica give an incorrect answer to this multiple integral?

text: This is not a new problem but I would like to understand why Mathematica gives the result that it does. (Volume of a hypersphere)               In[4]:= Integrate[       Boole[x1^2 + x2^2 + x3^2 + x4^2 + x5^2 + x6^2 < r^2], {x1, -Infinity,       Infinity}, {x2, -Infinity, Infinity}, {x3, -Infinity,        Infinity}, {x4, -Infinity, Infinity}, {x5, -Infinity,        Infinity}, {x6, -Infinity, Infinity}, Assumptions -> {r > 0}]          Out[4]= -(1/6) \[Pi]^3 r^6      A negative answer is obviously incorrect. Replace r^2 by 4               In[3]:= Integrate[       Boole[x1^2 + x2^2 + x3^2 + x4^2 + x5^2 + x6^2 < 4], {x1, -Infinity,        Infinity}, {x2, -Infinity, Infinity}, {x3, -Infinity,        Infinity}, {x4, -Infinity, Infinity}, {x5, -Infinity,        Infinity}, {x6, -Infinity, Infinity}, Assumptions -> {r > 0}]          Out[3]= (32 \[Pi]^3)/3      This is correct. If we reduce the number of variables, then we obtain a correct answer:               In[5]:= Integrate[       Boole[(x1^2 + x2^2 + x3^2 + x4^2 ) < r^2], {x1, -Infinity,        Infinity}, {x2, -Infinity, Infinity}, {x3, -Infinity,        Infinity}, {x4, -Infinity, Infinity}, Assumptions -> {r > 0}]          Out[5]= (\[Pi]^2 r^4)/2


title: Setting default Mathematica version

text: Is there a way to set the default Mathematica version? I would like to run both versions 7 and 8 (on a Win7 PC), but when version 8 is installed it takes priority. Clicking on a notebook automatically opens in version 8. What can I set to make version 7 the default?


title: Manipulating horizontal and vertical 'guidelines'

text: Is it possible to create an interactive plot that has drag-down / across horizontal & vertical guides a la Illustrator / InDesign? I would like to generate something like this: ![enter image description here](http://i.stack.imgur.com/pt5pG.gif) I would ideally like to drag multiple (unlimited?) horizontal and vertical guide lines, which would then stay in the positions that they are left in. In addition (if it is not asking too much!) I would really like the guidelines to 'snap' to integers as well. I have looked at various locator manipulations, with no success. Apologies for not including my _Mathematica_ coding effort, but I don't really know where to start with this one :/


title: Finding the linear regression of data and plotting it

text: This is for a physics report that I have to hand in. I have a list of two- dimensional data points that approximately form a linear line. I want to:   1. calculate the best linear fit.    2. put both data points and the linear fit line on a plot   3. put names and units on x and y axis   4. (if possible) put slope and intersection of best fit on plot Is it possible to do this in _Mathematica_ and if so how? Example data:               Time, Displacement              t (s)   d (m)         0       0         1       1.9         2       3.8         3       5.9         4       8.1         5       10.1


title: Replacements/Substitutions in Mathematica

text: I am a new user of Mathematica and have some questions about the simplifications of calculated expressions. I am unable to attach an image of the session, but my Mathematica commands are:               Element[{x,y,z},Reals]      Element[{x0,y0,z0},Reals]     rhatV={x-x0,y-y0,z-z0}     rhat=Norm[rhatV]      In the expression for rhat, I am unable to get rid of the `Abs` functions, despite the Reals declarations.               phi=1/rhat     D[phi,x]      In the evaluated derivative is there a way to have x-x0 in the numerator recognized as rhatV[[1]] and the denominator as rhat^3, such that it can be used in additional operations?


title: Selective evaluation of blocks of code in a Manipulate

text: Is it possible to attach certain pieces of code to certain controls in a Manipulate? For example, consider the following Manipulate               Manipulate[      data = Table[function[x], {x, -Pi*10, Pi*10, Pi/1000}];      ListPlot[{x, data}, PlotRange -> {{start, stop}, Automatic}]      , {function, {Sin, Cos, Tan}}      , {start, 1, Length[data]}      , {{stop, 300}, 1, Length[data]}      ]      Generation of the data is expensive but it only needs to be done if I change function. So, I'd like the line               data = Table[function[x], {x, -Pi*10, Pi*10, Pi/1000}];      to only run when I change the function control...i.e. I want to attach that line of code to the 'function' control. As it stands, the data is generated when I move the plot range too which is not what I want. ![enter image description here](http://i.stack.imgur.com/OHJeN.png)


title: Detect highest order of derivative in expression?

text: Is it possible to detect the highest order (or generally all orders) of derivatives in an expression? Consider               eqn = D[a[x,t],t] == D[a[x,t],x,x]      How would I go about detecting that the highest order of the partial derivative in x is 2 in eqn? I was thinking of using MatchQ, however this               MatchQ[Derivative[2, 0][a][x, t], eqn]      just returns False. Thank you!


title: Restrict Sensitivity of Locators in LocatorPane

text: We can restrict the **movement** of locators in a `LocatorPane` as follows: ![locator movement](http://i.stack.imgur.com/Is904.png) In the following example, the first locator's movement is confined to the x-axis and the second locator's movement is confined to the y-axis.               Manipulate[LocatorPane[Dynamic[pts],       Graphics[{}, PlotRange -> max, Axes -> True, ImageSize -> 350],      {{{-max, 0}, {max, 0}},      {{0, -max}, {0, max}}}],     {{pts, {{9, 0}, {0, 11}}}, ControlType -> None}, Initialization :> {max = 25}]      ![enter image description here](http://i.stack.imgur.com/NvUL8.png) However, a locator can be dragged without necessarily being selected. You can begin dragging a locator by clicking down on just about any point in the four quadrants and dragging from there. I would like to have the locator respond only to drags that are initiated by "mousedown"ing on the locator itself. Any ideas as to how I might achieve this? * * * **Addendum** In my the more complicated example I've been working with, I've made use of jump parameters to confine locators to integer values:               {{{-maxX, 0}, {maxX, 0}, {1, 0}},     {{0, -maxY}, {0, maxY}, {0, 1}}}      I'm not sure whether such constraints (to integers) can be imposed on locators outside of `LocatorPane`s.


title: How to obtain an approximate function for SmoothHistogram3D?

text: I have a random distribution of points in the $x\\!-\\!y$ plane. I can obtain a graphical representation of the probability distribution function using `SmoothHistogram3D`. Now I need to use this in another calculation. To do this I need a function that approximates `SmoothHistogram3D`. Could you please tell me how to do it?


title: How can I fill under a function in a plot just to right of a specified vertical line?

text: How do I plot a normal curve with filling under the curve and to the right of a vertical line. I would prefer that the vertical line starts at the x-axis and stops at the plotted curve. Basically trying to shade the area under the curve for a specific region.


title: Is there a version of Together that doesn't cancel common factors?

text: I'm running code that produces a long combination of rational functions with free constants that need to be tuned such that the combination vanishes. My current method is to put the combination over a single denominator with Together[], then look at the CoefficientArrays[] of the numerator and make sure all entries vanish. The trouble is, the step using Together[] is very time consuming, and seems in some cases to get stuck (basically, the process just runs the CPU with a fixed memory usage for hours, when normally Together has a pattern of rising and falling memory usage as it shrinks the expression it creates). My assumption is that the problem with using Together in this context is that it doesn't just put everything over a single denominator, it also tries to factor out common terms. But I don't _need_ it to factor out common terms, since a failure to factor something will just mean a few more redundant equations to solve. Is there anything like Together, that doesn't bother with trying to cancel things? Or an option to make Together give up after a certain (reasonable) amount of time? Edit: To those suggesting just multiplying through by the product of the denominators, one issue is that not all of the objects are expressed as P/Q. So for example, say I have:               (1/(1-v)-v/(1-w))/((1-v)(1-u)) - (1-w)/(u v w(1-v))      I want this expressed as one object, P/Q, and I don't care about canceling common factors between P and Q. Is there a function that does that? I suppose I could just repeatedly multiply through by all denominators for each subexpression, but that seems inefficient.


title: How to plot points with uncertainties and dates assigned?

text: I want to plot a graph from list of points, but each point also has uncertainty assigned AND date. Without uncertainties DateListPlot works great, without dates ErrorListPlot works OK, but how it could be done both at the same time? I tried displaying 2 plots (DateListPlot + ErrorListPlot) using Show, but it didn't work. Any ideas?


title: Shortcuts for integration and differentiation?

text: I am trying to learn the most useful keyboard shortcuts for doing basic operations such as integration, differentiation etc in standard form. A few questions -   1. I have checked the documentation and i found shortcuts such as Esc[intt]Esc for an integral and Esc[dintt]Esc for definite integral in standard mathematical form but i can't find a short cut for a standard derivative i.e d/dx ? I am aware you can use D[] function but i would like to be able to input in standard mathematical form. Esc[dt]Esc gives me a partial derivative but i just want standard d/dx for single variable calculus.   2. If i enter a indefinite integral and i want to change this into a definite integral is there anyway i can add the upper and lower limits or do i need to re-enter the whole integral using Esc[dintt]Esc ?  Thanks David.


title: curve on the surface

text: I have a bezier polygon aa=Table[{i^2.5, 2*Sqrt[i]}, {i, 1, 5}],is anyone can give me a example in Mathematica code that how to create another iso parametric curve on this bezier surface?Display the control polygon of this iso curve and the iso curve on the surface.


title: Using Multiple Kernels When Making Plots

text: I am running a notebook that makes multiple plots. I define a function and then I want to plot that function for different choices of parameters, using `RegionPlot`. Given the complexity of the function (which is why I'm not copying the code here), it takes ~2 hours to make each plot, and I need about 20 separate plots. Since the plots are completely independent of each other, this seems like the sort of thing that should be parallelized. This is my goal. I've figured out how to launch the subkernels and how to move the definition of the function to the subkernels using `DistributeDefinitions`. (Sorry if that's not quite the right terminology.) I've been trying to use the subkernels like this (pseudo-code):               ParallelSubmit[RegionPlot[* code with function[x,y,z] here *]]          ParallelSubmit[RegionPlot[* code with function[a,b,c] here *]];      However, it seems to me that the `ParallelSubmit` doesn't actually get evaluated until `WaitAll` is called, and I can only find a way to apply `WaitAll` to one of the two instances above; hence, I still end up evaluating them sequentially, which is not what I wanted. So my question is this: what is the easiest way to parallelize the production of plots (for different parameters) in _Mathematica_? Thank you in advance for all your help! It occurred to me that perhaps an example will help to clarify:               f[x_,y_,z_]:=x^2+y^2+z^2;     DistributeDefinitions["Global`"];            (* I do have a back tick on the Mathematica code but I'm revising this on my phone which      can't type one. *)     ParallelSubmit[RegionPlot[f[x,y,1]>5,{x,-10,10},{y,-10,10}]];     ParallelSubmit[RegionPlot[f[x,y,2]>5,{x,-10,10},{y,-10,10}]];      How can I run `WaitAll` so both `ParallelSubmits` evaluate at the same time? *** Clarification: *** I should have realized that my "simplified" example is amenable to using ParallelTable, whereas (so far as I know) my actual function is not. The reason being that I have two variables that I want to substitute, and I don't want all combinations of them. Let me try to explain with a revised version:               f[x_,y_,z_,w_]:=x^2+y^2+z^2+w^2;     DistributeDefinitions["Global`"];          ParallelSubmit[RegionPlot[f[x,y,1,1]>5,{x,-10,10},{y,-10,10}]];     ParallelSubmit[RegionPlot[f[x,y,2,2]>5,{x,-10,10},{y,-10,10}]];      When you run a table with the indices like `{i,1,2},{j,1,2}`, you get four entries: `i=1,j=1`, `i=1,j=2`, `i=1,j=2` and `i=2,j=2`. This is not what I want; it would increase the number of plots made dramatically. I tried making a table with `{{i,j},{1,1},{2,2}}`, but that gives the expected error that iterator does not have the expected bounds. Thanks for all the help!


title: Random Choice: List Format & Minimizing Memory Use

text: This is a two part question, and for that I apologize.. but they're related! Here's what I'm working with:               d1 = Import["file.CSV", "List"]          size = Length[d1]          dis1 = RandomChoice[{d1}, {100, size}]        * **Q1** : Length views `d1` as $300,000$ individual elements but `RandomChoice` views it as a single element. Thus when I execute I get $100$ repetitions of `d1` in the exact order `d1` is presented in.  Have I made an annotation error in assigning the `RandomChoice` number pool as `{d1}`? If I replace `{d1}` with a hand written list of values it executes perfectly, so I assume it is a presentation issue.. but I can't tell what I've done wrong from the documentation of the function.   * **Q2** : Asking to make $100$ random lists of `size` ~ $300,000$ elements requires a lot of memory. The thing is I don't need to save each `RandomChoice` output, I just need the mean/median/SD/SEM for each of the $100$ sets I've tasked `RandomChoice` with.  Is there a way to tell the program to spit out those end-point values and dump the accumulated list after each one is generated?


title: How can I add options to functions

text: One wish take easy advantage of the packages/codes buildt through our engagement with mathematica. Through building packages I see that I have made several functions which are simple and closely related. However, I would prefer one function with several options instead of many simple. I therefore wish to make a collection of ideas and examples, could be your own code, code located on this page or any other that show good practice of adding options to functions. Efficient smart/neat solutions that can be extended to arbitrarily large functions is appreciated. It is also easier to remember how to use the custom functions if they reassemble built in functions.I wish to provide an example Stefans answere of how an expansion where you can query certain properties using a string, very similar to LinearModelFit, even though I would assume that the code behind is very very different. Hopefully answer to this question would help the reader get an idea of how one can expand and add functionality to one function in a good way. I sure know that good examples definitely would help me. I would like to point out that any change/edit of the question that would increase its usefulness is appreciated!


title: Requiring NumericQ in Pure Function

text: Potential duplicate, but doesn't seem to solve my problem: Using patterns in pure functions I have a function that returns an `InterpolatingFunction`, and it works exactly the way I needed for passing to `NIntegrate` etc.: if I pass on a symbolic argument, the function returns itself; if the argument is numeric, it evaluates and gives a number.               func := Module[{...}, ... (y /. First@NDSolve[{y[1] == 1, y'[x] == x}, y, {x, -1, 1}])]     func[x] (* gives InterpolatingFunction[(-1. 1.),<>](x) *)     func[0.5] (* gives 0.625 *)       I need a slightly modified behavior: the returned function should return 0 if outside the range instead of attempting to interpolate. Seems easy enough:               func := Module[{interpolation,...}, ...             interpolation = (y /. First@NDSolve[{y[1] == 1, y'[x] == x}, y, {x, -1, 1}]);             Function[x,If[Not@IntervalMemberQ[Interval[interpolation[[1, 1]]], x], 0,                      interpolation[x]]]]     func[0.5] (* gives 0.625 *)      func[2] (* gives 0 since it's outside the interpolation interval *)     func[x] (* gives 0!! *)      How can one mimic the behavior of `InterpolatingFunction` such that `func[x]` for non-numeric `x` gives something like `Function[<>](x)` instead?


title: Centering date labels over the year in a DateListPlot

text: The canonical formatting for date labels in a `DateListPlot` is for the year or other date label to be centered over the tick at the start of the relevant period.               aapl = FinancialData["AAPL", {2000}];     DateListPlot[aapl, Joined -> True]      ![canoncial DateListPlot of Apple share price](http://i.stack.imgur.com/qWxK5.png) I would like the label to instead be centered on that year, like this. ![annual date labels, centered](http://i.stack.imgur.com/Ig28Y.png) Relevant facts:   * I know the font family and size I am using, so specifying offsets for `AdjustmentBox`es can be fixed explicitly.   * Custom functions for the plot are ok, especially if that is necessary to work out how many years there are in the data and therefore how far to offset an `AdjustmentBox`.   * I am assuming that the solution is a custom auxiliary function that can be passed to the `FrameTicks` option. I would be interested to know if that can be specified using `SetOptions` for `DateListPlot` instead of doing a custom plotting function.   * If there are a lot of years in the data, it is ok to specify explicitly that only every $x$th year label is shown. (We have explicit rules for the mapping from number of years to $x$).   * The partial last year can be specified explicitly by the user. The default would be to show the full year even if there is only a little bit of data for it. I already have something that works but would be interested in how other people approach it, to see if I can make my solution faster/ more elegant/ more concise. Currently it is a big mess because year labels are not the only option I have implemented.   As a bonus, please consider how one would implement labels like this: ![two-row date labels](http://i.stack.imgur.com/h2TBH.png)


title: CUDA 5.5 and Mathematica 9 code problem

text: In Mathematica 9, I entered the following sample code, but it returns an error. I can not figure what is not right. Any help?               CUDACCompilers[]          {{"Name" -> "GCC",        "Compiler" -> CCompilerDriver`GCCCompiler`GCCCompiler,        "CompilerInstallation" -> "/usr/bin", "CompilerName" -> Automatic}}          doubleFun = CUDAFunctionLoad["       __global__ void doubleVec(mint * in,  mint length) {           mint index = threadIdx.x + blockIdx.x * blockDim.x;              if (index < length)           in[index] = 2*in[index];         }", "doubleVec", {{_Integer}, _Integer}, 256,        ShellOutputFunction -> Print]          CUDAFunctionLoad::cmpf: The kernel compilation failed. Consider setting the option "ShellOutputFunction"->Print to display the compiler error message. >>          gcc: error trying to exec 'cc1plus': execvp: No such file or directory          CUDAFunctionLoad["      __global__ void doubleVec(mint * in,  mint length) {          mint index = threadIdx.x + blockIdx.x * blockDim.x;              if (index < length)           in[index] = 2*in[index];        }", "doubleVec", {{_Integer}, _Integer}, 256,       ShellOutputFunction -> Print]


title: How well does Mathematica code exported to C compare to code directly written for C?

text: Essentially what it says in the title. Mathematica can, IIRC, export it's code to C. How much overhead does that inflict on the code, as compared to writing it from scratch in C?


title: Connect to a MS Access database (*.accdb)

text: The _JDBC Connections_ section of the help file http://reference.wolfram.com/mathematica/DatabaseLink/tutorial/DatabaseConnections.html gives me the impression that I can connect to a MS Access Database (*.accdb) using the following statements:               << DatabaseLink`;     conn = OpenSQLConnection[JDBC["odbc", "MTData.accdb"]];      where _MTData.accdb_ is the name of my database. I have verified that the file does exist using `FileNames[]`. Upon executing the statements above, however, I receive the following error message: > JDBC::error: "[Microsoft][ODBC Driver Manager] Data source name not found > and no default driver specified ...". Typing `JDBCDriverNames[]` gives a list with " _Microsoft Access(ODBC)_ " Would somebody please be able to clarify whether I should be able to access a MS Access database using these statements? Thanks. **EDIT:** I have also tried accessing the database by providing a DSN (Data Source Name), created by opening the ODBC Source Administrator (as I have a 64-bit operating system, but 32-bit Office, I used the program at location C:\Windows\SysWOW64\odbcad32.exe). Executing the following code, where "MTDB" is the DSN: `conn = OpenSQLConnection[JDBC["odbc", "MTDB"]];`, I get the following error message: > JDBC::error: [Microsoft][ODBC Driver Manager] The specified DSN contains an > architecture mismatch between the Driver and Application


title: How can I compile function with Apply?

text: For example, I tried to compile this function but Mathematica gives "The only function arguments supported are Times, Plus, or List", I have no a way to compile this.               isPrime = Compile[{{n, _Integer}},       And @@ (Mod[n, #] != 0 & /@ Range[2, Sqrt@N@n])       ]


title: Solving a nasty equation

text: Here's an equation that I need to solve for $t_k$ $$ \theta_0 = \tan^{-1}\left(\frac{2(w_x - m)}{p - g {t_k}^2 - 2 t_k w_y}\right) - {\frac{1} {r}} \left( \left(\frac{m}{t_k}\right)^2 + \left( \frac{p - g {t_k}^2}{2t_k} \right)^2 \right) $$ All other variables ($m,p,r,g,w$) are constants. _Mathematica_ **fails** solve it with the constants in place, but **succeeds** when the actual values are substituted in, so I know it's **possible**. Unfortunately, I need the general form for a computer program. I'm certain it's failing due to the $tan^{-1}$. So is there a way to convince _Mathematica_ that the $tan^{-1}$ won't do anything funky on the interval in which I'm interested and just solve for the general case? Here's the code.               ass[c_] := c /. {p -> -400, g -> -4/50, m -> -300, a -> 0.45/50, r -> 27, u -> -2.3, v -> 0}     vx[t_] := (m/t) - u     vy[t_] := (p - g t^2)/(2 t) - v     rat[t_] := Simplify[-vx[t]/vy[t]]     ksq[t_] := (vx[t])^2 + (vy[t])^2     wholeWeak[t_] := ArcTan[rat[t]] - 1/(2 r^2 a)*ksq[t]


title: Plotting ErrorBars with a different style

text: I would like to plot the error bars of `ErrorListPlot` with a different style than the points. I know of `ErrorBarFunction`, but then I have to recreate the automatic ErrorBarFunction... Here is my current butt ugly hack (I draw the plot twice):               data = Table[{x, f[x], RandomReal[]}, {f, {Exp[2 #] &, Exp}}, {x, -5, 2, 0.2}];     Needs["ErrorBarPlots`"]          Show@{ErrorListPlot[data,         PlotStyle -> Directive[Thick, PointSize -> 0., Opacity@0.5],         ImageSize -> Large],       ListPlot[data[[All, All, {1, 2}]],         PlotStyle -> Directive[Thick, PointSize -> 0.015],         ImageSize -> Large]       }      ![example plot](http://i.stack.imgur.com/dJKmN.png) **What is a more elegant way of doing this?** Something like:               ErrorListPlot[data,             PlotStyle -> Directive[Thick, PointSize -> 0., Opacity@0.5],             ImageSize -> Large,            ErrorBarFunction -> {Opacity@0.5,Automatic}]


title: nonlinearnodelfit with a matrix as weights

text: I have to fit a non linear model to my data and I am trying to use `nonlinearmodelfit`. The problem is that I have systematic errors, so the `weights` options is not a simple vector but a matrix. To be clear: my chi squared is written as:               (diff)T*(weight)^(-1)*(diff)      Where `diff` is the difference between my model and the data (T means trasposed). Does anyone have any idea? I use Mathematica 8.


title: I integrate a real function, I want a real result

text: I want to count some integral in _Mathematica_ (actually, check that this integral is zero...) I arrive to an answer which has a zero real part but has some imaginary part! Why? This could be a mistake but I suppose that I am not writting down the commands correctly... What do you think?               r[ϕ_] = 2*(1 - (1/3)^2)/(1 + (1/10) *Cos[ϕ])          Integrate[(Sqrt[(r'[ϕ])^2 + r[ϕ]^2])/(Sqrt[2 (-1 + 1/(r[ϕ]))]), {ϕ, 0, 2 π}]      _Mathematica_ gives the following answer > >     0.` - 13.028165432276161` I >


title: Symbolic Integration along contour: branch cut problem?

text: **Context** Following this question on path integrals in the complex plane, having defined again a numerical and symbolic integrator along a path as                ContourIntegrate[f_, par : (z_ -> g_), {t_, a_, b_}] :=         Integrate[Evaluate[(f /. par) D[g, t]], {t, a, b}]      and                NContourIntegrate[f_, par : (z_ -> g_), {t_, a_, b_}] :=         NIntegrate[Evaluate[D[g, t] (f /. par) /. t -> t1], {t1, a, b}]      when I try on this path               ParametricPlot[Cos[t] + I (Sin[t] + Cos[2 t]/2) // {Re[#], Im[#]} &, {t, 0, 2 Pi}]      ![Mathematica graphics](http://i.stack.imgur.com/00B0E.png) I get numerically (note that I divide by $2\pi \imath$)               NContourIntegrate[1/x, x -> (Cos[t] + I (Sin[t] + Cos[2 t]/2)), {t, 0, 2 Pi}]/(I 2 Pi)           (* 1. *)      and symbolically (after a couple of minutes)               ContourIntegrate[1/x, x -> Cos[t] + I (Sin[t] + Cos[2 t]/2),          {t, 0, 2 Pi}]/(I 2 Pi) // N // Chop          (* 1.57088 *)      which suggests a branch cut problem in the symbolic solution(?) I have evaluated numerically the result of the above integration as it is a couple of pages long. ![Mathematica graphics](http://i.stack.imgur.com/8muIG.png) Note interestingly that this result is only equal to $\pi/2$ up to 4 digits! **Question** > Could anyone please reproduce what seems to be a bug?


title: Making a fit to my empirical data

text: I want of plot the fit for the graph ![enter image description here](http://i.stack.imgur.com/dLDYl.jpg) The Data for this graph is               {{0., -0.2203}, {0.034, -0.2075}, {0.067, -0.2006}, {0.1, -0.197},      {0.134, -0.1936}, {0.167, -0.189}, {0.2, -0.1855}, {0.234, -0.1802},      {0.267, -0.1704}, {0.301, -0.1678}, {0.334, -0.1573}, {0.367,      -0.1532}, {0.401, -0.1428}, {0.434, -0.1372}, {0.467, -0.1334},      {0.501, -0.1274}, {0.534, -0.1191}, {0.567, -0.111}, {0.601,      -0.1109}, {0.634, -0.1122}, {0.668, -0.1121}, {0.701, -0.1174},      {0.734, -0.1178}, {0.768, -0.1163}, {0.801, -0.1133}, {0.834,      -0.1132}, {0.868, -0.1077}, {0.901, -0.1028}, {0.934, -0.0994},      {0.968, -0.0977}, {1.001, -0.0929}, {1.035, -0.0913}, {1.068,      -0.0892}, {1.101, -0.0867}, {1.135, -0.0869}, {1.168, -0.085},      {1.201, -0.0847}, {1.235, -0.0822}, {1.268, -0.0822}, {1.301,      -0.083}, {1.335, -0.0865}, {1.368, -0.0884}, {1.402, -0.0923},      {1.435, -0.0975}, {1.468, -0.1079}, {1.502, -0.1115}, {1.535,      -0.1183}, {1.569, -0.1268}, {1.602, -0.137}, {1.635, -0.1464},      {1.669, -0.1532}, {1.702, -0.1647}, {1.736, -0.1789}, {1.769,      -0.1834}, {1.802, -0.197}, {1.836, -0.213}, {1.869, -0.2271}, {1.902,      -0.2353}, {1.936, -0.2432}, {1.969, -0.2642}, {2.002, -0.2804},      {2.035, -0.2881}, {2.069, -0.2996}, {2.102, -0.3128}, {2.136,      -0.3256}, {2.169, -0.3369}, {2.202, -0.3411}, {2.236, -0.3576},      {2.269, -0.3682}, {2.302, -0.3789}, {2.337, -0.3869}, {2.369,      -0.3965}, {2.402, -0.4033}, {2.436, -0.4121}, {2.469, -0.4163},      {2.502, -0.4202}, {2.536, -0.4214}, {2.569, -0.4209}, {2.603,      -0.4221}, {2.636, -0.4214}, {2.669, -0.4139}, {2.703, -0.4057},      {2.736, -0.394}, {2.769, -0.3857}, {2.803, -0.3828}, {2.837,      -0.3778}, {2.869, -0.3658}, {2.903, -0.3554}, {2.936, -0.3475},      {2.97, -0.3335}, {3.003, -0.3289}, {3.036, -0.3239}, {3.07, -0.3037},      {3.103, -0.2918}, {3.136, -0.289}, {3.17, -0.2812}, {3.203, -0.2754},      {3.236, -0.2594}, {3.27, -0.2453}, {3.303, -0.2388}, {3.337,      -0.2321}, {3.37, -0.2272}, {3.403, -0.2178}, {3.437, -0.2051}, {3.47,      -0.2013}, {3.503, -0.195}, {3.537, -0.1872}, {3.57, -0.1818}, {3.604,      -0.1758}, {3.637, -0.1612}, {3.67, -0.1523}, {3.704, -0.1458},      {3.737, -0.1458}, {3.77, -0.1458}, {3.804, -0.1445}, {3.837,      -0.1488}, {3.87, -0.1572}, {3.904, -0.1668}, {3.937, -0.1815},      {3.971, -0.1911}, {4.004, -0.2013}, {4.037, -0.2177}, {4.071,      -0.2349}, {4.104, -0.2464}, {4.137, -0.2637}, {4.171, -0.2757},      {4.204, -0.2825}, {4.238, -0.2914}, {4.271, -0.3086}, {4.305,      -0.3262}, {4.338, -0.3302}, {4.371, -0.3329}, {4.404, -0.3469},      {4.438, -0.3551}, {4.471, -0.364}, {4.504, -0.3701}, {4.538,      -0.3751}, {4.571, -0.3775}, {4.605, -0.383}, {4.638, -0.3953},      {4.671, -0.4037}, {4.705, -0.4078}, {4.738, -0.4144}, {4.771,      -0.4228}, {4.805, -0.4295}, {4.838, -0.4378}, {4.871, -0.4474},      {4.905, -0.455}, {4.938, -0.4648}, {4.972, -0.4697}, {5.005,      -0.4737}, {5.038, -0.473}, {5.072, -0.4675}, {5.105, -0.4561},      {5.138, -0.4466}, {5.172, -0.4368}, {5.205, -0.4258}, {5.239,      -0.4153}, {5.272, -0.3981}, {5.305, -0.386}, {5.339, -0.38}, {5.372,      -0.3693}, {5.405, -0.3535}, {5.439, -0.346}, {5.472, -0.3403},      {5.505, -0.3335}, {5.539, -0.3286}, {5.572, -0.3202}, {5.606,      -0.3111}, {5.639, -0.3035}, {5.672, -0.2954}, {5.706, -0.2865},      {5.739, -0.2776}, {5.773, -0.2655}, {5.806, -0.2516}, {5.839,      -0.2405}, {5.873, -0.237}, {5.906, -0.2302}, {5.939, -0.2204},      {5.973, -0.2095}, {6.006, -0.1968}, {6.039, -0.1929}, {6.073,      -0.1803}, {6.106, -0.1718}, {6.14, -0.1636}, {6.173, -0.1581},      {6.206, -0.151}, {6.24, -0.1381}, {6.273, -0.1225}, {6.306, -0.1185},      {6.34, -0.1153}, {6.373, -0.1049}, {6.406, -0.0932}, {6.44, -0.0855},      {6.473, -0.0732}, {6.506, -0.0675}, {6.54, -0.0593}, {6.573,      -0.0509}, {6.607, -0.0428}, {6.64, -0.0344}, {6.673, -0.0309},      {6.707, -0.0237}, {6.74, -0.0216}, {6.773, -0.0187}, {6.807,      -0.0188}, {6.84, -0.0183}, {6.874, -0.0192}, {6.907, -0.0143}, {6.94,      -0.0041}, {6.974, -0.0014}, {7.007, -0.0032}, {7.04, -0.0032},      {7.074, -0.0036}, {7.107, -0.0072}, {7.141, -0.0116}, {7.174,      -0.0196}, {7.207, -0.0246}, {7.241, -0.0311}, {7.274, -0.0419},      {7.307, -0.0484}, {7.341, -0.0665}, {7.374, -0.0792}, {7.408,      -0.0977}, {7.441, -0.1136}, {7.474, -0.1341}, {7.508, -0.1482},      {7.541, -0.1654}, {7.574, -0.1781}, {7.608, -0.1871}, {7.641,      -0.2008}, {7.674, -0.2182}, {7.708, -0.233}, {7.741, -0.2419},      {7.775, -0.2501}, {7.808, -0.2665}, {7.841, -0.2732}, {7.875,      -0.2784}, {7.908, -0.2848}, {7.941, -0.2894}, {7.975, -0.2984},      {8.008, -0.3096}, {8.041, -0.316}, {8.075, -0.322}, {8.108, -0.328},      {8.142, -0.329}, {8.175, -0.3312}, {8.208, -0.3441}, {8.242,      -0.3517}, {8.275, -0.3538}, {8.308, -0.3586}, {8.342, -0.366},      {8.375, -0.3684}, {8.409, -0.3689}, {8.442, -0.3684}, {8.475,      -0.3615}, {8.509, -0.3527}, {8.542, -0.3403}, {8.575, -0.3319},      {8.609, -0.3279}, {8.642, -0.3197}, {8.675, -0.3157}, {8.709,      -0.3132}, {8.742, -0.3012}, {8.776, -0.2907}, {8.809, -0.2884},      {8.842, -0.2847}, {8.876, -0.2776}, {8.909, -0.271}, {8.942,      -0.2561}, {8.976, -0.2431}, {9.009, -0.24}, {9.042, -0.2357}, {9.076,      -0.23}, {9.109, -0.222}, {9.143, -0.2137}, {9.176, -0.2081}, {9.209,      -0.1938}, {9.243, -0.1884}, {9.276, -0.1834}, {9.309, -0.1716},      {9.343, -0.1577}, {9.376, -0.153}, {9.41, -0.141}, {9.443, -0.1348},      {9.476, -0.1232}, {9.51, -0.1198}, {9.543, -0.1183}, {9.576,      -0.1109}, {9.61, -0.1083}, {9.643, -0.1024}, {9.676, -0.1018}, {9.71,      -0.107}, {9.743, -0.1158}, {9.776, -0.1319}, {9.81, -0.1418}, {9.843,      -0.1519}, {9.877, -0.1746}, {9.91, -0.1847}, {9.943, -0.1963},      {9.977, -0.2034}, {10.01, -0.2048}, {10.044, -0.2293}, {10.077,      -0.2595}, {10.11, -0.2873}, {10.144, -0.309}, {10.177, -0.3167},      {10.21, -0.317}, {10.244, -0.3063}, {10.277, -0.2916}, {10.31,      -0.2876}, {10.344, -0.2835}, {10.377, -0.2791}, {10.411, -0.2782}}      And I want to fit with the equation ,               de[c_, Omega, Phi_, k_] =      Total[Abs[B[c, Omega, Phi, k] - g]].      where               B[c_, Omega_, Phi_, k_] = c Sin[Omega t+Phi]+k      And the `t` is the 1st Column of the data and g is the 2nd column.


title: Solarized stylesheet and other goodies. Feedback welcome!

text: I was inspired by this post so I've made a Solarized stylesheet after mucking around with the text options and asking stupid questions on here. I know you can change the syntax highlighting by running option-setting commands [1][2][3], but I'd rather have a stylesheet that takes care of all that stuff. Here is the link to a notebook with the solarized stylesheet. After you open the notebook, you can access the stylesheet by going to Format > Edit Stylesheet and follow my instructions on there on how to modify the stylesheet to fit your needs, while observing the changes in the notebook as you change the stylesheet. One way to learn how to edit stylesheet is to look inside a style cell (select the cell and press Ctrl+Shift+E) and modify the parameters in there--such as color paramters in RGBColor[x,y,z]--and see what your notebook looks like after you exit the cell view (Ctrl+Shift+E again). You can switch between light and dark theme by going to File > Screen Environments and choose between Working (light) and Dark (dark) themes. When you're happy with the way it looks just install/add the stylesheet by clicking on the "Install Stylesheet..." button and choose the Source as the "NotebookObject", then choose a name and if you'd like to install it for just you or for all users of your computer. After that, you can apply the stylesheet to any notebook you'd like by going to Format > Stylesheet, and choose the name of the stylesheet you saved it as. I know the steps are pretty obvious but as a newbie to MMA I really appreciated the people who gives out step-by-step instructions, and I'd like to do the same here. Please let me know if you have any trouble testing and installing the stylesheet and I could help you if I'm able to. I do appreciate any feedback you guys might have. Do you find the color scheme too much? What do you think could be improved upon it? Enough talk: some examples of the theme, and there's also more examples in the notebook in the link. Reference (you can download the journal notebook reformatted in solarized theme here). ![Kobai Light](http://i.stack.imgur.com/g3rZ5.png) Reference ![Miydera Dark](http://i.stack.imgur.com/m0CYo.png) ![Miyadera Dark 2](http://i.stack.imgur.com/Tecut.png)


title: Rank functions of n by their order of growth

text: I'd like to rank some functions according to their order of growth (e.g. `n^2 < n^3`). I'm not sure how to do order of growth in mathematica, so I was trying to rank the functions by their `Limit[x,x->Infinity]`. Here's what I have so far:               v = {2^(Log[2, n]), n^(1/2), Log[10, n], 2^(2^n), Log[2, Log[2, n]],       n*Log[2, n], n!, Iteratedlog[2, n], 1, n^3,       Log[2, n], (n^2)*Log[2, n], n, n^n, 100, n^2, 2^(2^(n + 1)), 2^n}          Sort[v, Limit[#1, n -> Infinity] < Limit[#2, n -> Infinity] &]      However, this doesn't even seem to work to sort the functions as a limit. What steps should I take to solve my problem? Thanks!


title: Mathematica gives wrong answer for an integral

text: When I execute the following,               Integrate[ Exp[-w^2 + I w^3], {w, -∞, ∞}]      I get > >     (2 E^(2/27) BesselK[1/3, 2/27])/(3 Sqrt[3]) >   which agrees with the result obtained from `NIntegrate`, which is `1.38811`.   However, when I execute               Integrate[ Exp[ -a w^2 + b I w^3], {w, -∞, ∞}]      I get > >     ConditionalExpression[ 0, b ∈ Reals && Re[a] > 0] >   which evaluates to `0` when `a = 1` and `b = 1`. This is obviously wrong. The integral itself has no convergence issues, as the integrand is simply a Gaussian multiplied by a modulus-one third-order chirp factor, which clearly converges when integrated over the real line.   Why does _Mathematica_ give an incorrect answer for the second integral?


title: What is ImageDistance measuring?

text: What quantity is `ImageDistance` measuring, and what do the numbers mean? I found the `ImageDistance` command in _Mathematica_ 9, but I've been unable to find much explanation about what it's doing. I originally thought it might be calculating the distance between features on images, but I don't think it is any more. I created two images that had some obvious differences:               original = ExampleData[{"TestImage", "Mandrill"}];     shiftedImage =        Sharpen[         ImagePad[original, {{30, -30}, {5, -5}},           Padding -> "Reflected"]];      ![twin mandrills](http://i.stack.imgur.com/okCEM.png) and ran a set of `ImageDistance` operations past them:               flist = {EuclideanDistance, SquaredEuclideanDistance,         NormalizedSquaredEuclideanDistance, ManhattanDistance,         CosineDistance, CorrelationDistance, "MeanEuclideanDistance",         "MeanSquaredEuclideanDistance",         "MeanReciprocalSquaredEuclideanDistance",        {"MeanReciprocalSquaredEuclideanDistance", .3},         "MutualInformationVariation", {"MutualInformationVariation", 32},         "NormalizedMutualInformationVariation",        {"NormalizedMutualInformationVariation", 32},         "DifferenceNormalizedEntropy", {"DifferenceNormalizedEntropy", 32},        "MeanPatternIntensity", {"MeanPatternIntensity", .1, 3},         "GradientCorrelation", "MeanReciprocalGradientDistance",         "EarthMoverDistance", {"EarthMoverDistance", 4}};          results = Sort[        Table[         {f, ImageDistance[original, shiftedImage,            DistanceFunction -> f]}, {f, flist}],        #1[[2]] > #2[[2]] &];          Grid[      Table[       {First[row], PaddedForm[ Last[row], {Automatic, 6}]}, {row,         results}],       Alignment -> {{Left, "."}}]      ![results](http://i.stack.imgur.com/j71GQ.png) Trying different pairs of images hasn't helped, yet. Can anyone enlighten me (in novice-friendly terms)?


title: Compile with array operations

text: When I use the function `f` with only the `Module`               f[a1_, a2_, a3_]:= Module[.....]     f[0,0,1200]      works fine but gives errors when I use `compile` as follows.               demand[n_, k_, qr_] := Min[k Vf, n capacity - qr]; supply[n_, k_, qr_] := Min[(n Kj - k) w, n capacity - qr];     Nsupply[n_, k_, qsum_, qrsum_, qr_] := Min[(n Kj - k) Vf - qsum - qrsum, n capacity - qr];     floExct[n_, ku_, k_, qsum_, qrsum_, qr_] := Min[demand[n, ku, qr], Nsupply[n, k, qsum, qrsum, qr]];     gamma[ku_, kd_] := Min[1, supply[L, kd, 0]/(demand[L, ku, 0] + 0.001)];     inflow[phi_, qin_] := (phi - \[Beta] qin) dx;     density[qin_, qout_, qr_] := (qin - qout + qr)/Vf;          Kj = 150.; w = 20.; Vf = 100.; capacity = 2500.; n = 30; m = 100; p = 27; RML = 18; \[Alpha] = 1200.; \[Beta] = 0.; L = 1.; delta = 1.; dt =4./3600.; dx = 1./9.;          f= Compile[{{a1, _Integer}, {a2, _Integer}, {a3, _Integer}},         Module[{k0 = ConstantArray[0., n],                 Fk = Table[Table[0., {i1, n}], {j, 5}],                 kr = Table[Table[0., {i1, 1, p}], {i2, 1, n - 2}],                 Rk = Table[Table[Table[0., {i1, 1, p}], {i2, 1, n - 2}], {i3, 4}], \[Phi],                 Fq = Table[Table[0., {i1, n - 1}], {j, 4}], qin,                 Fin = Table[Table[0., {i1, n - 2}], {j, 4}], qr,                 Rq = Table[Table[Table[0., {i1, 1, p}], {i2, 1, n - 2}], {i3, 4}],                RMori = Table[0., {i1, 1, n - 2}],                 RM = Table[0., {i1, 1, n - 2}], TT = 0., qf, qsum, qrsum},            RMori = Table[a1 (i1 dx)^2 + a2 (i1 dx) + a3, {i1, 1, n - 2}];         kr = ReplacePart[#, (\[Alpha] delta/Vf), 1] & /@ kr; AppendTo[Rk, kr];              \[Phi] = demand[1, #[[-1]], 0] & /@ kr MapThread[gamma, {Take[k0, {2, -2}], Take[k0, {3, -1}]}];         qsum = N[Plus @@ Fq];         qrsum = Join[Plus @@ Fin, {0}];         qf = MapThread[floExct[L, #1, #2, #3, #4, #5] &, {Most@k0, Rest@(Fk[[1]]), qsum,qrsum, Join[\[Phi], {0}]}];         qin = inflow[\[Phi], Most@qf];         k0 += Join[{0}, density[Most@qf, Rest@qf, qin], {0}];         qsum = MapThread[Plus, #] &@Rq;         RM = MapThread[Min[#1, #2] &, {RMori, MapThread[floExct[1, #1[[RML]], #2[[RML + 1]], #3[[RML]], 0, 0] &, {kr,Rk[[1]], qsum}]}];         qr = MapThread[Join[#1, {#2}, #3, {#4}] &, {                MapThread[floExct[1, #1, #2, #3, 0, 0] &, {Take[#, {1, RML - 1}] & /@ kr,Take[#, {2, RML}] & /@ Rk[[1]], Take[#, {1, RML - 1}] & /@ qsum}, 2], RM,                 MapThread[floExct[1, #1, #2, #3, 0, 0] &, {Take[#, {RML + 1, -2}] & /@ kr, Take[#, {RML + 2, -1}] & /@ Rk[[1]], Take[#, {RML + 1, -2}] & /@ qsum}, 2], \[Phi]}];         kr = MapThread[(#1 + #2) &, {Join[{0}, #] & /@ (density[Most@#, Rest@#, 0] & /@ qr), kr}];              TT += Plus @@ k0; TT += Plus @@ (Plus @@ kr);              Fq = Delete[Fq, {1}]; Fin = Delete[Fin, {1}]; Rq = Delete[Rq, {1}]; Fk = Delete[Fk, {1}]; Rk = Delete[Rk, {1}];         AppendTo[Fq, qf]; AppendTo[Fin, qin]; AppendTo[Rq, qr]; AppendTo[Fk, k0]; AppendTo[Rk, kr];     TT]]      all the errors (as shown below) are related to the `qsum` variable. Can someone tell me what I am missing?               MapThread::list: List expected at position 2 in MapThread[Plus,Compile`FunctionVariable$266]. >>     Compile::cprank: Compile cannot determine the rank of the result tensor. The length of Compile`FunctionVariable$266 in MapThread[Plus,Compile`FunctionVariable$266] is unknown at compiling time; evaluation will use the uncompiled function. >>     Compile::cset: Variable qsum of type {_Real,1} encountered in assignment of type {_Integer,0}. >>     Compile::part: Part specification Compile`GetElement[qsum,Compile`Variable$912][[18]] cannot be compiled since the argument is not a tensor of sufficient rank. Evaluation will use the uncompiled function. >>     Compile::part: Part specification Compile`GetElement[qsum,Compile`Variable$912][[18]] cannot be compiled since the argument is not a tensor of sufficient rank. Evaluation will use the uncompiled function. >>     Compile::part: Part specification Compile`GetElement[qsum,Compile`Variable$1852][[18]] cannot be compiled since the argument is not a tensor of sufficient rank. Evaluation will use the uncompiled function. >>     General::stop: Further output of Compile::part will be suppressed during this calculation. >>     Compile::cplist: Compile`GetElement[qsum,System`Private`CompileSymbol[0]] should be a tensor of type Integer, Real, or Complex; evaluation will use the uncompiled function. >>     Compile::cplist: Compile`GetElement[qsum,System`Private`CompileSymbol[0]] should be a tensor of type Integer, Real, or Complex; evaluation will use the uncompiled function. >>     Compile::cplist: Compile`GetElement[qsum,System`Private`CompileSymbol[0]] should be a tensor of type Integer, Real, or Complex; evaluation will use the uncompiled function. >>     General::stop: Further output of Compile::cplist will be suppressed during this calculation. >>     MapThread::list: List expected at position 2 in MapThread[Plus,Compile`FunctionVariable$3193]. >>     Compile::cprank: Compile cannot determine the rank of the result tensor. The length of Compile`FunctionVariable$3193 in MapThread[Plus,Compile`FunctionVariable$3193] is unknown at compiling time; evaluation will use the uncompiled function. >>     Compile::cset: Variable qsum of type {_Real,1} encountered in assignment of type {_Integer,0}. >>      **Edit:** Please note that the above code is a simplified/partial piece of a larger code. I presented this to show the problem area. The original code has several hundred iterations (till a condition is met) of the above critical steps and the `compiled` function itself will be called several thousands of times (for direct search-based optimization). **Edit 2:** Thanks to xzczd, the following code compiles without any errors. However, it gives error/warnings during run-time. The code may look cumbersome, but the problem area is very specific.               f = With[{Kj = 150., w = 20., Vf = 100., capacity = 2500., n = 15, m = 30, p = 10, RML = 5, \[Alpha] = 1200., \[Beta] = 0., L = 1., delta = 1., dt = 4./3600., dx = 1./9.},          Module[{demand, supply, Nsupply, floExct, gamma, inflow, density}, demand = Min[#2 Vf, # capacity - #3] &; supply = Min[(# Kj - #2) w, # capacity - #3] &; Nsupply = Min[(# Kj - #2) Vf - #3 - #4, # capacity - #5] &;            floExct = Evaluate@Min[demand[#, #2, #6], Nsupply[#, #3, #4, #5, #6]] &; gamma = Evaluate@Min[1, supply[L, #2, 0]/(demand[L, #, 0] + 0.001)] &; inflow = (# - \[Beta] #2) dx &; density = (# - #2 + #3)/Vf &;          Compile[{{a1, _Integer}, {a2, _Integer}, {a3, _Integer}},           Module[{k0 = Table[0., {n}], Fk = Table[0., {5}, {n}], kr = Table[0., {n - 2}, {p}], Rk = Table[0., {4}, {n - 2}, {p}], Fq = Table[0., {4}, {n - 1}], Fin = Table[0., {4}, {n - 2}], Rq = Table[0., {4}, {n - 2}, {p}],             RMori = Table[a1 (i1 dx)^2 + a2 (i1 dx) + a3, {i1, 1, n - 2}], Shutoff = False, j = 0, \[Phi], qin, qr, qf, qsum, qrsum, RM, TT, NtwrkTT},            If[300 > Min[RMori] && Max[RMori] > 1200, Print["MR not within bounds"]; NtwrkTT = 10^20,             kr = ReplacePart[#, (\[Alpha] delta/Vf), 1] & /@ kr;             NtwrkTT = TT = Total@(Total@kr); AppendTo[Rk, kr];             While[TT > 0, TT = 0;              \[Phi] = demand[1, #[[-1]], 0] & /@ kr MapThread[gamma, {Take[k0, {2, -2}], Take[k0, {3, -1}]}];              qrsum = Join[Total@Fin, {0}];              qf = MapThread[floExct[L, #1, #2, #3, #4, #5] &, {Most@k0, Rest@(Fk[[1]]), Total@Fq, qrsum, Join[\[Phi], {0}]}];              qin = inflow[\[Phi], Most@qf];              k0 += Join[{0}, density[Most@qf, Rest@qf, qin], {0}];              qsum = Total@Rq;              RM = MapThread[Min[#1, #2] &, {RMori, MapThread[floExct[1, #1[[RML]], #2[[RML + 1]], #3[[RML]], 0, 0] &, {kr, Rk[[1]], qsum}]}];              qr = MapThread[Join[#1, {#2}, #3, {#4}] &, {MapThread[floExct[1, #1, #2, #3, 0, 0] &, {Take[#, {1, RML - 1}] & /@ kr, Take[#, {2, RML}] & /@ Rk[[1]], Take[#, {1, RML - 1}] & /@ qsum}, 2], RM,                    MapThread[floExct[1, #1, #2, #3, 0, 0] &, {Take[#, {RML + 1, -2}] & /@ kr, Take[#, {RML + 2, -1}] & /@ Rk[[1]], Take[#, {RML + 1, -2}] & /@ qsum}, 2], \[Phi]}];              kr = MapThread[(#1 + #2) &, {Join[{0}, #] & /@ (density[Most@#, Rest@#, 0] & /@ qr), kr}];              TT += Total@k0; TT += Total@(Total@kr); NtwrkTT += TT; j++;              Fq = Delete[Fq, {1}]; Fin = Delete[Fin, {1}]; Rq = Delete[Rq, {1}]; Fk = Delete[Fk, {1}]; Rk = Delete[Rk, {1}];              AppendTo[Fq, qf]; AppendTo[Fin, qin]; AppendTo[Rq, qr]; AppendTo[Fk, k0]; AppendTo[Rk, kr];              Print["j: ", j];              If[#[[2]] > Kj - \[Alpha]/w, Print["Ramp Spillback"]; NtwrkTT = 10^20; Break[]] & /@ kr;              If[(Shutoff == False) && j > m, Shutoff = True; kr = ReplacePart[#, 0, 1] & /@ kr];             ];            ]; NtwrkTT dt], CompilationOptions -> {"InlineExternalDefinitions" -> True}]]];      when I run the compiled function with `f[0,0,1100]`, it runs the `While` loop only once, gives the following error:               CompiledFunction::cfse: Compiled expression {Null,Null,Null,Null,Null,Null,Null,Null,Null,Null,Null,Null,Null} should be a machine-size real number. >>     CompiledFunction::cfex: Could not complete external evaluation at instruction 491; proceeding with uncompiled evaluation. >>      Then, it proceeds to run the program, I guess in an uncompiled fashion. One possible variable that refers to `{Null,Null,Null,Null,Null,Null,Null,Null,Null,Null,Null,Null,Null}` may be `RM` and I was wondering, if it is the source of problem.


title: Combinatorica Graph from Edge List

text: Can someone provide an example of a **_Combinatorica_** -based graph which uses **ShowGraph** and **Graph** and takes in an explicitly defined list of edges (not some auto-generated graph). I have not been able to find any documentation which describes the expected input format.


title: I want to update a financial chart when I select a new stock from a popup menu

text: I have the following code: Read all the DOW jones financial instruments `instruments = FinancialData["^DJI", "Members"]` Then I create a dynamic variable called ticker               Dynamic[ticker]          ticker =.      And I create a popup menu with               {PopupMenu[Dynamic[ticker], instruments], Dynamic[ticker]}      So far it all works. I have my list of stock instruments in variable instruments and the popup menu comes up and when I pick a stock from it, the ticker (displayed to the right of the menu) updates to show the ticker I chose from the drop down list My problem is that I would like to have a chart automatically updated once I pick a ticker. For now I have:               data = FinancialData[ticker, "OHLCV", {{2008, 7, 3}, {2008, 9, 30}}]      And I use               InteractiveTradingChart[data]      To display the chart This works if I hit Shift enter on the last line. However, if I go to the popup menu and select a different stock (say INTC for Intel) the chart is not updated. I am new to Mathematica and I am sure that my problem is not understanding how Dynamic works. What I don't understand               InteractiveTradingChart[data]


title: Derivative of the solutions by parameter

text: P0 = 0.1;     K = 1000;     Quiet[sol = Solve[{K*P*L == PL, P0 == P + PL, r*P0 == L + PL}, {P, L,PL}][[1]]];     complex = PL /. sol;     Plot[complex, {r, 0.1, 2}]      How can I make the solution into a function of parameter `r` in order to get the derivative of the solution, `D[complex[r],r]`?


title: Seeing the whole financial chart

text: I display a financial chart which I display with `InteractiveTradingChart[]`. My problem is that when my financial is displayed, even though I ask for 6 months of data, the chart only shows a subset of that. I can go to the bottom of the chart and enlarge the area of interest manually. How do I tell `InteractiveTradingChart[]` to display the whole time period I requested?


title: make specific cluster

text: I have set of coordinates. I want to make clusters in which every point is within 1.5 distance unit of it's neighbor. ex of point coordinates:               {{-12.945, 20.6509, 12.5901}, {-13.4452, 20.307, 111.626},      {-12.9731, 22.8458, 12.4215}, {-13.2381, 24.8167, 10.7147},      {-11.3668, 23.3908,11.8499}, {-11.6828, 23.7311, 10.8839},      {-13.3929, 21.1835, 9.86324}, {-11.5016, 21.3324, 10.1392},      {-12.3079, 22.096, 8.57246}, {-12.5268, 20.9679, 10.5444},      {-12.1951, 24.5423, 10.1807}, {-11.8887, 22.3883, 10.0751},      {-14.2529, 20.4808, 9.81084}, {-11.9876, 21.8094, 11.0478},      {-12.3718, 23.6176, 11.8266}, {-11.6179, 20.8324, 11.2154},      {-12.5927, 21.7492, 12.5087}, {-12.1665, 24.6649, 11.2909},      {-12.3854, 21.5571, 9.51876}, {-12.2237, 23.4278, 9.9787}}      what is the quickest way in `Mathematica` for this (for large data sets). I tried this to find all points that are within mentioned distance:               Table[Select[List, EuclideanDistance[List[[i]], #] < 1.5 &], {i, 1, Length[[List]]}]      but now I have troubles to join all sets that have common elements.


title: When to use built-in Graph/GraphPlot vs. Combinatorica

text: What are the pros and cons of using built-in Graph/GraphPlot (and related) types vs. types in the Combinatorica package?


title: Numerical Fourier transform of a complicated function

text: Say I have a function $f(x)$ that is given explicitly in its functional form, and I want to find its Fourier transform[1]. If $f$ is too complicated to have an analytic expression for $\hat f(k)$, how do I obtain it numerically? The naive and stupid way, which I currently use, is evaluating the integral for many $k$'s and then interpolating between them. This is outrageously inefficient, and I'm sure that FFT should be used, but I can't seem to find a good recipe for that. I keep getting the frequencies and the normalisation wrong. This task seems to be common enough so that advanced software like Mathematica would have a built-in function for that. Any ideas? * * * [1] Being a physicist, I use $\hat f(k)\equiv \int e^{ikx}f(x)dx$ as the definition of FourierTransform, but you can stick in $2\pi$ wherever you feel like if you're used to a different one.


title: Faster simplification of linear combinations of some specific functions

text: After some profiling I've found that my program spends most of its time in the simplification step. The program uses my simplification function many times (over different data). My calculation is not possible without simplifications (expressions quickly become too long). Here is a representative sample of of my data. (pastebin, 6413 lines of plain text) The expressions that I want to simplify contain one parameter `r`. They are linear combinations of the following functions:               { ExpIntegralEi[2 r], ExpIntegralEi[-2 r],     ExpIntegralEi[4 r], ExpIntegralEi[-4 r],     f000000[r], f000001[r],      Log[r], Log[4 r] }.      The coefficients of linear combination contain exact numbers, powers of `r` and               Exp[-2 r], Exp[2 r], Exp[4 r], Exp[-4 r]      **How can I make the simplification step in my program faster?** * * * Below I summarize the ideas that I have tried.               No.  Simplification function                 Timing          ByteCount          1   Collect[sample, r, Simplify]            0.512032        19 784     2   Collect[sample, _[r], Simplify]         0.348022        18 632     3   Collect[sample, _[_. r], Simplify]      0.228014        13 136     4   Collect[sample, _[_. r],                  Collect[#, r, Simplify]& ]      0.17601         20 536     5   Collect[sample /. logrule,                 _[_. r], Simplify]              0.284018        11 624     6   Collect[sample , _[_. r],                  Simplify[ExpandAll[                      Simplify[#]]]&  ]          0.284018        11 624      The first column of the table gives the number of the approach (for convenient reference), the second gives the simplification function, the third column gives the value given by Timing[] (for every `Timing[]` a fresh kernel session was used), the fourth column gives the `ByteCount[]` of the result. All calculations were done for the sample available via the link above. The definition of `logrule` is:               logrule = {Log[4] -> 2 Log[2],                 Log[4 r] -> 2 Log[2] + Log[r],                 Log[16] -> 4 Log[2]};      Simplificatiom methods `5` and `6` indeed give the same `Timing` and `ByteCount`, this is not a mistake. From the table above it can be seen that method no. `4` is the fastest one, methods `5` and `6` give the best compression (I believe that `5` should be generally better). Nevertheless, considering both speed and compression efficiency I conclude that my best function is method no. `3`. **How can this method be improved? Or maybe should I replace it with some other method?**


title: Detect Standalone CDF vs Browser Plugin environment

text: Recently, Wolfram informed me that there's no way to have a Print button in a CDF running within a plugin environment since the plugin does not interact with the operating system. If you have a way to solve that, it would be great! But now more importantly, since there are such significant differences between the 2 environments, including the security sandbox, is there any way to detect programmaticly in which environment the CDF is being displayed, so that one could adjust what is being displayed to the user, and what is not? Thanks in advance for your help!


title: Are there guidelines for avoiding the unpacking of a packed array?

text: Packed arrays are very useful because they save memory and generally allow speedier and more efficient calculation times. If a list of data currently stored as a packed array is unpacked, it can slow things down considerably. It has been suggested that using certain built-in functions has the advantage that unpacking doesn't occur. Short of some trial-and-error spelunking using `PackedArrayQ` from the Developer Utilites package, **are there any guidelines or best practices for using functions and coding styles that avoid these performance hits from inadvertant unpacking?**


title: Multivariate Function Approximation With a Large Dataset

text: I have a nice amount of data from a trading strategy I am working on, where I have two different liquidity parameters as x, y variables. Before entering a trade I am taking the moving average of `Volume*SharePrice & if > than my "liquidity requirement"` I enter, along with other unmentioned rules. The length of the moving average is my x variable and my liquidity requirement is my y variable. My data includes several outputs over these x and y variables such as P/L, ROI, $Won, etc. My question is: how can I use Mathematica to interpolate an approximate function for any output so that I can optimize x, y? For instance say I want to approximate ROI=f(x,y) or P/L=f(x,y)...I dont expect something that describes my data perfectly, but something that approximates it would greatly help.


title: Dark artifacts in mathematica plot

text: When plotting in _Mathematica_ I just got some "dark artifacts". Here is my code:               Plot3D[Exp[-100 x^2], {x, -5, 5}, {p, -5, 5}, PlotRange -> All, PlotPoints -> {100, 100}]      and the result is![enter image description here](http://i.stack.imgur.com/gRQdL.png) (I know that the `3D` is useless here, but I minimized my actual code to the relevant problem). I have the feeling that it has something to do with the precision, when there is the transition from `10^-200` or so to `0` but increasing the `WorkingPrecision` didn't change anything.   I tried plotting in `2D` from `x = 2.3` and there is still an exponential function with value `10^-175` to see. When I plot from `3` to `4` (which is after the dark artifact line) then the `2D` `Plot` says just zero. I don't need to caluculate with super high precision, I just want to get rid of those dark strips.   I also tried to look for similar questions but couldnt find one, perhaps because I don't really know if artifacts is the right word.


title: Import selected columns from a tab delimited text file

text: I have a very huge file (1GB) from which I desire to import only the 5th column. It is a tab delimited text file with a `.txt` extension. Can you please help me with this? I generally use `Import["filename.txt","Table"]` to import my files, but now, I don't want the whole file, which takes a long time to load.


title: MathKernel with `-noprompt` hangs indefinitely when converting simple TeX expression

text: If I enter               MathKernel -noprompt -run 'ToExpression["1", TeXForm]; Exit[]'      the kernel hangs, apparently while running `TeX.exe` as a `mathlink` (see below). But when I remove `-noprompt`, it runs just fine. Similar results hold if I pass these commands (to either `MathKernel` or `MathematicaScript`) as a script. Alternatively, even with `-noprompt`, any of the other formats accepted by `ToExpression` work just fine. Any ideas why this happens? * * * Rather than printing the output, I could just write to file and send all the prompt garbage to `/dev/null`, but this really doesn't fit into my tool chain very well. So I'd appreciate any solutions or workarounds. I'm running Mathematica 9.0 for Mac OS X x86 (64-bit) on OS X 10.6.8. My evidence for believing that it's `TeX.exe` causing the problem is that my processes look like this               2772 s000  S+     0:00.28 /Applications/Local/Mathematica.app/Contents/MacOS/MathKernel -noprompt -run Print[ToExpression["1", TeXForm]];Exit[]     2773 s000  S+     0:00.04 /Applications/Local/Mathematica.app/SystemFiles/Converters/Binaries/MacOSX-x86-64/TeX.exe -ml -mathlink -linkmode connect -linkprotocol SharedMemory -linkname jv5_shm      Now, without `-noprompt`, I also see `TeX.exe` in the process list with the exact same arguments. But it's only there briefly, and it returns normally. Also, I can run `file TeX.exe`, and see that it is indeed a Mac executable (not Windows, as the name would suggest).


title: Counting the number of instances of one sub-string within a given string within a lower- and upper-bound gap of a second sub-string

text: Please consider the situation where I give you a list where entries are drawn from a fixed set of characters:                alphabet = {0,1,2};      numElements = 10^3;      bigString = StringJoin[Map[ToString, RandomChoice[alphabet, numElements]]];      I provide you two strings: `string1` and `string2`. I'd like to count the number of instances where `string2` occurs within a lower-bound and upper- bound "distance" of `string1`, and by "distance" I mean this in terms of the count for the number of characters in the gap region between `string1` and `string2` (i.e. the number of characters counting from immediately after the last character in `string1` and the immediately before the first character in `string2` if `string1` occurs before `string2`, and vice versa if `string2` occurs before `string1`). There may be multiple instances of `string1` and `string2`, so in terms of overcounting, each instance of `string2` should only be considered a single possible "hit" (if its within the lower- and upper- bound cutoff distance of `string1`). Is there a built in function, or an easy way to do this? As Leonid Shifrin requests, let's construct a small case example:               string1 = "1111";     string2 = "1221";          lowerboundDistance = 3;     upperboundDistance = 10;          bigString = "000000111100012210111100000122100000001111000000000001221";      Now, in the above string, there are three instances of `string2`, so at most we can have an output count of `3`. From left-to-right, here are all possible instances where `string1` and `string2` are separated by a gap of at least `3` characters and at most `10` characters:               [1] "11110001221"     [2] "1111000001221"     [3] "122100000001111"      Notice however that instances [2] and [3] correspond to the same instance of `string2`, so we only increase the count by `1` after seeing both of these instances. The final count is therefore `2`. To clarify a particular point, note that:               string1 = "1111";     string2 = "1221";          lowerboundDistance = 3;     upperboundDistance = 10;          bigString = "11110001221001221";      Should give an output count of `2` considering that `"11110001221"` and `"11110001221001221"` (abstracted as `"1111.........1221"`) represent instances of `string1` and `string2` within the lower- and upperbound gap specifications.


title: What are \[InvisiblePrefixScriptBase] and \[InvisiblePostfixScriptBase]?

text: In the non-printing characters documentation, I see two named characters that are largely undocumented: `\[InvisiblePrefixScriptBase]` and `\[InvisiblePostfixScriptBase]`. Interestingly, they have input aliases defined: `[Esc]i-[Esc]` and `[Esc]-i[Esc]`. What are they used for?


title: Solving a system of linear equations modulo n

text: I have a system of linear equations $$ a+b+c \equiv 31 \pmod{54} $$ $$ 4a+2b+c \equiv 3 \pmod{54} $$ $$ 9a+3b+c \equiv 11 \pmod{54} $$ What should I input (I'm using `LinearSolve`)? It doesn't seem to work for composite modulo numbers. I have been unable to get _Mathematica_ to give me all the possible solutions.


title: Sorting lists with elements that are identical

text: How can I sort the following list:               list={{1498, 1495}, {1498, 1733}, {1553, 1552}, {1552, 1495}, {1733,1776}, {1776, 1553}};      such that the next group contains one element of the first. The result would be:               {{1498, 1495}, {1552, 1495}, {1553, 1552}, {1776, 1553}, {1733,1776}, {1498, 1733}}          Sort[list,SameQ]       does not work completely as the results are still incorrectly sorted. > >     {{1498, 1495}, {1498, 1733}, {1553, 1552}, {1552, 1495}, {1733,1776}, > {1776, 1553}} >   It does not matter if the elements are in increasing order. An equally acceptable result would be               {{1498, 1495}, {1498, 1733}, {1733, 1776}, {1776, 1553},{1553, 1552}, {1552, 1495}}


title: How do I avoid scoping collisions of iterator variables?

text: Yesterday I had an issue that kept for quite a while. My code wasn't producing the right results. Now I know why and I am wondering how to avoid the issue in future. Consider the following code.               Clear[fAux];     fAux[i_] := fAux[i] = NDSolve[{y'[x] == Sin[y[x]^i], y[0] == 1}, y, {x, 0, Pi}][[1, 1, 2]];     f[i_, z_] := fAux[i][z];      Here, `f` returns the value of the solution of a ODE with parameter `i` at the value `z`. The solution of the ODE (an interpolating function) is memoized. You can convince yourself that it works fine by evaluating `f[1,1.5]` for example. Now I want to evalute this:               Table[f[2, x], {x, 0, 3}]      and I get an error message > "NDSolve::dsvar: 0 cannot be used as a variable." as well as unexpected results: > {Sin[y[0]^2][0], Sin[y[0]^2][1], Sin[y[0]^2][2], Sin[y[0]^2][3]} Looking at the down values of `fAux` you can see some strange things:               DownValues[fAux]      > {HoldPattern[fAux[1]] :> InterpolatingFunction[{{0.`, > 3.141592653589793`}},"<>"],   >  HoldPattern[fAux[2]] :> Sin[y[0]^2],   >  HoldPattern[fAux[i_]] :> (fAux[i] = NDSolve[{(y^\\[Prime])[x] == > Sin[y[x]^i], y[0] == 1}, y, {x, 0, \\[Pi]}][[1,1,2]])} The culprit is the name of the iterator in the `Table` function. It has the same name, `x`, as the dummy variable in `NDSolve`. If you replace either with `xx` for instance, everything works as expected. I find this very confusing and dangerous, to keep track of what name you gave to which iterator variable throughout the entire notebook. I'm not even sure how this would behave across packages you call from within the notebook. Is this a wanted behavior? How can I make sure I won't make the same mistake again?


title: Two ways of map a function on the list: Which one is faster?

text: There are 2 ways to make a function listable on the list: Use `Map` or use `SetAttributes`. My question is, which one is faster, more efficient? Does `SetAttributes` use `Map` or another way?               In[135]:= f/@{1,2,3}     Out[135]= {f[1],f[2],f[3]}          In[136]:= g[{1,2,3}]     Out[136]= g[{1,2,3}]          In[137]:= SetAttributes[g,Listable]               g[{1,2,3}]     Out[138]= {g[1],g[2],g[3]}      === EDIT === Thank for the comments of @Yves Klett and of @Leonid, I do a check: There are so many functions that are listable in _Mathematica_ ; I wonder that help improving performance in _Mathematica_. There are total 379 Listable buit-in functions.               Select[Names["*"],MemberQ[Attributes[#],Listable]&]//Length     379      I'm interested in numerical calculation, so I do the `Timing` check:               list=N[Range[10^7]];          Sin/@list;//AbsoluteTiming     {0.721041, Null}          Sin[list]; // AbsoluteTiming     {0.147008, Null}      We found that `Listable` is much faster than using `Map`. So for numerical evaluation, should I `SetAttribute` my function as Listable instead of using `Map`?


title: How to make a big image/dashboard containing various data-graph

text: I want to make and image/dashborad (to export to PDF) with many VERTICAL bullet graphs gauges. And I can´t make it, in a automatic way. In general, the questions are: **QUESTION 1:** How to make a dashboard similar to this one: ![enter image description here](http://i.stack.imgur.com/KolwM.jpg) For example, with only 3 gauges, I write this code:               GraphicsRow[      Rotate[BulletGauge[{25, 98}, {80, 98, 107}, {0, 180},         ImageSize -> Large], 90 Degree],      Rotate[BulletGauge[{45, 62}, {20, 58, 107}, {0, 180},         ImageSize -> Large], 90 Degree],      Rotate[BulletGauge[{55, 82, 102}, {40, 88, 115}, {0, 180},         ImageSize -> Large], 90 Degree]      ]      and the result is: ![enter image description here](http://i.stack.imgur.com/9opwR.png) I modified the code and put "{ }" to separate the 3 graphs, to obtain no commas between graphs, and the text "Graph..." and the brackets... but the result is so strange to me, because I can only view a little piece of the graphs. **QUESTION 2:** Is this normal? How could I make my user view the entire graphs as in the previous image (without commas and "graph.." and brackets)?. ![enter image description here](http://i.stack.imgur.com/NVZ2Q.png) **QUESTION 3:** How I can rotate the text marks "0", "50", "150"... ? Another way might be make automatic this individual bullet graphs, and find all I need in a PDF with LATEX, or in a similar way. **What are the best options for achieving all these things?**


title: Expanding a polynomial with fractional powers

text: Given an expression like               a + b*y + c*y^2 + d*Sqrt[f + g*y + h*y^2]      How can I programatically, expand this to a quartic without any fractional powers? Right now, I am having to copy and paste it as input expression and manually move the Sqrt to the RHS and square. I suspect there's an easier way to do this in Mathematica, perhaps using the Coefficient function or something similar.


title: Algorithm used by IsomorphicGraphQ

text: I'd like to know which algorithm is used to test if two graphs are isomorphic?


title: Unable to solve a set of equations with Solve

text: I'm trying to solve the following equation using Mathematica 9.0.1.0 :               Solve[E^(-σ τ) k (1 + T σ)^-n == Subscript[M, 0] &&        2*E^(-σ τ) k (1 + T σ)^(-1 - n) (n T + τ + T σ τ) ==         Subscript[M, 1] &&        1/2 E^(-σ τ) k (1 + T σ)^(-2 - n) (n T^2 + n^2 T^2 + 2 n T τ +            2 n T^2 σ τ + τ^2 + 2 T σ τ^2 +            T^2 σ^2 τ^2)*6 == Subscript[M, 2] &&        k (-(1/6) E^(-σ τ) n (1 + n) (2 + n) T^3 (1 + T σ)^(-3 - n) -            1/2 E^(-σ τ) n (1 + n) T^2 (1 + T σ)^(-2 - n) τ -            1/2 E^(-σ τ) n T (1 + T σ)^(-1 - n) τ^2 -            1/6 E^(-σ τ) (1 + T σ)^-n τ^3) == Subscript[M, 3], {k, T,        n, τ}]      Mathematica outputs the following error:               Solve::nsmet: This system cannot be solved with the methods available to Solve. >>      And when I try to use "SolveAlwyas" instead of "Solve" I get the following errors :               Solve::incnst: Inconsistent or redundant transcendental equation. After reduction, the bad equation is 1-((1+T σ)^n)^(1/n) == 0. >>     Solve::incnst: Inconsistent or redundant transcendental equation. After reduction, the bad equation is -1+((1+T σ)^n)^(1/n) == 0. >>     Solve::incnst: Inconsistent or redundant transcendental equation. After reduction, the bad equation is 1-((1+T σ)^(-1-n))^(1/(-1-n)) == 0. >>     General::stop: Further output of Solve::incnst will be suppressed during this calculation. >>      This system can be solved. Is there any way to solve this equations with Mathematica without giving numerical values to the parameters ?


title: Export to Google Spreadsheet with OAuthAuthentication

text: # Context I'm trying to setup a connection between _Mathematica_ and Google Docs. Specifically, I would like to be able to **export** data to a Google Spreadsheet (Note: if the spreadsheet is public it's very easy to import data to _Mathematica_ , so the problem here is only how to **export** data to a Google Spreadsheet). I have little knowledge of Java, but as far as I could read in many posts and documentations (for instance, here, here, here, here, here, here), there are several Java commands and classes involved in the process. I believe there are basically two steps involved in this problem: **1)** Get the OAuth authentication from Google (you can get familiar with OAuth here); **2)** Export to Google Spreadsheet using GoogleData libraries (found here). I know there is a commercial package doing exactly that (link), but I would like to be able to control everything from _Mathematica_. # Attempt As said, I have little knowledge of Java. So this is not a serious attempt to solve this problem, but only a concatenation of ideas (hoping someone could actually help me in the process). I believe the first step to achieve the _Mathematica_ -Google Docs connection is to modify the Google Account security definitions (admin.google.com/AdminHome) to allow API access and also generate an OAuth- key. So far, so good. From now on, I'm completely lost. I believe the next step would be: **1)** Create the OAuth token using the OAuth-key from Google. Something like this:               token = HTTPClient`OAuthAuthentication[     "ConsumerKey" -> "mywebaddress.com",      "ConsumerSecret" -> "OAuth-key from Google",      "RequestEndpoint" -> "https://accounts.google.com/OAuthGetRequestToken",     "AuthorizeEndpoint" -> "https://accounts.google.com/o/oauth2/auth",      "AccessEndpoint" -> "https://accounts.google.com/o/oauth2/token"];      Do I need anything else inside the token?) **2)** URLFetch the data with the correct methods A list of methods to manipulate a Google spreadsheet can be found here. However, I'm not able to put them in the correct syntax inside _Mathematica_. Something like this:               url="https://spreadsheets.google.com/feeds/cells/{spreadsheet_key}/{active_sheet}/       private/full/{active_cell}/sheet.setColumnWidth(1, 200)"     URLFetch[url,"OAuthAuthentication" -> token]      So, when I try to use the code above I get the following error messages: > HTTPClient`OAuthSignURL::nopt: The option OAuthAuthentication is missing in > HTTPClient`OAuth`Private`OAuthURLFetchList[https://spreadsheets.google.com/feeds/cells/{sheet_key}/{sheet_sheet}/private/full/{sheet_cell}/sheet.setColumnWidth(1, > 200),{CredentialsProvider->None,<<1>>,<<1>>,OAuthAuthentication-><<30>>[<<30>>[<<30>>[<<30>>[<<1>>]]]]}]. > General::stop: Further output of HTTPClient`OAuthSignURL::nopt will be > suppressed during this calculation. I'm clearly doing lots of wrong things, however I believe someone in MMA.SE could help me to achieve this connection between _Mathematica_ and Google Docs.


title: How to make brute force coding more efficient?

text: Hi guys and guysettes, The little Mathematica I've been using/seen so far, it seems to be all about neat "one-liners" using the underlying functions and working with lists & maps to solve issues, and very little looping and down and dirty coding. So, when I attempt to do something like this, I get extremely inefficient code (yes, I'm relying on one explicit loop, though): (The task is to find the lowest value that is evenly divisible by 1 through 20)               results = {1}; i = 0;     While[Total[results] != 0,      i++;      results = Mod[i, #] &  /@ Range[1, 20];      ]     i      ..which takes about 8000 seconds to complete. Had I used another language, I would naturally had an inner-loop that breaks after the first "failing" 'Mod', but here I tried to use what I thought to be more of a "Mathematica way" and the results are horrible. So, I'm asking for advice on how you would construct a brute-force way of dealing with this? For comparison, creating a similar way to solve the problem in Python, I got it to complete in about 1000 Seconds. Creating an "early-exit" solution without using unecessary lists for results, (the way I would normally code), it got down to 120 seconds.


title: Change values in equation with slider

text: I want to make an equation where the values adjust to my slider which I inserted with manipulate. Well, I tried, but when I use the slider the equation starts to fall apart. ![quadratic equation in mathematica](http://i.stack.imgur.com/qkIHb.png) Actually this should happen ![quadratic equation steps](http://i.stack.imgur.com/nRnPB.png) Is it possible to make an quadratic equation in mathematica where the variables and their results adjust themselves to a slider which has been inserted with manipulate?


title: Reversibly merging sets of $k$ adjacent elements in an array

text: Say I have an array of the form:               ExampleArray = {{1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}};      I'd like to be able to reversibly merge sets of $k$ adjacent elements together s.t. I can go back and forth from, for example, arrays of the form:               ExampleArray = {{1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, {13}};      And, for $k = 2$:               ExampleArray2Star = {{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}, {11, 12}, {13}};      Or, for $k = 3$:               ExampleArray3Star = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}, {13}};      As we can see here, "leftover" elements at the end of the array will strictly be in a subset of size $\leq k$. Is there a name for this sort of operation, and is there an easy way to execute it in Mathematica 9.0?


title: Game theory packages

text: Is there any game theory package around? I mean supporting functions which take a game in matrix form and tell you all about nash equilibra, best strategies, ect


title: Obtain Data points from a graph on an image without axes

text: I have the following image: (which is a oscillation of the "magnetic susceptibility of gold" in y-direction, in arbitrary units, over the "magnetic field strength" from bmin = 36540 Gauss to bmax = 36784 Gauss, in x-direction).               pic = Import["http://i.stack.imgur.com/P6JOc.png"]      ![plot image](http://i.stack.imgur.com/P6JOc.png) Even if it looks periodic, it should not be so, it must be periodic in 1/x (i.e. in the reciprocal of the field strength). Changing the image to a plot over 1/x I already succeeded in with the following _Mathematica_ function:               bmin := 36540;          bmax := 36784;          f[a_, b_] := {1/(1/bmin - 1/bmax) (1/(a*(bmax - bmin) + bmin) - 1/bmax), b}           img = ImageTransformation[pic, f[#[[1]], #[[2]]] &, PlotRange -> Automatic]      Now I get an image which looks quite similar and goes from 1/bmax to 1/bmin in the x-direction. From that image I now want to obtain the data points (along x) in y direction, such that I can do a Fourier Transform to obtain the frequencies and hence the periods in the reciprocal field strength. How would I do that the easiest way? btw: The background is that my professor wants us to obtain those frequencies in a problem set on the De-Haas-Van-Alphen-effct but obviously "by hand" with ruler and pen on a printed version of the graph...and I´m not gonna do that :)


title: How can I shift the frame ticks to the corner of each element-cell in a Matrixplot?

text: I am using the following code,to create a Legend for my plot. I would like to shift (or re-position) the frameticks to the corner of each of the cell- elements instead of being in their middle. I wonder: is it possible?               legendwidth = 30;     plotheights = 400;     div = 10.;     ticks = Table[{i + 1, Rescale[i, {0, 10}, {-2., 30.}]}, {i, 0, 10}];          MatrixPlot[Transpose @ {Table[i, {i, 0, div}]/div},        AspectRatio -> plotheights/legendwidth,        FrameTicks -> {{None, ticks}, {None, None}},        FrameStyle -> Directive[Thick],        LabelStyle -> Directive[Black, 10, Bold],        ImageSize -> {legendwidth + 17, plotheights},        ImagePadding -> {{10, 20}, {33, 0}},       ColorFunctionScaling -> False,        ColorFunction -> (ColorData["Rainbow"]),       PlotRangePadding -> None,        DataReversed -> True     ]


title: Array of functions, evaluation in plot

text: I would like to create two arrays of functions `yfunc[[i]]` and `tfunc[[i]]`, with each entry of those functions being a function depending on t, that is to say               yfunc={yfunc[[1]][t],yfunc[[2]][t],...}       and the same for `tfunc`. Then I would also like to plot members of these array with `ParametricPlot` in pairs, e.g.               ParametricPlot[{yfunc[[i]][t],tfunc[[i]][t]},{t,0,1}]      This code works:               yfunc[t_?NumericQ, i_?IntegerQ] := i*t;     tfunc[t_?NumericQ, i_?IntegerQ] := 2 i*t;     comp[i_] := {tfunc[t, i], yfunc[t, i]};     Show[ParametricPlot[comp[1], {t, 0, 1}], AspectRatio -> 1]      But another try of creating this function array fails:               yfunc[t_?NumericQ] := Table[i*t, {i, 1, 100}]     tfunc[t_?NumericQ] := Table[2 i*t, {i, 1, 100}];     comp[i_?IntegerQ] := {tfunc[[i]][t], yfunc[[i]][t]};     Show[ParametricPlot[comp[1], {t, 0, 1}], AspectRatio -> 1]      I guess in this case it is a problem with the evaluation. What would be the correct way to do it in the second way? Thanks!


title: Timing differences between multiple executions of identical code

text: I have a `list` of pairs of numbers and I'd like to change the sign of the second element in each pair i.e. $(a,b)\rightarrow (a,-b)$. I'm sure there are many ways to do this. Starting from an example list the ways I know are               list = Table[{j, j}, {j, 200}];          Table[{list[[s, 1]], -list[[s, 2]]}, {s, 1, Length[list], 1}]          Partition[Riffle[Transpose[list][[1]], -1 Transpose[list][[2]]], 2]          {#1, -#2} & @@@ list      They all produce the same output and I expected the final method to be the fastest as it utilises Mathematica's functional programming abilities. More generally I expected the timings for each method to be constant upon repetition, meaning if I executed the same code many times I'd get the same answer. However when I timed them for 10 runs of 1000 executions each I get the following               Table[Timing[        Do[Table[{list[[s, 1]], -list[[s, 2]]}, {s, 1, Length[list],            1}], {1000}]][[1]], {10}]          (*{0.344, 0.281, 0.312, 0.313, 0.265, 0.297, 0.328, 0.375, 0.297, 0.297}*)          Table[Timing[        Do[Partition[Riffle[Transpose[list][[1]], -1 Transpose[list][[2]]],           2], {1000}]][[1]], {10}]          (*{0.11, 0.093, 0.125, 0.11, 0.109, 0.094, 0.109, 0.094, 0.109, 0.125}*)               Table[Timing[Do[{#1, -#2} & @@@ list, {1000}]][[1]], {10}]          (*{0.219, 0.219, 0.219, 0.25, 0.218, 0.219, 0.25, 0.188, 0.234, 0.312}*)      and it seems I was wrong on both of my expectations. Variable timings and `@@@` came in second place. `Partition[Riffle.....` was approx twice as fast as the others. Could someone explain the reasons for (a) the variable timing and (b) why the `Partition[Riffle.....` method is more efficient than the `@@@`method when I would have guessed it has more computational steps?


title: Accessing MathematicaScript over ssh/network

text: Here is the conundrum I am faced with. I have two computer. One with Mathematica (and hence `MathematicaScript`) but generally _poor_ resources. The other without Mathematica but _excellent_ resources (good amount of disk space, RAM, processor power). Since the local IT department who are the computer overlords here will take forever to get Mathematica installed on the better of the two machines... > Is there a way I could modify my Mathematica script's shebang to access > `MathematicaScript` over an ssh connection? So in essence, am I trying to > run Mathematica over a network? Is that > possible without a regular > gridMathematica license? The shebang, right now, looks like. I'd like to incorporate an ssh access functionality to it.               !#/usr/local/bin/MathematicaScript -script