title: Creating a conditional table

text: I'm trying to create a conditional table. Let's say I want to have such result: {1,2,3,4,5,0,0,0,0,0}. The idea is to create a table of n elements (10 in a given example), but when one element takes a specific value (5 in my example), then all of the remaining elements must take provided value (let's say zero). It's important not to use IF checking every element whether it satisfies provided condition.


title: Error computing sum of sum of digits

text: I've defined a function that computes the sum of the base-b digits of n:               DigitSum[n_, b_] := Total[IntegerDigits[n, b]]      Then I defined a function that computes the sum of the base-b digits of all of the integers up to x:               CumDigitSum[x_, b_] := Sum[DigitSum[n, b], {n, 1, x}]      Using these functions, I get               CumDigitSum[1000000,10]=27000001      which is correct. But then for larger inputs I get nonsense like               CumDigitSum[1000001,10]=500011500011      If I work in a different base, the same thing happens: at exactly 1000001, Mathematica begins computing the sum incorrectly. If I bypass my user-defined functions and just write what I mean, I get the correct answer:               Sum[Total[IntegerDigits[n, 10]], {n, 1, 1000001}] = 27000003      Any idea what could be happening here?


title: How to efficiently select elements from a Hash?

text: How can I write an efficient version of the following selection statement:               Keys[Select[hash, # < constant &]]; // AbsoluteTiming      hash can be made from:               hash = Association[Table[i -> i^2, {i, 1, 10^6}]];      On my computer, a last year MacBook Pro, it takes almost a half second. However, this is non an acceptable time for working with Hashs. Any other ways to do that? Thank you very much.


title: Suitability of Mathematica as platform for engineering calculations and programs

text: I am considering using Mathematica with Wolfram Workbench as a standard platform for calculations and programs in a large engineering department. I am looking for a solution that would provide better validation, documentation and revision control than Excel spreadsheets with VisualBasic macros. Additional benefits would be to use built-in functionality to reduce development effort and to allow engineers to use code interactively instead of in a black-box mode. I have used Mathematica and WebMathematica for individual projects in the past, and am familiar with the various customer examples that Wolfram advertises. However, I don't have experience or examples of using Mathematica across a large engineering department. I expect that we would develop packages for various back end functionality (likely on the order of 20,000+ lines of code), and users would access it either directly in the notebook, through CDF applications or through WebMathematica depending on the application. Is Mathematica suitable for this type of use? Can average users learn Mathematica without too much trouble and become productive quickly? Is there a better solution you would suggest evaluating?


title: How to track objects in video

text: I have a video that contains object moving in one direction, is it possible to track the objects and get information like object moving speed, object length and coordinates etc.? An example would be I have a video of highway traffic, and I want to get the car size, lane number and speed for each car. * * * **Simplified Problem** Here is a simple version of the problem: Say I have several rectangles moving in one direction, and I want to know their length and position. The following code creates 100 frames of moving rectangles:               N0 = 100;     lengthRange = {2, 3, 4, 5};     positionRange = {1, 2, 3, 4, 5};          objectsDimension = RandomChoice[lengthRange, {N0}];(*Different possible length of rectangle*)          objectsPosition = RandomChoice[positionRange, {N0}];(* Track number for the rectangle*)          objectsEndPoins = Transpose /@ Transpose[{Transpose[{objectsPosition - 0.2, objectsPosition + 0.2}], Partition[Prepend[Accumulate[objectsDimension], 0], 2, 1] /. {x_, y_} -> {x + 0.2, y - 0.2}}];     (* coordinates for rectangles*)          timePlot = Graphics[Rectangle @@@ objectsEndPoins, ImageSize -> {200, Automatic}, AspectRatio -> 8];(* the whole time plot*)          frames = Table[Show[timePlot, PlotRange -> {{1 - 0.5, 5 + 0.5}, {n, n + 50}}, AspectRatio -> 1, ImageSize -> {200, Automatic}], {n, 0, 300, 3}];(*show different part of the whole plot, to create video frames*)          frames = Graphics[#[[1]], Sequence @@ Options[#]] & /@ frames;(*workaround of [this][1] problem*)          ListAnimate[frames]      ![enter image description here](http://i.stack.imgur.com/q2iqY.gif) **So can we get the coordinates and the length of the rectangles in the video?** * * * **What I tried** I first use the `FindGeometricTransform` find the speed for the moving objects, then stack each frame together to get a whole time plot, then measure the rectangles.               stepPerFrame = Mean@Table[FindGeometricTransform[frames[[i]], frames[[i + 1]], TransformationClass -> "Translation"][[2, 1, 2, 3]], {i, 1, 20}]       (*calculate the object moving speed per frame. Assume constant speed, average speed for the first 20 frames.*)          blank = Graphics[{}, ImageSize -> ImageDimensions[timePlot]];(*constract a blank plot*)          result = ImagePad[Block[{tmp = blank},         Do[tmp =             ImageCompose[tmp,              frames[[i]], {0, (i - 1)*stepPerFrame}, {0, 0}];, {i, 1,            Length@frames}];         tmp], {{0, 0}, {10, 0}},         White];     (*stack each frame together with a offset of object moving speed.*)          imageData = ImageData[Binarize[ColorNegate[result]]];(*binarize the image*)          lines = Reverse /@         Transpose[         imageData[[All,           Range[20, 180, 40]]]];(*outlines at each lane center*)          position =        Table[lines[[           n]] //. {x__, PatternSequence[0, 1], y__} -> {x, 0, "start",             y} //. {x__, PatternSequence[1, 0], y__} -> {x, "stop", 0,            y}, {n, 1, 5}];(*mark object start and stop in the data *)          objects =        Table[(Transpose@{Flatten[Position[position[[n]], "start"]],            Flatten[Position[position[[n]], "stop"]]}), {n, 1,          5}];(*select the object start and stop position*)          recoveredOjbDim =        Flatten[Differences /@ Sort@Flatten[objects, 1]] /. {5 -> 2, 9 -> 3,          13 -> 4, 17 -> 5};(*calculate the object length*)          recoveredOjbDim == objectsDimension(*compare to the correct answer*)     (*True*)      * * * **Questions:**   1. Could you show your methods, I'm sure I can learn a lot.   2. In the problem, all objects have the same constant speed, what can we do for objects with different speed?


title: Using ParallelMap to run multiple Game of Life simulations simultaniously

text: **My Assignment and Code** As an exercise in Parallel computing I've been tasked with implementing Conway's GoL in a way such that at every iteration only a fraction of cells are updated. I'm then to run several simulations starting with the same seed, in order to study effect of non synchronous updating. I've implemented this sequentially as follows: Initial variables:               gridSize = 10;     updateFraction = 0.9;     sampleSize = 8;     seed = RandomInteger[{0, 1}, {gridSize, gridSize}];      Normal GoL rules, and updated rules for randomly updating a fraction of the cells:               rulestest[{neighbours_, cell_}] :=       Module[{},        Piecewise[{{1, neighbours == 3}, {0,           neighbours <= 1 || neighbours > 3}}, cell]]          rulestestrandom[{neighbours_, cell_, randomseed_}] :=       Module[{},        Piecewise[{{cell, randomseed == 0}},         Piecewise[{{1, neighbours == 3}, {0,            neighbours <= 1 || neighbours > 3}}, cell]]]      Applying the rules to the grid:               step[matrix_] :=       Map[{Total@Delete[Flatten[#], 5], #[[2, 2]]} &,         Partition[ArrayPad[matrix, 1, "Periodic"], {3, 3}, {1, 1}], {2}]          /.{p_, q_} -> rulestest[{p, q}]          steprandom[matrix_] :=       Map[Flatten@{Total@Delete[Flatten[#], 5], #[[2, 2]],            RandomChoice[{updateFraction, 1 - updateFraction} -> {1, 0},1]}&,             Partition[ArrayPad[matrix, 1, "Periodic"], {3, 3}, {1, 1}], {2}]          /. {p_, q_, r_} -> rulestestrandom[{p, q, r}]      Doing a bunch of iterations and plotting it:               controlMatrix = seed;     controlAnimateSet = {controlMatrix};      Do[controlMatrixtemp = step[controlMatrix];       AppendTo[controlAnimateSet, controlMatrixtemp];       controlMatrix = controlMatrixtemp;, {100}]          Map[Function[testMatrix[#] = seed], Range[sampleSize]];     Map[Function[testMatrixtemp[#] = {}], Range[sampleSize]];     Map[Function[testMatrixAnimateSet[#] = {testMatrix[#]}],        Range[sampleSize]];     Do[Map[(testMatrixtemp[#] = steprandom[testMatrix[#]];           AppendTo[testMatrixAnimateSet[#], testMatrixtemp[#]];           testMatrix[#] = testMatrixtemp[#];) &, Range[sampleSize]];, {100}]          Manipulate[{Table[        ArrayPlot[testMatrixAnimateSet[m][[n]], Mesh -> True,          ImageSize -> Medium], {m, 1, 8}],        ArrayPlot[controlAnimateSet[[n]], Mesh -> True,         ImageSize -> Medium]}, {n, 1, 100, 1}]      **The problem** The code runs fine just like this, sequentially. However the goal is to make it run in parallel. I figured there are two things that could potentially be parallelized. Firstly updating the grid could be done in parallel:               step[matrix_] :=       ParallelMap[{Total@Delete[Flatten[#], 5], #[[2, 2]]} &,         Partition[ArrayPad[matrix, 1, "Periodic"], {3, 3}, {1, 1}], {2}]          /.{p_, q_} -> rulestest[{p, q}]      Now this works fine, but for grid sizes up to 100x100 (Which I've been instructed to use) this is less efficient when it comes to computing time, resulting in speedups of around 0.8 on my quadcore machine. The second option, which in my mind seems more obvious, is to parallelize the iterations on the group of test matrices. I tried to do it as follows:               Do[ParallelMap[(testMatrixtemp[#] = steprandom[testMatrix[#]];           AppendTo[testMatrixAnimateSet[#], testMatrixtemp[#]];           testMatrix[#] = testMatrixtemp[#];) &, Range[sampleSize]];, {100}]      However this doesn't work, and I don't understand why. The code runs without errors and gives a very nice speedup of around 3.0, however the `testMatrixAnimateSet` never gets appended with future iterations of the grid. Is this an error in my code, or just _Mathematica_ being quirky? Is there a way to work around this?


title: Defining Tags in Reap

text: I am trying to use `Sow`/`Reap` to replace `Append` in my code. The problem is that I need to define the tags within my code, but doing so doesn't reap the desired results. A simplified version of my code is               Clear[tag];     Reap[tag = {a,b}; Sow[1, a];Sow[2,b];, tag]      However, if I define my tag outside of Reap, then it works               Clear[tag];     tag = {a,b};     Reap[Sow[1, a];Sow[2,b];, tag]      Any ideas as to how I can define tags within my code?


title: How to retrieve the remaining cashflows from a FinancialBond object

text: I would like to get the cash flows and dates for the remaining coupons and principal repayment for a `FinancialBond` object. These must be calculated internally by the `FinancialBond` object for many of its possible return values but I can't see how to get the cashflows explicitly. Thanks


title: Executing Mathematica script from inside SQL Server

text: Does anyone have experience in calling _Mathematica_ from inside SQL Server to do calculations? For example, how can I make a Procedure that uses _Mathematica_? Or a job that runs some _Mathematica_ script? I saw this post on MathGroup, but it's a little bit confusing to me. Is there an easy way? Being more specific, I would like to execute (from inside SQL Server) a _Mathematica_ script. The script works using `MathKernel -script myFile.m` but I don't know how to make SQL call it. The Mathematica is installed in another server, in the same local web.


title: How to manipulate gauge theory in Mathematica?

text: I want to know if there is a way of typing into Mathematica an expression like the following, $$\epsilon^{\mu \nu \lambda} f^{abc} A^a_\mu A^b_\nu A^c_\lambda + g\epsilon^{\mu \nu \lambda} A^a_\mu \partial_\lambda A^a_\nu + \bar{\psi}(\gamma^\mu(\partial_\mu + gA^a_\mu T^a))\psi$$ (..repeated indices are understood to be summed over..) where $g$ is a number, $A^a_\mu$ can be thought of as matrices with $a,b,c = {1,2,3,..,N}$ for some $N$ and $\mu, \nu, \lambda = \\{ 0,1,2\\}$. So the $\partial_\mu$ are partial derivatives as $\partial_\mu = \frac{\partial}{\partial x^\mu}$. $f^{abc}$ is a set of numbers depending on the values of a,b and c and it is completely cyclic and anti-symmetric in it. $\epsilon^{\mu \nu \lambda}$ evaluates to $0$ if any two or more of its indices are equal and evaluates to 1 or -1 depending on whether the three distinct entries are in cyclic or anti-cyclic order. $\psi$ should also be thought of as a matrix $\psi^a_i$ where $i,j = \\{0,1,2\\}$. $\gamma^\mu$ are a chosen set of $3\times 3$ matrices. Each of $T^a$ is a $N \times N$ matrix. Then the terms involving $\psi$ when expanded out look like, $$\bar{\psi}\gamma^\mu \partial _\mu \psi = (\psi^\dagger)^a_i (\gamma^0\gamma^\mu \partial_\mu )_{ij}\psi_j^a \quad{ \rm and }\quad\bar{\psi}\gamma^\mu A^a_\mu T^a \psi = (\psi^\dagger)^a_i(\gamma^\mu)_{ij}(A^c_\mu T^c)^{ab} \psi^b_j$$   * I would like to be able to input the above expression into Mathematica without having to explicitly specify the numbers $f^{abc}$ and the matrices $T^a$. I would like to be able to manipulate the expression with the matrices $T,A,\psi$ and the numbers $f^{abc}$,$g$ as being variables.  If the above is possible then I would eventually like to do something like write $A^a_\mu = B^a_\mu + C^a_\mu$ and $\psi^a_i = \eta ^a _i + \xi ^a _i$ and expand the expression in terms of B,C,$\eta$ and $\xi$.


title: Graph vs GraphPlot

text: What is the difference (in purpose) between `Graph` and `GraphPlot`? Which function is bested suited to which tasks? **Background:** I just spent the last two hours trying to make this graph readable:               trans = Uncompress@        "1:eJyVV01vwjAMRfu47U/sv3RKKc2KGsahxw2YOE0aXPff17RJSZD8/HIBga3Efn5+\     dl4/f/rT32q1ujyNH+35cj09+F8v40d1/j1+XY+\     Ht8P30T2Pf9ihbyvn7Y0T3GbjzZtyM5LbYmcP9Els++FdTWJy7EwrOEYzTjbeRkHyODnvB\     adgnb7d8KHi4e3OgBudmb5sB3xsV1CBOTLpymCdv1sp/\     mBlzhq9tJrfqolRC9aSDNSzGPwxFv5f05GAldDVoJKbrgBWJsnCIuFMB/\     28JVXNMR7IQsfVvZSTCD07V79Z78Clo1VLIS+YVn5/2H67Q3h4M83wZr2B4W/\     oCmhaFDXSWysUWcVpH4sElyUTFYsEGxnPRl7nlRgTFoFBu0xGjuDToRLAs5GeeDWqes22H\     ORPLDl/FENXLXCmuVWQanrkBwmT88uGjhh8JgIyYRI91EW4aBoqtOIbg60RxD+IAGjuZC+\     QRSeXfC2qkhGor6gqD60WfdoZTOy8SGu9iONKFEJeVO7eELQGMvOD0UDYaXHN5a6DT5Zlv\     GuYlu2TmhIyD726bP5gSnswmEttWR9puG1wH6WE1VuSBI2sVNA6cfxlK6JIx7utFDE7vI5\     lyAL+Kv09FopgpA9t+\     cIcCcjZMXgYV4YWrHd86DFyR2xpTh012aCEY8sSoy3sX3A0OHUHTjWYWgR8fv/wd/kB";     Graph[DeleteDuplicates@trans, VertexLabels -> Placed["Name", Center],       VertexShapeFunction -> "Capsule", VertexSize -> 1,       VertexLabelStyle -> Large,       EdgeShapeFunction ->        GraphElementData["ShortUnfilledArrow", "ArrowSize" -> 0.02]]      ![Unreadable](http://i.stack.imgur.com/Cyd6x.png) Then I discovered that `GraphPlot` produces much more readable results:               GraphPlot[      DeleteDuplicates@trans /. (DirectedEdge[a_, b_] -> Rule[a, b]),       VertexLabeling -> True, DirectedEdges -> True]      ![Readable](http://i.stack.imgur.com/PuYrg.png) Which prompted me to wonder what's the point of `Graph`. Of course I noticed this, which while related, asks about the _Combinatorica_ package.


title: How is OptionsPattern[] defined? Can I replicate this?

text: I am writing several functions which all take similar input parameters (a complicated nested list structure). Is there some way for me to define a pattern that can be used in multiple places and allows me to extract the individual parameters? (I find `OptionsPattern[]` interesting because its definition isn't really visible but somehow `OptionValues[]` is able to extract information from it.)


title: Non solutions returned by NSolve. And why does it return both phi and Cos[phi]?

text: Similarly to this thread NSolve gives additional solutions that don't satisfy the equations! NSolve returns "spurious" solutions, even increasing the working precision               fsys={1 - Cos[(11 \[Pi])/45] - (3 Cos[psi1])/4 - 2/3 Sin[phi + \[Pi]/6] == 0, h + 2/3 Cos[phi + \[Pi]/6] + Sin[(11 \[Pi])/45] - (3 Sin[psi1])/4 == 0, -0.0436952 - (3 Cos[psi2])/4 - 2/3 Sin[phi - \[Pi]/6] == 0,2/5 + h + 2/3 Cos[phi - \[Pi]/6] + Sin[(17 \[Pi])/180] - (3 Sin[psi2])/4 == 0}          NSolve[N[fsys], {phi, h, psi1, psi2}, WorkingPrecision -> 100]      The second solution returned is                   {h -> -1.99515, psi2 -> -1.22627, psi1 -> 1.68803, phi -> 0.0618559,     Sin[psi1] -> -0.993136, Cos[psi1] -> -0.116967,       Sin[psi2] -> -0.941237, Cos[psi2] -> 0.337748, Sin[phi] -> 0.0618165,       Cos[phi] -> 0.998088}, {h -> -1.99515, psi2 -> 1.22627,       psi1 -> -1.68803, phi -> 0.0618559, Sin[psi1] -> -0.993136,       Cos[psi1] -> -0.116967, Sin[psi2] -> -0.941237,       Cos[psi2] -> 0.337748, Sin[phi] -> 0.0618165, Cos[phi] -> 0.998088}      , I do not understand why both psi1 and Cos[psi1] are returned, with Sin[1.68803] actually not equal to 0.993136 (the sign is different)


title: Document settings for online viewing

text: I'm trying to figure out how to prepare a notebook for NICE online viewing when it's been converted to PDF form. The students I am working with (sadly!) will not be able to use the CDFPlayer to view existing documents. I'm to use Google Docs and save the notebooks in PDF form. I've been working with settings for margins and page sizes and paper sizes, I'll admit I'm out of my depth completely. Specifically, I'd like two things. FIRST When I save as PDF, I'd like the pages to be like actual slides in terms of size. It would be nice if each page was viewable on screen like a nice "distinct" slide. Below, a 2 second pdf creation, being viewed in Google Docs. ![sample](http://i.stack.imgur.com/U7Dlr.png) B Is there any way to set the stylesheets so I would be able to 'see' in Mathematica what my pages would look like so I can edit, space, page break accordingly. I know, I expect my question is too vague and may get "punted", but I'll need to get going on this ASAP and I simply can't get my mind around it myself. I have tons of content all ready to go in existing notebooks and now find I am faced with a massive reformatting task. I can simply format for nice "regular" pages and students would scroll, but I figured since they were viewing documents on computer, there HAVE to be ways to capitalize on that. Tom


title: How can I produce a branch cut in a surface plot based made with ListPlot3D?

text: I need to create some surface plots, based on a function that is computationally expensive (a few minutes per point). The function has some branch cuts. The command `Plot3D` does not work because it just takes too long -- never finishes at any acceptable resolution. I can get enough data points (over a day or three), put them in a matrix, and use `ListPlot3D` to produce a plot. But I don't see how to make _Mathematica_ recognize the branch cut and not connect the two sides at the discontinuity.


title: Manipulate with variable number of sliders plus variable number of functions

text: I'm trying to setup a Manipulate where I have a variable number of sliders similar to this one, where every slider controls a function. In my case, there will be an additional slider which sets the number of functions. I've tried with               Manipulate[       Block[{},         Manipulate @@            {Plot[Table[Cos[2\[Pi]Subscript[h, i]x], {i, 1, n}], {x, 0, 1}],             Sequence@@Table[{Subscript[h, i], 0, 1}, {i, n}]}],        {{n, 1, "Waves"}, 1, 4, 1}]      but that does not work. I hope I have been successful in explaining my problem. For instance this is partially working, except I can not add controls on functions, i.e. Subscript[h,i] in a nested manipulate               Manipulate[       Block[{         trange = {t, 0, tmax},         plotrange = {{0, xmax}, {-1, 1}},         aspectratio = 1/xmax,         f = Table[Cos[2 \[Pi] i t], {i, 1, n}]         },         Plot[Evaluate[f], Evaluate[trange], PlotRange -> plotrange,          AspectRatio -> aspectratio]         ],       {tmax, 0.1, 1},       {xmax, 0.1, 1},       {n, 1, 4, 1}     ]


title: Problem with convert matlab function into mathematica version of euler angle

text: I've wrote a function that will extract euler angle from matrix according to Matlab's function in AeroSpace toolbox's dcm2angle package file. But not quite right.                threeaxisrot[r11_, r12_, r21_, r31_, r32_, r11a_, r12a_] :=  Module[{r1, r2, r3},  (*        % find angles for rotations about X, Y, and Z axes*)          r1 = ArcTan[ r11/ r12];          r2 = ArcSin[ r21 ];          r3 = ArcTan[ r31/ r32];   If[Abs[r21] >= 1, Print["HA-ha"]; r1 = ArcTan[r11a/r12a];    r2 = ArcSin[r21]; r3 = 0];  {r1, r2, r3}  ]                 Matrix2EulerAngleZXY[matrix0_] :=  Module[{dcm = matrix0},   threeaxisrot[-dcm[[2, 1]], dcm[[2, 2]], dcm[[2, 3]], -dcm[[1, 3]],    dcm[[3, 3]], dcm[[1, 2]], dcm[[1, 1]]]]      * * * Matlab package directory in my computer is               "F:\\Program Files\\MATLAB\\toolbox\\aero\\aero\\dcm2angle.m"      * * *               matrixList =  Table[RotationMatrix[i, {1, 0, 0}], {i, 0, 2 \[Pi], \[Pi]/6}]//N;          Matrix2EulerAngleTrackExpression // Definition          (*         Matrix2EulerAngleTrackExpression[matrix0_,type_:ZXY]:=Module[{matrix=matrix0[[1;;3,1;;3]]}     ,ttt=ToExpression[StringCases[StringReplace[ppp=MATLink`MEvaluate[[yaw, pitch, roll] = dcm     2angle(<>matrix2Matlab[N[Chop[matrix,1/10^5]]]<>,'<>type<>')],x:(NumberString~~e-~~NumberS     tring):>0],NumberString]]]     *)      Result1 * * * This is the Matlab's result(good one).               Matrix2EulerAngleTrackExpression /@ matrixList          (*         {{0,0,0},{0,-0.5236,0},{0,-1.0472,0},{0,-1.5708,0},{-3.1416,-1.0472,-3.1416},{-3.1416,-0.5     236,-3.1416},{-3.1416,0,-3.1416},{-3.1416,0.5236,-3.1416},{-3.1416,1.0472,-3.1416},{0,1.57     08,0},{0,1.0472,0},{0,0.5236,0},{0,0,0}}     *)      * * *               Matrix2EulerAngleZXY /@ matrixList          (*         {{0.,0.,0.},{0.,-0.523599,0.},{0.,-1.0472,0.},{0.,-1.5708,0},{0.,-1.0472,0.},{0.,-0.523599     ,0.},{0.,0.,0.},{0.,0.523599,0.},{0.,1.0472,0.},{0.,1.5708,0},{0.,1.0472,0.},{0.,0.523599,     0.},{0.,0.,0.}}     *)      Where goes wrong? Do you have a robust euler angle function/package?


title: Projecting image or contour plot on xy-plane of Histogram3D?

text: I've generated a simple 3D histogram, where the x-y coordinates corresponding to the "location" of an event defined on a simple 160x160 grid, and the z-axis height is simply the count of events that occur at each x-y location. For this particular graph, I have an png image (think of it as a map) on which the 160x160 grid is defined. I'd like to use this image as the x-y floor of my Histogram3D. I'd also like to use a ListContourPlot as the x-y floor, in a companion image. Any suggestions would be most welcome. Thanks. Mark


title: Can 2D and 3D plots be combined so that the 2D plot is the bottom surface of the 3D plot boundary?

text: I have a `ListlinePlot` function, that I would like to combine with both a `Graphics3D` plot and a `ListPointPlot3D` plot, in such a way that the `ListLinePlot` is the bottom of the 3D boundary cube for the 3D plots. Can this be done in Mathematica 8.0.4? Obviously the code below fails to combine the plots in `Show`, but is there another way to accomplish this? Thanks!                   Needs["TetGenLink`"]     twodPts = RandomReal[{-1, 1}, {10, 2}];     threedPts = RandomReal[{-1, 1}, {50, 3}];     {pts, surface} = TetGenConvexHull[threedPts];          twoDptsPlot = ListLinePlot[twodPts, ImageSize -> {200, 200}];     threeDPtsPlot = ListPointPlot3D[threedPts, ImageSize -> {200, 200}];     surfacePlot =        Graphics3D[{EdgeForm[], Opacity[0.3],          GraphicsComplex[pts, Polygon[surface]], ImageSize -> {200, 200}}];          {twoDptsPlot,       Show[threeDPtsPlot, surfacePlot, ImageSize -> {200, 200},        BoxRatios -> 1, Axes -> False]}      ![Mathematica graphics](http://i.stack.imgur.com/vzAIF.png)


title: Problem In using Finding Root for an infinite series involving Hypergeometric function

text: Tc[κ_] := t /. Chop[       FindRoot[         1 == (4 κ^4 NSum[ 2/3 Hypergeometric1F1[3/2, 5/2, -((2 κ^2 l)/t)], {l, 1, Infinity}]                 + 2 κ^2 t (PolyLog[1, Exp[(-2 κ^2)/t]])                 + 2 t^2 (PolyLog[2, Exp[(-2 κ^2)/t]]                 + (2 κ^2)/t PolyLog[1, Exp[(-2 κ^2)/t]])),       {t, tstart}, AccuracyGoal -> 8, PrecisionGoal -> 8]      ]          tstart = 0.5; ni = 100; κmin = 0; κmax = 1;      dκ := (κmax - κmin)/(ni - 1);     dat = Chop[ Table[{κ = κmax - (i - 1) dκ, Tc[κ]}, {i, ni}] ];      ListLinePlot[dat]      _Mathematica_ keeps on running and doesn't produce the plot for `Tc`


title: Custom function not returning any output

text: I'm trying to write a custom function but it isn't returning any output. Here's my code so far:               Options[Alternate] = {AlternationType -> AlternationPlusMinus};          Alternate[Terms_, Exponent_, OptionsPattern[]] := (        tmpSet = {};        If[OptionValue[AlternationType] == AlternationPlusMinus,      Do[If[Mod[counter, 2] != 0,        AppendTo[tmpSet, (counter^Exponent) - 1] AppendTo[         tmpSet, (counter^Exponent) + 1]], {counter, Terms}],      Do[If[Mod[counter, 2] != 0,        AppendTo[tmpSet, (counter^Exponent) + 1] AppendTo[         tmpSet, (counter^Exponent) - 1]], {counter, Terms}]];        Return[Expand[InterpolatingPolynomial[tmpSet, x]]];        );     Alternate[20, 2]      When I execute it, no output block is even generated, let alone any error messages or warnings, is there any way to fix it? Thanks.


title: Limit for Matrix expression

text: Let's assume that $Q_0$ is $3\times 3$ matrix with $\det Q_0\neq0 $ and $$ Q_{i+1} = \frac{1}{2}\left[ Q_i+(Q_i^{-1})^T \right] $$ I need to find next limit: $\lim _{i \to +\infty}$$Q_i$. In other words I need to find such $Q_i$ that $\left|Q_{i+1} - Q_i\right| < \epsilon$. Does anybody know, is it possible to find such kind of limits with _Mathematica_?


title: noninteger indices for tables

text: Is it bad programming practice to use non-integer values to label data tables? For example, Do[data[dBx, Bz] = Table[{x,f[dBx,Bz]}, {dBx, .1, .5, .05}, {Bz, .4, 1.5, .1}] instead of introducing integer indices for the values of {dBx,Bz}. It works fine most of the time. But sometimes when I plot the data, i.e., ListDensityplot[Table[{dBx,Bz,data[dBx,Bz]},{dBx, .1, .5, .05}, {Bz, .4, 1.5, .1}]] some values are missing because for some reason mathematica adds some tiny numerical values to the indices that get called in the plot, so that 0.1 becomes 0.10000000000002


title: Automatically including custom stylesheet with notebook

text: > **Possible Duplicate:**   >  How can I easily eliminate the dependency of a stylesheet on a non-built-in > stylesheet? For some work I am doing, I take my notes in a notebook with a custom stylesheet. For my own convenience, I have separated the styles into their own stylesheet notebook, and reference within the notebook's stylesheet like is done with `Default.nb`: ![enter image description here](http://i.stack.imgur.com/vYJZl.png) Unfortunately, this makes sharing this notebook difficult with out also ensuring that the recipient has the stylesheet already installed. Barring that, what are the alternatives? The simplest would be if the `NotebookDirectory[]` was automatically included in the search for the stylesheets, then the stylesheet can be simply placed in that directory. This works great in the case of a shared network drive, but still requires a two step process for the case of email. Ideally, I would like to automatically embed _all_ of the style definitions up to a certain depth in the referenced stylesheets. How can this be most easily accomplished?


title: Cases[data,Colon[key,_]] vs. Cases[data,key:_] toward XPath, XQuery

text: Exploring methods to index and search tree-structured key:value pairs via named-entity index (key paths) as opposed to Position-based indexing.   * Using `Rule` as `key->value` causes difficulties for `Cases`, which is unfortunate since `Rule` could be combined with `ReplaceAll` to yield lightweight path queries.    * Using `List` as `{key,value}` works but too many parentheses are visually confusing especially in data fusion tasks where multiple datasets are imported separately but must be joined and indexed properly for subsequent analysis.   * Using `Equal` prevents the key from being a string, eg `"key1" = value1 --> "Set::setraw : Cannot assign to raw object key1"` Why does `Cases` interpret `Colon` shortcut `(key:value_)` differently than `Colon[key,value_]`? dataR (* for comparison *)                Out[110]= {row1 -> {key1 -> value1, key2 -> value2},       row2 -> {key1 -> value3, key2 -> value4}}           In[69]:= dataC = dataR /. Rule -> Colon           Out[69]= {row1 \[Colon] {key1 \[Colon] value1, key2 \[Colon] value2},       row2 \[Colon] {key1 \[Colon] value3, key2 \[Colon] value4}}      Then, using `Cases`:                In[113]:= Cases[dataC, Colon[row1  , v_] -> v]           Out[113]= {{key1 \[Colon] value1, key2 \[Colon] value2}}           In[114]:= Cases[dataC, (row1 : v_) -> v]           Out[114]= {row1 \[Colon] {key1 \[Colon] value1, key2 \[Colon] value2},       row2 \[Colon] {key1 \[Colon] value3, key2 \[Colon] value4}}      `Levelspec` can be specified to match the inner keys, eg `key2` at `Level 3`. Is there a more convenient syntax or method to rapidly restructure arbitrary tree-shaped data? XPath and XQuery, are W3C standards that could be adapted or improved. In particular, XQuery strikes me as being similar in flexibility as Cases in the ability to match and transform data. I've posed similar questions to Wolfram Tech Support. Has been suggested for implementation.


title: Morphing a "sheet of paper" into a torus

text: How can I visualise the standard topological "rubber-sheet" construction of a torus, that is, morphing a square into a torus? How can I start or are there any examples in the _Mathematica_ documentation respectively?


title: Problem with slot in If statement

text: I am struggling with slots, In this case I have a function int which gives either true or false. When it gives true, I want               Select[interest, (DateList[#[[1, All]]] === #)&]      to be applied however as you can see this does not work because of the slots. Problem is that I want the slot in function `int[#]` to be the same as the slot behind ===. How can I overcome this problem?                If[int[#], Select[interest, DateList[#[[1, All]]]& === #],          2 {False}] & /@ fasteDatoer]      Simple example Lets say that when first applied it states int[james], which is true. I then want it to `Select[interest, DateList[#[[1, All]]]& === james.`


title: User-defined Distance Functions with extra parameters

text: The `Nearest` function accepts a customized distance function. For example, a simple case that works well is               myDist[x_, y_] := Abs[x - y];     data = RandomVariate[UniformDistribution[{0, 1000}], 100];     nf = Nearest[data, DistanceFunction -> myDist]      So for instance, the 5 (random) numbers in `data` that are nearest 100 are               nf[100, 5]      For this particular function, I could have used `DistanceFunction->EuclideanDistance`. But I ultimately need more flexibility, to have a distance function that depends on another parameter. A simple example would be something like               myDist2[x_, y_, t_] := If[Abs[x - y] > t, t, Abs[x - y]];      where the distance is sort of as before, but if it is above the value of `t`, it returns `t` (the actual function is considerably more complicated, but this one already reveals the problem). The goal is to use `myDist2` in some way -- here are some of the statements that don't work               nf = Nearest[data, DistanceFunction -> myDist2[0.5]]     nf = Nearest[data, DistanceFunction -> myDist2[x, y, 0.5]]     nf = Nearest[data, DistanceFunction -> myDist2[#1, #2, 0.5] &]     nf = Nearest[data, DistanceFunction -> myDist2[#1, #2, 0.5]] &     nf = Nearest[data, DistanceFunction -> myDist2[#[[1]], #[[2]], 0.5] &]      (I know some of these don't make any syntactic sense, but they show how I was flailing around.) These give a variety of errors, most of which are that the               The user-supplied distance function myDist2 does not give a real numeric distance      Presumably, these are not calling `myDist2` properly. One fix would be to make the third parameter global, but this is probably a bad idea since it is embedded in a pretty complicated setting. So the question is how to add an extra parameter to the user-specified distance function.


title: How do I project a list of strings from another list to use in ChartLabels?

text: Say I have the following:               dataList = {{"One", 1}, {"Two", 2}};     PieChart[         #[[2]] & /@ dataList,         ChartLabels -> #[[1]] & /@ dataList,         PlotLabel -> "Test plot"     ]      But while the pie chart is displayed with the correct distribution, the chart labels are not displayed. This is because the output of               #[[2]] & /@ dataList      is               {One, Two}      not               {"One", "Two"}      I have also tried the following:               ChartLabels -> ToString[#[[1]]] & /@ dataList      but the outcome is the same as before. Thanks in advance for your help.


title: Strange behaviour of variables in Table

text: I'm trying to work with some vectors and have run into a strange problem. An obvious way to define a difference of two vectors would be               dif[x_,y_] := x-y      I thought an equivalent way of doing this would be               dif[x_,y_] := Table[x-z,{z,{y}}][[1]]      However, using this second method, there is some strange behaviour. When I evaluate               dif[{x,z},{0,0}]      I get the result               {x,{0,0}}      which is clearly not what I wanted. If I try evaluating               dif[{x,y},{0,0}]      instead, everything is ok, which leads me to think that the variable `z` in my definition of `dif` is treated as non-local. This seems pretty counterintuitive to me, as I was expecting `z` to act as a dummy variable. > What am I missing? One solution that works is using `Module`. This is a bit unsatisfying though, as it seems to me `z` should be treated as local even without having to explicitly demand this.


title: Finding all points of period n in an iterated map

text: I'm trying to implement an algorithm of Jenkinson and Pollicott to calculate the Hausdorff dimension of a Julia set for the map $f_c : z\mapsto z^2 + c$. It's described on page 40 of their paper, _Calculating Hausdorff Dimension of Julia Sets and Kleinian Limit Sets_. I can't seem to get the part about finding the periodic points with period $n$ to work. The idea is to partition the line from $0$ to $c$ through the complex numbers and use Newton's method on each $c_i$ using the solution from one as the initial guess to the next. For $c=0$ we know the solution because they are roots of unity. We also take another precaution: to avoid the sensitivity to initial conditions that's prevalent in Newton's method, we find the roots of $F_{c,n} - I$ instead of finding the roots of $f^n_c - \operatorname{id}$, where $$F_{c,n}(z) = \langle f_c(z_n),f_c(z_1),\dots,f_c(z_{n-1})\rangle$$ I threw this together:               partitionSize = 10;     f[z_, c_] := z^2 + c;     fDim[z_, c_] := f[#, c] & /@ RotateLeft[z, -1];     findPeriodN[N_, c_] :=        Nest[{FindRoot[fDim[z, #[[1]]] - z, {z, #[[2]]}] &, #[[2]] +            c/partitionSize &}, {NestList[#^2 &, (-1)^(1/(2 N - 1)), N], 0},         partitionSize];     findPeriodN[3, 0.25];      And it doesn't work at all. Does anybody know a simple way to do this, or some other implementation that does the same thing?


title: Take the next element in a nested list

text: My problem is the following: Consider a list of elements. To better understanding my following explanations, I would take this example:               ListA = {{a, b, c}, {d, e, f}, {g, h, i}};     ListB = {{{a, b}, {c}}, {{d, e, f}}, {{g}, {h, i}}};      Whatever the used list, I want to take an element only from the position of the previous. To illustrate (for ListA): An other program give me the position {1,3} which means the element `c` in `ListA` (`ListA[[1,3]]`). So I would take the element `d` (`ListA[[2,1]]`). I sketched a procedure: _step1_               pos1 = {1, 3};     ListA[[ pos1[[1]] ]][[ pos1[[2]] ]]; (* c *)      _step2_               Listofposition =                      Flatten[                              Table[                                    {i, j},                                    {i, 1, Length@ListA, 1},                                    {j, 1, Length@ListA[[i]], 1}                                   ],                              1                             ];      _step3_               interpos1 = Position[Listofposition, {1, 3}] + 1      _step4_               pos2 = Flatten[Listofposition[ [interpos1[[1]] ]], 1]      _final step_               ListA[[ pos2[[1]] ]][[ pos2[[2]] ]] (* d *)         We can not really say that this solution is elegant. Do you have any other solution? Knowing that most of the lists that I have to deal with have irregular dimensions as ListB. And this is, I think, the main difficulty.       _Edit_ * * * Firstly thank you for your fast answer. I wrote some code from it.   (With using Block to improve performance) Methode n°1 (Karsten 7 and Mr.Wizard) :               Index[x_] := Position[x, _, {Depth[x] - 1}, Heads -> False];          NextE1[x_, y_] := x[[Sequence @@                        Index[x][[Sequence @@ Flatten[Position[Index[x], y] + 1]]]]];          TheNextE1[x_, y_] :=       Block[             {step1, Res},             step1 = Index[x];             Res = x[[Sequence @@                    step1[[Sequence @@ Flatten[Position[step1, y] + 1]]]]]            ];      Method n°2 (Mr.Wizard) :               Index[x_] := Position[x, _, {Depth[x] - 1}, Heads -> False];     Lookup[x_] := Dispatch@Rule @@@ Partition[Index[x], 2, 1, 1, "EOF"];     NextP2[x_, y_] := y /. Lookup[x]     NextE2[x_, y_] := x[[ Sequence @@ NextP2[x, y] ]];          TheNextE2[x_, y_] :=       Block[             {step1, step2, step3, Res},              step1 = Index[x];              step2 = Dispatch@Rule @@@ Partition[step1, 2, 1, 1, "EOF"];              step3 = y /. step2;              Res = x[[ Sequence @@ step3]]            ];       Method n°3 (Mr.Wizard) (No modification) :               NextE3[expr_, pos_] :=       Module[              {f},              f[_, pos] := f[x_, _] := Return[x, MapIndexed];              MapIndexed[f, expr, {Length@pos}]             ];          NextP3[expr_, pos_] :=       Module[              {f},              f[_, pos] := f[_, p_] := Return[p, MapIndexed];              MapIndexed[f, expr, {Length@pos}]             ];      Method n°4 (Algohi) :               Index2[x_] := Cases[MapIndexed[f, x, {-1}], f[y__] :> {y}, {0, -1}]     NextP4[x_, y_] := Last@Index2[x][[Position[Index2[x], First@Cases[Index2[x], {_, y}]]                       [[1, 1]] + 1]] ;     NextE4[x_, y_] := x[[ Sequence @@ NextP4[x, y] ]];          TheNextE4[x_, y_] :=       Block[             {step1, step2, Res},             step1 = Index2[x];             step2 = Last@step1[[Position[step1, First@Cases[ step1, {_, y}]][[1, 1]] + 1]];             Res = x[[ Sequence @@ step2]]            ];            _Performance_ * * * NextE3 > TheNextE1 > TheNextE2 > TheNextE4


title: Draw only part of axis in graph

text: I'm looking to draw only one half of an axis in `ContourPlot3D`, mainly because I don't wan't the axis lines to be where the interesting stuff happens (intersection of two surfaces), but I do want to show where the axes are. This is my code so far:               ContourPlot3D[{y == x^2, z == x^3}, {x, -3, 3}, {y, -5, 5}, {z, -10, 10},        AxesLabel -> Automatic, Boxed -> False, AxesOrigin -> {0, 0, 0},        Mesh -> None, ContourStyle -> Opacity[0.3]]      This is the result it produces: ![enter image description here](http://i.stack.imgur.com/Mynnv.jpg) I would like only half of each axis to appear on the graph. I already dug through the documentation, but it seems I can only turn the axes on or off completely, no partial option. Thanks in advance for any help.


title: Mathematica implementation of Earth Movers Distance?

text: Has anyone implemented in _Mathematica_ the Earth Mover's Distance (EMD)? A concept dating back to Monge 1871, used to compare histograms and images, e.g., the CIEDE2000 Color Difference algorithm. Yossi Rubner's C implementation can be found here:   * Header file   * C source Computation of EMD is more involved than Euclidean metric. EMD is a linear constrained optimization problem, and so can be handled presumably via _Mathematica_ 's Linear Programming functionality. Although there's typically additional normalization stage, e.g.. found here.


title: Function argument to default under certain condition

text: Inspired by this and this question (and how I handle this in practice), what is the best way to default a function value when a certain condition is met? For example, if a function is defined as:               func[x_] := (x - 1)^2 + 5      and for values of `x` less than 0, `x` should equal zero. I also always want the function to evaluate even when `x` is less than 0. Normally, I would handle as such:               func2[x_] := Module[{xx = x},        If[xx < 0, xx = 0];        (xx - 1)^2 + 5]      If I try to use patterns to define the conditions, I have to define the function twice for each region:               func3[x_?Positive] := (x - 1)^2 + 5     func3[x_] := 6      I've had no luck using other patterns to define the function. While this is an admittedly easy example that can be easily handled using `Max[x,0]`, etc., patterns can be much more complex such as "integers divisible by a prime number". So, can a pattern married with a default argument handle this situation? And what is the most efficient on a computation and memory basis? **UPDATE:** Here is a more complicated version of a function to which I referred to in the comments:               func[qi_, dei_, b_, dmin_, rt_, pt_, t_] :=         Module[{ptt = Max[pt, 0], rtt = Max[rt, 0], di, diexp, xotime, xorate},         di = 1/b*((1 - dei)^-b - 1)/365;         diexp = -Log[1 - dmin]/365;         xotime = (di - diexp)/(di*b*diexp) + rtt + ptt;         xorate = qi*(1 + b*di*(xotime - ptt - rtt))^(-1/b);          Piecewise[{{qi/2 (1 + t/rtt), t <= rtt}, {qi, rtt < t <= (rtt + ptt)},             {qi*(1 + b*di*(t - rtt - ptt))^(-1/b), (rtt + ptt) < t <= xotime},             {xorate*Exp[-diexp*(t - xotime)], t > xotime}}]         ]      I'll plug in random variates (which can sometimes be zero based on the distribution), and evaluate this function multiple times. However, `rt` and `pt` should never be negative and should default to zero. In other words, have minimum value of zero. While the way I have it works well, the original question stemmed from the idea that this could be done more efficient with a pattern. jVincent's vanishing patterns solution works only if one argument has this pattern. If both `rt` and `pt` have this pattern, the vanishing pattern doesn't seem to work.


title: Is it possible to merge cells excluding results with one click?

text: Now when I merge two cells with right-click "Merge Cells", they merge with the results included, while I only want the commands merged. Can I make it a one- click button? Now I have to delete the results first then merge.


title: Annotating plots with plain (not italicized) mathematical text

text: I have a plot and I would like to annotate some mathematical text in it. Initially, Mathematica puts it in italics by using Drawing tools palette, but I want it all in plain text. How can I do it? Thanks for your time.


title: Launch a specific notebook automatically when Mathematica starts

text: I run Mathematica on an iMac running OS X 10.6.8. I have set the OS's "Launch Items" to include Mathematica so that the application opens when the computer boots. > Now I want to go further and set Mathematica to launch a specific notebook > on startup. Note: this note book has initialization cells so it will evaluate automatically. All of this goes to my ongoing automation of a variety of processes to run while I take a few days of vacation (IF I can get this working ;-) I've searched Mathematica's "Preferences" and "Options", but haven't found anything to identify or set a specific notebook to launch when Mathematica starts. If someone knows a way to do this that I haven't seen in these, please advise. The following link to an old StackOverflow question, mathematica start front end and eval notebook from command line looks like it provides a way to do what I want to do, but on a Windows OS. As I think about applying or translating this idea to my iMac, it seems like rather than having Mathematica as a "Launch Item", I have a couple of other possibilities:   * setup a shell script using something like OS X's launchD to launch Mathematica and a specific notebook OR   * use MathematicaScript to launch just the kernel and run the code currently in the desired notebook.  Neither of these are strong points. Can anyone recommend a way to do this or on Mac OS X 10.6.8 or some specific references that would help me learn what I need to do? * * * A bit of a footnote for some additional context. The notebook I need to run launches parallel kernels on a couple of servers. I've chosen this path of getting all of this to run on the machines' startup rather than putting all of this on a timer or even logging on remotely to run them because, I've found that (at least for now) restarting both Mathematica on the client machine and as parallel kernels on the servers just runs more reliably. It particularly avoids problems with kernels that haven't launched or some of which have shut down. The Mac OS has a very reliable method to launch and shutdown the machines at specific times. As I need the code in the notebook to run at specific times this seems like a good thing on which to layer the other functionality.


title: DynamicModule with constant image size

text: I am new to this forum - I wonder if someone can help me improve this code.   1. I would like the angle $\theta$ to start in the middle of the slider i.e. $\theta = 0$ instead of starting at $\theta = -90$.   2. How do I keep the circle size constant as I slide the $\theta$?               Mohr[σxx_, σyy_, τxy_] :=       DynamicModule[{g1, g2, g3}, OC = 1/2*(σxx + σyy);        R = Sqrt[((σxx - σyy)/2)^2 + τxy^2] ;        g1 = {Thickness[0.01], Circle[{OC, 0}, R]}; σxx1 :=         1/2*(σxx + σyy) + 1/2*(σxx - σyy)*Cos[2*θ*Degree] + τxy*          Sin[2*\[Theta]*Degree];        σyy1 := 1/2*(σxx + σyy) + 1/2*(σyy - σxx)*Cos[2*θ*Degree] - τxy*Sin[2*θ*Degree];       τxy1 := 1/2*(σyy - σxx)*Sin[2*θ*Degree] + τxy*Cos[2*θ*Degree];       τxy1a := 1/2*(σyy - σxx)*Sin[(2*θ*Degree + π)] + τxy*Cos[(2*θ*Degree + π)];        pts = {{σxx1, -τxy1}, {σyy1, -τxy1a}};       g2 = {PointSize[0.05], Red, Point[pts] ,          Inset[Row[{"\!\(\*SubscriptBox[\(σ\), \(xx\)]\) = ", NumberForm[σxx1, {6, 2}], ";",             "  \!\(\*SubscriptBox[\(τ\), \(xy\)]\) = ", NumberForm[-τxy1, {6, 2}]}],           Dynamic[{pts[[1, 1]], pts[[1, 2]]}]],         Inset[          Row[{"\!\(\*SubscriptBox[\(σ\), \(yy\)]\) = ", NumberForm[σyy1, {6, 2}], ";",           "  \!\(\*SubscriptBox[\(τ\), \(xy\)]\) = ", NumberForm[-τxy1a, {6, 2}]}],           Dynamic[{pts[[2, 1]], pts[[2, 2]]}]]         }  ;       g3 = {Thickness[0.01], Blue, Line[pts]};       {Column[{Graphics[{g1, Dynamic[g2], Dynamic[g3],             Inset[Text[Style["Mohr's circle", 18, Purple, Italic]], {49.58, 68.99}]},              ImageSize -> 300 ],           Row[{"θ = " Slider[Dynamic[θ], {-90, 90}], Dynamic@θ " degree"}]}]}]          Mohr[100, 0, 25]      ![enter image description here](http://i.stack.imgur.com/kQ6xc.png) **Edit** barebones version               Mohr[x_, R_] :=      DynamicModule[{g1, g2},       g1 = Circle[{x, 0}, R];       pts = Dynamic @{{R Cos@t + x, R Sin@t}, {R Cos[t + Pi] + x, R Sin[t + Pi]}};       g2 = {PointSize[0.05], Red, Point[Dynamic@pts],              Inset["A very long text", Dynamic@(pts[[1, 1]])]};       {Column[{Graphics[{g1, Dynamic[g2]}, Axes -> True],           Row[{"t = " Slider[Dynamic[t], {-Pi/2, Pi/2}], Dynamic@t }]}]}]          Mohr[100, 25]


title: Front End editing

text: As a new Mathematica user I have been grappling with many aspects of its powerful capabilities but am now beginning the find the front end very disappointing in a number of respects.   * Lack of multiple level undo (yes, I've just signed the petition and posted in the Wolfram community site on this)   * Global effect of "Replace All" in the "Find and Replace" dialog   * Weak IDE-like debugging capabilities (I will investigate DebugTrace later; I know Workbench could help but I resent the current €120 cost for what I believe should probably be core capabilities) (Rhetorical?) How do sophisticated and heavy users manage? The specific immediate question however is: does anybody have a viable approach/solution/workaround to undo/redo for (limited scope) _input cell edits_? I'm still amazed by what Mma can do, but what it can't do is becoming increasingly baffling.


title: Implementing efficient multiple undo

text: _At the time this question was asked, version 10 was not out yet. The Front End of Mathematica 10 does have multiple undo, see the answer by John Fultz._      The Mathematica Front End's built-in Undo command can only undo a single editing step. **Has anyone implemented or seen implemented an efficient and comfortable multiple undo?** I have in mind ideas such as, `CellEventActions` that keeps a stack in the cell context pushing the cell state every time a key among a list (brackets, @, operators) is pressed. Some other shortcut to recover older states (or a palette, or perhaps tweaking the front end's .tr files??) I am not familiar at all with typical text based implementations and their issues. I guess it wouldn't be a practical problem to lose the undo state between sessions, would it? So, has this been done, or is it doable or practical? What are your thoughts?


title: Get Mathematica to simplify $\cosh(i x)$

text: I want Mathematica to simplify `Cosh[I x]` to `Cos[x]` if I tell Mathematica that `x` is Real. I have tried everything, but it ends up giving `Cosh[I x]` back.


title: What does "Tag Integer is Protected" message mean?

text: _(Newbie question)_ For every function I define I get this message: ![enter image description here](http://i.stack.imgur.com/LT9kH.png) When I close and reopen Mathematica, and re-enter the function definition, I don't get the message anymore. What does it mean?


title: How to get matching starting dates for different `FinancialData` properties?

text: Why do the `"Return"` and `"Volume"` outputs of `FinancialData` differ? Consider the following input for `"Return"`               FinancialData["APL","Return",{{2014,8,14},{2014,8,19}}]      with output               {{{2014,8,15},0.00202899},{{2014,8,18},0.00578536}, {{2014,8,19},-0.00517688}}      versus this input for `"Volume"`               FinancialData["APL","Volume",{{2014,8,14},{2014,8,19}}]       with output               {{{2014,8,14},348800},{{2014,8,15},610700},{{2014,8,18},247200},{{2014,8,19},290500}}      **Notice** : Each function takes the same period, yet the Return input yields one less date. The output dates match if I make the following modification for the Return input               FinancialData["APL","Return",{{2014,8,13},{2014,8,19}}]      which outputs               {{{2014,8,14},0.0102489},{{2014,8,15},0.00202899},{{2014,8,18},0.00578536},{2014,8,19},-0.00517688}}      Now, the dates for Return and Volume match up and the crisis is averted. However, this seems an inelegant fix. Is there something that I am just missing in the aforementioned example? Additionally, I have tested this on multiple stocks, so it is not an artifact of "APL" which I chose at random.


title: Creating Do loop that cycles back to earlier values

text: I need to create a `Do` loop that distributes letters in a list of lists. I also need to be able to cycle back through to the beginning of the list. For example, I need to change               list={{a},{a},{a},{a},{a},{a},{a},{a}}       to > >     {{a,b},{a},{a,b},{a},{a,b},{a},{a,b},{a}}.   >   But, I need to add the `b` to `list[[5]]`, then `list[[7]]`, then `list[[1]]`, then `list[[3]]`. Is there any way to use a do function to do that or should I find another method?


title: Writing loops for triangle elements

text: ![enter image description here](http://i.stack.imgur.com/2yAIc.png) I'm kind of new to using Mathematica, so any help is great. I'm trying to write a program that will create a list or matrix that will give each small triangle's point numbers. For example if given an isosceles right triangle, the example below gives the sides as 4 and the numbering of the points is just like below, then it should give a list or table such as               dat= {{1,2,6},{2,3,7},{3,4,8},{4,5,9},{6,7,10},{7,8,11},{8,9,12},{10,11,13},        {11,12,14},{13,14,15},{2,6,7},{3,7,8},{4,8,9},{7,10,11},{8,11,12},{11,13,14}}.       I've tried writing a few loops, but am not getting anywhere. I know that the starting number on the diagonal of the big triangle will add whatever the side is and start decreasing that value as u go up. For example, the first point always starts at 1, and as u move up the rows of triangle, you add `1+(x+1)` to get 6. Then going up the next row of triangles, it is `6+(x)`, to get 10. And so on. So I see two iterators? once increasing? one decreasing? Any help or ideas will be helpful. Thanks!


title: Multiple plots on same graph for different parameter?

text: I would like to be able to `Plot` a function (with an implicit `Integrate` command) with various values for a certain parameter (`phi` in the code below for values `0.01` and `0.02`) all on the same `Plot` to compare.Below is my code:               e = 1.60217657*10^-19;     n = 10^-9/e;     R = 1.5;     sigma = 50*10^-6;     p = (R*phi^3)/(24 sigma);     g = D[Exp[-((curlEprime)^2/2)], curlEprime];          G = p^(-(1/3)) (Exp[-((curlE - p)^2/2)] - Exp[-((curlE - 4 p)^2/2)]) +     Integrate[1/(curlE - curlEprime)^(1/3) g, {curlEprime, curlE - p, curlE}];          de = (2 e^2 n)/(3^(1/3) Sqrt[2 Pi] R^(2/3) sigma^(4/3)) G          Plot[de, {curlE, -10, 10}] /. phi -> {0.01, 0.02}


title: How to prevent function from passing values to slot

text: For the following example:               {#, #} & /@ {1, 2}      I am trying to find a method to hold one of the slots (or both ) so that the function do not pass the values to the slot I want to protect. for example I want to get something like this:               {{1, #}, {2, #}}      I tried all type of Hold on the second slot but without and success. any suggestion?


title: Why is Chop ignored in Plot?

text: I want to plot multiple functions with the same settings side-by-side, so I use the pure function construct (for clarity, I only use one function in this example)               Plot[        #,        {x, 0, 1}        ] & /@     {        Chop[x, 0.5]     }      however, it somehow ignores the Chop function: ![enter image description here](http://i.stack.imgur.com/kAMYm.png) If I plot the function directly               Plot[        Chop[x, 0.5],        {x, 0, 1}     ]      everything works as expected: ![enter image description here](http://i.stack.imgur.com/cie3d.png) I get similar behaviour with Plot3D. Do you see a problem in my code? Does the pure function and Map mechanism (/@) have something to do with it? PS: I, in fact, want to use Plot3D. That's why I want to draw multiple plots next to each other instead of plotting all functions within one graphics object. I only chose showing the problem using Plot function in order to make the example simpler.


title: How to name a variable with the value of another variable?

text: A simple but very important (at least for me) question. In some languages for defining a variable, for example, we can do: i=10 "d"&i=30 So I have defined the variable d10, and... d10=30 That is to say... I've named a variable (d10) as as function of an other variable (i). How can I do this in Mathematica? Sorry if the title is bad. Regards!


title: How can I add drop shadows to the text of non-input/output cells?

text: Inspired by simon woods's wonderful shadow function, I want to add drop shadows to all the text of non-input/output cells in a notebook, something like this: ![enter image description here](http://i.stack.imgur.com/hokkY.jpg) By using simon woods's shadow function, I can take some text and add shadow to it:               style["Some text","Text"]//shadow[#,#]&      And then paste the resulting image back. But I can't automate this process. My question is   1. how to make a function that take a notebook as input, and output a "shadowed" version with all the text of non-input/output cells having shadow?   2. If 1 can be done, is it possible to reduce the size of the "shadowed" notebook? As all the text is replaced with images, the notebook may be large. Thanks very much!


title: Identifying critical points of 2/3D image/cubes

text: **Upshot** I am interested in identifying critical points of a 3D field/cubes (maxima, minima, tube-like and wall-like saddle points) and 2D field/image (maxima, minima, saddle points). I.e. the generalisation of How to find all the local minima/maxima in a range. **Attempt(s)** The mathematica functions `MinDetect` and `MaxDetect` address partially my request in 2D, as illustrated (using the `GaussianRandomField` function defined here)               u = GaussianRandomField[192] // Chop // GaussianFilter[#, 8] &;     iu = Image[u] // ImageAdjust //Colorize[#, ColorFunction -> "ThermometerColors"] &      ![Mathematica graphics](http://i.stack.imgur.com/dvstY.png) Indeed               um = Image[u] // MinDetect;     uM = Image[u] // MaxDetect;     ImageAdd[ImageAdd[iu, uM], um]      ![Mathematica graphics](http://i.stack.imgur.com/KeOHt.png) Shows that maxima and minima have been detected. On the other hand, saddle points are still to be found. A related query was made there, which is a possible starting point since critical points are the simultaneous zeros of the (2 or 3 components of the) gradient. Let us try and follow this method:               fu = u // ListInterpolation;     fux = Function[{x, y}, D[fu[x, y], x] // Evaluate];     fuy = Function[{x, y}, D[fu[x, y], y] // Evaluate];          fuxx = Function[{x, y}, D[fu[x, y], {x, 2}] // Evaluate];     fuyy = Function[{x, y}, D[fu[x, y], {y, 2}] // Evaluate];     fuxy = Function[{x, y}, D[fu[x, y], x, y] // Evaluate];          pts = FindAllCrossings2D[{fux[x, y], fuy[x, y]}, {x, 1, Dimensions[u][[1]]},           {y, 1, Dimensions[u][[2]]},           Method -> {"Newton", "StepControl" -> "LineSearch"},            PlotPoints -> 256, WorkingPrecision -> 20] // Chop;          dets = Map[fuxx @@ # &, pts] Map[fuyy @@ # &, pts] -      Map[fuxy @@ # &, pts]^2;     trs = Map[fuxx @@ # &, pts] + Map[fuyy @@ # &, pts];      Selecting saddles as critical points which have a Hessian determinant negative.               w = Map[If[# < 0, 1, 0] &, dets]*Map[If[# > 0, 1, 0] &, trs];     saddles = Most /@ Select[Transpose[Join[Transpose[pts], {w}]], #[[3]] == 1 &];      and the maxima and minima               w = Map[If[# > 0, 1, 0] &, dets]*Map[If[# < 0, 1, 0] &, trs];     max = Most /@      Select[Transpose[Join[Transpose[pts], {w}]], #[[3]] == 1 &];     w = Map[If[# > 0, 1, 0] &, dets]*Map[If[# > 0, 1, 0] &, trs];     min = Most /@      Select[Transpose[Join[Transpose[pts], {w}]], #[[3]] == 1 &];      Check that they are indeed at the intersection of the zero gradient contours               ContourPlot[{fux[x, y], fuy[x, y]}, {x, 1, 256}, {y, 1, 256},       Contours -> {0}, ContourShading -> False,       ContourStyle -> {Red, AbsoluteThickness[1.5]},       Epilog -> Join[{{AbsolutePointSize[6], Green, Point /@ saddles},      {AbsolutePointSize[6], Red, Point /@ max},      {AbsolutePointSize[6], Blue, Point /@ min}}]]      ![Mathematica graphics](http://i.stack.imgur.com/UW3mH.png) and that they correspond to critical points of the underlying field                Show[{ContourPlot[fu[x, y], {x, 1, 256}, {y, 1, 256}, Contours -> 35,       ColorFunction -> "ThermometerColors"],      Graphics[{AbsolutePointSize[6], Purple, Point /@ max}],      Graphics[{AbsolutePointSize[6], Gold, Point /@ min}],      Graphics[{AbsolutePointSize[6], Green, Point /@ saddles}]}]      ![Mathematica graphics](http://i.stack.imgur.com/QBwTN.png) **Questions** i) would you know of a more efficient way of finding the saddle points in 2D? ii) could this algorithm be generalized to 3D without significant loss of efficiency? (involves possibly writing a 3D version of `FindAllCrossings2D`) iii) how robust can it be in terms of the smoothness of the field? Here I am after an algorithm which would be efficient (I would like to identify thousands of critical points).


title: Numeric output formats

text: I want to print the expression $A[x] = 8020.6596 \times 1.055^x$ as is on a 2D graphic. I included the line               Graphics[Text[HoldForm[A[x] = 8020.6596 \[Times] 1.055^x],{2,0}]]      in the graphics call, but the first constant insists on printing as $8020.66$. How can I fix this problem?


title: Reverse engineer a sample value from a CDF

text: The image below shows the cumulative distribution of a normal distribution with mean = 4 and standard deviation = 1. Notice that if you have a value with a rank of 0.8 (meaning it would be 80th item from the bottom in a sorted list of 100 items) you could get the corresponding value from the CDF of a normal distribution of any mean/sd (if you knew how to do it). I'll bet there is a nice way to do this. I can only think of overly complicated, never do it what way! ways. ![enter image description here](http://i.stack.imgur.com/KBJau.png)


title: How can I merge multiple sets of morphological components (perhaps selected using different metrics)?

text: Let's say I use `SelectComponents` to select morphological components in an image according to some criterion, like "Elongation". Then let's say, I pull out a different set of morphological components using another criterion like "Area".               m1 = SelectComponents[testImage, "Elongation", # == 1 &];     m2 = SelectComponents[testImage, "Area", # > 42 &];      How can I properly merge `m1` and `m2` into a single set of non-intersecting morphological components?


title: Is there a way to plot a single level curve of a function of x and y through a given point?

text: For example, I am trying to plot the single level curve of               f(x,y)=xsin[y/x]+ysin[2x]       that goes through the point (3pi,3pi). Can anyone show me how to do this?


title: I need to draw a direction field and x1 vs t graph for the ode

text: I have written the following codes and i am able to get to the trajectory but not able to draw the direction field and x1 or x2 vs time plots.               A = ( {{2, -1},{3, -2}} )      Eigenvalues[A]      Eigenvectors[A]      X[t_] = {x1[t], x2[t]}      system = X'[t] == A.X[t]      sol = DSolve[system, {x1, x2}, t]      particularsols =      Partition[      Flatten[Table[{x1[t], x2[t]} /. sol /. {C[1] -> 1/i,      C[2] -> 1/j}, {i, -20, 20, 6}, {j, -20, 20, 6}]], 2];      ParametricPlot[Evaluate[particularsols... {t, -10, 10},      PlotRange -> {-1, 1}, AxesLabel -> {x1, x2}]


title: Why are all the lines commented when I create a Mathematica script?

text: When I created a _Mathematica_ script, I found that all my lines were commented out (when opened with `vi` or `gedit` or any other text editor). So I either need to get rid of the `(**)` manually or through a bash script before I run my _Mathematica_ script from a unix terminal. To create my script, I include the shebang `#!/usr/local/bin/MathematicaScript -script` on the first line and then save my file as a `.m` package. The resulting file looks something like this:               (* ::Package:: *)          (* ::Input:: *)     (*#!/usr/local/bin/MathematicaScript-script*)          (* ::Input:: *)     (**)     (*f[x_] := x*)      **Why are my lines commented? Is there anything I need to do?**


title: How can I efficiently check if a graph is unit distance?

text: A unit distance graph is a graph that is embeddable in the plane so that every edge has length 1.               UnitDistanceQ[input_]:=Module[         {g, x, F, v, min, nod, gl},         g = input;         gl = Length[g]; (* Vertex Count *)         (* 2 vertex count variables x1, x2, etc... *)         x = Table[Symbol@@ToExpression["x" <> ToString[i]], {i, 1, 2*gl}];          (* The force to minimize is the squared error of the lengths *)          F = \!\(     \*UnderoverscriptBox[\(\[Sum]\), \(i = 1\), \(gl\)]\(     \*UnderoverscriptBox[\(\[Sum]\), \(j = 1\), \(gl\)]g[[i, j]] \((\((x[[2  i]] - x[[2  j]])\)^2 + \((x[[2  i - 1]] - x[[2  j - 1]])\)^2 - 1)\)^2\)\);         (* Initial vertex positions *)           v = Table[gl*Random[], {i, 1, 2*gl}];         (* Minimization *)           {min, nod} = FindMinimum[F, Transpose[{x,v}], Method->"QuasiNewton"];         (* Output Solution *)                If[min < 10^-3,             Print[{min,nod}];             GraphPlot[g, VertexCoordinateRules ->                  Thread[Range[gl] -> Partition[ x /. nod, 2]],             AspectRatio -> Automatic,              VertexLabeling -> None,              ImageSize->Small]         ]     ]      For example, the golomb graph is unit distance.                g = Graph[               UndirectedEdge @@@ {{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 6}, {3,                   8}, {4, 5}, {4, 9}, {4, 10}, {5, 6}, {5, 10}, {6, 7}, {6,                   10}, {7, 8}, {7, 10}, {8, 9}, {8, 10}, {9, 10}}];         m = AdjacencyMatrix[g];         UnitDistanceQ[m]         (* gives             FindMinimum::sdprec: Line search unable                   to find a sufficient decrease in the function value with                   MachinePrecision digit precision. >>      *)      So the question is how to check for a unit distance embedding as fast as possible, my code is not working yet but I think something along these lines will work... My iterative approach works well for the golomb graph when run many times ![enter image description here](http://i.stack.imgur.com/89EOA.png) This is a great question and cool algorithms could be invented here!


title: How to plot the convolution of dirac delta series with a sine function

text: I am new to mathematica. I do the convolution of dirac delta :(DiracDelta(x-10)" with "sine(t),t=0-pi". How to plot the output ? Theoretically, the full wave should appear at the location of the singularity.


title: How to avoid CopyTensor in CompiledFunctions?

text: In a reply here  Leonid wrote, “Compile can handle a number of higher-level functions, such as Transpose, Partition, Map, MapThread, etc. Most of these functions return expressions, and even though these expressions are probably passed to the calling function, they must be created. For example, a call to ReplacePart which replaces a single part in a large array will necessarily lead to copying of that array. Thus, immutability generally implies creating copies.” However, I still don't understand what things besides the obvious would lead to a CopyTensor. Please help me understand what constructs lead to CopyTensor in my CompiledFunction, and how the CopyTensor can be avoided.


title: Generating Palindromic_number

text: I'm trying to construct Palindromic_number, I came up with this code:               palind[n_] :=        FromDigits /@ Join[#, #[[All, -Mod[n, 2] - 1 ;; 1 ;; -1]], 2] &@        Tuples[MapAt[Rest, Array[0~Range~9 &, Ceiling[n/2]], 1]];          palind[3]          (*     {101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, \     232, 242, 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, \     373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494, 505, \     515, 525, 535, 545, 555, 565, 575, 585, 595, 606, 616, 626, 636, 646, \     656, 666, 676, 686, 696, 707, 717, 727, 737, 747, 757, 767, 777, 787, \     797, 808, 818, 828, 838, 848, 858, 868, 878, 888, 898, 909, 919, 929, \     939, 949, 959, 969, 979, 989, 999}     *)      Any better ideas?


title: Preventing evaluation until all undefined symbols are resolved

text: FixedPoint[If[# <= 0, 0, # - 1]&, 2 x]      Causes an infinite loop because of 'x'. How do i automatically prevent evaluation until `2 x` is known? I have a similar function being fed into `Plot[]` and it has control over when `x` is known.


title: Adaptive sampling for slow to compute functions in 2D

text: **EDIT:** Although I have posted an answer based on my current progress, this in incomplete. Please see the "open issues" section in the answer. * * * Most plotting functions in Mathematica adjust the sampling density dynamically, based on the slope of the function:               DensityPlot[1/(      1 + Exp[10 (Sqrt[x^2 + y^2] - 3)]), {x, 0, 5}, {y, 0, 5},       Mesh -> All, PlotRange -> All]      ![Mathematica graphics](http://i.stack.imgur.com/w9zce.png) Unfortunately the internal algorithm that does this is not directly callable. * * * **Question:** I have a slow to compute 2D function (takes up to 10-40 seconds for a single point even though it's in optimized C++ called through LibraryLink) that I need to sample. How can I sample it adaptively, in a convenient and controlled way? Since the function is so slow to compute,   * I'd like to be able to take the existing points, and refine them more if needed (i.e. continue the computation using the existing results)   * I can't use DensityPlot directly because I can't control how many points it is going to compute, and I need an upper limit on that (i.e. an upper limit on computation time). It also can't be interrupted and continued later. I am looking for   1. effective methods to do this   2. implementations in Mathematica (either as an answer or pointers to libraries) **The messy details:** I am trying to compute a phase diagram and map the boundaries between the phases precisely. So I don't need the function value everywhere, only where it very suddenly drops. The function is either of magnitude 1 (say, between $0.1 \div 1$), or very small (close to zero). The function is computed using Monte Carlo methods, so at a small scale it doesn't appear smooth, and I might get inconsistent results close to the phase boundaries on subsequent runs of the function. This should give you an idea of what sort of function I'd like to apply this to, which might be important when choosing a method.


title: ImageCapture on Windows 8.1

text: I have an _Asus SmartTab_ tablet with _Mathematica 9_ on it. When I run `ImageCapture`, nothing shows up in the image window. Originally running this completely crashed the entire OS forcing a reboot, but I have done some updates since. Now I just get the blank window effect.   Does anyone have any ideas on if this is fixable, or has had this happen?


title: How to work with characters from CJK Unified Ideographs Extension B correctly?

text: **Background:** Recently I'm trying to deal with some Chinese characters which belongs to the **CJK Unified Ideographs Extension B** block. The motive comes from some further interest following a former question, and some ideas of using Mathematica for typesetting ancient Chinese scriptures. **Edit:** Here is some sample code which looks fine at first sight ( The Unicodes of the three characters involved here are `x20027`, `x200D5` and `x20137`. The setting of the `$SystemCharacterEncoding` of my Mathematica is `"CP936"`. ): ![enter image description here](http://i.stack.imgur.com/M82qV.jpg) But after saving then closing the notebook, I re-opened it, without touching anything, the Front End displays weird now (and note the attendance of the syntax errors): ![enter image description here](http://i.stack.imgur.com/gt1RE.jpg) It seems the Front End is not able to correctly render them. Furthermore, although I can create a textcell looking fine: ![enter image description here](http://i.stack.imgur.com/1iHMS.jpg) whose `CellExpression` is:               Cell["\:d840\:dc27\:d840\:dcd5\:d840\:dd37", "Text", CellChangeTimes->{3.5359048507534103`*^9}]      but if I trig `Ctrl+Shift+E` and edit the `CellExpression` directly (eg. deleting the `CellChangeTimes` item, which should not affect the "appearance" of the cell), then convert the cell back to normal status, things get wrong again: ![enter image description here](http://i.stack.imgur.com/Uy3ku.jpg) This kind of problem never happened when dealing with characters from **CJK Unified Ideographs** and **CJK Unified Ideographs Extension A** blocks, so I guess there may be a bug here. So my questions is: While I do realize the `"Unicode"` encoding in Mathematica referring to only 16-bit Unicode while the CJK-B begin with `x20000`, is there any method to render and work with characters from **CJK Unified Ideographs Extension B** correctly?


title: Efficient code for tallying entries in very large lists

text: I am dealing with data sets containing tens of millions of (hashable) entries and simply using the `Tally` function to count the frequency of each unique list element maxes out available memory. What's the most efficient way to perform this sort of operation on very large lists? Some clarifications:   1. I actually don't need all values. I need all values that occur more than once and a sizeable majority of the values occur only once.   2. The datasets themselves do fit in memory in their entirety.


_**How to explain the result of the two functins?_** Input1:               myperiodic[func_, {val_Symbol, min_?NumberQ, max_?NumberQ}] :=      func /. (val :> Mod[val - min, max - min] + min);     Plot[myperiodic[t, {t, -5, 5}] // Evaluate, {t, -40, 40}]      Input2:               f[t_] := If[-5 <= t <= 5, t, If[t > 0, f[t - 10], f[t + 10]]];     Plot[f[t] // Evaluate, {t, -40, 40}]       ![How to explain?](http://i.stack.imgur.com/vJ3c8.png)


title: Why is the Locator snapping back to the original coordinates? How can I prevent this?

text: Take the following code:               p = {3, 3};     Graphics[Circle[{5, 5}, 5], Epilog -> Dynamic@Locator[Dynamic[p]],      Axes -> True, GridLines -> {{3}, {3}}]      ![Mathematica graphics](http://i.stack.imgur.com/tLwho.png) Whenever I move the locator close to the original coordinates (marked by the grid on the plot), it quickly snaps back to them. This means that I am unable to position the locator at around `{3.25, 6}`. It will either snap to `{3.0, 6}` or to `{3.5, 6}`. (Please see the image, it is at `{3.5, 6}` there.) Is this a feature or a bug? If it is a feature, how can I turn it off? If it is a bug, how can I work around it? Note that I am using `Epilog` because the graphics in my actual problem are slow to compute/render (large `ListDensityPlot`).


title: extract values from replacement list

text: Solve returns a list of replacement rules               In: Solve[x + y == 3 && x - y == 6, {x, y}]     Out: {{x -> 9/2, y -> -(3/2)}}      I am only interested in the right hand side of these rules. To extract the right hand side I use substitution:               ({x, y} /. sol)[[1]]      It gives               {9/2, -(3/2)}      This works, but it is not very elegant. You have to adapt the list of the variables, each time you solve for different variables. Is there a more general way to extract the right hand sides form a list of replacements? **Edit** The number of variables and the number of solutions may both differ.


title: Quantile & TransformedDistribution

text: xd = ExponentialDistribution[1.0];     yd = ExponentialDistribution[5.0];     td = TransformedDistribution[x/(x + y), {x \[Distributed] xd, y \[Distributed] yd}];     Mean[td]     CDF[td, z]      All the above works as expected. But when I do               Quantile[td, 0.95]      I get the input echoed as the answer, i.e. MMA can not do this. Same answer in 9 & 10. Any suggestions? Known bug or am I doing something wrong?


title: Creating an animation illustrating the time-evolution of a pre-computed orbit

text: As the title says, I would like to use Mathematica in order to create an animation depicting the time-evolution of a three-dimensional (3D) orbit. To begin with, I have an ASCII file which contains the orbit data into four columns. The first column corresponds to the time, while the next three to the x, y and z coordinates respectively. Below, I present a simple code so as to visualize the orbit.               SetDirectory[" ... "];     data = ReadList["orb_3d.out", Number, RecordLists -> True];     dataOrb3D = Table[{data[[i, 2]], data[[i, 3]], data[[i, 4]]},      {i, 1, Length[data]}];      S0 = Graphics3D[Line[dataOrb3D], Axes -> True, AxesStyle ->     Directive[FontSize -> 17, FontFamily -> "Helvetica"], AxesLabel ->      {"x", "y", "z"}, BoxRatios -> {1, 1, 1}, ImageSize -> 500]      The above code produces this image: ![enter image description here](http://i.stack.imgur.com/jknDA.jpg) In order to obtain the ASCII data file, please follow this link. OK, so far so good. Now let me explain the simulation part. The orbit describes the motion of a test-particle (star) under the gravitational field of a galaxy. According to the data file, when t=0 the star must be at (x,y,z) = (0.5,0,0.5). So, I would like to plot at that point, let's say a blue dot, inside the 3D volume. Then as time evolves the blue dot which indicates the star should follow the path according to the data file moving from point to point, join them thus leaving a solid line behind it. When t=250 the simulation finishes and we should have reproduced the image I present earlier. Honestly, I am not sure if what I described is possible with Mathematica. Anyway, it would be great, if there was also a label inside the 3D box (or above it) giving the value of the time at every step of the simulation (i.e. t = 73.27). Finally, I would also like to be able to export this simulation as an .avi or .mp4 file. I know that I described a very ambitious project here! However, I also think that it is a very interesting topic. Many many thanks in advance and I look forward for your replies.


title: importing and manipulating data file

text: I have a large text file containing numeric data of 1000 groups each of 200 lines. The lines are unsorted. There is a 9 line header at the beginning of each group, i.e., 209 ⨉ 1000 lines altogether. I want to drop the headers to have a file containing 200 ⨉ 1000 lines. I also want the 200 lines of each output group sorted by the first number in the line. What is a way to do this efficiently in _Mathematica_? My actual data set is much larger than 200 lines and 1000 groups. I made up these number for the sake of discussion.


title: How can I extract the maximum value from a Histogram?

text: In Mathematica 8.04 I've created a histogram of returns on a stock using:               returns = FinancialData["SP500", "Return", {Date[] - {5, 0, 0, 0, 0, 0}, Date[]}, "Value"];     μ = Mean[returns];     h = Histogram[returns, 300, "PDF"];      ![Mathematica graphics](http://i.stack.imgur.com/rJO3b.png) where "returns" is a list of the daily returns, and I want 300 bins in the probability density method. Next, I would like to draw a line that represents the mean of the returns so I use:               meanLine = Graphics[{Thick, Darker[Green], Line[{{μ, 0}, {μ, maxFreq + 2}}]}];      The problem is that I need to calculate the highest y-value for the line, which should be equal to the count of the data points in the bin with the most points (I've called this `maxFreq` above). I am currently setting this value manually because I don't know how to extract it from the histogram (h). Note that the x-coordinate of this line (`μ`) is simply the mean of the returns. I've tried looking at `FullForm[h]` to see if I could figure out how to extract the data. Buried within that output is the following:               List[List[Rectangle[List[-0.0015, 0.], List[-0.001, 54.0111]      which shows that I want to set maxFreq = 54.0111. So, I suppose that I want to use the `Max` function, but I don't know how to access the heights of each bin. I think that I need to use some variation of the `Part` function, but I can't figure out how. Any clues would be appreciated. Here is the code that will generate what I'm looking for, but maxFreq is manually entered:               returns = FinancialData["SP500", "Return", {Date[] - {5, 0, 0, 0, 0, 0}, Date[]}, "Value"];     μ = Mean[returns];     h = Histogram[returns, 300, "PDF"];     maxFreq = 54;     meanLine = Graphics[{Thick, Darker[Green],Line[{{μ, 0}, {μ, maxFreq + 2}}]}];     Show[h, meanLine]


title: Puzzling behavior produced by Exists

text: I need to simplify a set of solutions of a system, say for example:               A := (a[1] == 3 && a[2] <= 1 && b[1] <= 5) || (a[1] == 3 && a[2] == 1 && b[1] == -7)      I care only about `a[1]` and `a[2]` but I can not use `Eliminate` since I have inequalities. So one solution is:               Simplify[Reduce[Exists[{b[1]}, A]]]      > a[1] == 3 && a[2] <= 1 It works! But since I have a large system (many b's) I need to automate this. Since:               Array[b, 1]      > {b[1]} I tried:               Simplify[Reduce[Exists[Array[b,1],A]]]      > a[1] == 3 && a[2] <= 1 && b[1] <= 5 The second method yields the wrong outcome! What am I doing wrong here?


title: "Not a valid Filling specification" error

text: I have a function, which plots the given function array `f`. This is a part of the function:               Plot[-f, {x,0,2}, Filling->{1->{2}}, PlotStyle->Green]      When I specify `{x^2, 2x}` as the function `f`, I get the errors `"2 must be an integer between 1 and 1. "` and `"{2} is not a valid Filling specification."`. I get this error because I have a minus sign in front of the argument `f`. If I plot `{-x^2,-2x}` then everything is fine. So how to multiply everything in `f` by -1 without getting these errors?


title: Replace function and its derivatives found with Solve

text: If I have an equation               eq = f[x] + g[x] == 0      and I solve for `f[x]`               sol = Solve[eq,f[x]]      how do I use `sol` to replace both `f[x]` and its derivatives in another equation? For example               eq2 = f'[x]*g[x] + f[x] == 0      and then               eq2 /. sol      outputs               {-g[x] + g[x] f'[x] == 0}


title: Running postgresql query with backslash

text: I've been able to connect to a Vertica database, and also been able to run a SELECT query. But I'm not being able to run a query with a backslash in it. (Vertica has commands like postgresql.) The command I'm trying to run is `\d;`. I've tried variations like below with a varying number of backslashes without success: `SQLExecute[conn, "\\\d;"]` What am I doing wrong? Any help would be greatly appreciated! Edit: I should add that the error I'm getting is this: `JDBC::error: [Vertica][VJDBC](4856) ERROR: Syntax error at or near "\" >>`


title: Builder pattern for complex objects construction

text: **Intro** I was watching "UnRisk-Q Instrument Builder" talk (https://www.youtube.com/watch?v=Xx3goIBpOdE) and those guys use builder pattern to build complex objects like this:               bondBuilder = BondBuilder[]     bond = bondBuilder @ Nominale[1.] @ StartDate[{2010,10,10}] @ Build[]      and later `bond` is immutable and you can invoke methods on it: `bond @ SomeMethod[]` The reason it works is them using JLink and `@` behaves weirdly there and associates to the left. **Question/Problem** How to implement a builder pattern that:   * looks good & concise in notebook and .m files? You could use custom operator instead of `@` or some `~infix~` notation, but that looks heavy.   * allows partial builder reuse like:              octBuilder = BondBuilder[] @ StartData[{2010, 10, 10}]     bond1 = octBuilder @ Nominale[1.] @ Build[]     bond2 = octBuilder @ Nominale[2.] @ Build[]        * has enough flexibility to add error checking to `Build[]` I obviously do not want to mess a lot with `@` and try to redefine its associativity. I do not want to copy the look but the idea.


title: Visualizing a 2-dimensional PDF

text: I have empirical data that describes a 2-dimensional Probability Density Function and I want to visualize that data in a meaningful way using Mathematica. My first instinct is to use a 2D Heat map style plot, where high probabilities would be shown in red, and low in blue or white. However I am a novice when it comes to Mathematica's visualization power so I would like some community input. Is there a better way to visualize this data?


title: How to plot a function with two parameters determined by another parameter?

text: I have one small question. My code is like follows.               a = 5;      mm = Solve[a x + y == 7 && x - y == 1, {x, y}];      t1 = x /. mm[[1]];      t2 = y /. mm[[1]];           myfunction[{x_, y_}] := (y + x)/(x + r)     Plot[myfunction /@ {{t1, t2}}, {r, 0, 3}, Evaluated -> True]      I want to change plot of `myfunction` for different `a` in one plot. How could I do? Thanks. **Edit** \- The actual code is more complex than the stripped down example above and fails to produce the figure showing the function ppw[r] for different values of bb. I have tried the replacement methods suggested by Peltio, but they do not work Here is a simplified version of the code using only linear ODEs:               xxin[aa_?NumericQ, bb_?NumericQ] :=NDSolve[{\[Psi]''[r] == -bb \[Psi][r], \[Psi]'[0.1] ==0, \[Psi][1] == aa}, \[Psi], {r, 0.1, 1}, PrecisionGoal -> 20]     xxshell[aa_?NumericQ, cc_?NumericQ] :=NDSolve[{\[Psi]''[r] == \[Psi][r] + 1, \[Psi][1] ==aa, \[Psi][1.5] == cc}, \[Psi], {r, 1, 1.5}, PrecisionGoal -> 20]     xxout[cc_?NumericQ] :=NDSolve[{\[Psi]''[r] == \[Psi][r], \[Psi][1.5] ==cc, \[Psi]'[3] == 0}, \[Psi], {r, 1.5, 3}, PrecisionGoal -> 20]     xxinaTry[aa_?NumericQ,bb_?NumericQ] := (Evaluate[\[Psi]'[1] /. xxin[aa, bb]])[[1]]     xxoutaTry[aa_?NumericQ,cc_?NumericQ] := (Evaluate[\[Psi]'[1] /. xxshell[aa, cc]])[[1]]     xxinbTry[aa_?NumericQ,cc_?NumericQ] := (Evaluate[\[Psi]'[1.5] /. xxshell[aa, cc]])[[1]]     xxoutbTry[cc_?NumericQ] := (Evaluate[\[Psi]'[1.5] /. xxout[cc]])[[1]]           bb = 0.8;       sols = FindRoot[{ xxinaTry[aa, bb] == bb xxoutaTry[aa, cc],       xxoutbTry[cc] == xxinbTry[aa, cc]}, {{aa, 0}, {cc, 0}}];      \[Psi]a =aa /. sols;     \[Psi]b = cc /. sols;     pww[r_] = Evaluate[Piecewise[{{Evaluate[ Exp[\[Psi][r]] /. xxin[\[Psi]a, bb]],       0.1 <= r <= 1}, {Evaluate[       Exp[\[Psi][r]] /. xxshell[\[Psi]a, \[Psi]b]],       1 < r < 1.5}, {Evaluate[Exp[\[Psi][r]] /. xxout[\[Psi]b]],       r > 1.5}}, Indeterminate]];       Show[Plot[pww[r], {r, 0, 3}], PlotRange -> All]      **Edit 2** : By using the above simplified code, I successfully created a plot in the end. (sorry, I do not know how to display a figure here) But when I modified the pww[r] function into the following:                pww[r_][bb_?NumericQ] = Evaluate[Piecewise[{{Evaluate[ Exp[\[Psi][r]] /. xxin[\[Psi]a, bb]],       0.1 <= r <= 1}, {Evaluate[       Exp[\[Psi][r]] /. xxshell[\[Psi]a, \[Psi]b]],       1 < r < 1.5}, {Evaluate[Exp[\[Psi][r]] /. xxout[\[Psi]b]],       r > 1.5}}, Indeterminate]];        Show[Table[Plot[pww[r][bb], {r, 0, 3}], {bb, 0.8, 0.8, 0.1}], PlotRange -> All]      Here, bb is a variable and I delete the bb=0.8; Then                  sols = FindRoot[{ xxinaTry[aa, bb] == bb xxoutaTry[aa, cc], xxoutbTry[cc] == xxinbTry[aa, cc]}, {{aa, 0}, {cc, 0}}];      does not work because it does not know bb. In this case, I tried to replace the `\[Psi]a` and `\[Psi]b` in the function `pww[r_][bb_?NumericQ]` by using the following code:                  Evaluate[aa /. FindRoot[{xxinaTry[aa, bb] == bb xxoutaTry[aa, cc],      xxoutbTry[cc] == xxinbTry[aa, cc]}, {{aa, 0}, {cc, 0}}]]        Evaluate[cc /. FindRoot[{xxinaTry[aa, bb] == bb xxoutaTry[aa, cc],      xxoutbTry[cc] == xxinbTry[aa, cc]}, {{aa, 0}, {cc, 0}}]]      In this case, I got the following kind of errors: > During evaluation of In[1]:= FindRoot::nlnum: The function value {0.244919 > bb+xxinaTry[0.,bb],-0.244919} is not a list of numbers with dimensions {2} > at {aa,cc} = {0.,0.}. >> > > During evaluation of In[1]:= ReplaceAll::reps: > {FindRoot[{xxinaTry[aa,bb]==bb > xxoutaTry[aa,cc],xxoutbTry[cc]==xxinbTry[aa,cc]},{{aa,0},{cc,0}}]} is > neither a list of replacement rules nor a valid dispatch table, and so > cannot be used for replacing. >> > > During evaluation of In[1]:= NDSolve::dsvar: 0.12251026530612244` cannot be > used as a variable. >> > > During evaluation of In[1]:= ReplaceAll::reps: > {NDSolve[{([Psi]^[Prime][Prime])[0.12251]==-0.8 > [Psi][0.12251],([Psi]^[Prime])[0.1]==0,[Psi][1]==0.},[Psi],{0.12251,0.1,1},PrecisionGoal->20]} > is neither a list of replacement rules nor a valid dispatch table, and so > cannot be used for replacing. >> > > During evaluation of In[1]:= FindRoot::nlnum: The function value {0.2 > ([Psi]^[Prime])[1.],0.} is not a list of numbers with dimensions {2} at > {aa,cc} = {0.,0.}. >> > > ... It should be very complex. Could you provide some help? The above code can be run in Mathematica 9.0 and generate the same error in your computer, I believe.


title: Calculating a potential function using the finite element method

text: This is my first attempt to use the Finite Element method available in version 10. There are questions and I am very open to suggestions. My example is flow around a cylinder which is a well known example of a potential problem. I wish to extend this to more general shapes. I first set up the region which is straightforward.               Needs["NDSolve`FEM`"];     x2 = 2; y2 = 1; r = 1/8;     reg = ImplicitRegion[0 <= x <= x2 &&0 <= y <= y2 &&      (x - x2/2)^2 + (y - y2/2)^2 >= r^2,{x, y}];      I make the mesh. Question 1: can I just put the refined boundary on the inner circle and not on the outer boundary?               mesh = ToElementMesh[reg, MaxCellMeasure -> 0.0005, "MaxBoundaryCellMeasure" ->0.01];     Show[mesh["Wireframe"], Frame -> True, PlotRange -> All]      ![Mathematica graphics](http://i.stack.imgur.com/lwZ6p.png) There is a problem around the circle at about 1 o'clock—expanded view below. Question 2: is this a problem with the grid generation or the plotting of the grid?               Show[mesh["Wireframe"], Frame -> True,PlotRange -> {{0.6, 1.4}, {0.3, 0.7}}]      ![Mathematica graphics](http://i.stack.imgur.com/gkGdN.png) The differential equation is just the Laplacian and a solution is found easily.               sol = NDSolveValue[{Laplacian[u[x, y], {x, y}] ==        NeumannValue[1., x == 0] + NeumannValue[-1, x == 2]},       u, Element[{x, y}, reg]];      The solution looks good except for the artifact close to {0, 0}. This artifact disappears if `PlotPoints` is increased to {50,25}. Question 3: Is this just a plotting bug that can be ignored?               Column[{       Plot3D[sol[x, y], Element[{x, y}, reg], BoxRatios -> {2, 1, 1},        ImageSize -> 300],       Plot3D[sol[x, y], Element[{x, y}, reg], BoxRatios -> {2, 1, 1},        ImageSize -> 300, PlotPoints -> {50, 25}]     }]      ![enter image description here](http://i.stack.imgur.com/Chd1T.png) A plot of the potential function around the circle, below, looks good. Question 4: if the grid is made up as a polygon how does the solution find the values that are on the circle but not on the grid?               Plot[Evaluate[sol[1 + (r) Cos[θ], 0.5 + (r) Sin[θ]]],      {θ, 0,2 π}]      ![Mathematica graphics](http://i.stack.imgur.com/ykRAA.png) I am interested in the velocity which is the gradient of the potential function. I calculate the velocity using Grad.               ClearAll[f];     f[x_, y_] := Evaluate[Grad[sol[x, y], {x, y}, "Cartesian"]]      The following should plot the speed of the fluid around the circle. Question 5: what is going wrong?               ϵ = 0.0;     Plot[Evaluate[Norm[f[1 + (r + ϵ) Cos[θ],      0.5 + (r + ϵ) Sin[θ]]]], {θ, 0, 2 π}]      ![Mathematica graphics](http://i.stack.imgur.com/oDBN1.png) Moving off the circle does not help much.               ϵ = 0.1;     Plot[Evaluate[  Norm[f[1 + (r + ϵ) Cos[θ],      0.5 + (r + ϵ) Sin[θ]]]], {θ, 0, 2 π}]      ![Mathematica graphics](http://i.stack.imgur.com/bfUHL.png) As usual StreamPlot has a mind of its own and does not produce the streamlines I ask for. Question 6: is there a way of using the region defined at the start rather than a new `RegionFunction`?               spts = Table[{0.001, y}, {y, 0, 1, 0.02}];     StreamPlot[f[x, y], {x, 0, 2}, {y, 0, 1}, AspectRatio -> Automatic,      RegionFunction ->       Function[{x, y, vx, vy, n}, (x - x2/2)^2 + (y - y2/2)^2 >= r^2],      StreamPoints -> spts,      Epilog -> {Point[spts], Circle[{x2/2, y2/2}, r]}]      ![Mathematica graphics](http://i.stack.imgur.com/yQ8m7.png) This is an edit to my problem which may help to establish the issue as being one of a bad mesh. Starting again but making a finer mesh we see that it is sill bad but good in parts. Question: Are there other methods for making a mesh?               mesh = ToElementMesh[reg, MaxCellMeasure -> 0.00001,      "MaxBoundaryCellMeasure" -> 0.01];      Show[mesh["Wireframe"], Frame -> True,PlotRange -> {{0.95, 1.2}, {0.5, 0.7}}]      ![Mathematica graphics](http://i.stack.imgur.com/mRU5B.png) If we now solve using this faulty mesh rather than in the original question by using a default mesh we have:               sol = NDSolveValue[{Laplacian[u[x, y], {x, y}] ==       NeumannValue[1., x == 0] + NeumannValue[-1, x == 2]}, u,        Element[{x, y}, mesh]];      Calculating the gradient as before               ClearAll[f];     f[x_, y_] := Evaluate[Grad[sol[x, y], {x, y}, "Cartesian"]]      The plot of the speed is now                ϵ = 0.0;     Plot[Evaluate[Norm[f[1 + (r + ϵ) Cos[θ],      0.5 + (r + ϵ) Sin[θ]]]], {θ, 0, 2 π}]      ![Mathematica graphics](http://i.stack.imgur.com/LhWpe.png) This is good at locations away from the bad mesh. Thus the problem seems to be a mesh problem with improved mesh resolution giving better results.


title: Manipulate indexed Interpolating Functions

text: **MWE** I have some data indexed by `gamma`. For each `gamma` I want to find the intersection points of two lists and plot the lists and the intersection points. I convert the two lists into two functions `ifun[gamma]` and `ifun2[gamma]` using `interpolation`, find their intersection using `FindRoot` and plot them. Instead of creating a separate plot for each gamma, I'd like to be able to throw that inside Manipulate. But I am running into trouble with Manipulate needing to explicitly define dependence on variables, as mentioned in the possible issues.               Table[ifun[gamma]=Interpolation[Table[{i, i^gamma}, {i, 1, 10}]], {gamma, 1, 2, 1}]     Table[ifun2[gamma]=Interpolation[Table[{i, gamma^gamma}, {i, 1, 10}]], {gamma, 1, 2, 1}]     Table[solE[gamma] = {x} /.FindRoot[ifun[gamma][x] == ifun2[gamma][x], {x, 0.15}], {gamma, 1,  2}]          Framed@Show[ListPlot[{#, ifun[1][#]} & /@ solE[1], PlotStyle -> PointSize[Large]], Plot[{ifun[1][x], ifun2[1][x]}, {x, 0, 10}],RegionPlot[x < solE[1][[1]] && -5 < y < 5, {x, 0, 10}, {y, -5, 5}, PlotStyle -> {{Yellow, Opacity[0.2]}}]]      ![enter image description here](http://i.stack.imgur.com/GNqZk.jpg) **Update2** Ok so I did the indexing on the data and not on the functions, solved for the solutions outside the manipulate and just stored the points, interpolated inside Manipulate for plotting..and it works.               Table[data1[gamma] = Table[{i, i^gamma}, {i, 1, 10}], {gamma, 1, 2}]     Table[data2[gamma] = Table[{i, gamma^gamma}, {i, 1, 10}], {gamma, 1, 2, 1}]     Table[solE[gamma] = {x} /.FindRoot[Interpolation[data1[gamma]][x] ==      Interpolation[data2[gamma]][x], {x, 0.15}], {gamma, 1, 2}]      This works:               Manipulate[fun = Interpolation[data1[gamma]];fun2 = Interpolation[data2[gamma]];Plot[{fun[x], fun2[x]}, {x, 1, 5}, Epilog -> {Black, PointSize[Large],   Point[{solE[gamma][[1]], fun[solE[gamma][[1]]]}]},  AxesOrigin -> {0.5, 0}], {gamma, 1, 2, 1}]      ![enter image description here](http://i.stack.imgur.com/GmbKM.jpg)


title: Needs entry point of a package from a Mathematica script

text: I am writing a bunch of _Mathematica_ scripts to run command line in a HPC environment. I am organising my solution in small chunks I can test separately. So I have a directory structure like:               ├── test     │   ├── coefficients-test.math     │   ├── main-test.math     │   ├── nearest-test.math     │   ├── rangek-test.math     │   ├── unit.m     │   └── wave-test.math     └── wde         ├── coefficients.m         ├── ???.m         ├── nearest.m         ├── rangek.m         └── wave.m      The `test` folder contains a bunch of unit tests using simple poor man's testing. Each test script begins (say `test/coefficients-test`)               #!/Applications/Mathematica.app/Contents/MacOS/MathematicaScript -script          $Path = Join[$Path, {Directory[]<>"/wde"}];     Needs["unit`"];     Needs["coefficients`"];      and then testing code. I `chmod`ed them with a+x and I just run them like: > $ ./test/coefficients-test.math (Needless to say that in the HPC the _Mathematica_ script path is different, but that is secondary for the moment.) So far so good. The problem is that when I try to develop the main component of my `wde` package, if I name the file `wde/init.m` or `wde/wde.m` or `wde/Kernel/init.m` and try to load it in the test script with `Needs["wde`"]` I get the infamous context not created error; although I have inside it `BeginPackage["wde`"]`. If I name my package, say `wde/main.m` and put inside `BeginPackage["main`"]`, it works. Easy work around, but I was wondering what I am doing wrong in the first place. Do I need to copy my package to a standard _Mathematica_ location for script loading? Why doesn't the `$Path` trick work in this case? Again, this is a purely scripting approach - not sure if this is suitable from the front-end in a notebook, although at this stage this not a concern. Actually, my plan is to develop the script further to generate a CDF via a script and load that in the front-end for demo-ing purposes, etc (I understand this is the recommended solution to CDF production.)