title: Deleting powers of a common prime except the highest one from a list with further only primes

text: In a list with factors of which most are prime, some are integer powers of some common prime as base. All the powers from `1` to `imax` of that base are present in the list. The value of `imax`, however, is unknown. I have to delete from the list all powers of that base except the highest. Equivalently we can e.g.:   * change all the values of the powers of the known base into the base value and multiply them,   * delete all the lower powers of the known common base from the list. An example with `base = 5` and `imax = 3`:               list1 = {2, 5, 13, 25, 125, 3001, 230686501}      should become {2, 13, 125, 3001, 230686501}      or one with `base = 13` and `imax = 2`:               list2 = {13, 169, 233, 741469, 159607993}     should become {169, 233, 741469, 159607993}      I did find `Gather` and `GatherBy`, is it possible to `GatherBy` common powers of the same (beforehand unknown common) base?               In[1]:= li3 = {2, 5, 11, 5, 7, 5};          In[2]:= Times @@@ Gather[li3]      > >     Out[2]= {2, 125, 11, 7}   >   Any help is appreciated. Thanks.


title: How to compute a discrete histogram of a list

text: I'm trying to compute the discrete histogram of a set of values. By histogram I mean the absolute frequency a value appears on the dataset, by discrete I mean the values are from a discrete set, e.g. integers. Example: given `data = {1,4,1,2,3,1,4}`, I would like to have an efficient way of obtaining something like               {{1,3}, {2,1}, {3,1}, {4,2}}      I Tried using BinCount and HistogramList, but both are more suitable for continuous values. My current solution is to use `Count` along with `DeleteDuplicates`:               {#, Count[data, #]} & /@ DeleteDuplicates[data]      My question is: do you know any more efficient way (without using procedural programming)? I ask this because if there are N elements from which M are distinct, this approach requires M sweeps on a dataset of size N (M calls of Count), which is not required for the outcome I'm searching for: this operation should be feasible in one sweep.


title: Hide output from when mouseover Locator graphic

text: When the mouse pointer passes over the Locator graphic (or one clicks at any point in the frame), the underlying equation that generates the `ContourPlot` is visible in a text box. How can I suppress this output? Here is the code.               Manipulate[     iv = Row[{"t0 = " , N[p[[1]], 3], ", ", "x0 = " , N[p[[1]], 3]}];           ContourPlot[(x - t - 1) Exp[x - p[[2]]] ==         p[[2]] - p[[1]] - 1, {t, -6, 6}, {x, -6, 6},        PerformanceGoal -> "Quality", BaseStyle -> {FontSize -> 14},        FrameLabel -> {t, x}, RotateLabel -> False,        ContourStyle -> Directive[Red, Thick],       Epilog -> {Point[p], Text[iv]}       ],      {{p, {-2, -2}}, {-10, -10}, {10, 10}, Locator,       Appearance -> Graphics[{Blue, Disk[{0, 0}, .1]}, ImageSize -> 14]}]


title: How to plot a figure like this

text: I saw a beautiful figure illustrating the optical lattice clock, and would like to make a similar one. This is the figure (taken from here) ![enter image description here](http://i.stack.imgur.com/2kZ2P.gif) Is it possible to make a similar one using Mathematica? Here is my try:               Show[      Plot3D[0.05 (Cos[3 x] Cos[            3 y])^4, {x, -\[Pi], \[Pi]}, {y, -\[Pi], \[Pi]},        PlotRange -> {All, All, {-0.1, 0.1}}, PlotPoints -> 200, Mesh -> 60,        MeshStyle -> Gray,        ColorFunction -> (ColorData["GreenPinkTones"][0.5 #3 + 0.5] &)],      Graphics3D[{Darker[Green],         Scale[Sphere[{0, 0, -0.5}],          0.25 {\[Pi]/3, \[Pi]/3, .1}, {0, 0, 0}]}, Lighting -> "Neutral"],      ImageSize -> {651.1743427005708`, 484.8`}, Lighting -> "Neutral",       Method -> {"RotationControl" -> "Globe",         "RotationControl" -> "Globe"},       PlotRange -> {All, All, {-0.1`, 0.1`}},       PlotRangePadding -> {Automatic, Automatic, Automatic},       ViewAngle -> 0.13079882249358044`,       ViewCenter -> {{0.5`, 0.5`, 0.5`}, {0.5218420229698426`,          0.6543497570242808`}},       ViewPoint -> {-2.144844931539977`,         1.84186142553857`, -1.8593511526229505`},       ViewVertical -> {0.`, 0.`, -1.`}]      ![enter image description here](http://i.stack.imgur.com/Ht29K.png)


title: New display format needed: "drag box"

text: I want to create a new display type, especially for numbers or text, but potentially for arbitrary objects as well. I want a "drag box" where not all of the number (object) is visible, but dragging left and right on the object itself slides it left and right (or in a generalized form both x and y). No scroll bars should be visible, and it should be tightly integrated much like `Framed` so that it can be used in different places without difficulty. In Chat Szabolcs showed how to get the basic functionality. However, there are problems with this implementation as he notes:   1. the `N[Pi,100]` shouldn't be recalculated constantly   2. ... Dynamic doesn't work inside the `ScrollPosition` setting ...   3. when the mouse leaves the region, it stops working, and for good usability it shouldn't I don't observe #3 on my system (Win7/mma7) but I do note another problem: Dragging the text left (looking at the least significant digits) it is possible to drag the object completely out of frame. Dragging it right does not move it out of frame but causes a memory of the drag such that it appears "stuck" when you start dragging left, though it eventually moves.   * How can this function be implemented most efficiently and flexibly?   * Can it be made to work inside a `Text` object the way `Frame` does?


title: Why the tensor product of list of variable change the subscript position in products

text: {Subscript[g, 1],Subscript[e, 1]}\[TensorProduct]{Subscript[g, 2],Subscript[e, 2]}\[TensorProduct]{Subscript[g, 3],Subscript[e, 3]}      I am expecting answer like ...               {{{Subscript[g, 1] Subscript[g, 2] Subscript[g, 3],       Subscript[g, 1] Subscript[g, 2] Subscript[e, 3]}, {       Subscript[g, 1] Subscript[e, 2] Subscript[g, 3],       Subscript[g, 1] Subscript[e, 2] Subscript[e, 3] }}, {{Subscript[e,       1] Subscript[g, 2] Subscript[g, 3],      Subscript[e, 1] Subscript[g, 2] Subscript[e, 3] }, {Subscript[e, 1]       Subscript[e, 2] Subscript[g, 3],      Subscript[e, 1] Subscript[e, 2] Subscript[e, 3]}}}      Why it change the sequence in the product?


title: Localizing variables within a Manipulate

text: I have a notebook with several examples of very similar computations, each involving the same variable/parameter names of the ingredients used in a final `Manipulate`. For example,               (* example 1 *)     c = 1;     L = 1;     f[x_] = 180 x^4 (1 - x);     g[x_] = 1;     \[Lambda][n_] = ((n \[Pi])/L)^2;     a[n_] = 2/L  Integrate[f[x] Sin[Sqrt[\[Lambda][n]] x], {x, 0, L}];     b[n_] = 2/(L Sqrt[\[Lambda][n]] c) Integrate[g[x] Sin[Sqrt[\[Lambda][n]] x], {x, 0, L}];     u[x_, t_] = Sum[(a[i] Cos[Sqrt[\[Lambda][i]] c t] +         b[i] Sin[Sqrt[\[Lambda][i]] c t]) Sin[Sqrt[\[Lambda][i]] x], {i, 1, 10}];          Manipulate[Plot[u[x, t], {x, 0, L}, PlotStyle -> {Thick, Blue}, PlotRange -> {-15, 15},         AxesLabel -> {x, "u"}], {t, 0, 5}]      followed by               (* example 2 *)     k = .2;     L = 1;     f[x_] = 180 x (1 - x)^4;     \[Lambda][n_] = (((2 n - 1) \[Pi])/(2 L))^2;     b[n_] = 2/L  Integrate[f[x] Sin[Sqrt[\[Lambda][n]] x], {x, 0, L}];     u[x_, t_] = Sum[b[i] Sin[Sqrt[\[Lambda][i]] x] Exp[-\[Lambda][i] k t], {i, 1, 10}];          Manipulate[Plot[u[x, t], {x, 0, L}, PlotStyle -> {Thick, Blue}, PlotRange -> {-1, 16},         AxesLabel -> {x, "u"}], {t, 0, 5}]      As discussed in the documentation, evaluating the second block of code dynamically updates the output of the first `Manipulate` since the underlying quantities being plotted share the name $u(x,t)$ (among other parts) in each. My question then is, what are some good ways to mitigate this behavior other than:   1. Choosing distinct names for all underlying quantities for each problem. (This is intractable since I may have 10+ such exercises in each notebook.)   2. Disabling dynamic updating. (This is unsatisfying since the point here is to see the `Manipulate` "movies".)   3. Wrapping everything in a `DynamicModule`, e.g.,               (* example 1a *)     DynamicModule[{a, b, c, f, g, L, \[Lambda], u},      c = 1;      L = 1;      f[x_] = 180 x^4 (1 - x);      g[x_] = 1;      \[Lambda][n_] = ((n \[Pi])/L)^2;      a[n_] = 2/L  Integrate[f[x] Sin[Sqrt[\[Lambda][n]] x], {x, 0, L}];      b[n_] = 2/(L Sqrt[\[Lambda][n]] c) Integrate[g[x] Sin[Sqrt[\[Lambda][n]] x], {x, 0, L}];      u[x_, t_] = Sum[(a[i] Cos[Sqrt[\[Lambda][i]] c t] +          b[i] Sin[Sqrt[\[Lambda][i]] c t]) Sin[Sqrt[\[Lambda][i]] x], {i, 1, 10}];           Manipulate[Plot[u[x, t], {x, 0, L}, PlotStyle -> {Thick, Blue}, PlotRange -> {-15, 15},          AxesLabel -> {x, "u"}], {t, 0, 5}]]      and then               (* example 2a *)     DynamicModule[{a, b, k, f, L, \[Lambda], u},      k = .2;      L = 1;      f[x_] = 180 x (1 - x)^4;      \[Lambda][n_] = (((2 n - 1) \[Pi])/(2 L))^2;      b[n_] = 2/L  Integrate[f[x] Sin[Sqrt[\[Lambda][n]] x], {x, 0, L}];      u[x_, t_] = Sum[b[i] Sin[Sqrt[\[Lambda][i]] x] Exp[-\[Lambda][i] k t], {i, 1, 10}];           Manipulate[Plot[u[x, t], {x, 0, L}, PlotStyle -> {Thick, Blue}, PlotRange -> {-1, 16},         AxesLabel -> {x, "u"}], {t, 0, 5}]]      This at least does what I am after: the variable/parameter names that are recycled across exercises _are_ localized to its respective `Manipulate`. This just felt a little clunky and requires quite a bit of explanation to students about why we need to do this. I was curious if there were other/better ways to accomplish this (that I could then share with them).


title: How do I "start a reference system"?

text: When I attempt to insert a citation or specify a database to use as a bibliography, I get a message that I need to "start" the "reference system" "manually": ![enter image description here](http://i.stack.imgur.com/8axyt.png) I have no idea what a references system is, let alone how to start one ("manually" or otherwise). I've followed all of the steps in the documentation, to no avail. * * * If it matters, I'm running OS 10.8.2, using a BibTeX file (which I've used without issues in other applications, e.g. LyX) for my references, and I have a fill MacTeX installation in the standard locations on my machine. * * * UPDATE: It matters.


title: Simplifying expressions involving square roots and 'i' factors

text: I am doing the contour integration using Mathematica. After extraction of residues, my expression contains a lot of unwanted pairs such as               (I t - u y[2]) (I t + u y[2])       or               (t^2 - I u Sqrt[w[1]]) (t^2 + I u Sqrt[w[1]]).      I want them to be combined so that $i$'s should be no longer involved in the expression. Any suggestions? added: Maybe I should write down the (part of) real example which I want to reduce.               Simplify[((I Sqrt[t/u] - y[1]) (I Sqrt[t/u] + y[1]) (-1 +        I Sqrt[t/u] y[1]) (1 + I Sqrt[t/u] y[1]) (1 +        y[1]^2) (I Sqrt[t/u] - y[2]) (I Sqrt[t/u] + y[2]) (-1 +        I Sqrt[t/u] y[2]) (1 + I Sqrt[t/u] y[2]) (1 +        y[2]^2) (I Sqrt[t/u] - y[3]) (I Sqrt[t/u] + y[3]) (-1 +        I Sqrt[t/u] y[3]) (1 + I Sqrt[t/u] y[3]) (1 +        y[3]^2) (I Sqrt[t/u] - y[4]) (I Sqrt[t/u] + y[4]) (-1 +        I Sqrt[t/u] y[4]) (1 + I Sqrt[t/u] y[4]) (1 +        y[4]^2) (I Sqrt[t/u] - y[5]) (I Sqrt[t/u] + y[5]) (-1 +        I Sqrt[t/u] y[5]) (1 + I Sqrt[t/u] y[5]) (1 +        y[5]^2) (I Sqrt[t/u] - y[6]) (I Sqrt[t/u] + y[6]) (-1 +        I Sqrt[t/u] y[6]) (1 + I Sqrt[t/u] y[6]) (1 +        y[6]^2))/(2  (-I Sqrt[t/u] + t Sqrt[w[1]]) (I Sqrt[t/u] +        t Sqrt[w[1]]) (t^2 + w[1]) (1 + t^2 w[1]) (Sqrt[u] -        I Sqrt[t^3 w[1]]) (Sqrt[u] + I Sqrt[t^3 w[1]]) (-I t + Sqrt[(       t w[1])/u]) (I t + Sqrt[(t w[1])/u]) (t^(3/2) -        I Sqrt[u w[1]]) (t^(3/2) + I Sqrt[u w[1]]))]


title: Are persistent variable values after the kernel is stopped possible?

text: Is there a way to make values of variables persistent even after the kernel is stopped? Example, if I were to set up a list for which I append new list items (such as a check ledger, as a basic example). If I stop the kernel, the value of the variable is lost. I can import/export to .csv, .txt, or .xlsx but that kind of defeats the point. Thanks!


title: Factorization of a list with composite integers to a combined list of all prime factors

text: The following function io[aIn_] produces a list bOut containing ALL the prime factors of an Integer via the standard function FactorInteger[]. My code is:               io[aIn_] :=      (bOut = {};fi = FactorInteger[aIn];Do[bOut~AppendTo~(PadLeft[{}, fi[[i, 2]], fi[[i, 1]]] ), {i, 1, Length[fi]}]; bOut = bOut // Flatten )      I would like to know whether there are other solutions for this "problem"? My solution does not work with e.g. aIn={12321}; io[aIn] nor with io[{12321}] or io[{12, 21}] and I do not understand all the warnings given by MMA. I do not like to build a function that treats the integers of an input seperately and combines the results into a single list.   I prefer a solution for io[] with "list in of composite integers" gives " list out of all prime factors".


title: Pasting monospaced text into Mathematica notebook destroys aligment

text: I drew the little ASCII-art electronics schema below in vim.   When i try to paste it into a Mathematica notebook, with:   A) A code cell   B) A monospaced font (Courier New)   Mathematica insists on destroying the vertical aligment. Here is what it looks like in vim: ![enter image description here](http://i.stack.imgur.com/3nMB5.png) And here's what it looks like in Mathematica: ![enter image description here](http://i.stack.imgur.com/vquS9.png) Even worse, when I try to re-align things by hand in the notebook, the end result looks very bad (note the misaligned vertical bars on the right hand side) ![enter image description here](http://i.stack.imgur.com/By0fh.png) For something so simple to be so hard ... I must be missing something glaringly obvious.   Help would be very much appreciated.


title: Real integral evaluating as indeterminate

text: Mathematica evaluates the following integral as:               In[1]:= Assuming[p \[Element] Integers && p > 0,       Integrate[Sin[x]*Cos[x]^p/(Cos[x] + 2), {x, 0, Pi}]]          Out[1]= -2^p Beta[2/3, -p, 1 + p] + ((-1)^ p Hypergeometric2F1[1, 1, 1 - p, 2])/p      However, when I evaluate the resulting expression, I encounter a complex infinity. For example, for `p = 3`:               In[2]:= -2^3 Beta[2/3, -3,  1 + 3] + ((-1)^3 Hypergeometric2F1[1, 1, 1 - 3, 2])/3          During evaluation of In[96]:= Infinity::indet: Indeterminate expression ComplexInfinity+ComplexInfinity encountered. >>         Out[2]= Indeterminate      Did I make a simple mistake in `In[1]` that is causing this problem? Certainly $\sin x\cos^p x/(\cos x + 2)$ is real and finite over the whole real line, for $p\in\mathbb{N}$.


title: Finding normals to a curve through a given point

text: I want to find x on curve $y(x)$, where curve $y(x)$ is perpendicular to point $(x_0,y_0)$. for this I minimize the distance between points $(x,y(x))$ and $(x_0,y_0)$, here's an example for point $x_0=4,y_0=3$.               y[x_] := 2 + 0.36 x     NMinimize[(4 - x)^2 + (3 - y[x])^2, x]      But somehow this does not give the right answer though _Mathematica_ seems to be finding the right minimum.               {0.171388, {x -> 3.85977}}      ![enter image description here](http://i.stack.imgur.com/6pITB.jpg) **Update:** In a more practical case, with `Ei` some data to be fitted, and `sol2` the fitted coefficients of `U[...]` (refer to the end of the question for detail), this is what I tried:               Do[      int = FindMinimum[{(Ei[1][[1, 2]] - U[x, 1] /. sol2[[2]])^2 + (i - x)^2}, x];      AppendTo[perpendicular, int],       {i, 1, 30}]          cc =        ListPlot[{         Evaluate @ Table[{i, Ei[1][[i, 2]]}, {i, 15, 23}],          Evaluate @           Table[{x, U[x, 1] /. sol2[[2]]} /. perpendicular[[i, 2]], {i, 15, 23}]},          Filling -> {1 -> {2}},          PlotRange -> {0, 5},          AspectRatio -> Automatic];          qq =        Plot[U[x, 1] /. sol2[[2]], {x, 15, 23},          PlotRange -> {0, 5},          AspectRatio -> Automatic];      ![enter image description here](http://i.stack.imgur.com/tn09u.jpg) This is the fitting function:               U[r_, o_] :=        Sum[-ehh (1 - (1 - Exp[-Ahh (raa[i, j, o] - rshh)])^2), {i, 2,            5}, {j, 7, 10}] +          Sum[-ech (1 - (1 - Exp[-Ach (raa[i, j, o] - rsch)])^2), {i, 1,            1}, {j, 7, 10}] +          Sum[-ech (1 - (1 - Exp[-Ach (raa[i, j, o] - rsch)])^2), {i, 2,            5}, {j, 6, 6}] -          ecc (1 - (1 - Exp[-Acc (raa[1, 6, o] - rscc)])^2) /. x -> r;      And this the the fitted coefficients:               sol2 = {ehh -> -4.07603, Ahh -> 3.75309, rshh -> 1.44794, ech -> 0.223024,              Ach -> 1.51935, rsch -> 2.84276, ecc -> -4.52077, Acc -> 2.99396,              rscc -> 2.60361}


title: How can I generate a nested array like this one?

text: Well, this is how the array looks like: ![enter image description here](http://i.stack.imgur.com/4QlF7.jpg) I came up with this code:               n = 10;     Nest[ArrayPad[#, 1, 1 - #[[1, 1]]] &, {{1}}, n] /. {1 -> "*"}      Any better ideas?


title: How to compute the `Automorphisms` of graphs with multiple edges?

text: I try to compute the `Automorphisms` of graphs with multiple edges from its `AdjacencyMatrix` but failed. The following code shows how to compute the `Automorphisms` of graphs without multiple edges:               Block[{$ContextPath}, Needs["Combinatorica`"];     Needs["GraphUtilities`"]]     m = ({     {0, 1, 1, 1},     {1, 0, 1, 1},     {1, 1, 0, 1},     {1, 1, 1, 0}     });     g = AdjacencyGraph[m];     Combinatorica`Automorphisms@GraphUtilities`ToCombinatoricaGraph[g]//Lenght (*24*)      As I have tried, `AdjacencyGraph`, `IncidenceGraph` will fail to convert a matrix into a graph. And               Graph[{1 \[UndirectedEdge] 2, 1 \[UndirectedEdge] 2}]      will fail also. But if I plot the graph as a figure directly `Automorphisms` will fail at that figure of graph. Other software will do this work, for example Sage. So, how to compute the `Automorphisms` of graphs with multiple edges in Mathematica?


title: Run encoded package code through .NET/Link?

text: An earlier question of mine, Prevent package from being opened in a notebook interface, never received an answer, but Albert Retey's comments did lead me to an entirely different solution. To secure my Mathematica code for distribution to a client I now plan to wrap encoded Mathematica code in C# code and compile it to a DLL. The client will then call the DLL from their .NET application with specific methods that will call my proprietary Mathematica functions. My compiled code will handle all .NET/Link operations. Wrapping encoded code in a DLL may seem like overkill (well I still tie double knots in my shoelaces). I just want to make the code as secure as possible and as I have to do the compiling on my client's Window's machine (I use Mac) I want to do everything to keep it from curious eyes. I've written a package and encoded it. I've tested the package in the client environment by loading the encoded package file from a notebook interface. This works fine. I've done a second test. In a notebook, I copied the encoded text and pasted it into a cell and assigned it to a variable, something like:               myEncodedString = "(*!1N!*)mcm     j<hTJue'P+lKh]7t>X#r/N5>m^c0Q j,fdE~0y@X>TkncC'AMluD1_R3,0?vQR0(n|p08B     D\O%!1o3t~`#0VL...a bunch more encoded text..."      Following this I tried:               Get[myEncodedString]      This didn't work. I revisited what I needed to do and realized I could make it work by using the form `Get[stream]` and tried the following:               Get@StringToStream[myEncodedString]      This gave me the following dialogue box: ![enter image description here](http://i.stack.imgur.com/cdYz6.png) Selecting "Yes" ran the code and made all of its function definitions available. Now I tried to do the same thing from C# via .NET/Link, which did not work. I think it didn't work because I need some way to insert escapes in the encoded text. Does anyone have an idea of how to do this or more generally how to get this to work?


title: Conveying density of 5-smooth (Hamming) numbers

text: A number is 5-smooth if its only prime factors are 2, 3 or 5. Example: > >     1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … >   Interesting thing is that as they become larger and larger, they are sparser and sparser, with respect to all natural numbers... Now, how to make a visual illustration of that fact (becoming sparser)? I was thinking of lets say a 300 x 1000 rectangle, where each pixel means a natural number, and red is 5-smooth, blue is otherwise. This would work for first 300,000 numbers. Here is a collection of programs in various language regarding 5-smooth numbers: link Including this:               HammingList[N_] :=        Module[{A, B, C},          {A, B, C} =            (N^(1/3))*{2.8054745679851933, 1.7700573778298891, 1.2082521307023026} - {1, 1, 1};         Take[Sort @ Flatten @            Table[2^x * 3^y * 5^z ,              {x, 0, A}, {y, 0, (-B/A)*x + B}, {z, 0, C - (C/A)*x - (C/B)*y}],           N]];      and               HammingList[20]      > >      {1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 27, 30, 32, > 36} >                 HammingList[1691] // Last      > >     2125764000 >                 HammingList[1000000] // Last      > > > 519312780448388736089589843750000000000000000000000000000000000000000000000000000000 >   Appreciate any idea and/or insight.


title: Can someone please help me to state assumption?

text: I am currently trying to solve under what condition does the following term will be zero?                  2*a*b*n*c*Q - 3*a*b*n*p*c*Q + a*b*n*p^2*c*Q - 4*a^2*b*n*p*Q^2 -         4*a*b^2*n*p*Q^2 + 6*a^2*b*n*p^2*Q^2 + 6*a*b^2*n*p^2*Q^2 -         2*a^2*b*n*p^3*Q^2 - 2*a*b^2*n*p^3*Q^2 + a^2*b*c*Q^2 +         a*b^2*c*Q^2 -         2*a^2*b*p*c*Q^2 - 2*a*b^2*p*c*Q^2==0      The assumption is that               0<a<1 && 0<b<1 && 0<c<1 && 0<n<2 && Q>0.  (Also, all of them are real)      * * * * * * Attempt:               Assuming[0 < a < 1 && 0 < b < 1 && 0 < c < 1 && 0 < n < 2 && Q > 0 &&        Element[a | b | c | n | Q, Reals], Reduce[       2*a*b*n*c*Q - 3*a*b*n*p*c*Q + a*b*n*p^2*c*Q - 4*a^2*b*n*p*Q^2 -          4*a*b^2*n*p*Q^2 + 6*a^2*b*n*p^2*Q^2 + 6*a*b^2*n*p^2*Q^2 -          2*a^2*b*n*p^3*Q^2 - 2*a*b^2*n*p^3*Q^2 + a^2*b*c*Q^2 +          a*b^2*c*Q^2 - 2*a^2*b*p*c*Q^2 - 2*a*b^2*p*c*Q^2 == 0]]      It returns,               (Q == 0 && (p == 1 ||           p == 2)) || ((-c + 2 c p + 4 n p - 6 n p^2 + 2 n p^3) Q != 0 &&         a == (2 c n - 3 c n p + c n p^2 + b c Q - 2 b c p Q - 4 b n p Q +           6 b n p^2 Q -           2 b n p^3 Q)/((-c + 2 c p + 4 n p - 6 n p^2 +             2 n p^3) Q)) || (p == 1/2 && n == 0 && Q != 0) || (Q == 0 &&         2 - 3 p + p^2 != 0 && n == 0) || (Q == 0 &&         n (2 - 3 p + p^2) != 0 && c == 0) || ((p == 1 || p == 2) &&         c == 0 && Q != 0) || (n == 0 && -1 + 2 p != 0 && c == 0 &&         2 p Q - 3 p^2 Q + p^3 Q != 0) || (p == 0 && n == 0 && c == 0 &&         Q != 0) || (Q != 0 && p == 0 && 2 n != 0 && c == 0) || a == 0 ||       b == 0 || Q == 0      Two questions: 1) Did I do this correctly? 2) How do I interpret the solution returned? Isn't that "||" represents OR? So between each "||", then that is a solution?


title: How can multiple null terminated strings be handled in a DLL-function result?

text: I am trying to connect a classic System Dynamics tool (Vensim DSS) with Mathematica using a DLL that is included in Vensim DSS. Reading though the instructions on how to define DLL functions on how to declare arguments - here strings - I found that if there are [out] strings one should use the .NET class _System.Text.StringBuilder_. So applying the advice given will look like this:               (* definitions *)     $maxBufLen = 1000;     strOutput = NETNew["System.Text.StringBuilder", $maxBufLen];     vensimGetInfo = DefineDLLFunction["vensim_get_info", vensimDLL,     "int", {"int", "System.Text.StringBuilder", "int"}];          (* usage *)     infoWanted = 3; bufLen = $maxBufLen;     vensimGetInfo[infoWanted, strOutput, bufLen];     strOuput@ToString[]       Unfortunately this only works properly for a single string and some information will be returned by the DLL function as a series of null terminated strings that is finally ended by a double null. In such a case the above procedure will only return the first string omitting the rest. What can be done?


title: Comparing NIntegrate with definite integration

text: I want to calculate without error a sum of double integrals with the following definitions for the functions within them:               fx[ x_ ] = PDF[NormalDistribution[10, 2], x];     Fx[ x_ ] = CDF[NormalDistribution[10, 2], x];     f[ x_ , y_ ] = Simplify[PDF[MultinormalDistribution[{10, 8},             {{2^2, 0.5*2*1.5}, {0.5 2 1.5, 2.25}}], {x, y}]];     \[Phi]m[q_ ] = Integrate[Integrate[(-q + x)*y*f[x, y],               {x, q, 25}], {y, 2, 15}]/(1 - Fx[q]);      When I compute the differential in q of [Phi][q] using two different methods, I get very different results. Compare:               D1[q_] = D[\[Phi]m[q], q];      With:               Td\[Phi]s = Table[{q,               1/(1 - Fx[q]) NIntegrate[-y f[x , y ], {x, q, 25}, {y, 2, 15}] +          fx[q]/(1 - Fx[q])^2 NIntegrate[(x - q) y f[x, y], {x, q, 25}, {y, 2, 15}]},               {q, 1, 23, 0.1}];     d\[Phi]s = Interpolation[Td\[Phi]s, InterpolationOrder -> 1]      Look at the difference in results between these 2:               Table[{D1[q], d\[Phi]s[q]}, {q, 4, 16}]                        {{0.0599831, -7.89327}, {0.213901, -7.6447}, {0.584625, -7.09157},            {1.25085, -6.1804}, {2.17537, -5.03748}, {3.22484, -3.88942},           {4.26853, -2.90709}, {5.23671, -2.14794}, {6.11377, -1.59297},           {6.91058, -1.19675}, {7.64478, -0.915004}, {8.33155, -0.71338},           {8.97959, -0.567722}}      If somebody can explain which is the best method (apart from the difference in computing time), I would be very grateful! Thanks. Xavier


title: Change font for the whole notebook

text: Is there any option Mathematica's preferences to change the font for the whole notebook? I know how to change the font of individual cells.


title: Create horizontal list in notebook

text: I want to create a multiple choice question paper and list the options horizontally. I am only looking at very simple document with horizontal list. What I want:   1. What is 1+1? a) 2 b) 4 c) 3 d) 7 Is there any correct way to do it with cells other than manually using spacebars?


title: Why does automatic scaling behave as it does in Plot?

text: The following command               Plot[Exp[-(x^2)], {x, -5, 5}]      draws ![enter image description here](http://i.stack.imgur.com/4VzsY.jpg) while the following command               Plot[Exp[-2 (x^2)], {x, -5, 5}]      draws ![enter image description here](http://i.stack.imgur.com/stPKp.jpg) I.e. the scale is changing which seems unexpected.


title: Programmatically quitting the FrontEnd or running without one?

text: I have a conundrum. I use an iMac's OS X 10.6.8 settings to start and stop the machine at the specific times that I need a particular notebook to run. I've done this because it has worked more reliably then timed events. _Mathematica_ launches automatically when my computer boots and the notebook with all its cells set as `Initialization Cells` launches automatically and evaluates when _Mathematica_ starts. The last expression in the notebook: `NotebookSave[]` as evident, saves this active notebook. I need this because some graphics in the notebook change and I want to review them later. This notebook will be the only open notebook at the time of its evaluation. So far so good. Now I want the notebook to programmatically quit the _Mathematica_ `FrontEnd`. This gets tricky and presents (at least) 2 problems: **Problem 1:**               NotebookSave[]     FrontEndTokenExecute["FrontEndQuit"]      begins the process, but gives me the following popup window: ![popup window](http://i.stack.imgur.com/BxE5K.png) This doesn't help me, because I want this to run on its own and as stated above I have an OS setting that will shut down the computer soon after Mathematica would quit. I won't have anyone in front of the computer to click "OK" and thereby allow the shutdown to proceed. No click no shutdown. **Problem 2:** All of the notebooks cells, including the one with the:                  FrontEndTokenExecute["FrontEndQuit"]      set as Initialization Cells presents another problem. IF I can find a work- around for the popup warning above, I still need a way to break, abort, or interrupt the flow of control so I don't have a notebook, which will always open, evaluate, then quit _Mathematica_. At some point I'll want it to stay open to edit or change the code. I've looked at variations of:               NotebookSave[]     Interrupt[];      FrontEndTokenExecute["FrontEndQuit"]         They give me a popup window like this: ![interrupt window](http://i.stack.imgur.com/PJ6Fj.png) Pressing "Continue" or "Abort" just gives me the same popup window ("The notebook ..... contains a running evaluation...." as I had in "Problem 1". * * * If my solution in doing this includes automatically opening and evaluating the notebook I think I need some way to have a button or popup window come up which gives me a period of time, say 30 seconds to abort the closing of the application and its notebook. If no one aborts the process before 30 seconds I'd want the machine to shut down.   * Is such a thing even possible given what I've found above?   * Do I need to consider dispensing with the FrontEnd for this altogether? If yes, can someone point me in the right direction? At least for now I'd feel content if I can rely upon the OS to boot and shut down the computer so I guess I could launch the code when the computer boots. This way I wouldn't need to worry about recurring timers, that to date have proven unreliable. The notebook in question does a lot of different stuff: opening parallel kernels, lots of parallel mapping, creating graphics, and emailing results both text and graphics. Is it even feasible for this kind of complication to run as a script on booting of the computer? Stumped and looking for some guidance. Thanks.


title: Signal processing by means of WaveletTransform

text: I updated my question to explain what I want. **I have the voltage-time curve from the real industial object.** This curve was gotten from the digital oscilloscope: ![Oscillogram](http://i.stack.imgur.com/lR9Go.png) As you can see it has **hight-frequency (kHz) interference**. We extracted data from the oscilloscope into the Microsoft Excel file and here it is: http://www.fileconvoy.com/dfl.php?id=g3c9169c7c6eb991d999470396248137bf77d4cabe Using this data we reconstructed the curve (in MathCAD). As an equivalent to time-axis we have n-axis ("n" - number of the point; every point corresponds to certain moment of time; in all we have 4000 points for 8 ms): ![curve](http://i.stack.imgur.com/i14H0.png) Using Fourier Transofrm we got frequency spectrum **(amp-freq curve)** : ![fourier frequency spectrum](http://i.stack.imgur.com/8KX7k.png) Inasmuch as this signal is **nonstationary** , the usage of _Fourier Transform_ **is not appropriate**. So we used _Fast Wavelet Transform_ and the result was quite different (and **probably** correct). This is an **amp-point curve** which is similar to the recostructed source curve, but there are displayed amplitudes for 4,7 - 5,5 kHz frequencies (for different wavelet coefficients), which appeared exactly in these moments: ![wavelet frequency spectrum](http://i.stack.imgur.com/u4k35.png) And now by some reason there is a need to process the source data in Wolfram Mathematica, also because it is far and away more powerful than MathCAD. But Mathematica is something new for me in the field of signal processing, and now I have no time to study it. There is almost one week left for us to have this task done. The main purpose of the work is to use different wavelet families and obtain the correct frequency spectrum **(amp-freq curve)**. We are working with power quality and electromagnetic compatibility. This task is an engeneering task. So here is the diference between datas. Original data is on the top and the interpolated is below. ![data](http://i.stack.imgur.com/sNbUC.jpg)


title: Modifying a column with a button within the column

text: I want a column with textcells and a button to add an extra textcell:               Column[{Button["New line"],     TextCell["a", "Text", FontFamily -> "Times", FontWeight -> Plain, Editable -> True]},     Editable -> False]      How to do this? I want the first click to make it be like:               Column[{Button["New line"],     TextCell["However this has been edited", "Text", FontFamily -> "Times", FontWeight -> Plain, Editable -> True],     TextCell["a", "Text", FontFamily -> "Times", FontWeight -> Plain, Editable -> True]},     Editable -> False]


title: Layers of Locators of Different Colors?

text: I am a Mathematica novice trying to do some interactive segmentation of microscopy images. I've been trying to understand and build upon some code from a previous StackExchange discussion (Can individual locators in LocatorPane be temporarily disabled?) about creating layers of locators that don't interfere with each other that are overlayed on the same image. My goal is to use this approach to help speed up my image segmentation so I can take a colorized WatershedComponents or MorphologicalComponents label matrix and join components together by grouping and selecting each component with the same color (i.e. layer) of locator. For example, if an image had two objects of interest in it an the segmentation has oversegmented the image so that this results in 3 components for object #1 and 5 components for object #2, I would like to simply put 3 red locators on the components of object #1 and 5 blue locators on the components of object #2 and then pass these component lists to other functions that join these components. Here's Where I'm Running Into Trouble with Building Upon the Code Below: i.) How can I apply locPaneSimplified function to a colorized WatershedComponents matrix so the layers and points still show up? ii.) How can I generate an arbitrary number of overlays as needed (i.e. new layers/colors of locators on demand as determined by the user viewing the segmented image) by pressing a "New Layer" button or something similar? iii.) How can I get rid of the Manipulate and use just a Dynamic or DynamicModule instead? Thanks for any suggestions or simple examples you can share with me! -GR               (*           The block of code below allows for adding arbitrary numbers of red and blue      locators by toggling between overlays and using LocatorAutoCreate->True.            This is simplifed from kguler's suggestions in previous StackExhange code discussion:         http://mathematica.stackexchange.com/questions/9148/can-individual-locators-in-       locatorpane-be-temporarily-disabled.          *)                    (*locator appearance graphics*)     redCircle = Graphics[{Red, Disk[]}, ImageSize -> 10];     blueCircle = Graphics[{Blue, Disk[]}, ImageSize -> 10];     grayDisk = Graphics[{Lighter@Lighter@Gray, Disk[]},      ImageSize -> 10] (* used when locator is "grayed out" (i.e. made inactive)      when another layer is selected *);               locPaneSimple[Dynamic[pts_], shape_] :=        LocatorPane[Dynamic[pts],         Dynamic@Module[{},           Graphics[Point /@ pts, PlotRange -> m, Axes -> True,            ImageSize -> {300, 300}]],          Appearance -> shape (* "Appearance" gives the style/shape of the two Locators *),          LocatorAutoCreate -> True (* allows for creating more locators by pressing Alt+Click*)          ];               Manipulate[m = 15 (* m sets PlotRange *);      Overlay[{locPaneSimple[Dynamic[pts],          Dynamic@If[layer == 1, redCircle, grayDisk]]  (*          preceding [] contains arguments to locPane.          If layer==1 then you get red circles at pts if layer1!=1 you get grayDisk *)         ,         locPaneSimple[Dynamic[pts2],          Dynamic@If[layer == 2, blueCircle, grayDisk]]},         All, Dynamic[layer]],          {{pts, {{6, 0}, {0, 9}}}, ControlType -> None},          {{pts2, {{7, 0}, {0, 7}}}, ControlType -> None},          {{layer, 1, "layer"}, {1, 2}} (* creates "layer" buttons to toggle between red and         blue locator layers that have beenoverlayed on same plot *)           ](* Close Manipulate *)


title: Mathematica Reference Book on Reliability Engineering?

text: Can anyone suggest a reference book titled “Reliability Engineering Using Mathematica” or similar that contains the version 9 or version 10 functionality ? Some topics/chapters I would be interested in are: Accelerated Life Testing, Bayesian Methods, Critical Systems (medical devices, nuclear power, aerospace, etc.), Degradation Analysis and Modeling, Derating, Design for Environments, DFR, DOE, ESS and other Manufacturing Screens, Failure Mode Modeling, Fault Tolerant/Redundancy/Voting Trade Offs, Fault/Success Trees, Financial Analysis & Cost Trade Studies, FMEA, HALT/HASS, Hardware Reliability, Life Cycle Costing, Life Data Analysis, Maintainability/Availability Theory/Applications, Markov Analysis, Modeling Series, Parallel, K of N and Complex Systems, RBDs, Reliability Apportionment, Reliability Growth Testing, Reliability Prediction, Risk Management, Software Reliability (white box/black box), Survivability, System Safety, Test Unit Sample Size Computations wrt Confidence Limits and Warranty Analysis. If no such books exist in this domain, any pointers to freely available papers from industry or academia would be appreciated. Thanks.


title: Finding a vector field from a set of points

text: I have a data set of the type $\{x,y,z\}$ where $(x,y)$ is a point and $z$ is the "value" or magnitude at that point. This gives me a triangular sort of shape since $(x,y,z)$ is not defined along the whole possibility set considering it is real data. Is there any way I can get a gradient using the points I have (using them if possible) and using the interpolation from Mathematica otherwise?


title: Derivative of generating function (Example from documentation)

text: In the documentation for `GeneratingFunction`, the following example is given under Examples -> Properties & Relations -> Derivative:               GeneratingFunction[n f[n], n, z]     (*z (GeneratingFunction^(0,0,1))[f[n],n,z]*)      When I evaluate the input, however, I obtain something different, namely:               GeneratingFunction[n f[n], n, z]     (*z GeneratingFunction[(1 + n) f[1 + n], n, z]*)      For me the first output would be preferable; indeed I would like Mathematica to express any expression of the form               GeneratingFunction[p[n] f[n], n, z] (*p[n] an explicit polynomial in n*)      in terms of derivatives of the generating function of the sequence `f[n]`. I think this is the intended behaviour of `GeneratingFunction` and certainly what I remember from v8. **Question:** Is there a way to achieve this behaviour? I am currently using version 9.0 on a 64bit Linux computer.


title: Saving and Reading data across computers

text: I DumpSaved some data from my home laptop, uploaded it onto google drive and now I am trying to open it at my school computer but I am getting errors, even though the data is in the correct directory. My data is bunch of data for different parameter values that I have stored as a function.               out[] := Cases[DownValues[out], _String, Infinity]     out[ToString[DataStep1[[l, 3]]]] = outNR     DumpSave["Renegotiation.mx", out]     << Renegotiation.mx      The data can be found here: The details of DumpSave says that "Files written by DumpSave can only be read on the same type of computer system on which they were written." What is a "type of computer system" ? Both my laptops are PCs with windows. Is there no way for me to read my data at the school laptop? In any event, can you please suggest how I can store data that I can open on different computers?


title: Contour heat graph (ListContourPlot?)

text: I have solved 2D incompressible Navier Stokes and written out a .dat file that includes x,y,u,v,p values. I am trying to get a 2D color heat graph like this one for my data ![enter image description here](http://i.stack.imgur.com/VrAYZ.png) Here is what I have done so far trying to use Contourplot:               Data = Import[     "C:\\Users...     UVP-steady-state.dat", "Table"];     x = Data[[3 ;; 16002, 1]];     y = Data[[3 ;; 16002, 2]];     u = Data[[3 ;; 16002, 3]];     v =  Data[[3 ;; 16002, 4]];     p =  Data[[3 ;; 16002, 5]];     grid = Transpose[{x, y}];     ListPlot[grid, PlotLabel -> "MeshPoints", AxesLabel -> {"x", "y"},      PlotRange -> Automatic, AspectRatio -> Automatic]     velocity = Transpose[{x, y, Sqrt[u*u + v*v]}];     pressure = Transpose[{x, y, p}];     ListContourPlot[velocity]     ListContourPlot[pressure]      My steady state solution is in this .dat file http://www.wikiupload.com/VSPA5GS9BAXQ830 I am able to make my solution look like this with TecPlot. ![enter image description here](http://i.stack.imgur.com/6U1ly.png) For some reason Mathematica with ListContourPlot plots two fairly large gaps in the middle of the graph.


title: Unexpected results from Thread

text: I've run into an issue where threading two lists with a generic function, `f`:               Thread[f[{{1,1}, {2, 2}, {3, 3}}, {4, 5, 6}]]      yields the wanted result: > >     {f[{1, 1}, 4], f[{2, 2}, 5], f[{3, 3}, 6]} >   However, if I define a function, `g`:               g[angle_, position_] := RotationMatrix[angle].position;      then the threading of those same two lists with `g` yields what seems like an inconsistent result: > >     {RotationMatrix[{1, 2, 3}].4, RotationMatrix[{1, 2, 3}].5, > RotationMatrix[{1, 2, 3}].6} >   It doesn't seem to thread the same way with the explicit function g as it does with the generic function `f`. It appears that it's treating the first thread as some type of atomic element and threading it individually to each element of the second list. This behavior _almost_ makes sense (as I don't quite understand how functions work at different sub-levels of lists yet), but it still doesn't explain the inconsistency between the generic and explicit functions.


title: Number of iterations in NSolve

text: In Excel's solver, one can define how many iterations are to be done, to one's liking. I am wondering if this is possible to do with `NSolve` in _Mathematica_? **Code** This is what I'm working with:               A = 3580/1000; (*constante*)     B = 736/1000;(*constante*)     R1 = 5/1000;(*0-1.5*)     R2 = 17/1000;(*0-1.5*)          fR1 = ((A + B) (1 - a)^2 (1/15 + P2/21 - (4 P4)/35))/         (A (1/15 (3 + 4 a + 8 a^2) + 4/21 (3 + a - 4 a^2) P2 +            8/35 (1 - a)^2 P4) + B (1 - a)^2 (1/15 + P2/21 - (4 P4)/35));     fR2 = (A (1 - a)^2 (1/15 + P2/21 - (4 P4)/35) + B (1 - a)^2 (1/15 - (2 P2)/21 + P4/35))/         (A (1/15 (3 + 4 a + 8 a^2) - 2/21 (3 + a - 4 a^2) P2 +            3/35 (1 - a)^2 P4) + B (1 - a)^2 (1/15 - (2 P2)/21 + P4/35));     fP4 = -((83 P2)/1000) + (1366 P2^2)/1000 - (1899 P2^3)/1000 + (1616 P2^4)/1000;     fRho = ((A + B) (1 - a)^2)/(A (8 a^2 + 4 a + 3) + B (1 - a)^2);          NSolve[R1 == fR1 && R2 == fR2 && P4 == fP4 && rho == fRho, {P2, P4, a, rho}, Reals];     MatrixForm[%]


title: How can an InverseQuantile or an interval valued Quantile function be implemented in Mathematica?

text: `Quantile[]` is the workhorse method in robust data analysis and statistics (see, eg Koenker's _Quantile Regression_ ). However, it should be complemented by an `InverseQuantile[]` method that ideally satisfies the equations `InverseQuantile[data,Quantile[data,q]]==q` (`0 <= q <= 1`) and `Quantile[data,InverseQuantile[data,v]]==v`, where either `MemberQ[data,v]==True` or perhaps `Min[data] <= v <= Max[data]`. The reason for the inverse is that in addition to computing median, interquartile ranges and so on, it's often necessary to test whether a data value is above or below median etc (eg, to color-scale in visualization) There are 2 immediate problems, invertibility and optional parameters and their interaction:   1. `Quantile` is not injective when considered as a function of `q` real number, eg `Quantile[{1, 2, 2, 4}, 1/3] == Quantile[{1, 2, 2, 4}, 2/3] == 2`. The obvious solution is to define `Quantile[]` and `InverseQuantile[]` to return an `Interval` value instead of a real; this interval is the solution of a constrained optimization problem since it should be the maximal interval consistent with the parameters.   2. Quantile is also partially defined by an optional 4-dimensional parameter space, whose default value is `{{0,0},{0,1}}` - corresponding to "inverse empirical CDF" method. 7 other specific parameter values listed in MMA8 docs are named methods, while other values presumably correspond to hybrid or interpolated methods. Comparing the behavior of `Quantile[]` on model data `{1,2,2,4}` versus `Table[RandomReal[], {100}]`, the choice of optional parameters seems to have a greater effect in the former, which represents data with tie values, eg:               ListPlot3D[#, Mesh -> None, InterpolationOrder -> 0,        Filling -> Bottom] &@Table[Table[        Quantile[Table[RandomReal[], {100}],         q, {{a = 1, b = 0}, {c, d = 0}}],       {q, 0, 1, 1/10}],      {c, 0, 1, 1/20}]      versus              ListPlot3D[#, Mesh -> None, InterpolationOrder -> 0,        Filling -> Bottom] &@Table[Table[        Quantile[{1, 2, 2, 4}, q, {{a = 0, b}, {c = 0, d = 1}}],       {q, 0, 1, 1/10}],      {b, -3, 3, 1/20}]      How can an `InverseQuantile` function be implemented to return an interval instead of a single number?


title: How to export to HTML and not lose Grid Frame in the generated HTML?

text: This is a known issue for me with Mathematica. When I export a notebook to HTML, Mathematica loses some decorations such as Grid Frame lines (in grid and like objects). For example, creating this small notebook:               Grid[{       {Text@Style["Wolfram pages"]},       {Hyperlink["http://www.wolfram.com"]},       {Hyperlink["http://demonstrations.wolfram.com"]}       }, Frame -> All      ]      Then I do SAVE AS and select HTML. When I look at the HTML, the frame is lost: ![enter image description here](http://i.stack.imgur.com/LUm1N.png) Here is a link to a post of mine at Math group asking on this in march of last year (link) I got one response, and I followed advice given in the response above, but nothing came out of it. I thought I ask again, may be some experts here would have a simple solution or a trick to this. I am thinking of using Mathematica notebook to save my URL's into instead of Microsoft word where I have them now, since I think I can organize them better with Grid and frames and such and it would look better, but if I can't get frames to show up, then there is no point of even trying. My other option would be to use Latex and generate HTML from Latex using Latex2html which I know pretty well. I find it strange that such a basic thing does not work, given that what this page says http://reference.wolfram.com/mathematica/guide/CreatingWebPages.html               Mathematica supports industrial-strength automatic creation of      full-featured web pages.       Well, if Grid frames and Dividers and items like these do not show up in the final exported HTML, then I do not think I would call it a full-featured web pages? Or Am I missing something here? I hope this is resolved in version 9, but I'd like to use Mathematica for this if it works. **note(1)** Thanks for all the responses. It seems editing the css will work ok for me now. It is not a big problem, since I keep the css commands in a small text file and just paste them each time I update my HTML. One nice thing about using Mathematica for this, is that now I can automate some things, like counters for html links and such, as the final grid is computed with whatever variables in it. Here is a small example, where the html link number is a simple counter. ![enter image description here](http://i.stack.imgur.com/R7PLR.png) I can now move all my saved URL's (have 100's of them) from word to the notebook and use this method. I need small help on something, could not figure how to do: Any one knows how to align all rows below the first row to the LEFT? I wanted to keep the top row centered and all the rows below LEFT aligned. Should I make a new question for this part since it is not related to my main question? I tried, but Grid alignment of separate entries has always been like black magic to me, I read the help many times, and can't decipher the description at all. thanks everyone for the help. **edit(2)** Please ignore my question above about `Grid` alignment. I gave up trying to figure how to use `Alignment` option to do this, and used the `Item` trick. This is much simpler. So each row I want to align in the center, I just use Item on it, and since Item has it own `Alignment` option, then I can use that instead. Here is how it works now. I like it now, and I think this will work well for me. I am a happy camper now. ![enter image description here](http://i.stack.imgur.com/q78an.png)


title: How can we implement "Sleep Sort"?

text: Inspired by Implement Sleep Sort: > Sleep Sort is an integer sorting algorithm I found on the Internet. It opens > an output stream, and for each input numbers in parallel, delay for the > number seconds and output that number. Because of the delays, the highest > number will be outputted last. I would like to know if it is possible to implement this in _Mathematica_. As a version 7 user I would of course like to see a solution that works there, but I think that `RunScheduledTask` may be needed to accomplish this.


title: Techniques To AutoReplace Browse

text: Let's say I have a function of the form.               Test[File_,text_]      What would be the most automated way and flexible way to generate an input cell of the form, ![enter image description here](http://i.stack.imgur.com/l3CUl.png) such that when you press the File Button and select `"C:\\\Users\\\path\\\testing.txt"` it autofill with the textual arguments. ![enter image description here](http://i.stack.imgur.com/nG6Mj.png) I'm quit interested to see what the Mathematica community thinks is the best technique for specifying which arguments should be File `Button`s and if it might be possible to incorporate the File buttons with Template Completion. My current code is below, which isn't generalized to all function definitions, but I knew it would be best to attempt to create a partially working solution. I used the following question to help piece a together my partially working example. * * *               MakeBoxes[replacementMarker[a_, tag_], StandardForm] ^:=        TagBox[MakeBoxes[a], tag];           replaceMark[rule_, nb_: EvaluationNotebook[], which_: All,         cell_: EvaluationCell] := (        SelectionMove[nb, which, cell];         NotebookWrite[EvaluationNotebook[],          NotebookRead[EvaluationNotebook[]] /. rule]        ) ;          CellPrint[      Cell[       BoxData[RowBox[{"Test", "[",             RowBox[{               ToBoxes@replacementMarker[              Button["Browse",               replaceMark[                file = SystemDialogInput["FileOpen"];                TagBox[_, "replaceThis"] :> "\"" <>                  StringReplace[file, "\\" -> "\\\\"]                  <> "\""                ]               ], "replaceThis"]            , ",",                TagBox[                 FrameBox["test"],                 "Placeholder"]}], "]"}]]       , "Output"]      ]


What are the Method options Solve command accepts? Solve has the Method option, however documentation contains no methods that it accepts...


title: How do I change the Font in BarChart Legend?

text: Just wondering if anyone knows the proper Syntax to change the Text properties in the BarChart's ChartLegend. I cannot seem to figure out how to get Style[] to apply. Here is an example:               BarChart[{1, 2, 3}, ChartStyle -> "Pastel",       ChartLegends -> Placed[{"John", "Mary", "Bob"}, Bottom]]          BarChart[{1, 2, 3}, ChartStyle -> "Pastel",       ChartLegends -> Placed[Style[{"John", "Mary", "Bob"},       FontFamily->"Courier"], Bottom]]      Any help would be greatly appreciated. t.


title: Saner alternative to ContourPlot fill

text: I am producing a large number of `ContourPlot` objects, which when exported generate notoriously large PDF files because it basically generates lots of little triangles (and on top of that, there are aliasing issues, which can be dealt with as in the linked post). So, I'm trying to find a way to deal with it in a robust manner. I compare this:               ContourPlot[Cos[x] + Cos[y], {x, 0, 4 Pi}, {y, 0, 4 Pi}, Contours -> Table[c, {c, -2.2, 2.2, 0.2}]]      which gives a 836 kilobytes PDF (here rendered with Mac OS Preview): ![enter image description here](http://i.stack.imgur.com/AVrFF.png) to some homemade code (most of it lifted from this answer):               graph[expr_, level_, color_] := Module[{g, lines},       g = RegionPlot[expr < level, {x, 0, 4 Pi}, {y, 0, 4 Pi},          PlotStyle -> None];       lines = Cases[Normal[g], _Line, Infinity];       Return[{         EdgeForm@Directive[Black, Thickness[Medium]],         FaceForm@Directive[Opacity[1], color],         FilledCurve[List /@ lines]         }];       ]          Graphics[Flatten[       Reverse[Table[         graph[Cos[x] + 1.1*Sin[y], c, Hue[(c + 2)/4]], {c, -2.2, 2.2, 0.2}]]]]      which produces a nice 45 kb PDF: ![enter image description here](http://i.stack.imgur.com/Qm748.png) * * * Now, what's the question? Well, I wonder how I can turn this core idea into a small routine that accepts options, well, just like `ContourPlot` would. I mean, generate axes, accept color options, etc. I don't have any idea where to start, because I'm not really knowledgeable about Mathematica…


title: Extracting values

text: I have imported a data from an excel sheet. I want to extract parts of the list based on some conditions. First I want to create one list whit the `The Coca-Cola` data and then I want another list with `McDonald` data. The key thing is that I want the extraction process to be able to spot when the data moves from one ticker to another.               AA = MatrixForm[DUBS]      > >     {{"Symbol", "Full Name", "Date", "Open", "High", "Low", "Close",   >        "Adj Close", "Volume", "Type"}, >        {"KO", "The Coca-Cola Company", {2013, 7, 19, 0, 0, 0.}, 40.88, 41.1, >          40.79, 41.09, 41.09, 1.14011*10^7, "Stock"},{ >        {"MCD", "McDonald", {2013, 7, 19, 0, 0, 0.}, 100.2, 100.41, 99.53, >          100.27, 100.27, 4.5083*10^6, "Stock"}, >        {"MCD", "McDonald", {2013, 7, 18, 0, 0, 0.}, 100.48, 100.77, 99.99, >          100.18, 100.18, 3.4016*10^6, "Stock"}, >        {"MCD", "McDonald", {2013, 7, 17, 0, 0, 0.}, 100.05, 100.35, 99.3, >          100.1, 100.1, 5.3774*10^6, "Stock"}} >


title: EdgeRenderingFunction on a Graph plot

text: This is my code, I want each line leaving a vertex to be the same colour from that vertex. So there should be 5 different coloured lines one colour for each vertex.               GraphPlot[{"Non-Drinker" -> "Non-Drinker",      "Non-Drinker" -> "Moderate", "Non-Drinker" -> "Harmful",      "Non-Drinker" -> "Deed", "Moderate" -> "Moderate",      "Moderate" -> "Hazardous", "Moderate" -> "Harmful",       "Moderate" -> "Deed", "Hazardous" -> "Non-Drinker",       "Hazardous" -> "Moderate", "Hazardous" -> "Hazardous",       "Hazardous" -> "Harmful", "Hazardous" -> "Deed",       "Harmful" -> "Non-Drinker", "Harmful" -> "Hazardous",       "Harmful" -> "Harmful", "Harmful" -> "Deed",       "Deed" -> "Non-Drinker"}, VertexLabeling -> True,       DirectedEdges -> {True, "ArrowheadsSize" -> 0.1},       MultiedgeStyle -> 0.1, PlotStyle -> {Black}, SelfLoopStyle -> 0.3,       EdgeRenderingFunction -> (If[First[#2] == Last[#2],          {Red, Arrow[#1, 0.05]}, {GrayLevel[0.1],Arrow[#1, 0.05]}] &)]      Thanks![This is what I have so far](http://i.stack.imgur.com/fk17p.jpg)


title: About evaluation in Block

text: I'm completely puzzled by the following codes:               Clear[func, f]     a = x^2 + z;     func[k_] := Block[{f}, (f[x_] := Evaluate[(a /. {z -> k})]; f[1])]     func[2]      > >     2+x^2 >   But I think it should be `3`, i.e., `2+1^2=3`. Actually for the following code:                f[x_] := Evaluate[(a /. {z -> k})]; f[1]      The output is 3. Can you explain the evaluation inside the `Block`? Taking Simon Woods' advice, for               func[k_] :=       Block[{f, tmp}, (tmp = Evaluate[a /. z -> k]; f[x_] = tmp; f[1])]          Trace[func[2]]      gives, > {func[2],Block[{f,tmp},tmp = Evaluate[a /. z -> 2],f[x_] = tmp; f[1]],...} But, for the codes               func[k_] := Block[{f}, (f[x_] = Evaluate[a /. z -> k]; f[1])]     Trace[func[2]]      gives, > {func[2],Block[{f},f[x$_] = Evaluate[a /. z -> 2];f[1],...} I notice that the arguments of `f` inside the `Block` are different in these two cases, and that is the reason. But why is the difference?


title: Pseudo-code for rules of probability?

text: I am having a hard time in Stats understanding some basic rules of probability and set-theory, namely $P(A|B)$, $P(A\ \textrm{and}\ B)$ and $P(A\ \textrm{or}\ B)$ where $A$ and $B$ depend on each other. I use _Mathematica_ all the time through my school, and I love to program in my free-time (sometimes writing small scripts for _Mathematica_ ). I can understand confusing subjects that deal with logic when they are in a programming language syntax, so I thought I could understand what's going on better if I had a written syntax to look at. Will anyone bother to help?


title: TransformedDistribution doesn't work

text: I'm trying to obtain a sum distribution of two discrete random variables. The function TransformedDistribution doesn't work for me in such case:               Z = EmpiricalDistribution[{0.7, 0.3} -> {0, 1}];     Y = EmpiricalDistribution[{0.6, 0.4} -> {0, 1}];          TransformedDistribution[z+y,{z \[Distributed] Z, y \[Distributed] Y}]      It gives an answer, which seems as a distribution of z+y, but when I ask to calculate a mean or CDF or PDF it gives no answer. TransformedDistribution works well for named distributions - geometric, poisson and etc. Thanks in advance.


title: How safe is Encode?

text: How safe is an encoded package (using locked, etc)? If I don't specify a personal key, I understand that the encoding key must be somewhere in the Mathematica program itself, and so it is not a perfect system, but:   * can we trust it for commercial deployment?   * has someone of you ever heard of it being found?   * do you know if there are backdoor to reverse the code, like shadowing the encode/decode system...? (don't want to know them, just checking how safe it is...) If I specify a key, I understand that it becomes a stronger system, but:   * how can the client use the app without me giving back the key (without him seeing the code -> I'm supplying the app, but with closed source)?   * is there a workaround for this personal key system?   * how do you typically do it, or see it done? I heard of MX files being used, but at first glance, they look very version/system specific, and so kind of difficult to manage when the client updates his Mathematica, or player. Nevertheless:   * are they safer than encode?   * can they be mixed up with encode to become safer? On other programming languages I use USB dongles:   * do you know how it could be done with Mathematica (my program is 100% coded on Mathematica language)?   * would I need to go through the new librarylink? I know that these are lots of questions, but I cannot find a lot of info on this theme.


title: How to make a parallel auto-generated .m package from Initialization cells?

text: according to the documentation at `ref/InitializationCell`, > When you first save a notebook that contains initialization cells, you have > the option to make a parallel auto-generated .m package that contains only > the contents of the initialization cells. The package is by default > automatically updated whenever the initialization cells in the notebook are > changed and saved again. This would be a REALLY NICE feature, because it would give me a beautiful way to document a package in a notebook (instead of just textual code)! To test it out, I took the documentation a bit literally and created a new notebook with a single initialization cell (with the little vertical-hook cell-bracket initialization-cell giveaway highlighted in yellow and circled in red in the screenshot, here: ![enter image description here](http://i.stack.imgur.com/m3DCh.png) The cell after the initialization cell is supposed to be just a reference to the initialization cell, and, when I evaluate the notebook, voila, there is the expected value. However, when I now save the notebook, I don't get the advertised "option to make a parallel auto-generated .m package." Ok, so I make one manually (Save As.../Save As Type.../Mathematica Package .m), no problem, as follows: ![enter image description here](http://i.stack.imgur.com/H12EV.png) But, of course, this one is not "automatically updated whenever the initialization cells in the notebook are changed and saved again." Here's the updated notebook: ![enter image description here](http://i.stack.imgur.com/CH6FQ.png) but the .m file is not automatically updated. I would use this feature daily if I could get it to work. As always, I'll be very grateful for advice, guidance, clues.


title: Variable length list with # and [[i]] as elements

text: I need to create a list that as an input receives the number $N$ of elements that it will contain and that returns:               {{_,_,#[[1]]},{_,_,#[[2]]},{_,_,#[[3]]},...{_,_,#[[N]]}}      I've tried using `Hold` and `Release` but haven't come up with a solution.


title: Finding length of intersection of two surfaces

text: I would like to know how we find the length of the intersection of two surfaces. For instance, in the following example,a surface intersects with a plane: ![Intersection of two surfaces](http://i.stack.imgur.com/E94iu.png) How do we find the length of intersection which is highlighted in the region? Is there a general method for computing the length in a given region for a surface and a plane? Here is the code for the above example:               h = Exp[-x^3 - y] - 1 - t ;     g = y - t ;          ContourPlot3D[{h == 0, g == 0}, {x, -4, 4}, {y, -4, 4}, {t, -4, 4},      MeshFunctions -> { Function [{x, y, t, f}, h - g]},      MeshStyle -> {{Thick, Blue}}, Mesh -> {{0}},      ContourStyle ->      Directive[Orange, Opacity[0.3], Specularity[White, 30]]]      It is the intersection of the function $e^{-x^3-y}-1=z$ and $y=z$


title: Getting over Mathematica Bar Chart Limitations….

text: I am trying to create a pareto chart for some non technical folks and having the hardest time formatting it correctly… Here’s my sample code:               (*Some dynamically generated data *)          mydata = {0.9436, 2.20725333345, 2.1402, 1.8729, 4.9436, 0.4819};     mylabels = {"l1", "l2", "l3", "l4", "some really long label", "another really long label", "l7"};          (*lets riffle and sort the data *)          a =  Sort[ Partition[Riffle[mylabels, mydata], 2], #1[[2]] > #2[[2]] & ];          BarChart[a , BarOrigin -> Left, BarSpacing -> -1, LabelingFunction -> (Placed[#, After] &), Axes -> None, Frame -> True, FrameTicks -> None, FrameLabel -> "Some Title", GridLines -> None, AspectRatio -> 0.3, ImageSize -> Full, ChartStyle -> "Pastel"]      A few questions:   * What is the best way to truncate to 2 digits in the labels, I tried using `NumberForm` in the Sort function but doesn’t work since Numberform is a wrapper.   * Labeling works reasonably well when labels are short but I seem to run into placement issues with long labels… Any ideas on better ways to handle this?   * Frame produced by Mathematica seems to overlap with the labels…  Any suggestions gladly appreciated!


title: Computing the minimum distance in a contour plot

text: I have the following Mathematica code               Clear["Global`*"];          V = -(M/Sqrt[b^2 + x^2 + λ*y^2 + (a + Sqrt[h^2 + z^2])^2]);     Vxx = D[V, {x, 2}];     Vyy = D[V, {y, 2}];     Vzz = D[V, {z, 2}];     ρ = 2.325/(4*π*100)*(Vxx + Vyy + Vzz);     ρyz = ρ /. {x -> 0};          M = 9500; a = 3; b = 4; h = 0.15; λ = 1.1;          Syz = ContourPlot[ρyz, {y, -50, 50}, {z, -50, 50}, Contours -> 20,      ContourStyle -> Black, PlotPoints -> 50,      RegionFunction -> Function[{y, z}, ρyz < 0],      PerformanceGoal :> "Speed", FrameLabel -> {"y", "z"},      RotateLabel -> False,      FrameStyle -> Directive[FontSize -> 17, FontFamily -> "Times"],      Epilog -> Inset[Graphics@Text[Row[{"b = ", b}],        BaseStyle -> {17, FontFamily -> "Helvetica", Bold}],      Scaled[{0.5, 0.95}]], ImageSize -> 550]      which produces this output ![enter image description here](http://i.stack.imgur.com/h2Xiq.jpg) This plot shows the contours $\rho(y,z) < 0$. Now I would like to compute the minimum distance at which these contours approach the center (0,0). The distance is defined as $d = \sqrt{y^2 + z^2}$. Inspecting by eye the plot, we see that in this case the minimum distance is approximately $d_{min} \simeq 16$. But of course, this is not sufficient at all. So, my question is how could I compute the minimum distance? Then, I assume it would be easy enough to add a DO loop in order to see the evolution of the minimum distance when a parameter (i.e $b$ or $\lambda$) varies. Many thanks in advance! **EDIT**               Clear["Global`*"];          V = -(M/Sqrt[b^2 + x^2 + λ*y^2 + (a + Sqrt[h^2 + z^2])^2]);     Vxx = D[V, {x, 2}];     Vyy = D[V, {y, 2}];     Vzz = D[V, {z, 2}];     ρ = 2.325/(4*π*100)*(Vxx + Vyy + Vzz);     ρyz = ρ /. {x -> 0};          M = 9500; a = 3; h = 0.15; λ = 1.1;          data = {};     Do[        sol = FindMinimum[{y^2 + z^2, ρyz == 0}, {y, z}];        dmin = sol[[1]];        AppendTo[data, {b, Sqrt[dmin]}],      {b, 0, 12, 1}      ]


title: Syntax Highlighting for Mathematica on a Blog

text: Every once in a while I want to paste Mathematica code on my blog. When I do, I would like it to be somewhat readable, and it would be nice to have syntax highlighting. So far all my searches have turned up with nothing. There are plenty of ways to colorize pretty much every language known to man, except perhaps Mathematica code. See this site, for example. The closest I've gotten to that is using :TOhtml in vim, which is pretty awesome, but gives me a whole HTML file, with and everything, and I'm not savvy enough to figure out exactly how to use it without destroying the rest of my post.


title: How to draw a 2D curve as epilog on a 3D surface plot?

text: I'd like to draw               Plot[Re@Sin[x+I*2], {x, -10, 10}]      as an epilog on               Plot3D[Re@Sin[x + I*y], {x, -10, 10}, {y, -10, 10}]      and position it at `y=2`. What's intuitive to me doesn't work:               epilogData = Table[{x, 2, Re@Sin[x + 2*I]}, {x, -10, 10, 0.1}];          Plot3D[Re@Sin[x + I*y], {x, -10, 10}, {y, -10, 10},       Epilog -> {Red, PointSize[Large], Point[epilogData]}]      Using               epilogData2D = Table[{x, Re@Sin[x + 2*I]}, {x, -10, 10, 0.1}];      will draws something, but not what i want (What's that anyway?). I've also played with `Inset` and got no luck so far.


title: Searching a string that may contain Null

text: I have an array of triplets that can be approximated by the following code:               data = Table[{RandomInteger[5], RandomInteger[10], RandomChoice[{"ABC", "BCD", "DEF"}]}, {10}]      The first two elements of the triplet are data and the third element is a set of single-character flags. Let's say that the flag "D" means "don't use" so I want to delete any cases containing a "D" flag. Easy enough:               DeleteCases[data, x_ /; StringCases[x[[3]], "D"] == {"D"}]      The problem comes in for a case where a triplet contains no flags. In this case, the third element is `Null`:               data = Table[{RandomInteger[5], RandomInteger[10], RandomChoice[{"ABC", "BCD", "DEF", Null}]}, {10}]     DeleteCases[data, x_ /; StringCases[x[[3]], "D"] == {"D"}]      The `StringCases` function throws an error whenever it attempts to compare `Null` to "D". I would like to avoid this error message without using something like `Quiet` just in case there are other errors that shouldn't be hidden. So the question is: how does one formulate a substring search that returns `False` instead of throwing an error if the variable passed does not have a `Head` of `String`?


title: Find minimum function value in data and give coordinates of minimum

text: I create with `Table` an array containing the function value of some function and the `n1`and `n2`arguments. Afterwards i want to look for the minimum function value within this array and find the corresponding arguments. And since i need that information for about 30 different functions that differ only slightly (in one parameter) from eachother, i want to create a code, that creates a list of functions and thus a list of minima and corresponding coordinates. I've written a code for that, but it's unbelievable slow. Maybe you guys know faster and more elegant ways to solve that problem. `Sin[n1]Sin[n2]`is of course only an examplary function, my actual function has only one global minimum. There is a condition to the code. I can't use FindMinimum or something similar on my function (don't want to get into that here), it needs to be a list of data points and one looks for a minimum value inside that list.               functiontable =        Table[{n1, n2, Sin[n1]Sin[n2]}, {i, 1, 5}];          temptabletable =        Table[Table[functiontable[[i]], {n1, 0, 5, 1}, {n2, 0, 5, 1}], {i,          1, 5}];          temppositiontable =        ux = Table[         Position[temptabletable[[i]], Min[temptabletable[[i]]]], {i, 1,           5}];          temppositiontablen1 =        Table[Take[Flatten[temppositiontable[[i]]], 1], {i, 1, 5}];          temppositiontablen2 =        Table[Take[Flatten[temppositiontable[[i]]], {2, 2}], {i, 1, 5}];          selectmatrixentrytable =        Table[{temppositiontablen1[[i]], temppositiontablen2[[i]]}, {i, 1,          5}];          minimumkoordinatentable =       Table[Flatten[{Take[Flatten[selectmatrixentrytable[[i]]], 1],          Take[Flatten[selectmatrixentrytable[[i]]], {2, 2}]}], {i, 1, 5}]          Min /@ temptabletable


title: Match sequence of zero or more characters except a given character

text: This looks like it should be simple: I want to match an "i" followed by an "o" with an arbitrary (possibly zero-length) sequence of characters in between, unless that sequence also contains an "i". Without this constraint it's easy: `___~~"i"~~___~~"o"~~___`. This will match "histology", but it will also match "adventitious". I've tried using a conditional or a predicate test in the pattern but I can't get the syntax right.


title: How can I export a html source string as a html file?

text: A little question. Consider one html source string,               Export["test.html", htmlsource]      Then I get one html file with a whole image of the source.               Export["test1.txt", fileToExoprt]     CopyFile["test1.txt","test1.html"]      Then I get the result html file. Is there a direct way?


title: NestList on a function of several arguments

text: I'd like to know if it is possible to use `NestList` on a regular function of several arguments, such as:               fc[x_, y_] := {x + y, x - y};     res = NestList[ fc[x,y], {100, 75}, 50]      I just started learning _Mathematica_ at my university, read about pure functions, but from the homework's text it doesn't look like I should use that. Roughly translated, it would be " _Define a function of 2 arguments (...) and apply`NestList` on this function._"


title: automatically add Global` to $ContextPath for all notebooks when using CellContext->Notebook

text: I have some definitions in my `init.m`. E.g. my `init.m` contains this:               hex[n_]:=BaseForm[n,16];      I know that Mathematica puts this in the `Global`` context, and in a default configuration, each notebook's `$Context` is `Global`` and its `$ContextPath` also contains `Global``. So my definitions are automatically available in any notebook I create. However, I prefer the `CellContext->Notebook` option so each of my notebooks automatically gets its own private context. The problem is that this option (obviously) changes `$Context` to something other than `Global``, and it also removes `Global`` from `$ContextPath`. So my `init.m` definitions are not automatically available in any notebook I create. Now, I could type `Global`hex` when I want to use my `hex` function, or I could do `AppendTo[$ContextPath, "Global`"]` in each notebook. But I would rather have `Global`` added to each notebook's `$ContextPath` automatically. Is there a way to get `Global`` into each notebook's `$ContextPath` automatically? Or is there some other way I can make my personal definitions available to each notebook automatically while using the `CellContext->Notebook` option?


title: removing elements that are contained in other elements

text: For example, I have a list of lists:               l = {{a,b,c},{a,b,d},{d,e},{d},{a},{a,b},{f}};      And I want to remove all the lists that are contained in other lists:               lafter = {{a,b,c},{a,b,d},{d,e},{f}};      What is the most efficient way of doing this? I know I could look at all the different sub lists, compare them to every other sublist and then select the ones that I want... but that seems inelegant. Is there a "right way" to do this in Mathematica? What is this called?


title: LinearProgramming and Maximize giving different results

text: I'trying to do an embarrassingly simple linear programming problem, and being a total Mathematica and maths analphabet I'm stuck. The problem is to optimize (maximize) the function $1.2x+y$, with constraints: $$ 10x+12y\leq1920 \\ 5x+3y\leq780 \\ x,y\geq0 $$ Doing it by hand, or like this:               Maximize[{1.2 x + y, 10 x + 12 y <= 1920 && 5 x + 3 y <= 780 && x >= 0 && y >= 0}, {x, y}]      I get the correct answer of $x=120,y=60$. But when I try to calculate it using `LinearProgramming`, like this:               LinearProgramming[      {1.2, 1},      {{10, 12}, {5, 3}},      {{1920, -1}, {780, -1}},      {{0, Infinity}, {0, Infinity}}]      I get $x=0,y=0$ as an answer. I've been staring at the `LinearProgramming` documentation for an hour and can't find the error. If I switch from `{{1920, -1}, {780, -1}}` to `{{1920, 1}, {780, 1}}` it gives the correct answer, but according to the docs it's then testing for $\geq$, and not for $\leq$, as my problem states. Any idea what am I doing wrong here? Thanks...


title: Dynamically Update Inset within Graphics with RunScheduledTask

text: I followed the instructions given below to play with `RunScheduledTask` within `DynamicModule`. ScheduledTask with scoped variables. Working with timed evaluation Everything works great until it comes to the Inset, which does not update with the local variable. Any hints are welcome.                RemoveScheduledTask[ScheduledTasks[]];      d=DynamicModule[{x=0,y=0},      {         Dynamic[x,TrackedSymbols:>{x}],         Framed@Graphics[{             Dynamic[Point[{2+#,2+#}]&@x,TrackedSymbols:>{x}],             Dynamic[                 Inset[                 Framed@Graphics[                     Point[{#+3,#+3}]&@x,                     PlotRange->{{1,5},{0,8}}                 ]             ],              TrackedSymbols->{x}             ]         },             PlotRange->{{0,6},{-1,9}}         ]      },      Initialization:>(RunScheduledTask[x++,{.5,3}];)      ]      Follow up: rasher is correct, wrap the inset point in `Dynamic` works. Thx so much!                RemoveScheduledTask[ScheduledTasks[]];        d=DynamicModule[{x=0,y=0},        {        Dynamic[x,TrackedSymbols:>{x}],        Framed@Graphics[{         Dynamic[Point[{2+#,2+#}]&@x,TrackedSymbols:>{x}],               Inset[             Framed@Graphics[                  Dynamic[Point[{#+3,#+3}]&@x,TrackedSymbols:>{x}],                 PlotRange->{{1,5},{0,8}}             ]         ]     },         PlotRange->{{0,6},{-1,9}}     ]     },      Initialization:>(RunScheduledTask[x++,{.5,3}];)     ]


title: How to deduce a generator formula for a polynomial sequence?

text: Consider a polynomial sequence $\{p_n\}$ generated by some (simple) rule: $$ \begin{array}{l} p_1(x)=x \\ p_2(x)=2 x-x^2 \\ p_3(x)= x^3-3 x^2+3 x \\ p_4(x)=-x^4+4 x^3-6 x^2+4 x \\ p_5(x)= x^5-5 x^4+10 x^3-10 x^2+5 x \\ p_6(x)= -x^6+6 x^5-15 x^4+20 x^3-15 x^2+6 x \\ p_7(x)= x^7-7 x^6+21 x^5-35 x^4+35 x^3-21 x^2+7 x \\ p_8(x)= -x^8+8 x^7-28 x^6+56 x^5-70 x^4+56 x^3-28 x^2+8 x \\ p_9(x)= x^9-9 x^8+36 x^7-84 x^6+126 x^5-126 x^4+84 x^3-36 x^2+9 x \\ p_{10}(x)= -x^{10}+10 x^9-45 x^8+120 x^7-210 x^6+252 x^5-210 x^4+120 x^3-45 x^2+10 x \\ \end{array} $$ Suppose we have only the above list of ten polynomials in expanded form. Is it possible to make Mathematica derive a formula that generates $p_n$ (I mean to get $p_n=1-(1-x)^n$ in this particular case)? Note that something like ` FullSimplify[Expand[1 - (1 - x)^5]] ` does not give the desired result, so at least it would be nice to see how to get `1 - (1 - x)^5` from here...


title: Define inverse for the custom operator

text: I want to define simple matrix algebra (inspired by the following posts: Block Matrix Algebra with Mathematica ; How to define custom operators ). I assume the funtion `MatrixMult[A_,B_]` to be the matrix product. I surely can define some properties of this function, like linearity, associativity etc. (see referenced posts). Now I want to solve simple matrix equation               Solve[MatrixMult[A, X]==B,X]      Obviously, the answer is               {{X -> InverseFunction[MatrixMult, 2, 2][A, B]}}      Now the question is how can I explicitly define that the inverse of my function is the following:               InverseFunction[MatrixMult, 2, 2][A_, B_] := MatrixMult[Inverse[A], B]      (the last line results in _"Tag InverseFunction is Protected"_ error)


title: GatherBy and two conditions

text: I have a list of 4 dim points, given by `list={{0, 1/100, 6, 1/3}, {0, 1/100, 5, 1/3}, {0, 1/100, 6, 2/3}, {0, 1/ 100, 5, 2/3}, {0, 1/100, 6, 1}, {0, 1/100, 5, 1}, {1/2, 0.0132789, 6, 1/3}, {1/2, 0.00603171, 8, 1/3}, {1/2, 0.0133361, 6, 2/3}, {1/2, 0.0059745, 8, 2/3}, {1/2, 0.0133552, 6, 1}, {1/2, 0.00595543, 8, 1}, {1, 0.0148608, 6, 1/3}, {1, 0.00444984, 8, 1/3}, {1, 0.0149013, 6, 2/3}, {1, 0.00440938, 8, 2/3}, {1, 0.0149147, 6, 1}, {1, 0.0043959, 8, 1}, {3/2, 0.0160638, 6, 1/3}, {3/2, 0.0032469, 8, 1/ 3}, {3/2, 0.0160968, 6, 2/3}, {3/2, 0.00321387, 8, 2/3}, {3/2, 0.0161078, 6, 1}, {3/2, 0.00320286, 8, 1}}` I would like to gather the elements of the list using two conditions and then create a ListPlot of them. So the first two elements of each point should be the x y coordinates and the last two should be the conditions. The first condition should check if the thrid element is equal 6 and the second codition should group elements for 1/3, 2/3 and 1. I tried               GatherBy[list, {#[[3]] == 6, Last} &][[All, All, {1, 2}]]      but it takes into account only the first condition, giving me 2 lists of points. I wanted to have 6 lists of points in this example. Any ideas?


title: For loop in Mathematica

text: I have set of statements               sol[ξ_] := NDSolve[{D[f[η], {η, 3}] + f[η] f''[η] + β (1 - (f'[η])^2) == 0,         f[0] == 0, f'[0] == 0, f''[0] == ξ}, {f[η]}, {η, 0, 5}]          β = 0;          DFEnd[ξ_?NumericQ] := D[f[η] /. sol[ξ], {η, 1}] /. η -> 5          SOL1 = FindRoot[DFEnd[ξ] == 1, {ξ, 0.5}]          plt1 = Plot[Evaluate[D[f[η] /. sol[ξ /. SOL1], {η, 1}]], {η, 0, 5},        PlotStyle -> {Red, Thick}, PlotRange -> All];      This is working fine, but what I want is to have a For loop in which my Beta starts from lets say 0 and i increase it to 0.25 everytime till 1 and block of code is executed. Then I can use Show[plt[1],plt[2],plt[3]...] command to add up every graph. is this can be done?


title: How can I convert this ListPlot to ArrayPlot?

text: I want to rewrite this code with `ArrayPlot`,               n = 10;     eqs = x^Range[0, n - 1].# & /@ Tuples[{-1, 1}, n];     g = ListPlot[{Re@#, Im@#} & /@ Flatten[x /. NSolve /@ eqs]]      ![enter image description here](http://i.stack.imgur.com/z9rlz.png) just like               ListPlot[Reap[        Do[If[x^2 + y^2 < 500, Sow@{x, y}],            {x, -100, 100}, {y, -100, 100}]][[2, 1]], AspectRatio -> 1]      can be written               ArrayPlot[      Table[If[x^2 + y^2 < 500, 1, 0], {x, -100, 100}, {y, -100, 100}]]      How can I do this?


title: Vertex Labeling Problem in a Graph

text: I am using following codes to create a graph.                cities = CityData[{All, #}] & /@ {"Germany"}; bigcities =       Select[Select[Join @@ cities, FreeQ[#, ""] &],       CityData[#, "Population"] > 100000 &];      cityCoords =       Select[CityData[#, "Coordinates"] & /@ bigcities, FreeQ[#, ""] &];      Needs["ComputationalGeometry`"];      pts = Reverse[cityCoords, 2];      dt = DelaunayTriangulation[pts];      toPairs[{m_, ns_List}] := Map[{m, #} &, ns];      edges = Union[Sort /@ Flatten[toPairs /@ dt, 1]];      Graph[edges, ImagePadding -> 20, GraphLayout -> "PlanarEmbedding",       VertexCoordinates -> pts, VertexStyle -> LightBlue,       VertexLabels -> bigcities[[All, 1]],       Prolog -> {LightBrown, EdgeForm[{Thick, Black}],       CountryData["Germany", "FullPolygon"]}, ImageSize -> 800]      But the problem is it doesn't change the labeling of vertexes into the name of cities.How can I solve it?


title: Determining End of Notebook with Mathematica 9

text: The application package I had working in Mathematica 8 no longer works in Mathematica 9. I believe the problem lies in how I cycle through cells and test for reaching the last cell of the notebook. In `MyTools\MySubTools1`, I previously used:               SelectionMove[nb, Next, Cell];       While[(*Keep moving cell by cell until the end of the notebook*)        MathLink`CallFrontEnd[FrontEnd`CellInformation[FrontEnd`NotebookSelection[nb]]]=!=$Failed,        (*Code*)         SelectionMove[nb, Next, Cell]}];      but have since changed the code to:               SelectionMove[nb, Next, Cell];       While[(*Keep moving cell by cell until the end of the notebook*)        Developer`CellInformation[nb] =!= $Failed,        (*Code*)         SelectionMove[nb, Next, Cell]}];      To my package I have added:               BeginPackage["MyTools`", {"Developer`", "MyTools`MySubTools1`", "MyTools`MySubTools2`"}]      The updated code now works as required when debugging in Eclipse but not when running in Mathematica. What is the best way to check whether I have reached the end of the notebook?


title: NDSolve error---equations expected

text: I keep getting an error trying to used `NDSolve` for three coupled equations. It works in another programming language, but I am having trouble apparently writing it correctly in _Mathematica_. The error message says that equations are expected. I really don't understand why this is written incorrectly.               Nn = 100;     R = 50;          Cc = .00008;     K = 0.5;     VP = 1.4;     VS = 0.33;     VMAX = 1.0;     a = 20;          TW = 40.0;     TP = 200.0;     DT = 1.0;     TS = 5.0;     TU = 10.0;     k1 = 1.0;     k2 = 10.0;     k3 = 1.0;     P1 = 0.001;     P3 = 0.001;     nw = a*x[t]/(1.0 - x[t]);     np = a*(1.0 - x[t])/x[t]*(VS/VMAX);     M = 50;          s =        NDSolve[{           x'[t] == y[t]/(TW + (a*x[t]/(1.0 - x[t]))*DT) - z[t]/(TP + TU +              np*DT)*VP/VMAX - Cc*x[t]*(Nn/M),            y'[t] == P1*(1.0 - x[t]) -              y[t]*(1.0 - k1*E (((nw/k2)^k3)))/(TW + nw*DT),            z'[t] == P3*x[t] -              z[t]*(1.0 - k1*E ((((a*(1.0 - x[t])/x[t]*(VS/VMAX))/k2)^k3)))/(TP + TU + np*DT),            x[0] == y[0] == z[0] == .1},          {x[t], y[t], z[t]}, {t, 10}];


title: Function as an option to a function

text: I am new to mathematica ,so this question may seem a little naive. I know how to use the option as an argument to a function, we can define an option by using `Options[]`and `SetOptions[]`, but the following usage confused me by passing a function as an option to a function .Here are two examples: Example1:               GraphPlot3D[{2 -> 3, 2 -> 4, 2 -> 5, 3 -> 4, 3 -> 5, 4 -> 5},       VertexRenderingFunction -> (Sphere[#, 0.1] &)]      Example2:               Graph[{1 \[UndirectedEdge] 2, 2 \[UndirectedEdge] 3,        3 \[UndirectedEdge] 1}, VertexShapeFunction -> "Square",       VertexSize -> 0.2]      My question is:   1. What is the difference between `VertexRenderingFunction -> (Sphere[#, 0.1] &)`,`VertexShapeFunction -> "Diamond"` and `VertexSize -> 0.2` as examples display.   2. The function as an option seems to be useful, so what is the right time to use it? How to apply it to the functions defined by myself?


title: Reproducing a graphic on Jensen's inequality for the probabilistic case

text: I am trying to reproduce the following graph on Jensen's inequality for the probabilistic case (source: wikipedia) but with   * the exponential function as Y,   * the normal distribution on the X-axis and therefore    * the log-normal distribution on the Y-axis coming out or the transformation. ![enter image description here](http://i.stack.imgur.com/ADQ42.png) I am not really a well versed user of Mathematica and here I don't have any idea whatsoever how to achieve the task. Thank you for your help. **EDIT** : To be more specific: I know how to plot the original distribution. What I don't know is how to turn the resulting distribution around by 90° in the same diagram.


title: Replacing a combination of terms

text: I have a quite simple question. I have an expression that looks similar to $T=\frac{1}{a_1}-\frac{1}{a_2}+1$ and I'd like Mathematica to use $A=\frac{a_1}{a_2}$ to reformat the expression (if possible) such that only $A$ appears in it. Any idea? Cheers, Pascal


title: Counting a cardinality of a subset satisfying special property

text: Suppose that we have a set of 9 2-dimensional vectors $c$ by               m=3;     n=2;     c=Tuples[Range[m],n];      We want to define a subset $S$ of vectors in $c$ by the following: $S=\{ (x,y)\in c~|~ x^2+2y^2=5\}$ Also, I want to count the cardinality of $S$. How can I do this?


title: Plot[] breaks behavior of custom data handling function - Recursion

text: I am working on a utility to analyze a set of data. I want to process the data with a sliding window, in such a way that there is an output associated with each sample of data. To start, I have a list of data: `MyData` I've defined the following utility function to pull 10 consecutive samples of data from `MyData` starting at an arbitrary location within `MyData`.               EvalWin[x_] := Take[MyData, {x, x + 9}];      This works. Now lets say I have a processing function that sums the 10 samples.               ProcData[x_] := Total[EvalWin[x]];      This also works. The problem comes if I attempt to use `ProcData[]` as an argument to a built in Mathematica function such as `Plot`. For example if I attempt to plot `ProcData[]` for a set of 100 samples...               Plot[ProcData[x], {x, 10, 110}]      The `Plot` function blows up due to recursion. Are there ways to control how built in functions handle data to avoid recursive blow up, or is there a more Mathematica friendly way to accomplish this kind of data manipulation?


title: 3x+1 on arithmetic chains, tree pruning and NestList

text: Given the following function `Collatz`:               Collatz[Subscript[m_, d_] /;  EvenQ[m] && EvenQ[d]] := Subscript[m/2, d/2]     Collatz[Subscript[m_, d_] /;  OddQ[m] && EvenQ[d]] := Subscript[3 m + 1, 3 d]     Collatz[Subscript[m_, d_] /;  OddQ[d]] :=          Collatz /@ {Subscript[m, 2 d], Subscript[m + d, 2 d]}      The immediate question that crops up, once `Collatz` is made `Listable` to handle the branching - is to manage the trajectories. This includes identifying and filtering cycles (ie, periodic orbits) from the transition graph. The first 5 iterates given the initial state `Subscript[1,1]` (the chain of natural numbers 1,2,3...) is:               Column@ NestList[Collatz,Subscript[1, 1],5]          (* Out[1]= Subscript[1, 1]     {Subscript[1, 2],Subscript[2, 2]}     {Subscript[4, 6],Subscript[1, 1]}     {Subscript[2, 3],{Subscript[1, 2],Subscript[2, 2]}}     {{Subscript[2, 6],Subscript[5, 6]},{Subscript[4, 6],Subscript[1, 1]}}     {{Subscript[1, 3],Subscript[16, 18]},{Subscript[2, 3],{Subscript[1, 2],Subscript[2, 2]}}} *)      Any suggestions for functional approaches to filter out cycles, in other words, states that are repeated in the output of `NestList` but are not observable at the level of a single call to `Collatz`? In the above simulation, `Subscript[1,1]` should be filtered out after the 2nd iteration. Recall, vertices of the transition graph are the chains `Subscript[n,d]` while the arcs link inputs of `Collatz` with its output chain(s).


title: 3d graphic for publication

text: Journals are very strict and some of them require special formats. They suggest the .tiff or .jpg format for graphics with many colors. I have problem how to export, for example, this figure consists of 4 smaller but to have optimized quality (Labels to be with correct size of fonts, viewable) and not with large file size.               plot1 = Plot3D[Sin[4 x]*Cos[4 y], {x, -2, 2}, {y, -2, 2},      PlotLabel -> "number 1, gamma, s=1,q=2", AxesLabel -> {x, y},      ColorFunction -> "NeonColors"];          plot2 = Plot3D[Sin[3 x]*Cos[4 y], {x, -2, 2}, {y, -2, 2},      PlotLabel -> "number 1, gamma, s=2,q=2", AxesLabel -> {x, y},      ColorFunction -> "NeonColors"];          plot3 = Plot3D[Sin[2 x]*Cos[4 y], {x, -2, 2}, {y, -2, 2},      PlotLabel -> "number 1, gamma, s=3,q=2", AxesLabel -> {x, y},      ColorFunction -> "NeonColors"];          plot4 = Plot3D[Sin[1 x]*Cos[4 y], {x, -2, 2}, {y, -2, 2},      PlotLabel -> "number 1, gamma, s=4,q=2", AxesLabel -> {x, y},      ColorFunction -> "NeonColors"];          GraphicsGrid[{{plot1, plot2}, {plot3, plot4}}, Frame -> True]


title: Using ListPlot and Joined, how to keep markers in colour but make all joining lines gray?

text: I want to create a `ListPlot` with three sets of data, where the data in each set are joined by a line. This is an example:               ListPlot[{{1, 2, 3, 5, 8}, {2, 3, 6, 9, 10}, {4, 5, 7, 10, 12}},       PlotMarkers -> {Automatic}, Joined -> {True}]      **Question:** How do I keep a unique marker and colour for each of the sets but specify that the joining lines be a single color (gray)?


title: NDSolve solution methods issue

text: I´m modelling a biological reaction thorugh a set of differential equations.               Modelo = NDSolve[{{dX[t]/dt == muapp*X[t] - 0.005*X[t], X[0] == Xo2},     {dSg[t]/dt == -Qs + 0.005*(100 - Sg[t]), Sg[0] == Sgo2},     {dAce[t]/dt == Qace - 0.005*Ace[t], Ace[0] == Aceo2},     {dBut[t]/dt == Qbut - 0.005*But[t], But[0] == Buto2},     {dAct[t]/dt == Qact - 0.005*Act[t], Act[0] == Acto2},     {dEt[t]/dt == Qet - 0.005*Et[t], Et[0] == Eto2},     {dSb[t]/dt == Qsb + 0.005*(2 - Sb[t]), Sb[0] == Sbo2}}, {X, Sg, Ace, But, Act, Et, Sb}, {t, 0, 400}, Method ->DOPRI];      Using NDSolve the system is solve with no problems. however, since this is a biological reaction, none of the solutions must be >0. I have already adjusted the parameters so that this condition is met and it works fine in matlab and modelmaker, but when solving it with mathematica X goes >0 between 200 < t< 400. In matlab I use ode15s, because is stiff at some points, but it works just as well with ode45 and ode23s, so i sat NDsolve parameters to those that mathematica tutorials say to be the same as ode45 in matlab:               DOPRIamat = {{1/5}, {3/40,9/40}, {44/45,-56/15,32/9}, {19372/6561,-25360/2187,64448/6561,-212/729}, {9017/3168,-355/33,46732/5247,49/176,-5103/18656}, {35/384,0,500/1113,125/192,-2187/6784,11/84}};     DOPRIbvec = {35/384, 0, 500/1113, 125/192,-2187/6784, 11/84, 0};     DOPRIcvec = {1/5, 3/10, 4/5, 8/9, 1, 1};     DOPRIevec = {71/57600, 0, -71/16695, 71/1920, -17253/339200, 22/525, -1/40};     DOPRICoefficients[5, p_] := N[{DOPRIamat, DOPRIbvec, DOPRIcvec, DOPRIevec}, p];     DOPRI = {"ExplicitRungeKutta", "DifferenceOrder" -> 5, "Coefficients" -> DOPRICoefficients, "StiffnessTest" -> False};      But still i get x<0. Is it possible to modifie NDSolve to work as ode15s in matlab? or can it at least be modified to keep it from giving negative values? thanks for your help, i leave down the script i use in mathematica. Mathematica               Xo2 = 1.0605;     Sgo2 = 43.9316;     Sbo2 = 3.5023;     Aceo2 = 0.3437;     Buto2 = 2.5299;     Acto2 = 1.0589;     Eto2 = 0.2334;     ksg = 154.060527452649;     kibut = 7.00180294979766;     ksgb = 13.6974233244128;     ksb = 1.10465168560025;     ksgact = 36.1766330476263;     ksget = 2.48715131190954;     ksgsb = 0.500075731973805;     ksba = 0.398637629396357;     kaa = 13.8244477511478;     kd = 0.00478170792619247;     m = 1.04817713477516;     maxx = 0.213696652849562;     maxbut = 0.150892601110339;     maxact = 0.778875361557128;     maxet = 0.0329313766102578;     maxsb = 0.131139790008708;     maxace = 0.142882096617404;     Ybutx = 1.22938023298761;     Yactx = 0.129135371286816;     Yetx = 0.0759697564493146;     Ysbx = 1.01875350101917;     Yacex = 2.10990339926643;     Yxsg = 0.284627874526466;     Ybutsg = 0.819985406580864;     Yactsg = 0.851780607333819;     Yetsg = 0.598346992105451;     Ysbsg = 0.995215479964112;     Yaceact = 0.973079461528239;     Ybutsb = 0.839985001333182;     Yacesb = 0.525389668809545;     mux = maxx*(Sg[t]/(ksg + Sg[t]))*(1 - (But[t]/kibut)^m);     muapp = mux - kd;     mubut = maxbut*(Sg[t]/(ksgb + Sg[t]))*(Sb[t]/(ksb + Sb[t]));     muact = maxact*(Sg[t]/(ksgact + Sg[t]));     muet = maxet*(Sg[t]/(ksget + Sg[t]));     musb = maxsb*(Sg[t]/(ksgsb + Sg[t]));     muace = maxace*(Sb[t]/(ksba + Sb[t]))*(Act[t]/(kaa + Act[t]));     Qs = X[t]*((mux/Yxsg) + ((mubut*Ybutx)/Ybutsg) + ((muact*Yactx)/Yactsg) + ((muet*Yetx)/Yetsg) + ((musb*Ysbx)/Ysbsg));     Qace = muace*X[t]*Yacex;     Qbut = mubut*X[t]*Ybutx;     Qet = muet*X[t]*Yetx;     Qact = X[t]*(muact*Yactx - ((muace*Yacex)/Yaceact));     Qsb = X[t]*(musb*Ysbx - ((mubut*Ybutx)/Ybutsb) - ((muace*Yacex)/Yacesb));


title: NIntegrate Warning / Error Messages

text: I am doing:                 NIntegrate[Sin[Exp[(x^4)]], {x, 2, Infinity}, PrecisionGoal -> 12]      It prints out a host of warnings, but also shows the results as: $$-0.0113737$$ This is a highly oscillatory integral and weirdness happens to the numerical routines as they are doing their thing. For example:   * integration with LevinRule failed.   * converging too slowly; suspect one of the following: singularity, value of the integration is 0, highly oscillatory integrand, or WorkingPrecision too small   * "NIntegrate failed to converge to prescribed accuracy after 9 recursive bisections in x near {x} = {4.531228269745986`}"   * ... You can see a plot as:                Plot[Sin[Exp[(x^4)]], {x, 2, 5}]      As an aside, the same input (exactly) using WA, produces: $$-0.00644455$$ Are those warnings/errors telling me not to trust the result as it is suspect?


title: Simplifying complex expression with Mathematica

text: I want do get the imaginary part of               Exp[I*t]/(1-Exp[I*t])      I've tried to do this               Im[ComplexExpand[Exp[I*t]/(1-Exp[I*t])]]       but the result still contains               Im[Cos[t]/((1 - Cos[t])^2 + Sin[t]^2) -         Cos[t]^2/((1 - Cos[t])^2 + Sin[t]^2) -         Sin[t]^2/((1 - Cos[t])^2 + Sin[t]^2)]       which in fact is 0 (t is a real variable). How can I convince _Mathematica_ to get rid of this part of the expression?


title: Behaviour of out (%%...%) with comments

text: Can please someone explain to me the diffrent behavior of this code               (6 - 3);     (5 - 3);     (4 - 3);     {%%%, %%, %}          Out= {3, 2, 1}      and this one               a;     b;     c;     (6 - 3);(*comment*)     (5 - 3);(*comment*)     (4 - 3);(*comment*)     {%%%, %%, %}          Out= {a, b, c}      ? I thought it should be the same. Do the comments block the outputs to be used with %? EDIT: I found a working case ... even if one adds spaces between the comments.               a;     b;     c;     (6 - 3);     (* comment *)     (5 - 3);     (* comment *)     (4 - 3);     (* comment *)     {%%%, %%, %}          Out= {3, 2, 1}


title: Modifying elements of a matrix after construction

text: Suppose I have constructed a matrix with all elements as a constant (say 1):               N=4;     A=ConstantArray[1, {N, N}];      Now I want to make A(2,3)=23 and A(4,3)=43. Can I modify such elements once the matrix is constructed? Thank you.