Plotting data points: Optimizing size and visuals

The following problem is one that may have showed up to you while plotting a large data collection. Suppose you have a data set of say 1 million points. `ListLinePlot` will use all of those points to create your plot. Unfortunately, if the points are so close together they will overlap in the plot and they become irrelevant. I was wondering if there is some quick way in _Mathematica_ to get rid of the redundancies in the plots. The term redundancies depends of course of the image resolution (size). Let us work with the following example               rx[n_] := Accumulate[Prepend[RandomVariate[ExponentialDistribution[1000], n], 0]]     ry[n_] := Accumulate[Prepend[RandomVariate[NormalDistribution[0, .001], n], 0]]     x = rx[100000];     y = ry[100000];     ListLinePlot[Table[{x[[i]], y[[i]]}, {i, Length[x]} ]]      Here is one of the many possible plots generated by the above ![random sample](http://i.stack.imgur.com/ZikXn.png) This plot was generated with 100,000 points and some of them may not even be visible since other points overlap part of the point. The question is, is there some built in function that gives us a way to remove the redundancies and thus reducing the size of the figure? I should be more precise. If this plot is to be exported as a raster plot (jpeg, png) then there is no problem. The problem arises if we export it as a pdf or eps. The resulting vector format will have to plot all of those points and it will take a while to display it when in reality we only have a few points to display. The very naive way I did before was to remove some points from my initial data, as follows:               ListLinePlot[Table[{x[[i]], y[[i]]}, {i, 1, Length[x], 100}]]      ![figure 2](http://i.stack.imgur.com/Uy2BR.png) And you can imagine what will happen if I skip 1000 points at a time               ListLinePlot[Table[{x[[i]], y[[i]]}, {i, 1, Length[x], 1000}]]      ![figure 3](http://i.stack.imgur.com/Iqkfz.png) ### Possible Solution 1 The first idea that came to my mind was to loop over my data and see if the points are close to each other, if they are sufficiently close (we can use a parameter to decide this) then we remove one of them. This solution will remove points from our initial data set but we want to make it so that we do not remove important features of the plot as I did with the 3rd plot. ### Possible Solution 2 The other solution was to export/rasterize the final figure I wanted (only the lines in the plot, this excludes the axes or any other objects). Once this is done then we outline the plot and make a vector figure of it again. Keep in mind that we are trying to reduce the size of points that are being plotted while making the plot resemble what _Mathematica_ plotted very naively. Any ideas of how to implement any of the ideas above or an even better one to achieve the desired result?


How to make custom discrete color data function

Attempting to make custom discrete color data function: my custom color: ![enter image description here](http://i.stack.imgur.com/slzDm.png) is it possible to use my custom color               colors = Reverse@Table[Hue@h, {h, 0, 0.7, 1/10}] // N;      Thanks to mfvonh, color function and color data               cf[x_] :=       Which @@ Flatten[       MapThread[       List, {x >= # & /@ Reverse@Most@Range[0, 1, 1/Length@colors],  colors}]]           colordata=cf /@ Rescale[pts[[All, 2]], {0,0.1}];


Precision of rendered Rectangles in stiff-scale graphics

The attchd graphics called chromograms represent a set of discrete-state, continuous-time - ie, discrete-event signals, generated with Mathematica 9 on OSX with a Cinema display. • Top 2 rows are independent signals. • Bottom two chromograms (red and green) shows the segments where the top 2 rows agree (green) in their temporal coding, and where they differ (red). So each `Rectangle`'s left and right positions are encoded by 2 timestamps (even-begin and event-end). X axis is the timeline in seconds, and this graphic shows [200,400] window. ![enter image description here](http://i.stack.imgur.com/RaVfR.png) The problem: note there are 3 red rectangles (bottom row) that have no corresponding "holes" in the complementary green signal. This is an error in Mathematica's graphics rendering because closer inspection reveals the holes to be there. The problem becomes extreme when zooming out to graph a larger time window. In the next figure the same data is shown for the window [0,1800]: ![enter image description here](http://i.stack.imgur.com/5CvNG.png) In such a stiff-scale graphic, there are many more instances of the above problem - again, closer inspection shows that the red and green event-signals partition the time-axis so red and green `Rectangle`s should never overlap. The problem is unrelated to choice of colors - flipping red and green still shows the upper signal to be problematic. So it seems Rectangles are rendered "too thick" and overlap where they shouldn't. Are there any `Option`s or methods one could use to control this issue? (Potentially generating a complementary set of interval events and actively rendering them in White may work but haven't tested this and would be a hack in any case).


Finding coefficients that make certain functional expression vanishing

My problem is to find a procedure that gives coefficients which make certain functional expression vanishing. For example if I have a polynomial $P(x)$ of one variable $x$ given by $P(x)=a_0+a_1 x+a_2 x^2...$ I would like _Mathematica_ to give $a_i=0$ as the solution to $P(x)=0$. Or consider more complicated example which is closer to the real task I'm dealing with. Suppose I have equation $a_1 K(x)+a_2 E(x)=0$ where $K,E$ are elliptic integrals. It only matters here that they are linearly independent functions of $x$, so the there is the unique solution $a_1=a_2=0$. Of course In the case with polynomial one can just require to vanish Coefficient[$P(x),x^i$]. Similarly, one can expand $a_1 K(x)+a_2 E(x)$ in powers of $x$ and find $a_1,a_2$ which makes several first terms of expansion absent. But isn't there a more elegant/standard way to handle this task? I would like to somehow explain to _Mathematica_ that $a_i$ in these expressions are fixed coefficients while $x$ is a variable and that equations must hold for every $x$ thus giving constraints on $a_i$.


How do I group a nested list further according to a rule, and average selected elements?

I have a nested list of numbers like { {36, -244}, {37, -225}, {38, -197}, {48, -200}, {49, -181}, {50, -133} } which needs to be further nested into "bins" according to a rule. I would describe the rule like: Elements belong into one bin when their first sub-elements (36, 37, 38 vs. 48, 49, 50) can form a chain of successive integers or in other words, if arranged from lowest to highest there is no "hole" greater than 1 in the so formed bins. In the following step, how can I tell Mathematica to average the second sub-elements (-244, -225...) inside the former defined bins?


Extracting Reduce results

I'm solving a Diophantine equation inside of a function using `Reduce` but I'm having trouble extracting the necessary parts of the answer. For example, if my input equation is linear, I get an output from `Reduce` like:               C[1] ∈ Integers && x == 8 + 49 C[1] && k == 1 + 5 C[1]      if the equation is a quadratic, though, I get:               (C[1] ∈ Integers && x == 20 - 49 C[1] &&         k == 41 - 200 C[1] + 245 C[1]^2) || (C[1] ∈ Integers &&         x == 29 - 49 C[1] && k == 86 - 290 C[1] + 245 C[1]^2)      if the equation is cubic, I get:               C[1] ∈        Integers && (x == 2 + 49 C[1] || x == 11 + 49 C[1] ||         x == 36 + 49 C[1]) && k == 1/49 (9 + 5 x^3)      How do I identify and/or extract, say, the resulting condition on x? I originally used `Part` when I just had the linear case. So for example I would do something like:               Ans=Reduce[SomeEquality[x,k],{x,k},Integers];     X=x/.ToRules[Ans[[2]]/.{C[1]->0}]      But the outputs in the quadratic and cubic cases are in wildly different places...


Fitting data without an equation

Let's say I have some data generated by anything. For practical sake, let's say I was able to generate a sequence of numbers through a recursion and I listed them out through a table of numbers.               F[1] = 1;     F[n_] := 3*F[n - 1]     H = Table[F[n], {n, 1, 10}]      Now I set the table of values to a variable 'w'               ListPlot[H]      Here I am plotting the data. What I want to do now is to "fit" a curve that connects all those points. I just want to see the fitted curve on the plot together the data points. I don't even need (or want to) see the equation that best fits the data. I tried using NonlinearModel and Fit, neither works well for me. The recursion is just an example. I could of course product new data from something else


Make EventHandler work for clicks and keys in a Dynamic display

I am trying to write a way that will do certain events depending on what screen is showing. What happens so far is that the screen will change in accordance to a click, but when you try to do the key presses associated with that screen, they won't respond. I think the events are being passed to the old screen that is being shown. Is there an option or way to fix this? My code thus sees if you click within certain coordinates (works, but not shown in simplified code below), then changes what it is showing. The arrow key pressing that corresponds to the new screen does not happen, unless I reevaluate the EventHandler block of code. Code is below:               displaying = True;           start[] :=      If[displaying,       Show[firstScreen],       Show[secondScreen]       ]          EventHandler[      Dynamic[start[]], {"UpArrowKeyDown" :> (If[!displaying, Print["up press"]]),        "DownArrowKeyDown" :> (If[!displaying, Print["down press"]]),        "MouseClicked" :> (If[displaying,           displaying = False])       }]


How do I set up conditions at infinity?

I having trouble with this equation: $$ -\frac{(2 m \text{U0}) \Psi (\rho ,z) \left(1-e^{-\text{} \left(\frac{z}{d}\right)^2-\left(\frac{2 \rho -(r+R)}{R-r}\right)^2}\right)}{h^2}+\frac{\partial ^2\Psi (\rho ,z)}{\partial z\, \partial z}+k^2 \Psi (\rho ,z)+\frac{\frac{\partial \rho }{\partial \rho } \frac{\partial \Psi (\rho ,z)}{\partial \rho }}{\rho }=0 $$ I need to solve it with several conditions: $\Psi$ has to tend to the zero at infinity, and it has to be bounded in the whole area greater than zero (including zero). I'm trying to use `NDSolveValue` to solve this equation numerically, but I don't know how to set up the conditions. Help me please. Here's code:               NDSolveValue[{k^2*Ψ[ρ, z] - (2*(1 - e^(-(z^2/d^2) -     (-r - R + 2*ρ)^2/(-r + R)^2))*m*U0*Ψ[ρ, z])/h^2 +     Derivative[0, 2][Ψ][ρ, z] + Derivative[1, 0][Ψ][ρ, z]/ρ == 0},     Ψ, {z, 0, 5}, {ρ, 0, 5}]


Are there built-in functions for testing if a point lies within Graphics3D primitives?

I noticed in this question, Behavior of Graphics`Mesh`InPolygonQ with self- intersecting polygons, that _Mathematica_ has some "psuedo-hidden" functionality for allowing one to quickly perform a winding number calculation to tell if a point is inside of a polygon mesh. As a shot in the dark, is there built-in functionality to detect if a point sits in a 3D graphics primitive like `Cylinder`?


Short syntax for accessing System`Utilities`HashTableAdd and System`Utilities`HashTableGet

I have a need for a struct analogue in Mathematica. After reading this post I came to the conclusion that `System`Utilities`HashTable` is one of the best options. But it's rather terse to write. Let's say we have a hash table:               h=System`Utilities`HashTable[];      Is there a way to auto-magically transform               h.somekey=value (*would be evaluated as===> System`Utilities`HashTableAdd[h, "somekey", value]*)      and               a = h.somekey (*would be evaluated as ===> a = System`Utilities`HashTableGet[h, "somekey"]*)      I have not yet been able to find the right combination of := or :> to get this to work, but `RuleDelayed` is still a bit mysterious for me:) * * * **EDIT** Some test cases:               h = System`Utilities`HashTable[];     h.first = "test";     h.second = "another test";     System`Utilities`HashTableAdd[h, "third", "yet another..."];     h.first    (*test*)     h.second  (*another test*)     h.third   (*yet another...*)     System`Utilities`HashTableGet[h, "first"]     System`Utilities`HashTableGet[h, "second"]     System`Utilities`HashTableGet[h, "third"]     (* is it possible to have dot hold the second argument only in the \     overloaded definition? so that this would still work?*)     second = a;     h.second (*should return: but does not another test*)     h.Unevaluated[second]     h."second"     Clear[second]     h.first = FIRST;     h.first     (*don't break the dot prodocut*)     Clear[a, b, c, d];     {a, b}.{c, d}     c = 5;     {a, b}.{c, d}      The obvious does not work:               Unprotect[Dot];     Dot[h_System`Utilities`HashTable, key_] :=        System`Utilities`HashTableGet[h, ToString[Unevaluated[key]]];     Dot /: Set[Dot[h_System`Utilities`HashTable, key_], value_] :=        System`Utilities`HashTableAdd[h, ToString[Unevaluated[key]], value];      If one leaves just h_ then it works, but breaks the dot product definition. As a work around this sort of works...               Unprotect[Dot, Set];     Dot[h_, key_Symbol] :=        System`Utilities`HashTableGet[h, ToString[Unevaluated[key]]];     Dot /: Set[Dot[h_, key_Symbol], value_] :=        System`Utilities`HashTableAdd[h, ToString[Unevaluated[key]], value];      **So, why doesn't the first version work?** **Also, is it possible to get`Dot` to hold its argument only for the overloaded version?**


Prevent PopupWindow from opening multiple windows

`PopupWindow` objects can be clicked multiple times, opening multiple popup windows for the same object. How can I prevent this? A bit more detail: I have an application which displays a graphic. The user can click on elements of the graphic to call up an information panel about that element using `PopupWindow`. The user might have several of these popups open at once. To prevent confusion, I would like to make sure that the user cannot open more than one popup per object. I can't see a straightforward approach to doing this, so I'm hoping for some ideas from this fine community. Example code:               DynamicModule[{col = ConstantArray[Blue, 5]},      Graphics[{Table[With[{i = i},          PopupWindow[           Dynamic[            col[[i]] = If[CurrentValue["MouseOver"], Red, Blue];            {Dynamic@col[[i]], Disk[{i, 0}, 0.5]}],           Dynamic[            col[[i]] = If[CurrentValue["MouseOver"], Red, Blue];            Framed[Style["Disk " <> ToString[i], White, 20],              FrameMargins -> 80, Background -> Dynamic@col[[i]]]],            WindowSize -> 280]          ], {i, 5}]}]]      _Here I have clicked on disk 4 twice, opening a duplicate of the information window. I want to prevent that:_ ![enter image description here](http://i.stack.imgur.com/0NZ5L.png)


Findings powers within strings - Cases function

Any idea which Cases statement will work for both A^2 and CA^4X^36 to find the powers? If I set sym to these two expressions, one requires a curly brackets around the first argument and the other doesn't.               (* Sample 1.  Returns {} *)     Clear[x]; Clear[y];     sym = "A^2";     Cases[ToExpression[sym], x_^y_ -> {x, y}]          (* Sample 2. Returns {{CA,4},{X,36}} - as required*)     Clear[x]; Clear[y];     sym = "CA^4X^36";     Cases[ToExpression[sym], x_^y_ -> {x, y}]          (* Sample 3. Placing brackets around the first argument of the Cases \     function returns {{A,2}}  - as required *)     Clear[x]; Clear[y];     sym = "A^2";     Cases[{ToExpression[sym]}, x_^y_ -> {x, y}]


Strange behaviour of MMA in derivatives of some standard functions

There are some peculiar things to be discovered in derivatives of some standard functions in MMA: **Strange behaviour** _Example 1: Abs_ We have               Abs[0.1]          (* Out[72]= 0.1 *)      But               Abs'[0.1]          (* Out[73]= Derivative[1][Abs][0.1] *)      Same thing if we avoid writing the prime:               D[Abs[x], x] /. x -> 0.1          (* Out[110]= Derivative[1][Abs][0.1] *)      That is, the derivative of `Abs[]` has no numerical value. When plotted, there's nothing to be seen. The derivative should of course be, or at least behave like, `Sign[x]` . _Example 2: Sign_ Sign[0.1] (* Out[78]= 1 *) Sign'[0.1] (* Out[79]= Derivative[1][Sign][0.1] *) That is, the derivative of `Sign[]` has no numerical value. When plotted, there's nothing to be seen. _Example 3: Floor_               Floor[0.1]          (* Out[80]= 0 *)      But which value has the derivative at 0 ? First possibility:               Floor'[0]          (* Out[89]= Derivative[1][Floor][0] *)      No value. Second possibility:               Floor[0.]          (* Out[90]= 0 *)      Hence the numerical value seems to be 0. No, bad luck, wrong guess! Look at that Third possibility: N[Floor'[0]] (* Out[93]= 36.2120995105236639865598801739718338716778459859 *) Furthermore:               Table[{x, N[Floor'[x], 5]}, {x, 0, 1/2, 0.05}]          (* Out[96]= {{0., 36.212}, {0.05, 12.5946}, {0.1, -4.29432}, {0.15,        1.61679}, {0.2, -0.532708}, {0.25, 0.13901}, {0.3, -0.0263362}, {0.35,        0.00318987}, {0.4, -0.000184538}, {0.45, 0.}, {0.5, 0.}} *)      Strange ocillatory behaviour for a quantity which should be = 0 throughout. It seems to be defined via a Fourier series. **Remedy ?: do it yourself !** Finally, let's create the derivative by ourselves as it is originally defined:               floorPrime[x_] := Limit[(1/h) (Floor[x + h] - Floor [x]), h -> 0]          Plot[0.1 + floorPrime[x], {x, -1, 1}, PlotRange -> {0, 0.2}]          (* Picture snipped *)               absPrime[x_] := Limit[(1/h) (Abs[x + h] - Abs[x]), h -> 0]          Plot[absPrime[x], {x, -1, 1}, PlotRange -> {-2, 2}]          (* Picture snipped *)      Ok, everything fine. But why has MMA such problems with its own standard operation ' (or D[]) in this class of functions? Please explain. Regards, Wolfgang


How do you set an Optional parameter with a global variable on a Function defined in a Package

In a Package I am writing, I'm trying to define a function with an `Optional` parameter in it that is set to a global variable.               PlotIndex[IndexLoopPlotMtx_:IndexLoopPlot]:=ListPlot[.....      However, the `Optional` value `IndexLoopPlot` is not set until after the package is loaded and other functions are run. Therefore `PlotIndex` is read in as,               PlotIndex[IndexLoopPlotMtx_:{}]:=ListPlot[.....      In other words, `IndexLoopPlotMtx` is set to `Null`, and when the function is run later it tries to `plot {}` instead of the matrix `IndexLoopPlot`. Is there a way to get it delay setting the `Default` until the function is called for the first time from the package?


Covariance of transformed random variables

I am trying to solve the following: $\begin{align*} &X \sim N(1,1)\\\ &\mathrm{cov}(X, X^3) = \text{?} \end{align*}$ where $\mathrm{cov}$ is the covariance. How would you do this in _Mathematica_? I have tried               X = NormalDistribution[1, 1]          cov[x_, y_] := Mean[TransformedDistribution[a*b,                         {a \[Distributed] x, b \[Distributed] y}]] - Mean[x] Mean[y]          cov[X, TransformedDistribution[a^3, a \[Distributed] X]]      But this doesn't seem to work.


Notebook UI: Autocompletion - Display function arguments when typing?

Is there a setting to display the required arguments of a function when typing as Visual Studio, Matlab, etc. does?


Constructing lists by applying functions to another list

Suppose f is a function of two variables: $f = f(x,y)\quad$ and $L$ is a list. Could someone help me in defining a list of the form: $D = \\{f(x,y)\ |\ x \in L,\ y \in L\\}$ I tried this:               D = List[ f[x,y], {x,y} ∈ KroneckerProduct[L,L]]      But I got syntax errors.


Display position information out of ListPlots inside a Manipulate

I often have the situation where I'll use Manipulate[] to compare and examine 2 or more lists. A simplified example follows:               list1 = NestList[3 # (1.25 - #) &, .1, 20];     list2 = NestList[3 # (1.3 - #) &, .1, 20];          Manipulate[      Column[{        ListLinePlot[list1[[windowStart ;; windowEnd]], ImageSize -> 350],        ListLinePlot[list2[[windowStart ;; windowEnd]], ImageSize -> 350]}       ], {windowStart, 1, Length[list1] - 1, 1}, {windowEnd, 2,        Length[list1], 1}]      ![Manipulate](http://i.stack.imgur.com/hFAMt.png) The 2 controls provide me a simple window on the data that lets me zoom in and out. This works great, but a couple of enhancements would make it much more useful. If you play with the "window" sizing you'll note that the x axis of each plot resets whenever you move either control, so that it only ranges over the number of data points immediately displayed instead of the positions of the data values in the original list. Does a simple way (or anyway) exist to display the original positions on the x axis? This would prove very useful when I look for anomalies in list calculations on very long lists. Secondly, as sometimes I have half a dozen lists to compare at a time, can anyone suggest a way to place a crosshair over the entire column of list plots that would do two things:   * Allow me to readily compare corresponding values in different lists   * Display the position of values from the original list. Something like this (ok, this doesn't have positions, but you get the idea): ![Manipulate2](http://i.stack.imgur.com/0TQib.png) Maybe a nested Manipulate[] might get me there? Just looking for some strategies to do this.


Expand List Operation

On applying a multiplication and subtraction on a list, like so:               x = 2y - 4;      Where y is a list containing fractions of complex numbers generated from dynamic input, instead of getting a new list with that operation applied to each element of the list, instead the output is simplified, in the form:               -4 + 2{element1, element2, element3, etc}      This means I can't then apply normal list functions to x. How can I convert this style of input into just one list:               {-4 + element1, -4 + element2, -4 + element3}      When I make y non-dynamic, it formats it correctly, so that seems to be part of the issue. My exact code is this:               mirror[v_] := v^2     a = 3;     b = 4;     {Slider2D[Dynamic[{a, b}], {{-10, 0}, {10, 100}, 1}], Dynamic[{a, b}]}          y = Dynamic[Replace[t, Solve[-1/D[mirror[t], t] == (mirror[t] - b)/(t - a), t]]];     x = 2 y - a


In what situation is the use of Directive required?

Sometimes I see code samples in the document or in this site using `Directive`, but I haven't yet find a case that `Directive` is necessary. Usually it can be replaced just by `List` (except for `Graphics` and `Graphics3D`, in which `Directive` can be replaced by `Sequence`) and their visual appearance won't change at all, though their `FullForm` structures will be different:               (* These samples are all modified from the examples in the document. *)          p[1] = Plot[Sin[x], {x, 0, 10}, PlotStyle -> Directive[Orange, Thick, Dashed]];     p[2] = Plot[Sin[x], {x, 0, 10}, PlotStyle -> {Orange, Thick, Dashed}];     p[2] === p[1]     p[3] =        Plot[2 Sin[x], {x, 0, 10},          Frame -> True, FrameLabel -> {x, 2 Sin[x]},          LabelStyle -> Directive[Medium, Italic]];     p[4] =        Plot[2 Sin[x], {x, 0, 10},          Frame -> True, FrameLabel -> {x, 2 Sin[x]}          LabelStyle -> {Medium, Italic}];     p[4] === p[3]     p[5] =        ParametricPlot3D[{Cos[φ] Sin[θ], Sin[φ] Sin[θ], Cos[θ]}, {φ, 0, 2 Pi}, {θ, 0, Pi},          MeshShading -> {{Directive[Red, Specularity[White, 10]],            Directive[Green, Opacity[0.5]]}, {Blue, Yellow}}];     p[6] =        ParametricPlot3D[{Cos[φ] Sin[θ], Sin[φ] Sin[θ], Cos[θ]}, {φ, 0, 2 Pi}, {θ, 0, Pi},          MeshShading -> {{{Red, Specularity[White, 10]},            {Green, Opacity[0.5]}}, {Blue, Yellow}}];     p[6] === p[5]     p[7] =        Graphics[{Purple, Arrowheads[Large], Arrow[{{4, 3/2}, {0, 3/2}, {0, 0}}]}];     p[8] =        Graphics[{Directive[Purple, Arrowheads[Large]], Arrow[{{4, 3/2}, {0, 3/2}, {0, 0}}]}];     p[8] === p[7]     p[9] =        Graphics3D[         Directive[Black, Thick, Dashed],           Line[{{-2, 0, 2}, {2, 0, 2}, {0, 0, 4}, {-2, 0, 2}}]}];     p[10] =        Graphics3D[{Black, Thick, Dashed,          Line[{{-2, 0, 2}, {2, 0, 2}, {0, 0, 4}, {-2, 0, 2}}]}];     p[10] === p[9]     Grid[Partition[p[#] & /@ Range@10, 2]]      > False   >  False   >  False   >  False   >  False ![enter image description here](http://i.stack.imgur.com/UzqFp.jpg) `Directive` was added in version 6, so its existence can't be a issue left over by history, so what's the significance of `Directive`? Is there a case where `Directive` is required? Does `Directive` give any advantage over `List` or `Sequence` that I haven't noticed?


Combining functions - is this a case for Piecewise?

I have a function $Eb1$ which was the subject of a question I asked recently - you can see it here on stack exchange. Now, in that example it's specified between a boundary $r_n$ and $r_o$ where $r_o > r_n $ and it works as expected. I also want to specify the value of the function between 0 and $r_n$ - fcor all $r < r_n $, the function is a constant with the value $Eb1(r_n)$, so the same value it is at the boundary. I am however unsure how to code this, and how to combine these two specifications into a single expression. I was considering using piece-wise, but I am unclear about how to specify this and so far my attempts have failed. Any ideas?


A few entwined/related questions: **Can Wolfram's Player Pro use proprietary packages?** I have searched Wolfram's site pages on Player Pro and don't see anything that provides a clear answer to this question. See:   * CDF, Player Pro, and Mathematica Features Comparison Chart   * FAQ **If yes, does it work the same as in Mathematica?** To load packages automatically in Mathematica I typically use the `"Applications"` directory and then place an `init.m` package with a `Get[]` command in the `"Kernel"` directory. The following code identifies the appropriate directories:                   appDirectory = FileNameJoin[{$UserBaseDirectory, "Applications"}]         kerDirectory = FileNameJoin[{$UserBaseDirectory, "Kernel"}]      **If it works differently, can someone explain how it works and what directory structure it uses?** A related question got placed last year, but as it never received any answers and I thought it might benefit from a more specific formation.


Using two color functions in a MatrixPlot

I'm trying to use two color functions within one `MatrixPlot` in _Mathematica_. Is it possible to do this? For example, using a very simple matrix:               test = Partition[Table[i, {i, 1, 9}], 3]      I would like to make the even numbers vary in color increasing from white to red; and the odd numbers vary in color from grey to black. How could I do this? I know how to get the whole matrix to vary in color, but no more than this.


Problem with Function and Postfix

![how to revise it](http://i.stack.imgur.com/3nreu.png) _**My Methods:_**               Style["Mathematica", Pink]     "Mathematica" // Style[#, Pink]     Style@("Mathematica", Pink)      _How to revise it?Thanks!_


Initialize table in a Module but Break if criteria not met

I am initializing a table inside a function as follows:               f[a1_, a2_, a3_] := Module[{RM = Table[a1+a2+a3+i1, {i1, 1, 10}]}, Plus@@RM]      I am calling the function `f` multiple times with different values of `a1, a2, a3` and want the function to exit, if `300<a1+a2+a3+i1<500` How can I do it elegantly by not initializing the table and later checking to proceed or `Break`? This is what I have started to do, but could not go too far:               LL[a1_, a2_, a3_, x_] := 300 < a1+a2+a3+i1 < 500;     f[a1_, a2_, a3_] := Module[{RM = Table[If[L[a1, a2, a3, i1]==True,L[a1, a2, a3, i1],             Break[]] , {i1, 1, 10}]},Plus@@RM]


How to save all data in all variables in context different than "global"?

I have seen questions on saving data on "global" context. Now if I set my notebook's evaluation context "unique to this notebook". the global context doesn't work quite well. Any idea what should i do to save every variable to a file in such a case? Thanks! OK, solved. What I should do is to replace "Global`" by whatever $Context returns (Actually we should have a feature request so that Mathematica automatically saves everything in the notebook.)


How to efficiently distinguish the rewired edges in WattsStrogatzGraphDistribution?

The `WattsStrogatzGraphDistribution` function is a way to construct random graphs based on Watts and Strogatz small world model. The `WattsStrogatzGraphDistribution` is constructed starting from `CirculantGraph[n,Range[k]]` (`k=2` unless you assign another value for it)and rewiring each edge with probability **p**. Each edge is rewired by changing one of the vertices, making sure that no loop or multiple edge is created. For instance,               WattsStrogatzGraphDistribution[100,0.05]      can give: ![Random Graph](http://i.stack.imgur.com/mQp7n.png) I need to distinguish the rewired(short-cut) edges from the original ones so I can measure some of their statistical properties(Average of short-cut and non- short-cut edge betweenness). One possibility was to forget about this subroutine in _Mathematica_ , and construct everything I need from scratch. I have not ruled out that possibility yet, but since I will be dealing with not so tiny graphs(about 500 nodes) and I will have to repeat the procedure few hundred times in order to obtain reliable average values; I would rather do something more efficient. Another idea which I had was to calculate the `EdgeBetweennessCentrality` of all the edges and then cluster them into two groups(one naively expects the betweenness of the short-cut edges to be higher). Unfortunately this doesn't work because the edges close to rewired edge will also get higher betweenness centrality and I couldn't distinguish them apart from the each other.


Easy NMinimize does not converge

I try to minimize the following for a>0:               f[a_] := Gamma[3]*a^(-3)*(Integrate[Exp[-u]*(u - a)*1/u, {u, a, Infinity}])^(-1)      I put in               NMinimize[{f[x],x>0},x]      but then he gave me an error that the function might not be bounded at said:               NMinimize::cvdiv: Failed to converge to a solution. The function may be unbounded. >>     {-3.18118*10^14, {x -> 1.11822}}      Obivously, that is not true. What am I doing wrong? Cheers


Unintentional function memoisation via Dynamic

I needed to display edge labels of a graph in a way that allows the edge labels to be moved.               With[      {coords = {{1.08, 0.94}, {1.08, 0.036}, {0., 0.97}, {0., 0.}, {1.94, 0.49}},       edges = {{1, 2}, {1, 3}, {2, 5}, {3, 4}, {4, 2}, {5, 1}}},      DynamicModule[       {edgePosns = Table[0.5, {Length@edges}]},       (betweenPnt[a_, b_, l_] := (1 - l) a + l b;        DynamicModule[         {edgeCentres =           MapThread[            With[{av = coords[[#1[[1]]]], bv = coords[[#1[[2]]]]},              Dynamic[betweenPnt[av, bv, #2]]] &,            {edges, edgePosns}]},         Column@{           Graphics[            GraphicsComplex[             coords,             {{Line[edges]}, {Darker@Red, PointSize[0.02],                Map[Point, Range[5]]},              Map[Locator, edgeCentres]}], ImageSize -> 400],           Dynamic[DownValues[betweenPnt]]}])]]      ![picture of output of above](http://i.stack.imgur.com/YonSp.jpg) What puzzled me is that calls to `betweenPnt` are memoised when the `Locator`-s are moved, as shown in the next image (apologies for tiny fonts): ![picture of output with locator moved](http://i.stack.imgur.com/g5IRT.jpg) What I do not understand is how or if the cacheing and the locator positions are connected, though I've understood from the related question that it is standard behaviour that the latter persist even when graphic is deleted and the code is re-evaluated. Incidentally, I noticed that the `DownValues` are not updated dynamically despite the `Dynamic` wrapper around them; only after re-evaluating the whole expression do these changes appear.


Integro-differential eqn with double integral

I am looking at the following variation of a integro-differential, with `y[0]=1`. The output is not great, any solutions to this?               Clear[s, t, J, w];     J[w_] := 1/(2 + w^2)     eqn = y'[t] == -Integrate[y[t1] J[w] Exp[I (0.1 - w) (t1 - t)], {w, 0, \[Infinity]}, {t1, 0,t}]           LaplaceTransform[eqn, t, s]           InverseLaplaceTransform[%, s, t]           ySol[t_] = y[t] /. First[%] /. y[0] -> 1          Plot[ySol[t], {t, 0, 10}, PlotRange -> {-1, 1}]


Add a letter to a variable name from a list

Basically I am searching for a way to add the letter `u` to an existing list of variables `{a,b,c,d}` to obtain the variable list `{ua,ub,uc,ud}`. I am trying to make an function for an automatic calculation of the propagation of uncertainty.               U[term_Expression, varlist_Expression] := Sqrt[     Sum[i,{i,     Function[var,       Power[D[term, var], 2]*u] /@ varlist     }]]      The Input `U[a*b, {a, b}]` gives me `Sqrt[a^2*u + b^2*u]` but I want it to be `Sqrt[a^2*ua + b^2*ub]`. Probably this is a very easy task but I am struggling for hours with this small problem. Maybe you know a solution? Thanks! **UPDATE** Made it with               U[term_, varlist_] := Sqrt[Sum[i, {i,      Power[       Function[var,          D[term, var]          ] /@ varlist*        ToExpression[StringInsert[#, "u", 1] & /@ ToString /@ varlist]       , 2]      }]]      Thank you!


Matrix containing ellipse

I have to make a matrix which contains elements in an ellipse shaped region, but I need to make ellipse region in such a way that larger axis of ellipse is inclined with angle θ with horizontal. With `Colorize` the matrix should look like this: ![](http://i.imgur.com/sYh3nHw.png) I have employed two ways so far for this:   * Use `Graphics`, followed by `MorphologicalComponents` and then use `Position` to get a list and then convert it into matrix.   * Write the equation of an inclined ellipse as `f[x,y] = 0` and then use condition `f[x,y] <= 0` and run it on matrix coordinates to get the list and then finally convert it into matrix. However, these two methods are a bit slow and I would like to use something like `DiskMatrix` or any other way to make it faster.


Derivative inside a function

I am trying a problem that should be simple: to create a function that contains a derivative. I need to do a more complex example, but even with the simplest I'm having trouble: Let's consider               d[psi_[a_, b_, c_]] := D[psi, a] + D[psi, b]     p[x_, y_, z_] := x + y;     d[p[x, y, z]]      If I do that i receive the follow answer:               d[x + y]      I am only receiving a generic answer. Sometimes, I don't know why, I receive the evaluated answer (rarely). Do you know what is wrong? I'm using Mathematica 9. **Update** How do I have to modify the definitions above if I want to apply `d` to a list of functions?


How to replace variables in an expression?

I have generated a matrix using _Mathematica_ , $\left( \begin{array}{ccc} \text{cos$\theta $} & -\text{sin$\theta $} & \text{cos$\theta $}\, \text{dx}+\text{dx}-\text{dy}\, \text{sin$\theta $} \\\ \text{sin$\theta $} & \text{cos$\theta $} & \text{cos$\theta $} \,\text{dy}+\text{dy}+\text{dx}\, \text{sin$\theta $} \\\ 0 & 0 & 1 \\\ \end{array} \right)$ Now I want to change the variable names $dx$ to $xr$ and $dy$ to $yr$. How could I do this?


How to visualize the interior of a complicated 3d plot

I have an external data file (can be downloaded here: link 1 or link 2) which contains a dense grid of initial condition in the (x,y,z) space. I read it with Mathematica and plot these initial conditions with different colors according to some specific properties               m = Import["data_3d.out", "Table"];          getColor[m_List, i_Integer] :=      Module[{s = m[[i, 6]]},      Which[s == 0, Black, s == 1, Red, s == 2, Darker[Green], s == 3,      Brown, s == 4, Blue, s == 5, Orange, s == 6, Cyan, s == 7,      Magenta, s == 8, Yellow, True, White]];          data = Table[{PointSize[0.004], getColor[m, i],      Point[{m[[i, 1]], m[[i, 2]], m[[i, 3]]}]}, {i, 1, Length[m]}];          P0 = Graphics3D[data, Axes -> True, BoxRatios -> {1, 1, 1},      PlotRange -> 6, ImageSize -> 550]      and here is the output ![enter image description here](http://i.stack.imgur.com/bUOJY.jpg) We observe, that several color patterns appear but we can see only the surface of the three-dimensional grid. So, the question: Is there a way to penetrate inside the 3d surface and visualize how these color patterns are? Any suggestions? Please, us the original data file for testing. I think, generating simpler but random 3d grids in this case, could be very illusive since all the story is about the color patterns that appear and obviously cannot be replicated randomly. **EDIT** A second working link for retrieving the data file is added.


Need to run evaluation 2 times

Why does this only work after running the evaluation 2 times?               diff[var1_, y0_, funk_, {var2_, a_, b_}, N_] := (            Module[{h},            var1 := #1;       var2 := #2;       h = (b - a)/N;            FoldList[var1 + h*funk &, y0, Range[a, b - h, h]] ])      Evaluation the first time               diff[y, 2, -t y^2, {t, 0., 2}, 20]      > >     {2, #1 - 0.1 #1^2 #2, #1 - 0.1 #1^2 #2, #1 - 0.1 #1^2 #2, #1 - >     0.1 #1^2 #2, #1 - 0.1 #1^2 #2, #1 - 0.1 #1^2 #2, #1 - >     0.1 #1^2 #2, #1 - 0.1 #1^2 #2, #1 - 0.1 #1^2 #2, #1 - >     0.1 #1^2 #2, #1 - 0.1 #1^2 #2, #1 - 0.1 #1^2 #2, #1 - >     0.1 #1^2 #2, #1 - 0.1 #1^2 #2, #1 - 0.1 #1^2 #2, #1 - >     0.1 #1^2 #2, #1 - 0.1 #1^2 #2, #1 - 0.1 #1^2 #2, #1 - >     0.1 #1^2 #2, #1 - 0.1 #1^2 #2}   >   Evaluation the second time               diff[y, 2, -t y^2, {t, 0., 2}, 20]      > >     {2, 2., 1.96, 1.88317, 1.77678, 1.6505, 1.51429, 1.37671, 1.24404, > 1.12023, >         1.00728, 0.905822, 0.815565, 0.735748, 0.665376, 0.603394, 0.548781, > 0.500596, >         0.457994, 0.420238, 0.386684} >


Appending to $Assumptions - Error "Nonatomic expression expected"

I need to use lots of assumptions in my code. Therefore I put them into the `$Assumptions` variable. When I do it like this, all is well:               $Assumptions = {x > 0, y > 0}     Simplify[Sqrt[x^2]] (* returns "x" *)      But as my code got longer, I wanted to break my `$Assumptions` definition into parts by appending to `$Assumptions` whenever a new assumption comes up. This works great - except when I first run the `AppendTo` command (when `$Assumptions` only contains `True`)               AppendTo[$Assumptions, x>0]         --> AppendTo::normal: "Nonatomic expression expected at position 1 in AppendTo[$Assumptions,x>0]"      Once I already have an assumption, the code works fine:               $Assumptions = {True, x>0}  (* included True just for fun *)         AppendTo[$Assumptions, y > 0]  (* works *)      Why does it not work the first time?


Using Array Elements as Function Arguments

Suppose I have an array               p = {a,b,c,d}      and a function f that takes a variable number of arguments. I want to evaluate               f[a,b,c,d]      It won't do to type               f[p]      because this returns the array `{f[a],f[b],f[c],f[d]}` which is not at all the right thing. How do I get f to accept the elements of p (as opposed to p itself) as arguments? Edited to add: Per a request in comments, here is a concrete example. Suppose p={2,3,4}. I would like an expression that returns Multinomial[2,3,4], which is to say 1260. It doesn't work to type Multinomial[p], because this gives {Multinomial[2],Multinomial[3],Multinomial[4]}={1,1,1}, which is not at all the same as 1260.


If/else re-evaluate (integer only solutions)

I am trying to get _Mathematica_ to do an if/else loop. I can get as far as the if, but I would like it to re-evaluate until only integer solutions are found. Here is what I have:               If[sols =      Flatten[{x, y} /.      Solve[{(q1 =          RandomChoice[Join[Range[-5, -1], Range[1, 5]]] y +            RandomChoice[Join[Range[-5, -1], Range[1, 5]]] x ==           RandomChoice[Join[Range[-10, -1], Range[1, 10]]]),       (q2 =          RandomChoice[Join[Range[-5, -1], Range[1, 5]]] y +            RandomChoice[Join[Range[-5, -1], Range[1, 5]]] x ==           RandomChoice[Join[Range[-10, -1], Range[1, 10]]])}, {x, y}]];     IntegerQ[sols[[1]]] && IntegerQ[ sols[[2]]], {q1,      q2}, "Not Integers"]      # Update After playing with rasher's first code:               TraditionalForm[Column[Table[n = While[(sols = Flatten[{x, y} /.          (sol =             Solve[{(q1 =                 RandomChoice[Join[Range[-5, -1], Range[1, 5]]] y +                   RandomChoice[Join[Range[-5, -1], Range[1, 5]]] x ==                  RandomChoice[                  Join[Range[-10, -1], Range[1, 10]]]), (q2 =                 RandomChoice[Join[Range[-5, -1], Range[1, 5]]] y +                   RandomChoice[Join[Range[-5, -1], Range[1, 5]]] x ==                  RandomChoice[                  Join[Range[-10, -1], Range[1, 10]]])}, {x, y}])];        Not[IntegerQ[sols[[1]]] && IntegerQ[sols[[2]]]])];       Grid[{{Column[{q1, q2}],       Flatten[sol]}}, ItemSize -> 10,        Alignment -> {{Left, Left}}], {n, 1, 10}]]]


CoordinateTransformData that works for any dimension

The function `CoordinateTransformData` in _Mathematica_ only works for three dimension. For example,               CoordinateTransformData["Cartesian" -> "Spherical", "Mapping", {1, 2, 3, 4}]      > CoordinateTransformData::dimp: Evaluation point {1,2,3,4} has dimension 4, > which does not match dimension specification 3. >> Can anybody provide an efficient version of `CoordinateTransformData` that will work for any dimension?


CUDA and GPU hardware and compatibility questions?

We have iMac desktops and have just begun to parallelize computations across them see: Wolfram Light Weight Grid and parallel computing. This still does not look like it will give us the performance we would like to see so we've started looking at CUDA. Unfortunately, Apple informs me that CUDA does not work with the iMac's ATI Radeon HD 4670 GPU cards. Further more, one can't replace the ATI cards with NVIDIA cards on an iMac ;-( We do have a MacPro and Apple tells us we can replace it's ATI Radeon card with an NVIDIA Quadro 4000 for Mac.   * _Has anyone had any successful experience running CUDA functions on this NVIDA Quadro 4000 card?_ Apple tells me that the current Mac Pros only support a single graphics card (although the next version of the machine should support multiple ones). This leads to a couple of more questions:   * _Could one setup an array of GPU cards in a separate chassis or maybe in a Linux box that Mathematica could access?_   * _In such a configuration, would one need Mathematica installed on the machine or could it simply see the GPUs as resources on the network?_ Just hoping to understand the range of possibilities. Thanks. * * * P.S. Some more context in response to the first two comments follow. We have to simultaneously process large sets of sequential data (> 10,000 in length) for survival analysis (related to actuarial studies or time to failure studies). We look at a broad set of inner data structures -- think of them as data compression sets or maybe just a subset of possible Permutations[]. We have developed a custom mixture distribution, which models this data pretty well. Using this custom distribution we find we have four types of calculations that appear to take the most time:   * Fitting parameters for the distribution;   * NExpectation[] at each time step (using the distributions described above);   * NSolve[]to find the intersection of pairs of PDFs of the above distributions; and   * NProbability[]  Currently a single study can take 90+ minutes. We have lots of research to do so anything we can do to speed things up would help a lot. Not certain if a CUDA and GPUs can help on the parameter fitting but, as I understand it, GPUs excel at moving large blocks of data around and floating point calculations. _We have lots of data to move in and out of the processors and wouldn't NExpectation[], NSolve[], and NProbability[] all benefit from using CUDA?_


What are ways to debug while Mathematica is running?

I would like to know if we can "watch some values" during running time of _Mathematica_. I remember that `C` and `Pascal` compiler allow us to "add watch" on some variables. Some times I use a check point "if keypressed print...". But the latter style is unavailable here.


Debuging in Mathematica

## Description I have using **_Mathematica_** to solve all kinds of problems that encountered in my study. However, the function that I define to solve specific problem is not always right, in other words, it will occur all kinds of unexpected error. So I think I can debug it by looking over `middle values` of function's running process. ## Example I write a function`GridLineData`to solve my data.`(the ultimate right edition as below, but I takes much time to debug it many times)`               GridLineData[data_List, \[CapitalDelta]_] := Block[      {sortData, length, OriginData, deleteData},      sortData = DeleteDuplicates@(Sort@data);      length = Length@sortData;      OriginData =       Append[        Prepend[sortData, 2 sortData[[1]] - sortData[[2]]],        2 sortData[[length]] - sortData[[length - 1]]];      deleteData =        List /@ (First /@ Select[         Thread[List[Range[length - 1], Differences@sortData]],         #[[2]] < \[CapitalDelta] &]) + 1;      Delete[Total@#/2 & /@ Partition[OriginData, 2, 1], deleteData]     ]      **Using this fuction**               DebugData =     {{0.349661, 0.380297}, {0.858156, 0.8442}, {0.906745, 0.171579},      {0.0847783, 0.277227}, {0.198453, 0.40206}, {0.941614, 0.347187}};     GridLineData[DebugData[[All, 1]], .1]     (*==>{0.027941, 0.141616, 0.274057, 0.603909, 0.959049}*)      ## Question When I debug this function, I always want to know its `middle value` in running process. I use a tedious method that `output the middle values as the return result of this function`. So the function can be rewritten as below:                 GridLineData[data_List, \[CapitalDelta]_] := Block[      {sortData, length, OriginData, deleteData},      sortData = DeleteDuplicates@(Sort@data);      length = Length@sortData;      OriginData =       Append[        Prepend[sortData, 2 sortData[[1]] - sortData[[2]]],        2 sortData[[length]] - sortData[[length - 1]]];      deleteData =        List /@ (First /@ Select[         Thread[List[Range[length - 1], Differences@sortData]],         #[[2]] < \[CapitalDelta] &]) + 1;       {sortData,OriginData,deleteData,        Delete[Total@#/2 & /@ Partition[OriginData, 2, 1], deleteData]}     ]      **Rerun the function that give middle values**               GridLineData[DebugData[[All, 1]], .1]     (**==>{{0.0847783, 0.198453, 0.349661, 0.858156, 0.906745,             0.941614}, {-0.0288964, 0.0847783, 0.198453, 0.349661, 0.858156,             0.906745, 0.941614, 0.976483}, {{5}, {6}}, {0.027941, 0.141616,             0.274057, 0.603909, 0.959049}})      I know the **_Mathematica_** has the inner function `Trace`, but it gives complex transform process. So my question is **How to extract middle value to debug in Mathematica enviroment.**


Multiply each element of an array by another array?

I would like to multiply an array by each element of another array, and am having a lot of trouble finding a built-in or automated method of doing. Here is an example of what I'd like to achieve:               a = 0.5;     b = 4.0;          mat = {{0, 1}, {a, b}};     Rmat = RandomInteger[10, {4, 4}]     m11 = mat[[1, 1]]*Rmat;     m12 = mat[[1, 2]]*Rmat;     m21 = mat[[2, 1]]*Rmat;     m22 = mat[[2, 2]]*Rmat;          fmat = ArrayFlatten[{{m11, m12}, {m21, m22}}]      As you can see, the first matrix `mat` is multiplied by each individual element of `Rmat`. I feel like this should be easy, but I'm not finding a built-in function that works? Thanks!


How to keep markers as dots in a joined ListPlot?

Consider the following typical interactive sequence. First I produce a `ListPlot`: ![enter image description here](http://i.stack.imgur.com/YPqKy.png) OK, not bad, but I want those dots to be bigger, and also joined. First, I make the dots bigger, like this: ![enter image description here](http://i.stack.imgur.com/1hena.png) Good. Next, to join the dots, I do this: ![enter image description here](http://i.stack.imgur.com/amEHg.png) Aaaarrrrrgh! The dots disappeared! Why??? Don't they know _anything_ about usability at WRI? I have tried to achieve the desired effect in a bazillion ways, and they all fail for one reason or another: either the dots no longer look like dots (but rather like diamonds, squares, triangles), or they are no longer the same color as the lines joining them, or something else... So my question is: how can I achieve the simple effect of several plots of (distinctly visible) dots joined by lines, and each plot of a different, but uniform, color? I also have a meta-question: The frustration illustrated by the interaction above is entirely typical of my experience with _Mathematica_ , since day 1. I used to think that the reason why I had such difficulty getting the simplest things done with _Mathematica_ was that I just didn't know it well enough... But this problem has persisted over the years, with hardly any improvement, even though I've devoted considerable effort to learning more and more about _Mathematica_. I have been using _Mathematica_ now for about 20 years (!), and I _still_ struggle _for hours at a time_ with trivialities like this one. This makes me wonder whether these difficulties are really more a reflection with a fundamental flaw in some aspect of _Mathematica_ 's design (one that somehow makes conceptually simple things turn out to be disproportionately difficult). Sure, when one is starting out with some new software simple things may take a long time to accomplish, but _Mathematica_ is the only software that I've been using for more than, say 4-5 years, and that I still have to struggle with for hours to get simple things to work (and very often I just have to give up with)...


Capturing an F1

I teach an _Intro to Mathematica_ course, and one of the things I try to reinforce early on is just how helpful Mathematica's help is. In the very first lab for the course, I even give the students a randomly selected command (from among simple ones like `PrimeQ`, `IntegerDigits`, etc.) and ask them to tell me what that command does. As of right now, they get this question right if they correctly explain what the given command does. What I'd like to do is make sure they are actually going to the help. Is there some way to capture an **F1** key press within an `EventHandler` or something similar?


Numerical differentiation methods

Is it possible to write a code in _Mathematica_ that implements various differentiation methods (like forward, central, extrapolated, etc.)?


MemberQ weird inside Compile

Compile[{{x, _Real, 1}}, MemberQ[x, 2]][{2}]      outputs `False`. In fact, it seems to get compiled as `False` for every input if you look at a `CompilePrint`. It doesn't call the main evaluator, and `MemberQ` is included in the `Compile`CompilerFunctions[]` list Any ideas?


Product of Fibonacci numbers using For/Do/While loops

I want to find the product of the first 20 Fibonacci numbers (the fibonorial). I want implementations using `While`, `Do`, and `For` loops. This is my code using `Do`:               Do[Sum[Print[a = a*fib[n]], {n, 1, 20}], {a, 1}]      But I can't get it working with `While` or `For`. ### Edit My fib code is as follows:               Clear[fib, x, a]     fib[1] = 1; fib[2] = 1;     fib[n_] := fib[n] = fib[n - 1] + fib[n - 2]     fib[10]


Solving a linear equation in Mathematica

This should be easy but I can't seem to find the right way to do it. I have an equation of the form $a x + b x + c y + a z + d z = 0$, and I'd like to solve for relations between the parameters $a,b,c,d$, etc. such that the equation holds for all values of $x,y,z$, etc. This is a very simplified example of the kind of equation I'm dealing with; there are actually 308 variables $x,y,\ldots$ and 42 parameters $a,b,\ldots$, making this nontrivial. As in the short sample equation, different variables could have the same parameter and could appear multiple times with different parameters. So far my best attempt is:               Solve[ForAll[{x, y, ...}, a*x + b*y + ... == 0], {a, b, ...}]      This yields the correct solution on a smaller equation (about 20 variables and 9 parameters) but is far too slow for this one. Is there a more specific technique I could use that's more optimized for this kind of problem specifically? Leaving out `ForAll` yields solutions in terms of the x-variables, which is kind of useless. **EDIT:** nikie mentioned a much better way to do it (in the comments)! Thanks!


Color of numbers and defined functions

How do I change the color of numbers and the text representing defined functions in my notebook?


Why doesn't Mathematica make an obvious simplification?

I am doing some calculation with summation and the Kronecker symbol. Here are my steps :               $Assumptions =        k1 ∈ Reals &&  k2 ∈ Reals &&  k3 ∈ Reals &&  p1 ∈ Reals &&  p2 ∈ Reals &&  p3 ∈ Reals     k = {k1, k2, k3};     p = {p1, p2, p3};     d[i_, j_] := KroneckerDelta[i, j]     proj[i_, j_, k1_, k2_, k3_] :=        d[i, j] -         (d[i, 1]*k1 + d[i, 2]*k2 + d[i, 3]*k3)*        (d[j, 1]*k1 + d[j, 2]*k2 + d[j, 3]*k3)/        (k1^2 + k2^2 + k3^2)     test1 = proj[i, j, k1, k2, k3]*proj[i, j, p1, p2, p3];     test2 = Sum[Sum[test1, {i, 1, 3}], {j, 1, 3}]     test2 // Expand      To explain the steps: 1) I define $\vec{k}$ and $\vec{p}$ with real components.   2) I define a projector $P_{ij} \left( \vec{k} \right) = \delta_{ij} - \frac{k_i k_j}{k^2}$.   3) I compute a summation on the repeated subscript. After the last step, I have a relatively big expression, the product of k and p components. It looks like $$3-\frac{a}{a+b+c} - \frac{b}{a+b+c} - \frac{c}{a+b+c} +...-...$$ The a, b and c stands for k1, k2 and k3 (or p1, 2, 3). Now the question: why doesn't _Mathematica_ make the simplification because, as anyone can see, the preceding expression can be simplified to $2 +...-...$ Is the problem linked to the `Expand` operation? How can I make the simplification I want?. I thought of using `/.` to do it, but that doesn't work either. I hope someone will understand my question!


How to make plot with frame and two different scales on the x-axis (CMB power spectrum example)

Let us take CMB spectrum as an example. I get data of $C_l$ as a function of multipole moment $l$. Also, multipole moment is a function of angular scale. The question is: how to make a plot with a frame and two different scales on the x-axis as on the plot below ![CMB power spectrum](http://i.stack.imgur.com/dTG45.png) EDIT: See below for what I've done. Any easier way of doing it?               ListLogLinearPlot[a, Frame -> True,      FrameTicks -> {{Automatic,      None}, {{{10,        10}, {20, , {.006, 0}}, {30, , {.006, 0}}, {40, , {.006,         0}}, {50, , {.006, 0}}, {60, , {.006, 0}}, {70, , {.006,         0}}, {80, , {.006, 0}}, {90, , {.006, 0}}, {100,        100}, {200, , {.006, 0}}, {300, , {.006, 0}}, {400, , {.006,         0}}, {500, , {.006, 0}}, {600, , {.006, 0}}, {700, , {.006,         0}}, {800, , {.006, 0}}, {900, , {.006, 0}}, {1000,        1000}, {2000, , {.006, 0}}}, {{360, "0.5"}, {90, "2"}, {900,        "0.2"}, {9, "20"}}}}, AxesOrigin -> {10, 0}]      ![enter image description here](http://i.stack.imgur.com/MQFVE.png)


Flat function with repeated sequence

There are functions like `Join[ ]` that accept a variable number of arguments. `Join` is a flat function, as the order of arguments matters, but `Join[a,b,c]` equals `Join[a,Join[a,c]]`. I want to create a module that has the same behavior. It's no problem to create a function with two variables. In this example nested lists are joined horizontally: `JoinH[f_,g_] := Transpose[Join[Transpose[f],Transpose[g]]];` How do I rewrite this function/module so that I can pass a variable number of arguments to this function, like `JoinH[a,b,c]`?


How to stop Animate animation when reaching a defined value

I have following code               Animate[     Plot[myvariable x,{x,0,100}     ],     {myvariable,0.1,1},AnimationRunning->If[myvariable==1,False,True]     ]      How do I make the animation stop automatically when reaching a defined value? NOTE: I tried to make it stop by evaluating myvariable in a If expression, but I get the error " _An unrecognized option name ("AnimationRunning") was encountered while reading a AnimatorBox._ "


NIntegrate & non-numerical values

I am wondering why I am receiving the message "The integrand ... has evaluated to non-numerical values for all sampling points in the region ..." for a particular calculation I am running. How can I change my code so that this is not an issue? A simple example is copied below.               a = 1/20; b = 1/5;     FF[y_] := Exp[I a y - 1/2 b^2 y^2];     f[x_] := NIntegrate[E^(-I x y) FF[y], {y, 0.0, 100}];     NIntegrate[f[x], {x, -100, 100}]      Thanks...


How do I programmatically add to contextual menus?

To programmatically add to menus you can do as described here: How do I add to menus? What can I do to programmatically add to contextual menus? Is something similar to `AddMenuCommands` available?


NMinimize with defined function call getting error NMinimize::nnum

I want to call the `NMinimize` function for my own defined calculations but I got an error. Below is a simple example.               NMinimize[x^4 - 3 x^2 - x, x] returns     {-3.51391, {x -> 1.30084}} but          f[x_] := x^4 - 3 x^2 - x;      calling `NMinimize[f, x]` gives an error > `NMinimize::nnum: The function value f is not a number at {x} = > {-0.829053}.` What's wrong with this approach?


Limit of sequence of functions behaving strange

I'm trying to determine the limit of the sequence of functions $$f_n(x)=\left(\frac{1}{\pi}\arctan(n x) + 1/2\right)^n. $$ I define               f[x_, n_] := (1/2 + ArcTan[n x]/Pi)^n      And enter               Limit[f[x, n], n -> Infinity]      This gives the answer 0. If I instead enter               Assuming[x > 0, Limit[f[x, n], n -> Infinity]]      I get the answer $$e^{-\frac{1}{x\pi}}. $$ While               Assuming[x < 0, Limit[f[x, n], n -> Infinity]]      gives the answer 0 again. Why does the normal Limit give the answer assuming that x<0? Is this a bug, or have I missed something? Thanks in advance.


What is a Mathematica packed array?

A simple sounding question with a few sub questions:   * What is the difference between unpacked vs packed array?    * Are packed arrays more space efficent, how much so?   * Are packed arrays more time efficient for certain types of access over the unpacked form? **Bonus:** Is it ever undesirable to make use of packed arrays, even if the data can fit?


Trouble with NMaximize

I am having trouble with maximizing a function I am interested in. Below is the code I am using.               NMaximize[{(p^2)^alpha + ((c - p)^2)^alpha + (1 - (c - p)^2 - p^2)^alpha,        {c/2 - Sqrt[2 - c^2]/2 < p, p < c/2 + Sqrt[2 - c^2]/2, c == 1.2, alpha == 0.7}}, {p}]      I get the following error: > NMaximize::bcons: "The following constraints are not valid: {alpha == 0.7, c > == 1.2, c/2 - Sqrt[2 - c^2]/2 < p, p < c/2 + Sqrt[2 - c^2]/2}. Constraints > should be equalities, inequalities, or domain specifications involving the > variables." Why is this happening?


Function simplification: factoring $f(r,x)$ into $f1(r) \times f2(x)$

I have a function of two variables $f(r,x,c)$, where $r$ and $x$ are variables and $c$ is a constant that appears in the function. I would like to write it as a product of two functions $f1(r,c) \times f2(x,c)$. If I set `c = 1` and use `FullSimplify`, it automatically gives me the function in the form `f1[r]*f2[x]`. However, if no assumptions about `c` are provided `c`, `FullSimplify` doesn't work. (Based on the Physics problem I am trying to solve there are reasons to believe that I should be able to write down function in the form $f(r,x,c)=f1(r,c) \times f2(x,c)$ ) Is there any command or procedure in _Mathematica_ to separate the functional dependence of a given function with two variables?


NDSolve, Schrödinger equation, and decaying solution

I am trying to solve a Schrödinger equation for a particle hitting a step potential using `NDSolve` in Mathematica. Here is my code:               mu = 6.;     m = mu;     R  = 5.;     Vs2 = 4./(2*m*R^2);     Vs = -10./(2*m*R^2) + Vs2;     Energy = 0.001     VCC[r_] = Vs*UnitStep[R - r] + Vs2*UnitStep[r - R];     L = 0;          system = {RC''[r] +       2/r*RC'[r] + (-L*(L + 1)/r^2 - 2*mu*(VCC[r] - Energy))*RC[r] ==      0, RC[0.001] == 1.0, RC'[0.001] == 0.0 };          syssol = NDSolve[system, {RC[r]}, { r, 0.001, 1000.}, MaxSteps -> 10000000];          Plot[Evaluate[{RC[r]} /. syssol], {r, 0.001, 200.0}, PlotRange -> {-1.1, 1.1}]      There should be decaying wave when particle hits the potential step, but `NDSolve` gives an increasing result. I am sure there is some trick to fix this, so I am waiting for you help.


Is there a faster way to create a matrix of indices from ragged data?

I have data that is given as a list of ordered pairs mixed with scalars. The pairs can contain infinite bounds. My goal is to convert the data into an index used in future computations.               data = {{1, Infinity}, {-Infinity, 2}, 3, {2, 2}, {2, 3}};      This gives me all of the unique values present in `data`.               udata = Sort[DeleteDuplicates[Flatten@data], Less]          ==> {-∞, 1, 2, 3, ∞}      Now I use `Dispatch` to create replacement rules based on the unique values.               dsptch = Dispatch[Thread[udata -> Range[Length[udata]]]];      Finally I replace the values with their indices and expand scalars `a` such that they are also pairs `{a,a}`. This results in a matrix of indices which is what I'm after.               Replace[data /. dsptch, a_Integer :> {a, a}, 1]          ==> {{2, 5}, {1, 3}, {4, 4}, {3, 3}, {3, 4}}      NOTES:   1. The number of unique values is generally small compared to the length of `data` but this doesn't have to be the case.    2. Any real numbers are possible. The `data` I've shown simply gives a sense of the structural possibilities. **Question: Is there a way to create the final matrix of indices that is much faster than what I'm doing here?** **Edit:** To test the how potential solutions scale I recommend using the following data. It is fairly representative of a true-to-life case.               inf = {#, \[Infinity]} & /@ RandomChoice[Range[1000], 3*10^5];     neginf = {-\[Infinity], #} & /@ RandomChoice[Range[1000], 10^5];     int = Sort /@ RandomChoice[Range[1000], {10^5, 2}];     num = RandomChoice[Range[1000], 5*10^5];          testData = RandomSample[Join[inf, neginf, int, num]];


How to distribute definitions when loading external *.m packages

i'm struggling with the following. I use `ParallelTable` and it works transparently as it automatically distributes the needed definitions. However, I run into problems if inside `ParallelTable` I call a package with `Get["code/example.m"]`. For example, the value of `const` which was set in the master kernel is not propagated in the evaluation of `Get["code/example.m"]`.


Using non-Graphics primitives when exporting to .cdf

I'm trying to embed a "Manipulate" applet I've created into a webpage by embedding a .cdf. I'm running into a problem with displaying outputs from functions I've written. Here is a simpler example that demonstrates the problem. If I code something this way (which involves defining a new function):               Moof[n_] := Append[{Circle[{0, 0}, n]}, Circle[{1, 1}, 3]]     Manipulate[Graphics[Moof[a]], {a, 1, 4}]      then I get on the webpage the error "Moof is not a Graphics primitive or directive." This code works fine within Mathematica when the appropriate cell is evaluated. On the other hand, if I code the same Manipulate applet without defining a new function:               Manipulate[Graphics[Append[{Circle[{0, 0}, a]}, Circle[{1, 1}, 3]]], {a, 1, 4}]      then everything works fine on the webpage. Here is what the two different codes produce on a live webpage. Unfortunately, the applet that I actually want to post is considerably more complicated and it would be difficult to write the Manipulate command all in native Mathematica functions. I assume that the difficulty has something to do with initialization of my user-defined functions. Is there any way around this besides rewriting my code from the ground up? Any advice on how to resolve this would be greatly appreciated.


Retrieving the ImagePadding in absolute units

Consider the following graphic:               g = Graphics[Circle[], Frame -> True, FrameLabel -> {"one", "two"}]      Retrieving the `ImagePadding` by traditional means does not work:               AbsoluteOptions[g, ImagePadding]          (* ==> {ImagePadding -> All} *)      My guess for the reason behind this is that it is the Front End that can compute the actual value of the ImagePadding to use, so this can't be obtained without first rasterizing the image in the front end. Is there some trick to get a numerical value for the `ImagePadding` so I can align two figures (make them have the same `ImagePadding`) _and_ use an optimal value (not too small cutting off something, not too large wasting space), perhaps by asking the Front End directly? Note that the `ImagePadding` is in absolute coordinates (printer's points, not plot coordinates).


Surprises simplifying simple polynomials

I came across some somewhat surprising behavior of `Simplify` today, on something very simple. Let's take two cubic polynomials that we know have the same value:               bySum = Sum[k^2, {k, 1, n}]      > >     (1/6)*n*(1 + 3*n + 2*n^2) >                 byBernoulli = (BernoulliB[3, n + 1] - BernoulliB[3])/3      > >     (1/3)*((1 + n)/2 - (3/2)*(1 + n)^2 + (1 + n)^3) >   Now, I haven't done anything to simplify these two polynomials, so it's no surprise that they look different. However, `Simplify` helps less than you might think:               {bySum, byBernoulli} // Simplify      > >     {(1/6)*n*(1 + n)*(1 + 2*n), (1/6)*n*(1 + 3*n + 2*n^2)} >   Mathematica can still figure out that they're the same if you ask it, but the `Simplify`'d forms are different.               bySum == byBernoulli // Simplify      > >     True >   I was somewhat surprised by this. `FullSimplify` works as I'd expect, but this isn't the sort of problem where I'd expect to need it. For what it's worth, this is Mathematica 8.0.4 on Windows 7 (x64).


Changing the order of elements in a chart legend

In a stacked `BarChart` or `Histogram` the bars are stacked from bottom to top, while the legend entries are listed from top to bottom. Is there a way to make the legend entries go the other way round to improve the visual correspondence between the chart and the legend? E.g.               {bottom,middle,top}=RandomReal[NormalDistribution[0,1],{3,200}];     Histogram[{bottom,middle,top},10,ChartLayout->"Stacked",ChartLegends->{"Bottom","Middle","Top"}]      ![histogram](http://i.stack.imgur.com/Mc0PT.png)


Why does ListPlot ignore some global options?

Why does the following plot no use the global `PlotMarkers` option?               SetOptions[ListPlot, {ImageSize -> Automatic, PlotMarkers -> {"A"}}];     ListPlot[Range[10]]      Checking the global options for `ListPlot` shows that `PlotMarkers` is set on a global level:               Options[ListPlot, {PlotMarkers}] -> {PlotMarkers -> {"A"}}      If I just feed the `ListPlot` function all of it global options it plots correctly, but it defeats the purpose of having globally set defaults.               ListPlot[Range[10], Options[ListPlot]]      To my knowledge `ListPlot[Range[10]]` and `ListPlot[Range[10], Options[ListPlot]]` should always return the same result but in this case it does not. I'm running Mathematica 8.0.0.0 on Mac OS X 10.6.8


Evaluation in lambda function

If I have a function, that returns a function, for example:               f[a_] := a^2 * # &      then               f[3] == 3^2 # &      Is there a way to tell mathematica that I want part of the function evaluated, so that               f[3] == 9 # &      Obviously this example is quite simple, but in general the evaluation may be slow, and better if it's only performed once. I tried wrapping the important part (in this case, a^2) in 'Evaluate', but that didn't help. Thanks!


How can I mix colors?

As far as I know if you combine `Blue` and `Green` the result is `Cyan` (using additive mixing). I would like to know some basic arithmetic of colors for making a _Mathematica_ game for kids (using colored numbers). **My problem is** what is the result of mixing $2\times Blue + 1\times Cyan$? Or consider a more complicated example: $3\times Red + 2\times Green + 2\times Blue$. Is this color arithmetic the same for subtractive and additive mixing?


Extract pointer to a structure via netlink

In a dll library I have the `C` function `DRV_DioReadBit`, containing the structure `PT_DioReadBit`. The C++ declaration is:               FEXPORT LRESULT FTYPE DRV_DioReadBit(LONG_PTR DriverHandle, LPT_DioReadBit lpDioReadBit);       The structure `PT_DioReadBit` contains the pointer `*state` as below:                typedef struct tagPT_DioReadBit     {         USHORT      port;         USHORT      bit;         USHORT far  *state;          } PT_DioReadBit, FAR * LPT_DioReadBit;      The `lpDioReadBit` is a pointer to the structure `PT_DioReadBit` that stores target port number `USHORT port`, bit order number `USHORT bit` and returned bit status `USHORT *state`. I set the port and the bit, then I want to read the state. How can I extract this information (the value of the variable "state") by using `DefineDLLFunction` in _Mathematica_? I tried the following code: digreadbit = DefineDLLFunction[" [StructLayout(LayoutKind.Sequential, Pack=1)] public class PT_DioReadBit { public ushort port; public ushort bit; public ushort state; } [DllImport(\"Adsapi32.dll\")] public static extern Int32 DRV_DioReadBit (int DriverHandle, ref PT_DioReadBit DioReadBit)"] ctxt = Context[ Evaluate@First@Cases[digreadbit, If[ _, sym_ [_], _] :> sym]]; typeName = StringDrop[StringReplace[ctxt, "`" -> "."], -1] <> "+PT_DioReadBit"; structreadbit = NETNew[typeName] structreadbit@port = 1; structreadbit@bit = 0; error = digreadbit[placa1742, structreadbit] structreadbit@state When I call the function via error = digreadbit[placa1742, structreadbit], I obtain an error. What's wrong in my syntax?


Convolution of two distribution functions

I have two functions;               f[x_] = (1/k) Exp[-x/k] ;     g[x_] = (1/p) Exp[-x/p] ;      How I can convolve them? In Mathematica for convolving two functions we have this function:               Convolve[f, g, x, ??]      But I don't know how to do the convolution with the above function for my case. before I ask this question I searched in detail but I didn't find what I need. Note: the solution of the above functions is:               (1/k) Exp[-x/k]  *  (1/p) Exp[-x/p]  =  (1/(k-p)) ( Exp[-x/k]  - Exp[-x/p] )      where * is the convolution. So, how to do this convolution in Mathematica?


Finding the maximal `t` at which `u[x,t] == 1`?

Given the smooth function `u[x,t]` on a domain, how do I find the maximal `t` at which `u[x,t] == 1` (leaving `x` unconstrained)? I can plot the level curve with               ContourPlot[ u[x,t] == 1, {x, -50, -58}, {t, 50, 58} ]      but I'm not sure how to numerically locate the point I want. Edit: My `u` is the solution to a PDE:               sol = NDSolve[           { D[u[x, t], t] == D[u[x, t], x, x]                + D[u[x, t], x] - u[x, t]^3               + 3 u[x, t]^2 -2 u[x, t],             u[x, 0] == 3 Exp[-x^2 /6],             u[-100, t] == 0,             u[30, t] == 0 },             u, {x, -100, 30}, {t, 0, 100}]      The point of interest lies in the domain $-58<x<-50$ and $50<t<58$.


Test First row of matrix

What is a good way to test the first row of a Matrix to check if one of the values equal a value. For instance, In this example, I want to get vector in the second row that has the bigger value in the first row, 10. I can quickly do it with a lop, but don't think it's the best way... ![enter image description here](http://i.stack.imgur.com/1pQOB.png)


How to improve this dynamic progress bar code

I created this progress bar to use in my codes:               progressBar1[var_,total_]:=Row[{ProgressIndicator[var,{0,total}]," ",                Row[{NumberForm[100. var/total,{\[Infinity],2}],"%"}],"% ",var}]      But to use it I have to implement like this:               Module[{n = 10, i = 0},         Print[Dynamic@progressBar1[i, n]];         (i++; Pause[0.1]) & /@ Range[n];      ]      I tried to implement like this, but with no success.               progressBar2[var_,total_]:=Print[Dynamic@Row[{ProgressIndicator[var,{0,total}]," ",                Row[{NumberForm[100. var/total,{\[Infinity],2}],"%"}],"% ",var}]]          Module[{n=10,i=0},         progressBar2[i,n];         (i++;Pause[0.1])&/@Range[n];     ]      The idea is to change `progressBar2` to make it usable inside Module without necessity to call Dynamic and Print. I've seen this similar post How to create a progress bar? , but didn't get how to upgrade my code. Some clue?


Graph a Function with general conditions

> **Possible Duplicate:**   >  Plot Even Piecewise function Based on Howell's Principles of Fourier Analysis, I found a function $ f(x)= \begin{cases} \sqrt{|x|} & \text{ if }-\pi < x < \pi \\\ f(x-2\pi) & \text{ in general } \end{cases} $ and the author seem to be able to produce a graph with Maple that is like a bun and continuous. Now my question is how can I produce the same graph of this type in Mathematica. I am aware that I can use the piecewise function but the second condition say "in general" and hence I am lost. Please give advise.


Simplifying a symbolic product of rational powers

I'm trying to symbolically evaluate a lot of equations that can consist of up to 10 parameters. The form of these expressions is a product/quotient of rational powers of the mentioned parameters, where the exponents are rational expressions containing a unknown number `p`. Here is a simplified example (containing parameters `Bcr` and `Ft`):               ( (Ft Bcr)^(2 p + 4) * Ft^(23 p - 4) )     / ( Bcr^(1/(2.5 p - 4)) * Ft^( (24 p + 4)/(3 p - 1) ) )^( 3 p - 6)      I would expect, that using `Simplify`, `FullSimplify` or another, similar function I could reduce this expression to a product like this:               Ft^F[p] *Bcr^G[p]      where `F[p]` and `G[p]` are some rational functions of `p`. Now I understand there is a problem with considering complex numbers, multiple roots etc. However, even if I use assumptions:               $Assumptions = p > 0 && Bcr > 0 && Ft > 0      Mathematica still does not evaluate the answer neatly. A follow up question would be: why such calculations take so much time, considering this seems to be the simplest of symbolic expression manipulation - something Mathematica should excel at? So is there a way to simplify such expressions e.g. with a function similar to `FullSimplify`, but which ignores problems concerning domains of variables and multiple values?


How to specify the time variable for NDSolve

I recall that it is possible to specify which independent variable is the "time" variable in `NDSolve`, but I can't find it documented anywhere. Does anyone recall how it works? I'm getting the following error because (I believe) `NDSolve` is confused about which is the time variable:               NDSolve::bcedge: Boundary condition [...] is not specified on a single edge      of the boundary of the computational domain.      I think this is because my _initial_ condition is inside (not an extremum of) the (time) domain of the interpolating function that specifies it. **Update:** `TemporalVariable` is an option of `NDSolve`MethodOfLines`. Therefore, it does not work directly as an option in `NDSolve`, and should be called in the following manner:               Method ->       {         "MethodOfLines",         "TemporalVariable" -> t       }      However, this did not solve my problem (see the comments).


Find the values of parameters so that the matrix is symmetric positive definite

Good evening , I have a matrix 20x20 in symbolic form. The matrix depends on 5 parameters (a,b,c,d,e). I would like to get the interval of each parameters that ensures that the matrix S is symmetric positive definite. Should I first compute the symbolic expression of the eigenvalues and then solve a system of 20 inequalities to find the interval of the 5 parameters? Or can I do it directly with some Mathematica command? Thank you.


Manipulate for Electric Field

I'm kind of new to Mathematica but I'm getting the hang of it slowly. Anyways, I'm trying to do a project on the electric field of two particles so my professor helped me with this code (sorry in advanced for the length)               Clear[x, y, lof, Δθ];     V = -1/Sqrt[(x + 1)^2 + y^2] + 1/Sqrt[(x - 1)^2 + y^2];     Grad[V, {x, y, z}] // Simplify;     Ex[x_, y_] = -Grad[V, {x, y, z}][[1]];     Ey[x_, y_] = -Grad[V, {x, y, z}][[2]];          Emag[x_, y_] =        Sqrt[Ex[x, y]^2 + Ey[x, y]^2] // Simplify // PowerExpand;     lof = {};     Δθ = 10 °;          For[θ = 0 °, θ < 360 °,      x0 = 1 + .2*Cos[θ];      y0 = .2*Sin[θ];      Δs = .01;      pts = {};      nsteps = 1000;      AppendTo[pts, {x0, y0}];      For[n = 1, n <= nsteps,       Δx = Ex[x0, y0]/Emag[x0, y0]*Δs;       Δy = Ey[x0, y0]/Emag[x0, y0]*Δs;       x = x0 + Δx;       y = y0 + Δy;       If[Sqrt[(x - 1)^2 + y^2] > .2, AppendTo[pts, {x, y}]];       x0 = x;       y0 = y;       n = n + 1;       ];      AppendTo[lof, Line[pts]];      θ = θ + Δθ;      ]     For[ θ = 0 °, θ < 360 °,      x0 = -1 + .2*Cos[θ];      y0 = .2*Sin[θ];      Δs = .01;      pts = {};      nsteps = 1000;      AppendTo[pts, {x0, y0}];      For[n = 1, n <= nsteps,       Δx = -Ex[x0, y0]/Emag[x0, y0]*Δs;       Δy = -Ey[x0, y0]/Emag[x0, y0]*Δs;       x = x0 + Δx;       y = y0 + Δy;       If[Sqrt[(x - 1)^2 + y^2] > .2, AppendTo[pts, {x, y}]];       x0 = x;       y0 = y;       n = n + 1;       ];      AppendTo[lof, Line[pts]];      θ = θ + Δθ;      ]     ContourPlot[V, {x, -3, 3}, {y, -3, 3},      Contours -> Table[z, {z, -2, 2, .2}],      ContourShading -> False,      ContourStyle -> {{Black, Dashing[{.01}]}},      Frame -> False,       Epilog -> {AbsolutePointSize[7], Blue, Point[{-1, 0}], Red,         Point[{1, 0}], Yellow, lof}, Background -> Gray, PlotRange -> All]      The output should be: ![enter image description here](http://i.stack.imgur.com/A9nGF.jpg) What I'm trying to do is do a manipulate function. One that will just move the position of the left particle. So in the code I just want to change the three- starred one (`***1***`) into a variable for the manipulate function.                V = -1/Sqrt[(x + ***1***)^2 + y^2] + 1/Sqrt[(x - 1)^2 + y^2];      But I can't figure out the correct syntax. Could someone lend a helping hand? Thank you!


Conjugate of InterpolatingFunction?

From `NDSolve`, I got this:               {{a1 -> InterpolatingFunction[{{0., 40.}}, "<>"]}}      What would be a sensible approach to getting the complex conjugate of this function, particularly bearing in mind that we might have to deal with derivatives higher than the zeroth and that the (possibly nonuniform) sampling of the interpolation should be respected?


Generating the set of all strings within a fixed edit distance of a initial string?

Provided a starting string `initialString`, and a particular alphabet of allowed characters `{"A","B","C","D","E",...}`, how can I generate the set of all strings such that `EditDistance[initialString,setElement] = k`, where `k` is specified as desired? How can I do the same if I only consider `HammingDistance`? Rather, I should say, how do we do the above without generating all of the `Tuples` of relevant length, then checking each one for `EditDistance` or `HammingDistance`, which is probably the most naive way to proceed? Here's a partial example of that naive strategy (partial because for `EditDistance` we need to generate tuples of the string length of the initial string $\pm \space k$):               k = 1;          stringTestLength = 8;          alphabet = {"0", "1", "R"};          tuples = Map[StringJoin, Tuples[alphabet, stringTestLength]];          testString = "00000000"          distanceOneList = {};     editDistanceCounter = 0;     For[i = 1, i <= Length[tuples], i++,       If[EditDistance[tuples[[i]], testString] == k,         editDistanceCounter += 1;         distanceOneList = Append[distanceOneList, tuples[[i]]];         ];       ];          distanceOneList     editDistanceCounter      The output here is of course the following length sixteen array:               {"00000001", "0000000Q", "00000010", "000000Q0", "00000100", "00000Q00", "00001000", "0000Q000", "00010000", "000Q0000", "00100000", "00Q00000", "01000000", "0Q000000", "10000000", "Q0000000"};      The "real" answer for `EditDistance` is 1 (for the length 7 tuple set) + 19 (for the length 9 tuple set) + 16 (for the length 8 = length of the initial string) tuple set. Thus, there are 36 strings over this alphabet within `EditDistance k = 1` of the initial string `"00000000"`.


Turn expression into function

I'm new to _Mathematica_ and I spent the last hour trying to make the expression               expression =        3 + 2 cos[t] + 3 cos[2t] + 5 cos[3t] + 7 cos[4t] + 9 sin[t] +  4 sin[3t] + 5 sin[4t]      into a function of `t`. I tried               f[t_] := expression      but it didn't work.


finding an argument of a complex number

What is the simplest way to find the argument of the following function? `((1 - E^((I π (1 - α))/(β - α)) z)/(1 - E^(-((I π (1 - α))/(β - α))) z))` as I tried the polar way, but it is so complicated and I didn't reach the result yet. Thank you.


How does `LongestCommonSubsequence` work?

When I recently came across this posting about `LongestCommonSubsequence` I was curious about how the function worked. `LongestCommonSubsequence` appears to behave as I expected from the description in the documentation.               ?LongestCommonSubsequence      ![lcss](http://i.stack.imgur.com/d62zS.png) For example               LongestCommonSubsequence["DOLORE", "LOREM"]     LongestCommonSubsequence[{"D", "O", "L", "O", "R", "E"}, {"L", "O", "R", "E", "M"}]          LongestCommonSubsequence["AD", "MAGNAD"]     LongestCommonSubsequence[{"A", "D"}, {"M", "A", "G", "N", "A", "D"}]      > "LORE"   >  {"L", "O", "R", "E"}   >  "AD"   >  {"A", "D"} The documentation provides very little information about `LongestCommonSubsequencePositions` , but it presumably returns the positions of the longest common substrings of two words (or lists of characters). ![lcssp](http://i.stack.imgur.com/cpNbt.png) Sometimes it behaves as I expect:               LongestCommonSubsequencePositions["DOLORE", "LOREM"]     LongestCommonSubsequencePositions[{"D", "O", "L", "O", "R", "E"},      > {{3, 6}, {1, 4}}   >  {{3, 6}, {1, 4}} At other times it returns the positions in the incorrect order:               LongestCommonSubsequencePositions["AD", "MAGNAD"]     LongestCommonSubsequencePositions[{"A", "D"}, {"M", "A", "G", "N", "A", "D"}]      > {{5, 6}, {1, 2}}   >  {{5, 6}, {1, 2}} Is this a bug? Or am I misunderstanding how `LongestCommonSubsequencePositions` works? * * * **Edit** HyperGroups raises the hypothesis that the relative string length of the words may lie behind this behavior. Let's do a quick check. In the examples below, the first word grows in length until it surpasses the stringlength of the second word.                d = {{"AD", "MAGNAD"}, {"ADE", "MAGNAD"}, {"ADEV", "MAGNAD"}, {"ADEVO", "MAGNAD"},        {"ADEVOL", "MAGNAD"}, {"ADEVOLT", "MAGNAD"}, {"ADEVOLTI", "MAGNAD"},       {"ADEVOLTIC", "MAGNAD"}, {"ADEVOLTICK", "MAGNAD"}};           TableForm[{#, LongestCommonSubsequence @@ #, LongestCommonSubsequencePositions @@ #,       (StringLength[#[[1]]] > StringLength[#[[2]]])} & /@ d]      > ![data](http://i.stack.imgur.com/kOlPS.png) There is clear support for this idea. Whenever the length of the lefthand word is equal to or greater than that of the righthand word, the greatest common substring positions are returned in the respective order. Otherwise, the order of the positions is inverted. * * * The same pattern holds for words given as lists of characters. (Note: `Length` is used instead of `StringLength`.)               d1 = Characters@d;     TableForm[{#, LongestCommonSubsequence @@ #, LongestCommonSubsequencePositions @@ #,      (Length[#[[1]]] >  Length[#[[2]]])} & /@ d1]      > ![data1](http://i.stack.imgur.com/lzMJp.png) By the way, `LongestCommonSubsequence` seems to work correctly whenever the strings are of the same length (I checked by running the same tests, but with the order of each pair reversed.) * * * The question remains: **Why does this happen?** Bug or feature? Looks to me like a bug, one that can be kept under control by checking the relative stringlengths and correcting when needed.


Avoiding white lines inside filled area in RegionPlot exported as PDF or PS

When doing a `RegionPlot`and then exporting (or saving from the front end) as PDF or EPS, there are small white lines in the filling of the region. Here's an example created with `RegionPlot[x^2+y^2<1,{x,-1,1},{y,-1,1},PlotStyle->Black]`:   ![output of RegionPlot after saving as EPS](http://i.stack.imgur.com/FBLyv.png) Is there any way to prevent those white lines while keeping it vector graphics? Note that those lines do _not_ appear on screen, only in the exported file. Also note that my actual graphics is more complex and especially has several different-coloured regions.


Strange behavior of PlotMarkers with ListLinePlot[] and InterpolationOrder->0

I want to create a ListLinePlot with `InterpolationOrder->0`. However, when using plot markers like in               ListLinePlot[{{1, 2, 3, 5, 8}, {2, 3, 6, 9, 10}, {4, 5, 7, 10, 12}},       PlotMarkers -> Automatic, InterpolationOrder -> 0]      the plot markers become mixed up. How can this be avoided?


Read a file into a list of vectors

I have file structured as `(Axis 1) (Axis 2) Data`.   As an example:               1.2E-003 -0.500        0.0000000000000000          1.2E-003 -0.493       1.53468784818295775E-004     1.2E-003 -0.487       5.89210645476378352E-004     1.2E-003 -0.481       1.23713800962565101E-003     1.2E-003 -0.475       1.99285240196946144E-003          2.8E-003 -0.500        0.0000000000000000          2.8E-003 -0.493       1.65202052327590321E-004     2.8E-003 -0.487       6.34230407238311057E-004     2.8E-003 -0.481       1.33156043724947304E-003     2.8E-003 -0.475       2.14469618088317755E-003      In other words:   * Each line has 3 real values   * The data is divided in blocks separated by a blank line.      * The size of each block is between 200 and 3000 (this size is unknown prior to reading the file, but I could write a shell script to extract and store this information somewhere if that makes things easier).     * The first value is the same for the entire block.   * There are exactly 1000 blocks. I would like Mathematica to open this file and store this information inside a variable. This variable would be a list of vectors. In this list, each element (a vector) corresponds to 1 block, and this vector contains the data from the third column (all other data is discarded). In this example, the variable should be a list of 2 vectors:               {{ 0.0000000000000000 , 1.53468784818295775E-004 , 5.89210645476378352E-004 , 1.23713800962565101E-003 , 1.99285240196946144E-003 },      { 0.0000000000000000 , 1.65202052327590321E-004 , 6.34230407238311057E-004 , 1.33156043724947304E-003 , 2.14469618088317755E-003 }}      Is this easy to do?


Find names of the functions defined in a file

Lets say I have a file named `file.m` that contains:               test[] := (       Print["test"]     )      How would I go about extracting the function declarations in such a file consistently as a list? I have figured out how to extract the data without having it execute.               Import["file.m", "Text"]      This is my current code.               Cases[      FullForm[       MakeExpression[Import["file.m", "Text"], TraditionalForm]       ],      SetDelayed[x__, y__] -> f[x, y]      ]


Choosing an initializer list in With

I'm trying to have several initializer lists in a `With` function and choose which one I want to use. So far I have this:               With[Evaluate@{Unevaluated@{a = 2, b = 3}, Unevaluated@{a = 4, b = 6}}[[1]], a + b]      which doesn't work on a pretext that " _Local variable specification Unevaluated[{a=2,b=3}] is not a List._ ", and gives me `With[Unevaluated[{a = 2, b = 3}], a + b]` for an answer. Now, if I just feed this same purportedly erroneous expression back to the kernel, it evaluates just fine with the correct result of 5, showing that Unevaluated list not being a list is a rather moot point. But how do I connect `Unevaluated` with `With` without me in between?


Can mathematica solve this equation?

I have the following _Mathematica_ code to solve an equation coming from isoparameteric finite element for quadratic tetrahedron element. I need to get the iteroplation fast and accurate. I only find articles by iterative method and I want to know whether it is possible to get an analytical solution:               sol = Solve[ ( 2(1 - xi - eta - zeta)^2 - (1 - xi - eta - zeta)) x1 + (2xi^2 - xi) x2                   + (2eta^2 - eta) x3 + (2zeta^2 - zeta) x4 + 4(1 - xi - eta - zeta) xi x5                   + 4xi eta x6 + 4(1 - xi - eta - zeta) eta x7 + 4eta zeta x8                   + 4(1 - xi - eta - zeta) zeta x9 + 4xi zeta x10 == x  &&                  ( 2(1 - xi - eta - zeta)^2 - (1 - xi - eta - zeta)) y1 + (2xi^2 - xi) y2                  + (2eta^2 - eta) y3 + (2zeta^2 - zeta) y4 + 4(1 - xi - eta - zeta) xi y5                  + 4xi eta y6 + 4(1 - xi - eta - zeta) eta y7 + 4eta zeta y8                  + 4(1 - xi - eta - zeta) zeta y9 + 4xi zeta y10 == y  &&                   ( 2(1 - xi - eta - zeta)^2 - (1 - xi - eta - zeta))z1 + (2xi^2 - xi) z2                 + (2eta^2 - eta) z3 + (2zeta^2 - zeta) z4 + 4(1 - xi - eta - zeta) xi z5                 + 4xi eta z6 + 4(1 - xi - eta - zeta) eta z7 + 4eta zeta z8                  + 4(1 - xi - eta - zeta) zeta z9 + 4xi zeta z10 == z, { xi, eta, zeta}];     xx =   xi /. sol;     yy =  eta /. sol;     zz = zeta /. sol;      by collecting the coefficient of `xi`, `eta` and `zeta`, the original equation can be transformed to the following:               sol = Solve[{  a1 xi^2 + a2 xi + a3 eta^2 + a4 eta + a5 zeta^2 + a6 zeta                   + a7 xi eta + a8 eta zeta + a9 zeta xi == a0,                    b1 xi^2 + b2 xi + b3 eta^2 + b4 eta + b5 zeta^2 + b6 zeta                   + b7 xi eta + b8 eta zeta + b9 zeta xi == b10,                    c1 xi^2 + c2 xi + c3 eta^2 + c4 eta + c5 zeta^2 + c6 zeta                   + c7 xi eta + c8 eta zeta + c9 zeta xi == c10}, { xi, eta, zeta}];     xx =   xi /. sol;     yy =  eta /. sol;     zz = zeta /. sol;      where               {a1 b1 c1} = 2( {x1 y1 z1} + {x2 y2 z2} - 2{x5 y5 z5})      and so on. However, it seems to hang there for tens of minutes and it maybe impossible to get the analytical solution. I noticed that in real engineering, not all facets are curve facets. By this fact, we can suppose that               2x5 = x1 + x2     2x7 = x1 + x3     2x9 = x4 + x1      and so on. Therefore, the above equation is simplified as follows:                   sol = Solve[{ a2 xi + a4 eta + a6 zeta + a7 xi eta + a8 eta zeta + a9 zeta xi == a10,                       b2 xi + b4 eta + b6 zeta + b7 xi eta + b8 eta zeta + b9 zeta xi == b10,                        c2 xi + c4 eta + c6 zeta + c7 xi eta + c8 eta zeta + c9 zeta xi == c10},                      { xi, eta, zeta}];     xx =   xi /. sol;     yy =  eta /. sol;     zz = zeta /. sol;      Is there any good method to solve this equation?


Vertical "fractions" with more than 2 parts

Standard `FractionBox` syntax allows only 2 arguments and creates 2-part fraction for numerator and denominator. Is it possible to draw similar construction, but with more than 2 parts? Some sort of column with separators only between inner parts? The following code               Column[{"x", 200, Integrate[Sin[x^2], x]}, Alignment -> Center, Dividers -> Center]      draws best what I found but it does dividers of similar length in entire column. I would like dividers to accommodate two adjacent parts only.


Grid layout problems: different sizes when rendering on Mac and Windows

From the documentation for `ItemSize`: > {w,h} make all items the specified width and height and > In Grid, w is measured in ems, and h in line heights. This implies that a specification `ItemSize->{4,2}` means the item is 4ems wide and 2 line heights high, which in turn suggests that the item size in pixels will be `CurrentValue["FontMWidth"]*4` wide and `CurrentValue["FontLineHeight"]*high`. Therefore to make grids that render to a fixed number of pixels across various platforms you presumably should do (for an item of pixel dimension w,h = 100,20):               ItemSize:>{100/CurrentValue["FontMWidth"],20/CurrentValue["FontLineHeight"]}      **If this is not correct stop reading now and let me know!** The problem I have is that from Mac to Windows I am unable to get the same dimensions:               img1 = Rasterize[Grid[RandomInteger[{1, 100}, {10, 8}],        Alignment -> {Center, Center},        Background -> None,        BaseStyle ->          Directive[FontFamily :> CurrentValue["PanelFontFamily"],           FontSize :> CurrentValue["PanelFontSize"],           RGBColor[0, 0, 0.25]],        Frame -> All,        FrameStyle -> Directive[AbsoluteThickness[0.5], GrayLevel[0.7]],        ItemSize :> {{80, 260, {130}}/CurrentValue["FontMWidth"],           22/CurrentValue["FontLineHeight"]},        Spacings -> {0, 0}]]      ![enter image description here](http://i.stack.imgur.com/oBdd4.png)               ImageDimensions[img1]      Mma 8.0.4 on Mac 10.6.8               (* {751, 224} *)      Mma 8.0.4 on on Windows 7               (* {983, 274} *)      And when we check the em widths and line heights on both systems: Mma 8.0.4 on Mac 10.6.8               {CurrentValue["FontMWidth"], CurrentValue["FontLineHeight"]}     (* {12.9621, 9.875} *)      Mma 8.0.4 on Windows               {CurrentValue["FontMWidth"], CurrentValue["FontLineHeight"]}     (* {12.6, 10} *)      In other words similar em widths and line heights. The upshot is that I have had problems creating a grid on a Mac that doesn't go offscale when viewed on Windows. The screen resolutions (`SystemInformation["Devices", "ScreenInformation"]`) are 72 for Mac and 96 for Windows. The ratio of Windows image width for Mac width is close to 96/72 but the heights are not close to that ratio at all -- but in any case there is no mention of screen resolutions in the documentation. Does anyone have any thoughts on what is happening here and how I can get a grid of the same size on both Mac and Windows? **Edit** I think this example by @SjoerdC.deVries nails it:               Grid[{{"MMMMMMMMMMM", "MMMMMMMMMMMMMMMMMMMM"}}, ItemSize -> 5,      Spacings -> {0, 0}]      If the item size is in ems then you should expect only 5 "M" characters to fit in a grid cell ...right? Following the comment from @Silvia I have tested Serif, Sans-serif and monospace fonts: Sans-serif -- Helvetica gives 4Ms ![enter image description here](http://i.stack.imgur.com/uWTsi.png) Serif -- Times gives 4Ms ![enter image description here](http://i.stack.imgur.com/fihqL.png) Monospace -- Monaco gives many Ms ![enter image description here](http://i.stack.imgur.com/KdcPa.png) Note that using lower case "m" made no difference. Note that further investigation shows that the word wrapping has an effect here. With _just_ 5Ms the item size almost works. ![enter image description here](http://i.stack.imgur.com/7OGLO.png) Initial summary: So either the documentation is wrong, or it is incomplete, or the implementation is broken. Subsequent summary: the problem seems to reside with how Mathematica determines the font being used when doing the size calculations. It clearly responds when StandardForm is changed but does not respond to local font usage (apparently). Otherwise an item size of x/CurrentValue["FontMWidth"] should surely deliver an item xMs wide. **Edit #2** Confirmed as a bug by WRI tech support.


Use of Mathematica to generate report

I would like to generate a report for codes written in Mathematica, but I don't see basic features such as:   1. Table of Content generator   2. List of Figures   3. Abstract   4. Bibliography and other standard report generators like LaTex?


Importing web page data

I tried importing a webpage using `Import`: `Import["http://ultrasignup.com/m_results_participant.aspx?fname=Troy&lname=Siemers"];` which should give some info about a runner friend of mine (he gave permission to have his name shown here). Using `Import` as shown above gives generic HTML information but the table containing the data I want. Using the options `"Data"` and `"FullData"` do not give anything useful, either. However, in my web browser I can see the HTML code for the table when I "View Source." Is there an option for importing a web page in _Mathematica_ that I am overlooking? How do I import the data from the page?