Shaving the last 50 ms off NMinimize

**The epilogue:** A paper where the below answer is used was published. The answer below is cited among the references:) **The background:** I have to fit an objective function for ~10 000 datasets in near real time (with near real time being on the order of about 10 seconds). I compile the huge objective function, so that it takes about 30 microseconds to execute. I'm using the Nelder-Mead method, which on average converges in about 300 steps. This means that one minimization should take about 9 miliseconds (300*30 microseconds). And the whole fitting could be done in about 10 seconds on eight cores (300*10000*0.00003/8). **The problem:** No matter how quickly the objective function can be calculated, `NMinimize[]` always takes at least 50 ms. This means the fitting takes about 4 minutes on my eight cores. **The question: Can I somehow get rid of this 50ms delay that`NMinimize[]` has?** Otherwise I will have to rewrite my program in C (or Delphi which I like much better). But I'm still not looking forward to that. Here is a toy example that illustrates the problem: Regardles of the value of `LOOPCOUNT`, the " _deadtime_ " is always similar.               ClearAll[Hi2p];     LOOPCOUNT = 100;     Hi2p[a_?NumericQ, b_?NumericQ] := (         Do[Cos[0.3], {LOOPCOUNT}];          (a - Cos[a^2 - 3 b])^2 + (b - Sin[a^2 + b^3])^2     );     n = 10000;      {t, tt} = Do[Hi2p[1, 1], {n}] // AbsoluteTiming;      Print["TimePerFunctionEvaluation: " <> ToString[t/n]];          {{time, sol}, {points}} = Reap[AbsoluteTiming[         NMinimize[Hi2p[a, b], {a, b},           Method -> {"NelderMead", "PostProcess" -> False, "RandomSeed" -> 1796},           MaxIterations -> 500, PrecisionGoal -> 10,           AccuracyGoal -> 100, EvaluationMonitor :> Sow[{a, b}]]         ]];     {time, sol, Length[points]}     deadtime = time - t/n*Length[points];     Print["Deadtime: " <> ToString[deadtime]];          (*"TimePerFunctionEvaluation: 0.00004190240"            ==> {0.0650037, {3.08149*10^-33, {a -> 0.6037, b -> 0.429039}}, 278}     "Deadtime: 0.0536606"*)      **EDIT:** Thank you, I almost solved my real problem. I'm struggling with a technical detail, which stems from the fact that I don't completely understand how the in-lineable `apply` works. Here is the problem: (also I'm not sure if this should be a separate question or not...) My objective function is set up, so that it takes a number of data points apart from the parameters to fit. The number of data points is the same in all data sets, but can change between experiments. This way I can compile the objective function just once for all 10 000 data sets I have to fit. But the way `NelderMeadMinimize` is set up now it compiles the algorithm for each different dataset, which has a non-negligible overhead, especially when compiling to C. Here is a toy example:               ClearAll[f, toy, bench]     (*toy objective function which takes about 30 microsconds to run*)     toy = Compile[{a, b, c, x, y, z} , Do[Cos[RandomReal[]], {800}];        (a - x)^2 + 50 (b - y)^2 + (c - z)^2        , "RuntimeOptions" -> {"EvaluateSymbolically" -> False,           "CompareWithTolerance" -> False}, "CompilationTarget" -> "C"];     SetAttributes[bench, HoldFirst];     bench[expr_, n_] :=       Module[{tt, t}, {t, tt} = Do[expr, {n}] // AbsoluteTiming;        t/n]; bench[toy @@ RandomReal[{-1, 1}, 6], 10000]     toyf = Evaluate@toy[Sequence @@ {1, 2, 3}, Sequence @@ {x, y, z}];          (* ==> 0.00003000005 *)          (*compile once to C*)     NelderMeadMinimize[toyf, {x, y, z},        CompilationTarget -> "C"] // AbsoluteTiming     bench[NelderMeadMinimize[toyf, {x, y, z},        CompilationTarget -> "C"], 100]          (* ==> {0.6600009, {1.82172*10^-21, {x -> 1., y -> 2., z -> 3.}}} *)          (* ==> 0.028300039 *)          (*compile once to VMW*)     NelderMeadMinimize[toyf, {x, y, z},        CompilationTarget -> "WVM"] // AbsoluteTiming     bench[NelderMeadMinimize[toyf, {x, y, z},        CompilationTarget -> "WVM"], 100]          (* ==> {0.0400000, {1.82172*10^-21, {x -> 1., y -> 2., z -> 3.}}} *)          (* ==> 0.028200039 *)          (*but these seem to get compiled every time*)     bench[NelderMeadMinimize[       Evaluate[toy[Sequence @@ {1, 2, 3}, Sequence @@ {x, y, z}]], {x, y,         z}, CompilationTarget -> "WVM"], 100]     bench[NelderMeadMinimize[       Evaluate[toy[Sequence @@ {1, 2, 3}, Sequence @@ {x, y, z}]], {x, y,         z}, CompilationTarget -> "C"], 5]          (* ==> 0.032300045 *)          (* ==> 0.51200072 *)      From this benchmarks one can see that:   * Compilation to C is much slower then to WMV (already known:)   * It does not matter much whether the algorithm is compiled to C or WMV    * In the last benchmark one can see, that the algorithm is **compiled every time** (as each minimization takes half a second)  **Is there a way to compile the minimization algorithm just once for the whole data set?** So that code similar to this would get compiled only once instead of 5 times                 bench[         NelderMeadMinimize[         Evaluate[toy[Sequence @@ RandomReal[{-1, 1}, 3], Sequence @@ {x, y, z}]],          {x, y, z}, CompilationTarget -> "C"],        5]      **EDIT 2:** I managed to hack a version which works great for my purposes here. I can compile once like this               (*Hi2 first takes the varaibles then the data points of the spectrum \     as constants*)     vars = {int, p1, lm1, lm2, bl1, bl2};     symbolicSpectrum = Array[Unique[a] &, Length[spectrum]];     cm = NelderMeadMinimize`Dump`CompiledNelderMead[Hi2, Evaluate[vars],          symbolicSpectrum, CompilationTarget -> "C"]; // AbsoluteTiming      Then I call the compiled function 10000 times (once for each different spectrum).               (*then I jsut call cm 10000 times, once for each spectrum*)     cm[initialPoints, spectrum, 10^-9, 300]      This takes about 12 ms per dataset on my computer, with 10 ms spent on the evaluation of the objective function. I think this is simply _amazing!_ Oh, and by setting               Needs["CCompilerDriver`"]     $CCompiler = CCompilerDriver`IntelCompiler`IntelCompiler;      I got a free factor of 2 (so it takes about **6 ms** per data set).


How does one draw a parallelepiped in Mathematica?

I'm a bit new to the application, and I'm not sure how to draw a parallelepiped in _Mathematica_.


Grid rows height & SpanFromAbove issue

I would like to understand why the following code produces such a different result (Mathematica 9, Win7). Is this a bug? Is there a way to avoid this line height problem?               Grid[      {{"a", "b", "c", "d"},       {"L1\nL2\nL3", "e", SpanFromLeft, "f"},       {SpanFromAbove, "g", SpanFromLeft, "h"},       {SpanFromAbove, "i", SpanFromLeft, "j"},       {SpanFromAbove, "k", SpanFromLeft, "l"}}, Dividers -> All]      ![enter image description here](http://i.stack.imgur.com/IolUl.png)               Grid[      {{"a", "b", "c", "d"},       {"L1\nL2\nL3", "e", "m", "f"},       {SpanFromAbove, "g", SpanFromLeft, "h"},       {SpanFromAbove, "i", SpanFromLeft, "j"},       {SpanFromAbove, "k", SpanFromLeft, "l"}}, Dividers -> All]      ![enter image description here](http://i.stack.imgur.com/FlUaF.png) **UPDATE** : Maybe I oversimplified my need making the question difficult to understand. Here is a more practical example of the problem:               Grid[      {{"", SpanFromLeft, "simple\nmodel", "improved\nmodel"},       {"Test\nSim\nParams", "param1 =", 1, SpanFromLeft},       {SpanFromAbove, "param2 =", 2, 3},       {SpanFromAbove, "param3 =", 4, 5},       {SpanFromAbove, "param4 =", 6, 7}}, Dividers -> All]      ![enter image description here](http://i.stack.imgur.com/YKBVP.png)


Write any positive integer as a sum of squares

With `n = 17` I would like to get > {4, 1} and with `n = 999` > {31, 6, 1, 1} so that, for example,               Total[#^2 & /@ {31, 6, 1, 1}]      gives > 999 I don't want to get all possibilities, but only the shortest.


Remote Kernel and CUDALink

I have setup a remote kernel on my Mac, which connects to a more powerful Linux 64Bit Desktop. Mathematica is setup fine on the Linux machine. CUDA is also working fine and `NVIDIA_DRIVER _LIBRARY_PATH` and `CUDA_LIBRARY_PATH` are set just fine, although they are not the default paths. When I connect from my mac using the mathematica frontend the connection via remote kernel is initialized fine and I can do my calculations, but CUDA is not working. Taking a closer look shows, that the paths mentioned above are not set properly any more. This can be seen by checking GPUTools`Internal`\$NVIDIADriverLibraryPath and GPUTools`Internal`\$CUDALibraryPath. On the linux machine I set the paths manually using /etc/profile file. It is my understanding that the remote kernel being setup to call the `math` command should just start a mathematica terminal session. Starting mathematica via terminal using the `math` command on the linux machine works just fine and has the paths setup correctly. What am I missing?


Counting the zeros in a factorial expansion

A number, as big as 1000! (! = factorial) is given. I need to find how many zeros are there in the number. I counted the no of terminal zeros by dividing 5, 25, 125, ... (untill fifth power < number). But thats just a part of it. I also need to count number of zeros in between the digits. For example 8! has a zero after 4 (40320). I need to count those to. I spent hours still got nothing :P Is it actually even possible? I am trying to write a program in C++ to count. I could divide the number by 100 and count zeros but 1000! is too huge even for a 64bit computer. Any ideas, algorithms, formulae?


How do I re-direct FilePrint's output?

I recently wanted to use `FilePrint` to print the contents somewhere else but in the notebook I was using. However, the obvious-seeming solution doesn't work at all:               In[137]:= temp = With[{str = OpenWrite[]},                  Block[{$Output = str},                   Print["fee fi fo fum"]];                  Close[str]];          In[138]:= FilePrint[temp]               "fee fi fo fum"          In[139]:= With[{str=OpenWrite[]},                Block[{$Output = str},                 FilePrint[temp]];                Close[str]];               "fee fi fo fum"      Since the obvious solution doesn't work, does anybody know a less obvious solution, preferably one that doesn't involve re-implementing `FilePrint` myself? Sure, that would be easy, but I'd prefer not to do it.


Convert coefficients of polynomials into a matrix

I have several sets of 5 polynomials of the form:               a0 = 0.00301472 - 0.0961879 beta - 0.860642 beta^2 - 4.73786 beta^3 -        0.00897697 z + 0.0389941 beta*z + 0.0131329 z^2 - 0.00552858 z^3      for a0,a1,...,a5, they form a vector A. My independent variables are `beta` and `z`. I want a Matrix Q of the coefficients, such that when I multiply it by a vector of the form:               B={1, beta, z, beta z, beta^2, z^2, beta^3, z^3}       like `A=Q.B` i recover my vector of polynomials. How do I get the matrix Q in the easiest way? I have many sets, so it would take me hours. I have been trying some solutions with `Coefficient[]`, but I am not fully satisfied. Thanks!


How do I plot a U- form cylinder

I'm really new to _Mathematica_ , trying to learn some things, but I need help trying to plot this kind of cylinder, a U tube like cylinder. Tried to use an example code like this, and then vary some parameters, but still unclear on how to do that. Any help is apreciated. ![](http://imagizer.imageshack.us/v2/280x200q90/905/I9itfx.png)               Graphics3D[{Yellow,        Cylinder[{{v1 t, 0, h1}, {v1 t + Δx1, 0, h1}}, Sqrt[A1/π]],        Cylinder[{{8 + A1/A2 v1 t, 2, h2}, {8. + A1/A2 v1 t + A1/A2 Δx1, 0, h2}}, Sqrt[A2/π]]       Also I have used this               Tube[{{4, 10, h1}, {4, 3, h1}, {3, 0, h2}, {10, 1, h2}},       {Sqrt[A1/2 π], Sqrt[A1/2 π], Sqrt[A2/2 π], Sqrt[A2/2 π]}]}


Color linear interpolation of ParametricPlot3D

I am looking for any ideas about how to colorize an ellipsoid with a custom gradient style or by a `Blend` function. I would like to colorize ellipsoid as follows:   * at $(5,0,0)$ and $(-5,0,0)$ should be red color,    * at $(0,2,0)$ and $(0,-2,0)$ should be green color   * at $(0,0,2)$ and $(0,0,-2)$ should be blue color All other points should be interpolated, respectively to their locations. I tried to use `Blend` function, but something went wrong. My code:               ParametricPlot3D[{5 Cos[u] Cos[v], 2 Cos[v] Sin[u], 2 Sin[v]},     {u, 0, 2 Pi, Pi/10}, {v, -Pi/2, Pi/2, Pi/10}, Axes -> False,      Boxed -> False, Mesh -> None,      ColorFunction ->Function[u, v,      Blend[{Red, Green, Blue}, {5 Cos[u] Cos[v], 2 Cos[v] Sin[u], 2 Sin[v]}]]]


Help with Reduce, quadratic system of inequalities

I'm trying to obtain an equivalent system of inequalities to the one below but **without** the variables x and z. Somehow Reduce just repeats the command.               v[x_, y_] := a*x^2  + b*x*y + c*x       sc1 := ForAll[{x, z}, {z >= x && x >= 0 && z <= 1}, v[z, x] - v[x, x] >=0  ]     sc2 := ForAll[{x, z}, {x >= z && z >= 0 && x <= 1}, v[z, x] - v[x, x] <=0  ]     Reduce[(sc1 || sc2), {a, b, c}]      Is there some basic error I can't see? I looked at questions about using Reduce with ForAll but did not find anything similar.


Few quick Mathematica questions about Dictionary

_a. Get the list whose elements are of the form {language,number of words in dictionary)_ I tried this, and it gave me the number if words in dictionary, but I don't know how to get the language part:               lang = DictionaryLookup[All];          langlength =Table[{lang[[i]], Length[DictionaryLookup[{lang[[i]], All}]]}, {i, 1,     Length[lang]}]      _b. Now sort this list in descending order by the number of words and get a list of the form_ `{position in sorted list, language, number of words}`. For part b, I have               sorted = Sort[langlength, #1[[2]] >= #2[[2]] &]     placeList[list_] := Table[{i, list[[i]]}, {i, 1, Length[list]}]      pl = placeList[sorted]      And I got > {1, {"Finnish", 728498}, 2, {"Catalan", 602208}, 3, {"Galician", 515385}, 4, > {"Portuguese", 459996}, 5, {"Hebrew", 455264}, 6, {"Danish", 376469}, 7, > {"BrazilianPortuguese", 264713}, 8, {"Croatian", 260752}, 9, {"Polish", > 234907}, 10, {"Hungarian", 230206}, 11, {"Dutch", 229368}, 12, {"French", > 139657}, 13, {"Swedish", 121430}, 14, {"Italian", 116854}, 15, {"Faroese", > 108508}, 16, {"English", 92518}, 17, {"BritishEnglish", 86135}, 18, > {"Spanish", 86016}, 19, {"German", 76155}, 20, {"IrishGaelic", 65203}, 21, > {"Arabic", 43768}, 22, {"Breton", 32733}, 23, {"Russian", 31801}, 24, > {"Hindi", 15983}, 25, {"ScottishGaelic", 15670}, 26, {"Esperanto", 14780}, > 27, {"Latin", 8777}}` From here I don't know how to get rid of the braces around `Finnish, 728498` and others.


Using KalmanFilter or KalmanEstimator

I have the following:               samplePoints = Range[0.0,6.0,1/60.0];     noiseFunction = Function@@{{t},Total[Sin[RandomReal[{\[Omega]s,188.0},12]t]],        {Listable}};     signalFunction = Function[{t},(36(1-E^(-2 t))+        (3*Sin[54*t]+4Sin[35.1*t]))Piecewise[{{E^-((0.5t-2)^2),t<4},{1,True}}],      {Listable}];     inputSignal = signalFunction@samplePoints + noiseFunction@samplePoints      How would one use KalmanFilter or KalmanEstimator to do a good job of suppressing the high frequency noise in (inputSignal). I am not interested in forecasting ahead. I want to estimate the latest sample of signalFunction from the most recent and previous points from (inputSignal). EDIT This figure is a close up of some of the samples. ![enter image description here](http://i.stack.imgur.com/PcEbS.jpg) The noisy points are in red and the single without noise is black. I am trying to simulate a situation where I have the noisy points, and get a good approximation of the black points (without noise).


How can I get the style of selected cells?

How can I get the style such as Input, Text, Code, etc., of a selected cell? If a group of cells is selected, how can I get styles of all the cells in the group?


Trouble using If[] within TabView Manipulate control

If I place an `If` in the "body" of a `Manipulate` as in:               Manipulate[tick;      Dynamic@If [ s1 == 1,        {"m1 ", Manipulator[Dynamic[m1, (m1 = #; tick = Not[tick]) &], {1, 4}], " ", Dynamic[m1]},        {"m2 ", Manipulator[Dynamic[m2, (m2 = #; tick = Not[tick]) &], {0, 1}], " ", Dynamic[m2]}        ]      , TabView[{ "1" -> Grid[tabNumber = t1;(*Dynamic@*){ }],        "2" -> Grid[tabNumber = t2; {           {"s1 ", SetterBar[Dynamic[s1, (s1 = #; tick = Not[tick]) &], Range[2]], " ", Dynamic[s1]}           }]        }, Dynamic@tabNumber]      , {{tick, False}, None} , {{tabNumber, 1}, None}      , {{t1, 1}, None} , {{t2, 2}, None} , {{m1, 1}, None} , {{m2, 1}, None} , {{s1, 1}, None}      , TrackedSymbols :> {tick}, ControlPlacement -> Left      ]      Then the selection of the s1 `SetterBar` control switches the m1/m2 control in the `Manipulate` display without any trouble: ![If within Manipulate](http://i.stack.imgur.com/Hm8Gy.png) I'd like to have this condition within the `TabView` control, something like:               Manipulate[tick;      Dynamic@If[tabNumber == t1, Plot[x^2, {x, 0, 1}],        Plot[1 - x^2, {x, 0, 1}]]      , TabView[{        "1" ->(*Dynamic@*)Grid[tabNumber = t1;(*Dynamic@*){           (*Dynamic@*)If [ s1 == 1,            {"m1 ", Manipulator[ Dynamic[m1, (m1 = #; tick = Not[tick]) &], {1, 4}], " ", Dynamic[m1]},            {"m2 ", Manipulator[ Dynamic[m2, (m2 = #; tick = Not[tick]) &], {0, 1}], " ", Dynamic[m2]}            ]           }],        "2" -> Grid[tabNumber = t2; {           {"s1 ", SetterBar[Dynamic[s1, (s1 = #; tick = Not[tick]) &], Range[2]], " ", Dynamic[s1]}           }]        }, Dynamic@tabNumber]      , {{tick, False}, None} , {{tabNumber, 1}, None}      , {{t1, 1}, None} , {{t2, 2}, None} , {{m1, 1}, None} , {{m2, 1}, None} , {{s1, 1}, None}      , TrackedSymbols :> {tick}, ControlPlacement -> Left      ]      However, instead of one of the two desired controls showing up within the `Tab, this produces`Grid[...]` text instead: ![Grid text in TabView](http://i.stack.imgur.com/0scqM.png) Is there a way to get the If condition in the Tab definition to evaluate before the `TabView`? I have tried all the variations of `Dynamic@` that I can think of, but they didn't help.


StringCases using RegularExpression fails when there is missing data

I got some text scraps with this _structure_               "Focal Plane: 198'  Active Aid to Navigation: Yes  *Latitude: 35.250 N  *Longitude: -75.529 W"      But some of them lack of parts like this               "Focal Plane: 198'  Active Aid to Navigation: Yes  *Longitude: -75.529 W"      Using regular expression matching, I want to extract all the info available, included getting a tag "NotAvailable" for missing data., I wrote this code, but it can't tell when a pattern does not match -- should the pattern in the middle not match, my code just skips it and goes on to the next pattern:               ptrFocal = "(?<=\\Focal Plane: )(.*?)(?=\\')";     ptrLat = "(?<=\\*Latitude: )(.*?)(?=[a-zA-Z])";     ptrLon = "(?<=\\*Longitude: )(.*?)(?=[a-zA-Z])";          r =        StringTrim /@ StringCases[text,          RegularExpression[ptrFocal <> "|" <> ptrLat <> "|" <> ptrLon]       ];      I would want some pointers on how to do this. **EDIT:** The expected transformation of the example data I gave above is > >     {198, 32.250, -75.529} >     {198, "NotAvailable", -75.529} >


Applying a function with the HoldAll attribute inside NestList

I'm trying to write an update function, which can be applied to a list and then to `NestList` it. As the function has to manipulate the given variable I figured I need `HoldAll` or `HoldFirst`, so the variable is passed by reference.               update[x_] := (x[[1]] = x[[1]]*2; x)     Attributes[update] = HoldAll;      This works:               mylist = Table[3, {i, 1, 3}]; update[mylist]      It gives:               {6,3,3}      But now I want it to be nested in a list. The code               NestList[update, mylist, 3]      should give               {{6,3,3},{12,3,3},{24,3,3},{48,3,3}}      but it gives               Set::setraw: Cannot assign to raw object 12.      Set::setraw: Cannot assign to raw object 12.      Set::setraw: Cannot assign to raw object 12.      General::stop: Further output of Set::setraw will be suppressed during this calculation.          {{12,3,3}, {12,3,3}, {12,3,3}, {12,3,3}}      Am I right that this is happening because `NestList` evaluates `mylist` before applying update? If so, how can I stop this? I can't set `Attributes[NestList] = HoldAll;` , right? Any help is appreciated :) Cheers :D


How to write a function to remove comments from a .m source file preserving formatting such as line wrapping reasonably? This means if I have               foo;     (* comment 1 *)     bar[         baz (* comment 2 *)         (* comment 3 *)     ];      I'd ideally end up getting               foo;     bar[         baz     ];


How do we make a negative integer out of a string of a negative number and vice-versa?

Negative numbers are not taken into consideration by mathematica's built-in functions.               FromDigits["-2"]      Gives me this message:               FromDigits::nlst: The expression -2 is not a list of digits or a string of valid digits. >>      Also:               In[2]:=IntegerString[-2]      Gives:               Out[2]:="2"      I was wondering if someone had some code to do this. I'm currently making a small program in mma which will help me enter matrices manually because it's cumbersome to type in every single ,{} for each row/column. Here's what I had in mind:               enterMat[x_, y_] := MatrixForm[ReleaseHold[         Table[Hold[FromDigits[InputString[]]], {x}, {y}]]]      Gives me a series of popups in which I enter the value 1 by 1 pressing enter after each to pass to the next value. It's faster and more comfortable to do it this way since I can use the numpad instead. My only problem is that it just doesn't work with negative numbers! If you have a solution or you know a great way to enter/scan/manipulate matrices, I would like to hear it. Thanks!


Connecting a vertex to middle of an edge with GraphPlot?

using GraphPlot I'd like to make directed arrow connecting a vertex (node) to the middle of an edge but couldn't find a way. Is this even possible using GraphPlot or other graphics-related commands in Mathematica. Basically I'd like to plot enzyme-substrate network and so like to connect node E (enzyme) to an edge connecting substrate S to product P, and scale-up for all Enzyme-Substrate-Product combination. Any help greatly appreciated!!


Replace interior of matrix with zeros

I have f.e. the following square matrix:               x = {{2, 5, 5, 11, 11, 23, 37, 41, 43, 47},         {2, 5, 11, 17, 19, 23, 41, 41, 43, 67},         {2, 7, 11, 19, 19, 41, 41, 43, 47, 73},         {3, 11, 17, 19, 23, 41, 43, 53, 67, 79},         {3, 11, 19, 19, 31, 43, 47, 59, 67, 83},         {3, 17, 19, 29, 37, 43, 53, 59, 73, 83},         {5, 17, 29, 31, 37, 47, 53, 71, 73, 83},         {7, 19, 29, 31, 37, 53, 59, 73, 73, 89},         {11, 23, 31, 41, 43, 53, 61, 73, 79, 97},         {29, 29, 37, 41, 53, 67, 71, 79, 79, 97}};      I want to keep the first and last row / column and replace all other numbers with `0`. I have written:               n = Length@First@x;          Table[x[[i, j]] = 0, {i, 2, n - 1}, {j, 2, n - 1}];          x // MatrixForm      ![enter image description here](http://i.stack.imgur.com/IA50p.jpg) Before that I tried to find a more functional solution (f.e. with replacement patterns) but gave up after some unsuccesful attempts. Thanks for showing me some alternatives.


Dashboard TV with CDF Player

I'm experimentally trying to use CDF Player to create an Dashboard TV here in the company (like in the airport, see image below). I would like to configure the CDF file so It could be displayed in full screen as a slide show. The TV has a resolution of 1280x720. ![enter image description here](http://i.stack.imgur.com/ubHKY.jpg) The idea is to setup each slide to have some time duration, and use some fade transition. Each slide is a image with the 1280x720 resolution, generated by Mathematica and saved in one specific file folder. As I use enterprise version, I have no problem in make CDF Player to have external folder access, and ready there images. Important points:   1. If the files in the folder are updated, it should be automatic updated in the dashboard, without need to restart it. The image file names and number in the folder are always the same.   2. Nice transition effect (like new version 9 options)   3. Make the mouse disappear   4. Should works on CDF (enterprise version, that can import local files) I'll be very glad with some ideas on how could I implement it.


Problem with ParametricPlot of multiple Curves

I have written a function `f[Ne,t,T]`, that gives back a **list** of results when evaluated with numeric values of the variables `Ne`, `t` and `T`. Now I want to make a `ParametricPlot` of the first element of the resulting list against another function `g[t,T]` for different values of the parameter `T`. So I try it for example like this:               TList={0,1,2};     ParametricPlot[ Table[ {Part[f[5,t,T],1] , g[t,T]} , {T,TList}] ,{t,0,10}]      Since I didn't use `Evaluate` inside `ParametricPlot`, all the curves have the same color. But if I do us `Evaluate` inside `ParametricPlot`, for example like this:               TList={0,1,2};     ParametricPlot[ Evaluate@Table[ {Part[f[5,t,T],1] , g[t,T]} , {T,TList}] ,{t,0,10}]      then `Part` is acting too early, and `f[5,t,T]` is evaluated to 5 (which is of course the first part of the expression `f[5,t,T]`), but that's clearly not that what I want. I want the `Table` command to be evaluated, so that `ParametricPlot` can "see" the different curves, but I want the first part of `f[Ne,t,T]` to be taken **after** the function `f[5,t,T]` is evaluated for the actual value of `t`. So what can I do?


Manipulate[]'ing complex roots of an equation using a 2D slider

I want to make a demonstration of how the complex roots of a polynomial change when I alter the coefficients. Here is my attempt:               QuintRoots[t_] := Map[{Re[#], Im[#]} &, x /. NSolve[x^5 - x - t == 0, x]]          DrawRoots[t_] := ListPlot[QuintRoots[t], PlotRange -> {{-1.5, 1.5}, {-1.5, 1.5}},                                     PlotStyle -> PointSize[Large], AspectRatio -> Automatic]          Manipulate[DrawRoots[t[[1]] + I*t[[2]]], {t, {-1, 1}, {-1, 1}}]      `QuintRoots[]` and `DrawRoots[]` work exactly as I would expect. The final command produces a nice-looking 2D slider and ListPlot below it but, when I try to move the slider, it doesn't move. A one dimensional slider, such as                Manipulate[DrawRoots[E^{I*t}], {t, 0, 2 Pi}]      works fine. So does the documentation center's example of a 2D slider,                Manipulate[ParametricPlot[{Sin[t + d[[1]]], Sin[t + d[[2]]]}, {t, 0, 2 Pi}],                {d, {0, 0}, {Pi, Pi}}]      PS Bonus question: If I can get this to work, I would also like to mark the points $\pm 3/ \sqrt{32}$ and $\pm 3 i /\sqrt{32}$ in the slider field, which are the points where we get multiple roots. Can this be done?


Finding critical points of a function

Let's say we'd like to find the critical points of the function $f(x)=\sqrt{x-x^2}$. Finding out where the derivative is 0 is straightforward with `Reduce`:               f[x_] := Sqrt[x - x^2]     f'[x] == 0     Reduce[%]      which yields:               (1 - 2 x)/(2 Sqrt[x - x^2]) == 0          x == 1/2      To find out where the real values of the derivative do not exist, I look for values of $x$ that make the denominator 0:               Reduce[2 Sqrt[x - x^2] == 0]      which yields:               x == 0 || x == 1      To do this, I manually extracted the denominator expression from the derivative and ran it through `Reduce`. My question is, is there a better way to ask Mathematica for values of $x$ where an expression doesn't have a real value? E.g. in this case, I'd like to pass in the expression for the derivative $\frac{1-2x}{2\sqrt{x-x^2}}$, and have it report that at 0 and 1, the real value doesn't exist.


Spherical harmonic derivative

Consider the following substitution               Derivative[2, 0][S][th, ph] /. S -> Function[{th, ph}, SphericalHarmonicY[3, 0, th, ph]]      which gives correct answer. While for some cases, eg.               Derivative[2, 0][S][th, ph] /. S -> Function[{th, ph}, SphericalHarmonicY[3, 3, th, ph]]      will produce the               Infinity::indet: Indeterminate expression (0 24 \[Sqrt]70 E^(-I \[Phi]) ComplexInfinity)/(12 \[Sqrt]35) encountered. >>      error. Of course the command               D[SphericalHarmonicY[3, 3, th, ph], {th, 2}]      will produce the desired output. So the question is what is wrong with the substitution rule?


Better Autocompelete for the Front-End

I wonder if it is possible to improve the front-end's autocomplete capability. Compared with some other more sophisticated editors/IDEs, such as eclipse, Mathematica's front-end does not provide a good autocomplete capability. The front-end provides an autocomplete feature through `(Control|Command)[+Shift]+K` key bindings. But it has several different shortcomings. First off, the key binding is not the easiest one to use. I really prefer `Control+Space` or `tab` key combination which is used in many other editors rather than the Mathematica's unique `Control+K`. However, one can modify the key binding to his own choice. Second, the function/variable name autocomplete feature, shows a list of options just over the line that you are typing rather than underneath the line. So, you cannot see what you have already typed in: ![Mathematica's AC](http://i.stack.imgur.com/VlsFD.png) Compare it with eclipse: ![eclipse AC](http://i.stack.imgur.com/vH21n.png) Another nice feature of eclipse, that Mathematica supports a simpler version of through `Control+Shift+K`, is the parameter suggestion feature. Once you choose a function/class name from the above list, it shows you another list with all possible function/constructor parameters, which makes the life much more easier. ![Parameter Completion](http://i.stack.imgur.com/8l70Y.png) Eclipse even provides camel case notation: ![Camel Case](http://i.stack.imgur.com/0SXJS.png) Is that possible to modify the Mathematica's front-end to support such capabilities? _Note:_ Here is a list of Mathematica functions/options that might be useful: `NotebookEventActions`, `NotebookSelection`, `CurrentValue`, `Names`.


Calculating an exact orthogonal modal matrix in Mathematica

I can calculate the modal matrix of a matrix **A** using the command `JordanDecomposition[A][[1]]`, and a decimal approximation of the orthogonal (or normalised) modal matrix using `JordanDecomposition[N[A]][[1]]` but I would like to know how to calculate the answer in an exact form. The example I'm using is `A = {{1, 1/2, -(1/2)}, {1/2, 1, 1/2}, {-(1/2), 1/2, 1}}` where using the method above I get a orthogonal modal matrix of               {{0.57735, -0.57735, 0.57735}, {-0.57735, 0.211325, 0.788675}, {0.57735, 0.788675, 0.211325}}      which results in, for $ y = x^T . A . x $               {{y1}, {y2}, {y3}} == {{0.57735 x1 - 0.57735 x2 +      0.57735 x3}, {-0.57735 x1 + 0.211325 x2 +      0.788675 x3}, {0.57735 x1 + 0.788675 x2 + 0.211325 x3}}      rather than the exact form: $$ y_1 = \frac{1}{\sqrt{3}} x_1 - \frac{1}{\sqrt{3}} x_2 + \frac{1}{\sqrt{3}} x_3 $$ $$ y_2 = \frac{1}{\sqrt{2}} x_2+\frac{1}{\sqrt{2}} x_3 $$ $$ y_3 = \frac{2}{\sqrt{6}} x_1 + \frac{1}{\sqrt{6}} x_2 - \frac{1}{\sqrt{6}} x_3 $$ How can I get this exact form using Mathematica commands?


Generation function of recurrence sequence

I'm trying to find generation function of recurrence sequence               ClearAll[c];     c[1] := 0;     c[2] := 1;     c[n_] := (2 + 2*(n - 2)*c[n - 2] + (n - 2) (n - 1) c[n - 1])/(n (n - 1));     Table[c[i], {i, 1, 15}]      FindGeneratingFunction[%, x]      but _Mathematica_ just output > >     FindGeneratingFunction[{0, 1, 2/3, 5/6, 4/5, 37/45, 52/63, 349/420, > 338/405, >                               873/14175, 14554/17325, 157567/187110, > 466498/552825, >                               11994551/14189175, 41582906/49116375}, x] >   How I can find `GeneratingFunction`?


How to distinguish between lists and values?

I have a (hopefully small) problem with some numerical integration algorithm, more specifically I want to integrate the imaginary part of a complex valued function, e.g. `f[u_]:=Exp[-iuK]` with $K\in\mathbb{R}$. As mentioned I am only interested in `Im[f]`, in the example `-Sin[u K]`. Now if I integrate with Mathematica               NIntegrate[f, {s, Min[roots[[ 1 ]], roots[[ 2 ]]],                     Max[roots[[ 1 ]], roots[[ 2 ]]]}, AccuracyGoal->aGoal,                      PrecisionGoal->pGoal, WorkingPrecision->wPrecision ];      I get two different results depending on `f`:   1. if I use `-Sin[u K]`, it returns `somenumber`   2. if I use `Im[f]`, it returns a list `{ somenumber }` Those two have to be treated differently and that crashes my program. I have a few questions: Why does Mathematica sometimes return lists, and sometimes values? How can I distinguish between a list and a value, i.e.               If xyz is a list then        do something      else        do something else     end      Any other ideas how one could avoid these different return "types"? The manual and anything I found hasn't been useful so far.


Why doesn't Mathematica simplify a square root of an expression that equals a square of a positive real?

When I try and simplify this expression:               In[1]:= FullSimplify[Sqrt[ x^2 + 2 y^2 + 2 y Sqrt[x^2 + y^2] ], (x | y) \[Element] Reals]     Out[1]= Sqrt[x^2 + 2 y (y + Sqrt[x^2 + y^2])]      it does not simplify properly.   However, _Mathematica_ knows it equals a simpler expression:               In[2]:= FullSimplify[ Sqrt[x^2 + 2 y^2 + 2 y Sqrt[x^2 + y^2] ] == Sqrt[x^2 + y^2] + y, (x | y) \[Element] Reals]     Out[2]= True      Why doesn't _Mathematica_ simplify this expression, and how can I make it do it anyway, even if the expression is part of a larger expression?


Check in a series if there exists adjacent values with less than a certain number of missing values

I'm working with a large number of series of different experiments, where there exist a lot of experiments where there are no entries. I now want to draw a sample where there should exist at least 200 adjacent values of data with less than 100 entries of null (A 200 day period of complete data). I started to do it with a loop, checking for 0-200, 1-200 for each dataset which takes ages... Should I use `Row / Scan/ Reap/ Sow`? I'd appreciate a help and guidance on possible functions I can use.


Lesser and greater symbols in the axeslabels

I need a plot with $\Gamma^<$ as axeslabel using: **AxesLabel -> { $\Gamma^ <$}** But I get an error. **AxesLabel -> { $\Gamma^{a <b}$}** works though. I think I've to tell mathematica that $\Gamma^<$ is not a mathematical expression or something in that direction. Is there some solution for this problem? Thanks


DSolve solves PDE only without boundary condition, but fails otherwise

I'm trying to solve for `Te[w, Pprobe, t]` in a partial differential equation. What's surprising is that it manages to solve it when I don't put in any initial conditions. But when I put in `Te[w, Pprobe, 0] == 0.3` it doesn't work:               C1 = 10^-10;     C2 = 0.1*C1;     R = 50;     Tb = 0.1;     Geb = 5*10^-15;     Z0 = 50;     L[Te_] := 10^-9 + 10^-9*(Te - 0.1);     Zlcr[Te_, w_] := (1/R + 1/(I*L[Te]*w) + I*C1*w)^-1;     Zload[Te_, w_] := -I*w*C2 + Zlcr[Te, w];     Γ[Te_, w_] := (Zload[Te, w] - Z0)/(Zload[Te, w] + Z0);     y[Te_, w_] := (Abs[Γ[Te, w]])^2;     p[Te_, w_] := Abs[Γ[Te, w]]     Co = 10^-35;     Vol = 10^-21;     Cv = Co/Vol;     Te0 = 0.3;          pde =        Cv*D[Te[w, Pprobe, t], t] ==          -Geb (Te[w, Pprobe, t] - Tb) + (1 - y[Te[w, Pprobe, t], w])*Pprobe          soln =        Te[w, Pprobe, t] /.          First @ DSolve[{pde, Te[w, Pprobe, 0] == 0.3}, Te[w, Pprobe, t], {w, Pprobe, t}]


How to achieve Set+Part like behaviour in custom Set function?

So I've been toiling away on my DataFrame package. I've been trying to get `Set` to work with it, but it seems it either can't be done (ie via `UpValues`), or is ill advised. So I decided to bite the bullet and just roll my own custom `DFSet` function. But I can't figure out how the get the evaluation to work like it does when you `Set` the `Part` of something. This is my `DFSet` function:               DFSet[Part[DataFrame[DFMetadata[metastore_], DFData[store_]], name_String], data_List] :=         (             If[                 Length@data =!= metastore["Length"],                  Abort[]             ];             If[                 !MemberQ[metastore["Names"], name],                  metastore["Names"] = Append[metastore["Names"], name]             ];             store[name] = Developer`ToPackedArray@data;         )      The idea is that it would be called like this:               DFSet[frame[["a"]], {1, 2, 3}]      The problem is that if I run it as is the `Part` bit will try to evaluate and that won't do. But if I set the attribute `HoldFirst` on `DFSet` `frame` won't evaluate to its `OwnValue`. A test case with code:               (****Code needed for a working test case but not part of the problem****)     (*Helper functions*)     StringVectorQ[x_] := MatchQ[x,{__String}]     TopMatrixQ[x_] := Length[Union@(Length/@x)]==1     (*Constructor*)     DataFrame[names_?StringVectorQ, data_?TopMatrixQ] :=          Module[             {store, metastore, length},             If[Length@First@data =!= Length@names, Abort[]];             store = Unique[DFstore];             metastore = Unique[DFmetastore];             metastore["Length"] = Length@First@Transpose@data;             metastore["Names"] = names;             Thread[                 Set[#1,#2]&[store/@names, Developer`ToPackedArray/@Transpose@data]             ];             DataFrame[DFMetadata[metastore], DFData[store]]         ]      (*Pretty Formatting*)     Format[DataFrame[DFMetadata[metastore_], _DFData]] :=          "DataFrame"[Length[metastore["Names"]]]     (*UpValue for Part*)     DataFrame /: Part[DataFrame[DFMetadata[metastore_], DFData[store_]], name_String] :=          (             If[!MemberQ[metastore["Names"], name], Abort[]];             store[name]         )     (**************************)     (****The actual problem****)     (*DFSet function*)     DFSet[Part[DataFrame[DFMetadata[metastore_], DFData[store_]], name_String], data_List] :=         (             If[                 Length@data =!= metastore["Length"],                  Abort[]             ];             If[                 !MemberQ[metastore["Names"], name],                  metastore["Names"] = Append[metastore["Names"], name]             ];             store[name] = Developer`ToPackedArray@data;         )     (*******************)     (****A test case****)     (*Arrange*)     frame = DataFrame[{"a","b"},{{1,2},{1,2},{1,2}}]     (*Act*)     DFSet[frame[["c"]],{3,3,3}]     DFSet[frame[["b"]],{4,4,4}]     (*Assert*)     frame[["c"]]=={3,3,3}     frame[["b"]]=={4,4,4}     (****Output from successful test should be:     Out=DataFrame[2]     Out=True     Out=True     *)


Using a MacBook's builtin sudden motion sensor with Manipulate

With the following code I can get the value of the "Sudden Motion Sensor", which is build into MacBooks:               Dynamic@ControllerState[{"X", "Y", "Z"}, ControllerPath -> {"Sudden Motion Sensor"}]      I want to use the values to control some variables in a `Manipulate` statement, however this doesn't seems to work:               Manipulate[x,"X" -> {x, -1, 1}, ControllerPath -> "Sudden Motion Sensor"]


BarChart FrameLabels with only partial Frame?

This test BarChart is generated by the code that follows it: ![enter image description here](http://i.stack.imgur.com/96Weu.png)               data = Table[RandomInteger[{1, 10}], {3}, {4}];          BarChart[MapThread[Labeled[#1, #2, Above] &, {data, {1, 2, 3}}],       ChartLayout -> "Stacked",       ChartStyle ->        Reverse@{Lighter@Blue, Blue, Darker@Blue, Darker@Darker@Blue},       ChartLabels -> {{"a", "b", "c"}, None},      Frame -> {False, True, False, False},      FrameLabel -> {"x axis", "y axis"},       BaseStyle -> {FontFamily -> "Helvetica", FontSize -> 14}]      Since only a y-axis component of Frame is rendered: `Frame -> {False, True, False, False}` the "x axis" label of `FrameLabel -> {"x axis", "y axis"}` is omitted - and that's consistent with documentation. Is it possible to display "x axis" at the location it would be if the bottom component of the Frame were there _and_ preserving the set `BaseStyle` values (eg `Font`, `FontSize`)? This can be done using `Inset` but positioning is ad-hoc and it does not preserve `BaseStyle` values. Wrapping `Labeled` around `Barchart` doesn't correctly center the text and moreover does not use the `BaseStyle` values, as the following screenshot shows. Here for comparison the bottom component of Frame is True - and note the disastrous clash of graphical elements. ![enter image description here](http://i.stack.imgur.com/jeAo7.png) Finally, using the bottom `Frame` component: `Frame -> {True, True, False, False}` but without ticks: `FrameTicks -> {None, Automatic, None, None}` results in an ugly double axis and overlap in labels: ![enter image description here](http://i.stack.imgur.com/28ntM.png) Any other options, eg using `LabelingFunction`?


Write a number as the product of its two largest divisors

For even `n >= 10 && n <= 98` I want to write `n` as the product of its two largest divisors (excluding `n` itself, i.e. `1 * 60 == 60` is not permitted). **EDIT** (to account for rasher's criticism) I have tried:               First@Reverse@Take[Transpose[{#, Reverse@#}], Length[#/2]/2] &[        Rest@Most@Divisors@#] & /@ {10, 12, 52, 60, 66, 70, 72, 98}      giving > {{2, 5}, {3, 4}, {4, 13}, {6, 10}, {6, 11}, {7, 10}, {8, 9}, {7, 14}} but this fails, f.e., on `16`, which should give `{4, 4}`


Formatting and inserting a parameter table into a plot

I'm fitting data, and I want to put the parameter table generated by `NoninearModelFit` into the plot. How can I do that in a reasonable way? I want to format the parameter table so that it only shows two decimal places and doesn't show the t-statistic and P-Values.


How to get the associated popup menu?

I have three`PopupMenu` and they work in such a way that second `PopupMenu` value depends on the value selected by the first `PopupMenu` and third `PopupMenu` value depends on the second `PopupMenu` value being selected. If first `PopupMenu` has two option a and b. Then second `PopupMenu` should have c,d,e if a is selected and f when b is selected. And if c is selected from second `PopupMenu` then third `PopupMenu` should have g,h and so on. These options are imported from Excel files. I wanted this to be dynamic; if someone makes any change to this file, then it should work accordingly. At the starting time, all three `PopupMenu` should show Popup1, Popup2, Popup3 as the name of `PopupMenu` and the selected value should be shown in its title name from White color and all `PopupMenu` background is black.


Computers running Wolfram lightweight grid manager won't fall asleep

I have a computing environment comprised of:   * 27" iMac with dual cores running Mac OS X 10.6.8 and   * 2 XServes each with 2 quad cores running Max OS X Server 10.6.8   * All networking by ethernet to a Time capsule. I now run Mathematica on the iMac and use the XServes for parallel processing. I have Wolfram lightweight grid manager running on the XServes. Since installing the grid manager the XServes won't fall asleep. Their energy use settings look like this: ![Energy Saver settings](http://i.stack.imgur.com/JiOIj.png) which should trigger them into sleep mode after 5 minutes of inactivity. The warm summer weather has made this a pressing issue. XServes run hot and power hungry. I don't need them running constantly and don't want to run air conditioning all the time to cool them. Also, I want to run some processing from a remote location while I escape NY's summer heat for a few days. Sleeping and waking the servers figure into my working vacation plan ;-) Does grid manager run some process which prevents the XServes falling asleep? If so, how can I start and stop the process?


Executing Maple Code Inside Mathematica

Is it possible to create a C++ program using MathLink that will invoke the Maple kernel and execute a very basic Maple command using OpenMaple? I'm envisioning the following:               Install["MapleLink"]      starts the external program MapleLink and installs the _Mathematica_ definition RunMaple.               ?RunMaple          RunMaple[expr] returns a string which is the output when Maple executes expression expr      A sample output:               RunMaple["seq(i, i=0..3);"]          "0, 1, 2, 3"      I'm also open to using J/Link.


How can I make a list animation of images that fade in and out?

I'm not sure how to get a "fade in" effect.


Transform Root objects into Trigonometric expressions

Consider the Root objects               roots = Table[Root[-1 + 27 #1^2 - 162 #1^4 + 243 #1^6 &, i],{i,1,6}]      These can be expressed in terms trigonometric functions as follows               trig =        {-2/3 Cos[Pi/18], -2/3 Cos[5 Pi/18], -2/3 Cos[7 Pi/18],          2/3 Cos[7 Pi/18], 2/3 Cos[5 Pi/18], 2/3 Cos[Pi/18]}      This can be checked Numerically, but also exactly using the following expression:               And @@        MapThread[         PossibleZeroQ[ToNumberField[#1 - #2], Method -> "ExactAlgebraics"] &,          {roots, trig}]      > True Is there a way to have Mathematica translate between these two things? I have not been able to make FullSimplify do it. Does anyone know of something like a RootToTrig function?


How to edit a HYPERLINK once created inside a notebook?

When a hyperlink is created in a notebook, there does not seem to be an easy way to actually edit the hyperlink (maybe to correct the URL). To make some text HYPERLINK, one selects the text using the mouse, then does a right-click and then selects `Make HyperLink ...`, then a popup menu comes up where one enters the actual URL. Then clicks ok and hyperlink is made. ![Mathematica graphics](http://i.stack.imgur.com/0aIEr.png) Now the text becomes a hyperlink. But how can one bring this menu back up in order to modify the link if needed? Right-clicking on the now hyperlink does not bring up the above menu used to create the hyperlink. Selecting the cell and typing `Ctrl+Shift+E` is not really practical, as the cell can be very large and contain many links. question is: How to bring up the original menu used to make the hyperlink in order to modify any specific link when needed?


Recursion on a moving window

I need to apply some computations to a moving window of $N$ items in a time series and I am struggling with doing recursion and shifting the considered window. To illustrate, please consider the simple function below.               myFunction[state_] := Append[state[[2 ;;]], RandomInteger[10]]     initialState = {1, 2, 3};     RandomInteger[10];     state1 = myFunction[initialState]     state2 = myFunction[state1]      In reality I am doing some time series analysis. I am predicting the `t4` based on `t1`, `t2` and `t3`. Then I want to predict `t5` based on `t2`, `t3` and my predicted `t4` and so on. So after 3 iterations, I will be predicting based on my 3 first predictions


Finding a percolation path

I would like to examine percolation on a random lattice. To be exact, I wish to find the minimum length of a 'bond' needed such that the leftmost site can be connected to the rightmost site. Here is an example of the lattice:               randPts = Table[RandomReal[{-10, 10}, 2], {200}];      randPlot = ListPlot[randPts,                      PlotStyle -> {PointSize[0.0125]},                      PlotRange -> {{-10, 10}, {-10, 10}},                      AspectRatio -> 1,                      Frame -> True]      ![random lattice](http://i.stack.imgur.com/Q5vMj.png) I have tried for a while to get this but have not had success. The basic plan was:   1. Define a bond length $R$   2. Look at each site one at a time. If another site(s) is within $R$ of a site, they will be in the same cluster. Each site will be in a cluster of 1 or more (obviously the larger $R$ chosen, the larger each cluster size)   3. Take a site. Does it bond with other sites? If so then combine the two clusters together.    4. Repeat step 3 for all sites.   5. At the end ask if the leftmost cite and the rightmost sites are included in the conglomerate cluster. If so, percolation has occurred.   6. Decrease $R$ and start over again until a threshold is found. I think I am stuck somewhere in the step 3,4 area. Here is some of what I've tried: I have defined a module to find the distance between a site, `j`, and its nearest neighbor. The table, `t`, gives distance between `j` and all other sites:               minD[j_] :=        Module[{},         t = Table[{randPts[[i]],                    Sqrt[(randPts[[j, 1]] - randPts[[i, 1]])^2 + (randPts[[j, 2]] -                       randPts[[i, 2]])^2]},                   {i, 1, Length[randPts]}];              For[i = 1, i < Length[t] + 1, i++,            If[t[[i, 2]] == RankedMin[t[[All, 2]], 2],              coord[j] = t[[i, 1]] ]];         Return[{coord[j]}];       ];      This module takes the table of distances and picks out ones that are within the chosen bonding radius (1.5 here. the `y>0` condition to so to not count the same site):                 cluster[k_] :=          Module[{},           minD[k];           Return[             Table[Cases[t, {x_, y_} /; y < 1.5 && y > 0][[i]][[1]],                    {i, 1, Length[Cases[t, {x_, y_} /; y < 1.5 && y > 0]]}]];         ]      So `cluster[k]` gives the sites within the cluster that is centered at site `k`. Now combining these clusters is what I am having a problem with. My idea was to start with a site and its cluster; find out what clusters that cluster intersects with and continue. I was not able to implement this correctly. Another way to visualize or maybe solve the problem is in terms of increasing the site radius at each site until a percolation network is achieved:                randMovie =         Manipulate[         ListPlot[randPts,              PlotStyle -> {PointSize[x]},              PlotRange -> {{-10, 10}, {-10, 10}}, AspectRatio -> 1,              Frame -> True],          {x, 0.00, 0.12, 0.002}]      ![enter image description here](http://i.stack.imgur.com/gMV87.png)


Trying to solve a trig identity

Given $\sin 2x+\sin x=1$, find the value of $\cos 2x+\cos 4x$. I know $\cos 2x+\cos 4x \implies 1-2\sin^2x+1-2\sin^22x$, but didn't get the answer.


Precision differences

I run this sum and get the symbolic answer below :               Sum[ (1/(k^2 - k) - 1/k^2), {k, 2, Infinity}]      > $2 - \frac{\pi^2}{6}$ I look up the sequence on OEIS and find these digits:               RealDigits[ N[ 2 - Pi^2/6, 105]]      > {{ **3, 5, 5, 0, 6, 5, 9, 3, 3, 1, 5, 1, 7, 7, 3, 5, 6, 3, 5, 2, 7, 5, 8, 4, > 8, 3** , 3, 3, 5, 3, 9, 7, 4, 8, 1, 0, 7, 8, 1, 0, 5, 0, 0, 9, 8, 7, 9, 3, > 2, 0, 1, 5, 6, 2, 2, 6, 4, 4, 4, 1, 7, 7, 0, 6, 2, 9, 9, 9, 2, 5, 2, 9, 5, > 9, 6, 7, 9, 9, 1, 2, 6, 1, 6, 6, 3, 7, 1, 0, 9, 9, 3, 8, 0, 2, 4, 1, 2, 9, > 4, 6, 9, 5, 9, 9, 5}, 0} When I try to replicate those digits, I get some differences at the 27th digit.               RealDigits[ NSum[ (1/(k^2 - k) - 1/k^2), {k, 2, Infinity},     WorkingPrecision -> 105]]      > {{ **3, 5, 5, 0, 6, 5, 9, 3, 3, 1, 5, 1, 7, 7, 3, 5, 6, 3, 5, 2, 7, 5, 8, 4, > 8, 3** , 2, 1, 5, 3, 5, 8, 4, 4, 8, 1, 8, 6, 0, 5, 0, 6, 9, 8, 9, 7, 9, 3, > 3, 4, 8, 2, 1, 4, 0, 3, 2, 9, 8, 8, 0, 8, 5, 6, 2, 7, 0, 3, 0, 0, 8, 1, 8, > 8, 4, 1, 0, 2, 5, 2, 8, 6, 3, 7, 0, 7, 4, 1, 8, 9, 3, 1, 3, 7, 3, 4, 0, 4, > 0, 3, 0, 3, 2, 3, 5}, 0} So, which is correct ? The symbolic sum or the NSum? **Edit** I tried with a plus between the two sums, which returns `Zeta[2]` and I get the same variances starting at the $28$-th digit.


Difficulties in creating strict and robust equivalence between two symbols using the Notation package

I am investigating the use of the `Notation` package facilities to create strict the equivalence between pretty-printed symbols such as `OverBar[SuperStar[af]]` that formats as $\overline{af^*}$, and easy to type (but hard to read) symbols such as `afstarbar`. My issue is that I fail at making two such symbols strictly equivalent. **I would like that** , after typing `Notation[ParsedBoxWrapper[\[Beta]]\[DoubleLongLeftRightArrow]ParsedBoxWrapper[beta]]`, I get the following behavior:                In[] beta = 3      Out[] 3           In[] \[Beta]      Out[] 3           In[] \[Beta] = 0      Out[] 0           In[] beta          Out[] 0           In[] beta = 4      Out[] 4          In[] Information[beta]      Out[] \[Beta]           \[Beta] = 4      It is to be noted that with Mathematica 8.0.0.0, the Notation behaves differently on Windows and Linux and on Mac, as I figured out by starting this reddit discussion, but on all platforms, I could not manage to get assignments to one symbol propagate to the other symetrically. **The behavior that I get instead** of the above is:                In[] beta = 3      Out[] 3           In[] \[Beta]      Out[] 3           In[] \[Beta] = 0      Out[] 0           In[] beta          Out[] 3           In[] beta = 4     Out[] 4          In[] Information[beta]      Out[] \[Beta]           \[Beta] = 4      Is there a way to get the scrict and robust equivalence between symbols instead of the assymetrical behavior shown above?


Continuous evaluation of complex calculations

When having a first look at some system, it's often very useful to just play with the parameters and see how it develops. Therefore, I would like to let a certain evaluation run "until I cancel it". Take a nonlinear differential equation for example, say the Duffing oscillator, $\ddot{x} + \delta \dot{x} + \alpha x + \beta x^3 = \gamma \cos (\omega t)$, and try to investigate when the solutions start to become different when you alter the initial condition of the one evaluation by 1/1000. ![Duffing oscillator with a very small bump at t=20.](http://i.stack.imgur.com/OIW5Y.png) I'd like to `NDSolve` this system, with the ability to look at the current state while doing so. Note that this was only an example, the answer does not necessarily have to be constrained to `NDSolve`. Another example would be a cellular automaton that one observes until a certain pattern emerges in some region.


Manipulate evaluation sequence

`Manipulate` doesn't always evaluate in the order I expect it to. What is the evaluation sequence for `Manipulate` and other functions involved with the front end? I have seen the evaluation sequence for kernel only functions, but that was for a reference for Mathematica 3, and doesn't deal with the front end.


The space in default output of `ExportString` to Latex

# Are there any reasons for converting subscriptbox to Tex with space? * * *               ExportString[Subscript[\[Alpha], 1], "TeX"]          (*         %% AMS-LaTeX Created by Wolfram Mathematica 9.0 : www.wolfram.com\documentclass{article}\u     sepackage{amsmath, amssymb, graphics, setspace}\newcommand{\mathsym}[1]{{}}\newcommand{\un     icode}[1]{{}}\newcounter{mathematicapage}\begin{document}\[\alpha _1\]\end{document}     *)      Of course, I can remove the space in via the option "BoxRules", and `$\alpha _1$` can also rendered well in SE. But many people would edit my `$\alpha _1$` into `$\alpha_1$`, do you know whether there are any reasons for the default space generated by `ExportString`? The same to other boxes.


Flatten command: matrix as second argument

One thing I could never wrap my head around is how `Flatten` works when provided with a matrix as the second argument, and the _Mathematica_ help isn't particularly good on this one. Taken from the `Flatten` _Mathematica_ documentation:               Flatten[list, {{s11, s12, ...}, {s21, s22, ...}, ...}]      > Flattens `list` by combining all levels $s_{ij}$ to make each level $i$ in > the result. Could someone elaborate on what this actually means/does?


Make fraction with selection in denominator

Using `ctrl``/` you can make a fraction. If you have selected something it will appear in the numerator. Does there exist a shortcut to make the selected text appear in the denominator instead? If not, is it possible to create a shortcut that does this?


Given two samples, how does LocationTest select its AutomaticTest?

How does `LocationTest` select its `"AutomaticTest"` when testing two samples? **Background** : A previous post poses a similar question but in that case the choice concerned a single sample. The question involving two samples is harder since the idiom apparently in use - using the significant level set for the overarching test to set significance levels for `"Normality"`, `"EqualVariances"` and `"Symmetry"` diagnostic tests - has more complex interactions and raises issues about the entire idiom (including for the family of hypothesis-testing functions - `VarianceTest`, `DistributionFitTest`, `IndependentTest` etc) while also suggesting certain usage guidelines. Note that the following applies two user-defined functions (both defined in the related post); `ShowSignificanceLevelThresholds` \- for showing those significant levels at which `LocationTest` changes its choice of `"AutomaticTest"` and the `"HighlightAutomaticTest"` option - for highlighting (in a the gray background) the selected `"AutomaticTest"`. First define two samples:               SampleA =        {17.375, 20.375, 20, 20, 18.375, 18.625, 18.625,         15.25, 16.5, 18, 16.25, 18, 12.75, 15.5, 18};          SampleB =        {23.5, 12, 21, 22, 19.125, 21.5, 22.125, 20.375,         18.25,21.625, 23.25, 21, 22.125, 23, 12};      Now find the significance level thresholds.               LocationTest[{SampleA, SampleB}, Automatic, {"TestDataTable", All},        "HighlightAutomaticTest" -> True] // ShowSignificanceLevelThresholds      ![enter image description here](http://i.stack.imgur.com/iz3yS.jpg) Similar to the single sample case, Normality of now both samples affects the test chosen and hints at the generation of the first threshold               Row[{       DistributionFitTest[SampleA, Automatic,          {"PValueTable", All},"HighlightAutomaticTest" -> True],       Spacer @ 50,       DistributionFitTest[SampleB, Automatic,         {"PValueTable", All},"HighlightAutomaticTest" -> True]     }]      ![enter image description here](http://i.stack.imgur.com/EfgLB.jpg) Perhaps, the normality of the second sample is being assumed for significance levels less than 0.016 as when the overarching significance level is passed down to the `PearsonChiSquare` normality test it is halved to correspond to the extra evidence required (the number of tests being effectively doubled due to the two samples)? As for the other transition point, 0.826, `"EqualVariance"` and `"Symmetry"` are likely to be involved. As far as `"EqualVariance"` is concerned, the same threshold analysis can be performed.               VarianceTest[{SampleA, SampleB}, Automatic, {"TestDataTable", All},        "HighlightAutomaticTest" -> True] // ShowSignificanceLevelThresholds      ![enter image description here](http://i.stack.imgur.com/UpDFb.jpg) Now disentangling becomes trickier - bear in mind that the `"EqualVariance"` test presumably used by `LocationTest` presumably uses the passed-down significance level to presumably both select the test assessing an assumption and to determine its outcome - by comparing this (adjusted) significance level with one of the tabled p-values above. Furthermore, `VarianceTest` presumably applies its own tests of normality so how this interacts with `LocationTest`'s own normality test and selected significant values rapidly renders rabbit- warren-like - and this is even before factoring in (undocumented?) tests of `"Symmetry"`. Furthermore, in the last transition significance value, 0.016, doesn't change `Conover` as the chosen `"AutomaticTest"` but rather those "appropriate" or "applicable" (plausible?) tests - but under exactly what criteria does a test become "appropriate" or "applicable"? According to the documentation `"LocationTest"` chooses all tests that apply ..." suggesting `"AutomaticTest"` as the most powerful, applicable test and implying the nub of the post's question a more general, "How does `LocationTest` select its _applicable_ tests?" In such a scenario the significance level further affects `"AutomaticTest"`'s selection since it impacts on relative powers between applicable tests (particularly for tests with large degrees of freedom and low significance levels such as, for example, with genome-wide association studies) further adding to the tangle. Apart from a lack of transparancy (surely impacting `LocationTest`'s prospects for use in published research?) there is something epistemologically suspect about this significance level inheritance that goes against the grain of NHST's logic. The point of a significance level is that it is sets a standard of evidence to be met in order to make a decision/accept an effect. The point of a p-value is that it constitutes this evidence - a measure (probability) of the "extremeness" of a given experimental outcome. They are separate. This is the basis of their subsequent comparison: If the outcome is "sufficiently extreme" this apriori-decided standard of evidence is reached. The notion that a different significance level can change an outcome's p-value subverts this relationship and completely alters the methodology's logic while setting up convoluted dependencies inimical to repeatability, intuitive understanding and natural invocation - all fundamental tenets of scientific practice. Ultimately however, this is not a function of Wolfram Language's design per se nor does it superficially follow from the specific decision to link the significance level of diagnostic tests` significance levels; it is instead, an inevitable consequence of the decision to adopt formal, diagnostic tests for assessing such assumptions (or, as some have argued, the inherent incoherence of the NHST paradigm itself). This changes the definition (and perception) of Type 1 and Type 2 errors including for example when a t-test is selected: ![enter image description here](http://i.stack.imgur.com/KSwca.jpg) This approach has long been regarded as highly problematic as far back as 19441 and with plenty of empirical evidence emerging since2-5 and yet ... for example, > Preliminary tests of equality of variances used before a test of location > are no longer widely recommended by statisticians, although they persist in > some textbooks and software packages.3 In particular, it is used in SPSS, SAS and Statistica although seemingly, studiously eschewed in R. The Wolfram Langugage apparently adopts this strategy of the former group and despite the above inherent complications and conventional criticism just outlined, the concerns can perhaps be ameliorated (albeit IMO not in "natural usage" of the current implementation) while retaining certain advantages. More specifically, balancing Type I/II errors in many ways represents a theoretician's mirage resting as it does on distributional assumptions requiring judgement in the real world. The problems flowing from replacing this judgement with automatic computation in diagnostic tests are well made by numerous researchers but what they also consistently fail to do is demonstrate the superiority of the alternative (or any hybrid thereof): > In practice we conclude that graphical diagnostics are better than a formal > pretest.2 How so? That the shortcomings of a formal pretest can be analyzed, quantified and demonstrated fails to imply bettter outcomes from a vaguely defined and never-measured alternative. Hence, `LocationTest` has scope for improvement and attempting to tap into its test-choosing machinations is, I'd argue, far from idle spelunking; it's directly related to reproducibility concerns plagueing NHST as a scientific methodology virtually since its inception. In its current incarnatation, `LocationTest` is already useful in terms of suggesting relevant and powerful tests and for providing overviews but IMO caveats are needed for its routine usage: 1) Caution is needed in using its defaults as currently implemented - instead it may currently be more prudent to manually set assumptions via `"VerifyTestAssumptions"` option (surely a more natural, and in the light of the above, emphasised distinction would include a dedicated `"SetTestAssumptions`" option?) 2) If manually setting assumptions, confirm the logic dovetails with the automatic test chosen as described in the literature. Improvements would therefore see the significant values of diagnostic tests demonstrably preserving both meaningful diagnostics and overarching Type 1 and Type 2 errors (at least to a point where feasible and in particular in a more refined way than `" ... using \[Alpha]/k where k is the number of datasets being tested."` or alternatively when not feasible having an option to set these levels separately) while having the logic used to select automatic and applicable tests made much more transparent. These changes would not only satisfy Frequentists in this NHST implementation but also lay the groundwork for a casting/translation more amenable to Baysians (in a way beyond this post's scope). This would require an extension of the language - in particular of the input types and generated `"HypothesisTestData"` object as part of resolving multiple design tensions: human judgment vs machine determinations; smallest possible functional unit vs increasing functional scope; command-line vs object-like input & output etc all of which, albeit in a different guise, similarly (and perhaps even more pervasively) arise in more general data science invocations ... but this post digresses. ![enter image description here](http://i.stack.imgur.com/GSTqC.jpg)


Is there a PrimeQ whose accuracy guarantee you can adjust?

Say I have a list of a million integers each with a million digits, and I want a crude sieve to see which have a chance at being prime. Mathematica has a PrimeQ function, which appears to be slow because it performs a large number of trials of Miller-Rabin's primality test and the Lucas primality test before giving a Yes/No answer. Now I could try looking at small factors first, but say this only removes a small fraction of my list. Is there a way to turn down the certainty of PrimeQ, or are there other, faster, tuneably-cruder ways to test for primality within _Mathematica_?


Is there a way to use pause in Manipulate?

Is there a way to do any similar to               Do[Print["Iteration...", j]; Pause[1], {j, 1, 6}]      with `Manipulate`? (to show the evolution of each iteration slowly) What I have viewed is all with `Table`, and all the data is showed without no pause. Using `Pause[1]` or wating for `"click a button or to press any key"`. I was trying               Manipulate[Do[Print["Iteration...", j];   Pause[1], {j, 1, 6}],                {{k, 5}, {2, 3, 4, 5, 6, 7, 8}}]      or similar things with `Row`, `Column`, `Style`,... but... no success!


Cluster integration: Problem connecting to Sun Grid Engine

I'm trying to launch some kernels in a cluster engine running _Sun Grid Engine_ using _Cluster integration_. But I'm getting the error "Cannot find components required for SGE".               Needs["ClusterIntegration`"]     kernels = LaunchKernels[SGE["server", 16]]      > SGE::load: Cannot find components required for SGE. >> I doubt this is an error in the cluster side, as I get the same error regardless if I point to the correct server host name or not, so I think it fails locally (Mathematica 9.0.1.0) Also the documented option "Timeout" doesn't seems to exist, and the option "NetworkInterface" does not explain how to specify the interface..               Options[SGE]      > {"EnginePath" -> "/usr/local/sge/sge_root", "KernelOptions" -> "-subkernel > -mathlink -LinkMode Connect -LinkProtocol TCPIP \ -LinkName `linkname`", > "KernelProgram" -> "/usr/local/Wolfram/Mathematica/7.0/Executables/math", > "NativeSpecification" -> "", "NetworkInterface" -> "", "ToQueue" -> False} Any help would be appreciated.


Dataset with no members

I am trying to plan a framework for relational algebra using the Dataset capability of Mathematica 10. In the work of Date and Darwen, there are two concepts known as TABLE_DEE and TABLE_DUM. TABLE_DEE is a relation with a (column) header but no rows, whereas TABLE_DUM is simply: Dataset[{}] How might I create a TABLE_DEE with Dataset--a table with headers, but no data? I feel this would allow a framework for performing orthodox relational database operations.


Badly conditioned matrix (General::luc)

With some matrices I am receiving the following message > >     Inverse::luc Result for Inverse of badly conditioned matrix (M) may > contain significant >     numerical errors. >   How can I tell to _Mathematica_ to isolate (or detect) that result (or badly conditioned matrix)? For instance, using the `If` statement, which _condition_ should I put into the argument of `If` statement when my matrix is badly conditioned? P.S. Some advice to tackle with these kind of matrices would be good.


Data structures sought for storing particular list information

I have a set of lists. These lists contain two dimensional coordinates of natural numbers. So a list can be                list1 = {{1, 1}, {1, 2}, {3, 4}}       list2 = {{3, 6}, {5, 5}}.        In each step of the calculation a list can disappear, can grow, can diminish, new lists can appear and so on. I want for some points, elements of the lists, say for example {3, 3} to do bookkeeping to see in which list it is contained in every step of the calculation. It can be contained in one and only one list or in no list at all. So I want to do bookkeeping for {3, 3} in the sense that I want to know exactly at every step in which list it is contained. For example               bookkeeping[ {3, 3}] = {list2, list5, list3, none}       which says that at the first step {3, 3} is in list2, at the second step {3, 3} is in list5, at the third step {3, 3} is in list3 an at the last step it is in none of the lists. I have not the faintest idea how to do it. Should I define a bookkeeping[] function with downvalues? Or what is an elegant way to deal with it? What is the most elegant data structure I can use for such kind of bookkeeping?


Resolving Error: Mathematica evaluation order on Lists

I have a table that is 27 x 27, each entry corresponds to an element from the periodic table. I use the replacement rules in element list to allow me to convert a list of elements into a list of coordinates, so that I can access values from the table. Here test is a list of elements whose values I want to access. The function getBigSeg returns {0,0} if the core == shell, and otherwise returns the value from the table.               bigSegTable = Table[i + j, {i, 27}, {j, 27}];     getBigSeg[core_, shell_] :=       If[core == shell, {0, 0}, {bigSegTable[[core, shell ]] ,         bigSegTable[[core, shell]]}]         elementList = {"Sc" -> 1, "Ti" -> 2, "V" -> 3, "Cr" -> 4, "Mn" -> 5,         "Fe" -> 6, "Co" -> 7, "Ni" -> 8, "Cu" -> 9, "Zn" -> 10, "Y" -> 11,         "Zr" -> 12, "Nb" -> 13, "Mo" -> 14, "Tc" -> 15, "Ru" -> 16,         "Rh" -> 17, "Pd" -> 18, "Ag" -> 19, "Hf" -> 20, "Ta" -> 21,         "W" -> 22, "Re" -> 23, "Os" -> 24, "Ir" -> 25, "Pt" -> 26,         "Au" -> 27};          test = {{"Ti", "Ag"}, {"Zr", "Ag"}, {"Nb", "Ag"}, {"Tc", "Ag"}, {"Ru",          "Ag"}, {"Ag", "Ag"}, {"Hf", "Ag"}, {"Ta", "Ag"}, {"Re",          "Ag"}, {"Os", "Ag"}, {"Ir", "Ag"}};      I want to know why if I do: getBigSeg[#1, #2] & @@@ test /. elementList I get an error. But I do not get an error if I do                   getBigSeg[#1, #2] & @@@ {{2, 19}, {12, 19}, {13, 19}, {15, 19}, {16,         19}, {19, 19}, {20, 19}, {21, 19}, {23, 19}, {24, 19}, {25, 19}}      This is strange to me because               test /. elementList      gives               {{2, 19}, {12, 19}, {13, 19}, {15, 19}, {16,         19}, {19, 19}, {20, 19}, {21, 19}, {23, 19}, {24, 19}, {25, 19}}      So I do not understand why I am getting an error, and what is different between the two expressions.


Make the y-axis of a plot be in terms of an arbitrary parameter instead of a number?

Sorry if the title is wordy. Basically what I am asking would probably be easier if I just use an example. Say I wanted to plot f(x) = Asin(x) and have the graph come up with the sine function, and then the tics on the y axis be like half integer multiples of A. What I have been doing for my homework assignments is just plotting f(x)=sin(x) and then turning off the ticks and manually adding my ticks. It would be really cool if mathematica could do this for me.


Equivalence under common permutations

I have lists which consists of sublists of equal length. The outer list is regarded as a multiset (that is, permutations of the sublists don't matter, but repetitions do), but the order in the sublists _does_ matter, except that if the _same_ permutation is applied to each of the sublists, it also doesn't matter. Now my problem is that I want to write a function that tests whether two lists are equivalent under those rules. An obvious solution would of course be to generate all "inner" permutations for one set and seek the other one in there (the outer permutations can then, of course, be gotten rid of through sorting), but I feel there should be a simpler (and more efficient) solution. But I don't seem to be able to figure it out. To make some concrete examples, I'd like to get e.g. the following results:               equiv[{{1,1,1,2},{1,1,2,2},{2,2,2,2}},           {{2,1,1,1},{2,1,2,1},{2,2,2,2}}] == True      because you get the second from the first by exchanging the first and the last element in each sublist. On the other hand,               equiv[{{1,1,1,2},{1,1,2,2},{2,2,2,2}},           {{2,1,1,1},{1,1,2,2},{2,2,2,2}}] == False      because there's no _common_ permutation which transforms the first to the second. Of course I also want               equiv[{{1,1,1,2},{1,1,2,2},{2,2,2,2}},           {{1,1,2,2},{2,2,2,2},{1,1,1,2}}] == True      because here only the sublists are permuted in the outer list. And also,               equiv[{{1,1,1,2},{1,1,2,2},{2,2,2,2}},           {{2,1,2,1},{2,1,1,1},{2,2,2,2}}] == True      because this just combines a permutation of the sublists with a _common_ permutation of the elements in each list. So what is the best way to write this `equiv` function above?


Can I read Chinese characters with ReadList correctly?

Just try this example:               Export["a.txt", "这乱码问题该怎么解决呢\n***\n怎么解决嘛"]     ReadList["a.txt", Record]      > >     {"è¿ä¹\[PlusMinus]ç é®é¢è¯¥æä¹è§£å\.b3å¢", "***", "æä¹è§£å\.b3å"} >   I know `Import` can handle it correctly:               StringSplit@Import["a.txt"]      > >     {"这乱码问题该怎么解决呢", "***", "怎么解决嘛"} >   But `ReadList` is generally much faster, right? Well, after scanning this post and the links inside it I noticed that _Mathematica_ may be just not good at this, but still want to make sure if it's not possible.


Generate array of every $n^{th}$ integer between two bounds

I want to generate the series `{1930, 1934, 1938, ..., 2014}` with _Mathematica_. I found that I can use `Sum[2014-m*4, {m, 20}]` to get the sum of these numbers, so I tried `Array[2014-m*4, {m, 20}]`, but no luck. How do I do this?


How to output Mathematica Lists as a Table to a file?

Given the following List:                 lis =  { {-2.8336, -1.1088, -0.1232, 1.23493}, {-2.8336, -1.1088, 0.1232,            1.08433}, {-2.8336, -0.8624, -0.616,            1.04417}, {-2.8336, -0.8624, -0.3696,            1.10441}, {-2.8336, -0.8624, -0.1232, 1.17469}, {-2.8336, -0.8624,            0.1232, 1.09437}, {-2.8336, -0.8624, 0.3696,            1.43574}, {-2.8336, -0.8624, 0.616,            1.07429}, {-2.8336, -0.616, -0.8624,            1.26506}, {-2.8336, -0.616, -0.616, 1.43574} }      One can convert it to a table as follows: `lis//TableForm` But that just works for displaying it in _Mathematica_. How can one easily save that list to a text file so that it appears as a table?


Function definition and delayed assignment

I need to define the following function               MyWavelet[n_]["PrimalLowpass", prec_ : MachinePrecision] :=         Table[(-1)^(j - 1) h[[2*n - j]], {j, 0, 2*n - 1}]      which depends on the following code               num = T;     precis = 32;     p[n_, x_] := Sum[ Binomial[n-1+j,j]*x^j, {j,0,n-1}]     pol[n_, z_] := Expand[z^(n-1) * p[n, (1 - (z + 1/z)/2)/2]]     roo[n_] := NSolve[pol[n, x] ==0, x, precis]     absgreater[x1_, x2_] := Abs[x1] < Abs[x2]     sroo[n_] := Sort[roo[n], absgreater]     insidehalf[n_] := Take[sroo[n], n-1]          rootlist = x /. insidehalf[num];     prod = Expand[Product[(w - rootlist[[j]]), {j, 1, num - 1}]];     normalizer = prod 2^(num - 1/2) /. w -> 1;     polyn = Expand[(1 + w)^num * prod/normalizer];     h = Reverse[N[CoefficientList[polyn, w], precis]];      where T is an integer. My problem is I need to replace `num` with the value of `n` when calling the `MyWavelet` function and then dynamically evaluate, so I can get the `h` table values assigned to the specific `MyWavelet[n]`. I tried couple o'times using `With, but with no success.


Variable substitution in sum's index

How cam I simplify               Sum[UnitStep[-1 + n]/Sqrt[n!], {n, 0, ∞}]      to $$\sum _{n=1}^{\infty } \frac{1}{\sqrt{n!}}$$ and then to $$\sum _{n=0}^{\infty } \frac{1}{\sqrt{(n+1)!}}$$ I tried `Simplify` and `FullSimplify`, but neither of them worked.


Capture an image by non-default device

Guys! I need capture video from certain webcam which isn't `$DefaultImagingDevice`. As I know there is one legal way: `ImageCapture["Device"->$ImagingDevices[[x]]]` where x is number of needed device. However ImageCapture doesn't allow to make a grid on the image like this:               grid = Graphics[{Gray,         Table[Line[{{(i - 1)*16, 0}, {(i - 1)*16, 240}}], {i, 1, 21}],         Table[Line[{{0, (i - 1)*16}, {320, (i - 1)*16}}], {i, 1, 16}]         }];          Dynamic[Show[       CurrentImage[],       grid,       ImageSize -> 800]]      ![http://s18.postimg.org/hek0gtp2h/Camera_small.jpg](http://i.stack.imgur.com/XDXDQ.jpg) May be somebody knows how to apply CurrentImage for certain non-default imaging device? Or how to take just image without any interface elements using ImageCapture?


Export command in Mathematica trial version

_Mathematica_ trial version does not support `Export[]` command. Is there a command equivalent to `Export[]` in order to export, say, a matrix?


How do I keep my Animate running at high resolution?

I'm building an Animate where I have a 3D plot with some of its parameters changing: `Animate[SphericalPlot3D[Sin[(3/z)*x], x, y, PlotStyle -> Opacity[0.7]], {z, 1, 5}]` Whilst it is running through the changes though, the entire plot goes very low-res. How can I ensure that the resolution stays high throughout the animation, and not just when it stops running?


Return a local variable from a Module containing a Manipulate

I would like to create a set of custom controls that call Manipulate[] and return the value(s) set during the Manipulate session. I can easily make a version that uses something like:               MyControl[] := Manipulate[...{a, -10,10}, {b,-1,1}]      This works but variables a, b and any additional variables set by Manipulate are global. Is it possible to do something like this (Return a Dataset with the selected values for a and b when a "Set" button is clicked and Return Null if "Forget" is clicked):               MyControl[]:= Module[ {a, b},                           Manipulate[...{a, -10, 10}, {b, -1, 1},                                      Button["Set", Return[Dataset[Association @ {aValue->a, bValue->b}]]],     Button["Forget", Return[]]]]


JLink Get ALL output from a mathematica command

I have the following code (Java code using JLink).               String arguments = "-linkmode launch -linkname 'math -mathlink'";     KernelLink link = MathLinkFactory.createKernelLink(arguments);     String mathCommand = "applyState[processLRV,{{Q000847$JV$9198831378,Q000847$JV$9198831378.state},{{Null,Null},Null,\"<math><mn>16</mn><mi>p</mi><mo>+</mo><mn>25</mn><mi>p</mi><mo>=</mo><mn>1792</mn></math>\"}}]";     String output = link.evaluateToOutputForm(mathCommand, 0);     System.out.println(output);      If I run the command in **math** client I get the following output:               In[3]:= applyState[processLRV,{{Q000847$JV$9198831378,Q000847$JV$9198831378.state},{{Null,Null},Null,"<math><mn>16</mn><mi>p</mi><mo>+</mo><mn>25</mn><mi>p</mi><mo>=</mo><mn>1792</mn></math>"}}]                                                   General::aofil: HoldForm["Q000847$JV$9198831378.response"] already open as HoldForm["Q000847$JV$9198831378.response"].          OpenAppend::noopen: Cannot open HoldForm["Q000847$JV$9198831378.response"].          WriteString::strml: HoldForm[$Failed] is not a string, stream, or list of strings and streams.          General::stream: HoldForm[$Failed] is not a string, InputStream[ ], or OutputStream[ ].          OpenRead::noopen: Cannot open HoldForm["Q000847$JV$9198831378.state"].          General::stream: HoldForm[$Failed] is not a string, InputStream[ ], or OutputStream[ ].          General::stream: HoldForm[$Failed] is not a string, InputStream[ ], or OutputStream[ ].          General::stop: Further output of HoldForm[General::stream] will be suppressed during this calculation.          ToExpression::notstrbox: HoldForm[Read[$Failed]] is not a string or a box. ToExpression can only interpret strings or boxes as Mathematica input.         {{Q000847$JV$9198831378 . state, "reProcessLRV"}, Null, {{Null, Null}, Null, Null}, FullForm["unrecognized syntax Q000847[(16Users`p) + (25Users`p) == 1792]\n"], Null}          General::aofil: HoldForm["Q000847$JV$9198831378.response"] already open as HoldForm["Q000847$JV$9198831378.response"].          OpenAppend::noopen: Cannot open HoldForm["Q000847$JV$9198831378.response"].          WriteString::strml: HoldForm[$Failed] is not a string, stream, or list of strings and streams.          Out[3]= {{Q000847$JV$9198831378 . state, reProcessLRV}, Null, {{Null, Null}, Null, Null}, "unrecognized syntax Q000847[(16Users`p) + (25Users`p) == 1792]\n", Null}      But from my app I just get Out[3] text:               {{Q000847$JV$9198831378 . state, reProcessLRV}, Null, {{Null, Null}, Null, Null}, "unrecognized syntax Q000847[(16Users`p) + (25Users`p) == 1792]\n", Null}      How can I get the text between In[3] and Out[3] using Java code? Hope it makes sense! :)


Selecting items in a list based on multiple tests

I have an array of strings that look like this:               list = {{valueA1, valueB1, valueC1, valueD1, valueE1, valueF1, valueG1, valueH1}, {valueA2, valueB2, valueC2, valueD2, valueE2, valueF2, valueG2, valueH2}, {valueA3, valueB3, valueC3, valueD3, valueE3, valueF3, valueG3, valueH3}, ...}      I'd like to prune the list so that I generate some `selectedItemsList` which contains only the entries where some select set of (`valueA...` through `valueH...`) pass some test. For example, `valueB...` and `valueH...` could be real numbered values, and I'd like to only put entries in list when its the case that, for some entry `k` we have `1 < valueBk < 3` && `-10 < valueHk... < 5` and so forth. If `list` has millions of entries, so maybe we don't want to go through the list in multiple passes, what is the most efficient way to perform this selection?


What can I do to eliminate the error FindFit::nrjnum:?

I am testing the "Power Law with finite-time singularity" hypothesis for world population growth for a project. The data I'm using (same behaviour should also be exhibited by the stock market, thats why I am trying this with financial data):               raw = FinancialData["GE", All];     fraw = Flatten[raw];     data = Table[fraw[[4*i]], {i, 1, Length[raw]}]; (*extracting just the prices*)      I was trying the following regression model:               model = A + B*(c - x)^z;      And then the following curve fit method:               FindFit[data, {model}, {A, B, c, z}, x]      But I always get the result: > Power::indet: "Indeterminate expression 0.^0. encountered." FindFit::nrjnum: > "The Jacobian is not a matrix of real numbers at {A, B, c, z} = {1., 1., 1., > 1.}. " > > {A -> 1., B -> 1., c -> 1., z -> 1.} If I do a normal Power law regression, `FindFit` works perfectly, but the title of the project being "Power Law with finite-time singularity" I need to have the singularity `c` in the model and the main aim is to find when this singularity occurs. Is there a way to use `FindFit` to get the correct answer? Or should I be using some other function? I have seen other articles on this site concerning issues with `FindFit`, but none of them has helped me resolve this problem. Remark: I have already tried the version belisarius has stated below, but the problem with that is that it gives me a `z > 0`. What I need is `z < 0` for `x = c` to be a singularity. So I also tried the following models: `A + B*Abs[c - x]^(-z)` and `A + B*(c - x)^(-z)` with `-z` instead of `z` but those just gave me like 15 other warnings.