Compile with array operations

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


Combinatorica Graph from Edge List

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


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

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


Derivative of the solutions by parameter

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


Seeing the whole financial chart

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


make specific cluster

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


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

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


Numerical Fourier transform of a complicated function

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


Faster simplification of linear combinations of some specific functions

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


Detect Standalone CDF vs Browser Plugin environment

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


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

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


Multivariate Function Approximation With a Large Dataset

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


Dark artifacts in mathematica plot

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


Import selected columns from a tab delimited text file

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


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

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


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

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


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

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


Solving a system of linear equations modulo n

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


Sorting lists with elements that are identical

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


How do I avoid scoping collisions of iterator variables?

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


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

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


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

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


Expanding a polynomial with fractional powers

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


Algorithm used by IsomorphicGraphQ

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


Unable to solve a set of equations with Solve

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


Export to Google Spreadsheet with OAuthAuthentication

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


How to make brute force coding more efficient?

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


Change values in equation with slider

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


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

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


Game theory packages

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


Obtain Data points from a graph on an image without axes

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


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

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


Array of functions, evaluation in plot

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


Timing differences between multiple executions of identical code

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


Accessing MathematicaScript over ssh/network

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


How to track dynamically generated manipulators?

In the code below the manipulators that are generated from the stakes buttons are not tracked by the `Manipulate` expression that contains them. How can I make the plot update with these sliders? If I add 'stakeWeights' and 'roi' (the values of the manipulators) to the tracked symbols, the manipulators won't move. My apologies for posting the complete code but I couldn't find an easy way to isolate this from the rest of the code.               RandomWalk[n_, roi_, bi_, rake_] :=      (*If errors return list with zero so ListPlot does not complain *)      Quiet@Check[(pwin = bi (1 + roi)/(2 (bi - rake));          NestWhileList[# + RandomChoice[{pwin, 1 - pwin} -> {1 - 2 rake/bi, -1}] &,            0, True &, 0, n]),          {0}]          trial = 0;     allStakes = {1.5, 3.5, 7, 15, 30, 60, 100, 200, 300, 500, 1000};     rakes = {0.06, 0.1, 0.15, 0.31, 0.63, 1.26, 1.88, 3.34, 4.49, 6.65, 11.2}     MapIndexed[(rakebyStake[#1] = rakes[[#2]]) &, allStakes]              Manipulate[trial;      data = RandomWalk[nrTournaments, avgROI/100, avgBI, avgRake];      (stakeWeights[#] = 100) & /@ allStakes;      (roi[#] = 1) & /@ allStakes;      avgBI =        Quiet@Check[         Total[(# stakeWeights[#]/Total[stakeWeights /@ stakes]) & /@             stakes // N], 0];      avgRake =        Quiet@Check[         Total[(rakebyStake[#][[1]] stakeWeights[#]/                Total[stakeWeights /@ stakes]) & /@ stakes // N], 0];      avgROI =        Quiet@Check[         Total[(roi[#] stakeWeights[#]/Total[stakeWeights /@ stakes]) & /@             stakes // N], 0];      biWon = Quiet@Check[Last[data], 0]; dollarWon = biWon avgBI;       pwin = Quiet@Check[avgBI (1 + avgROI/100)/(2 (avgBI - avgRake)), 0];      expectedBiWon =        Quiet@Check[((1 - 2 avgRake/avgBI) pwin - (1 - pwin)) nrTournaments, 0];      expectedDollarWon = expectedBiWon avgBI;      sampleROI = Quiet@Check[dollarWon/(nrTournaments avgBI), 0];      Dynamic@ListPlot[data, Joined -> True, PlotStyle -> {RGBColor[0, 0.2, 0.6]}],       {{nrTournaments, 3000, "tournaments"}, 0, 100000, 100, Appearance -> "Open"},      {{stakes, {60}, "stakes"}, allStakes, ControlType -> TogglerBar},      Dynamic[Column@{Grid[({#,               Manipulator[Dynamic[stakeWeights[#]], {0, 100, 1}],               Dynamic[Quiet@                Check[100 stakeWeights[#]/                   Total[stakeWeights /@ stakes // N], 0]],              "ROI",               Manipulator[Dynamic[roi[#]], {0, 75},                Appearance -> "Labeled"]}) & /@ Sort[stakes]]}],      {{avgROI, 1.5, "avg ROI (%)"}, 0, 75, 0.01, Appearance -> "Open"},       {{avgBI, 60, "avg BI ($)"}, 0, 10000, 1, Appearance -> "Open"},           {{avgRake, 1.26, "avg rake ($)"}, 0, avgBI/10, 0.01, Appearance -> "Open"},           {{rakeback, 37, "rakeback (%)"}, 0, 100, 0.01, Appearance -> "Open"},           Delimiter,           Panel[Grid[{{Dynamic[               Row[{"sample ROI: ",                  Style[ToString[sampleROI 100] <> "%",                   If[sampleROI >= 0, Darker[Green], Red]]}]]}, {Dynamic[               Row[{"# BI won: ", ToString[biWon], " (",                  Style["$" <> ToString[dollarWon],                   If[dollarWon >= 0, Darker[Green], Red]], ")"}]]},             {Dynamic[               Row[{"rakeback: ",                  Style["$" <> ToString[avgRake rakeback/100 nrTournaments],                   Darker[Green]]}]]}, {Dynamic[               Row[{"$ won after rakeback: ",                  Style["$" <>                    ToString[dollarWon + avgRake rakeback/100 nrTournaments],                   If[dollarWon + avgRake rakeback /100 nrTournaments >= 0,                    Darker[Green], Red]]}]]},             {Dynamic[               Row[{"expected # BI won: ", ToString[expectedBiWon], " (",                  Style["$" <> ToString[expectedDollarWon],               If[expectedDollarWon >= 0, Darker[Green], Red]], ")"}]]}},         Alignment -> Left]],       Button["Run again", trial++, ImageSize -> Medium],       SaveDefinitions -> True,       TrackedSymbols :> {nrTournaments, avgROI, avgBI, avgRake, trial,         stakes, rakeback}]


Override @ to mock Java Classes

This question appears impossibly long so apologies in advance (skip to the bottom if you want to see the actual questions). I want to be able to mock Java Classes in _Mathematica_ code. For example, I may have a simple Java bean `Point` that has two fields `x` and `y`. Using JLink, I would interact with objects of the point class as:                   obj = JavaNew["java.awt.Point"]         obj@x = 22         obj@y = 42      There are countless ways that this could be done in _Mathematica_ but to mock (so I can later swap out the _Mathematica_ code with the actual Java classes) I'd like to be able to do something along the lines of                   obj = Point[0, 0]         obj@x = 22         obj@y = 42         obj == Point[22, 42] (* evals to True*)       I have taken two stabs at this. First using the Notation package and overriding the following type of expressions:               Notation[      ParsedBoxWrapper[        RowBox[{RowBox[{"obj_", "@", "field_"}], "=", "val_"}]] [DoubleLongLeftRightArrow]          ParsedBoxWrapper[           RowBox[{"ApplySet", "[", RowBox[{"obj_", ",", " ", "field_", ",", "val_"}], "]"}]]      The above maps code like                   obj_@field_ = val         obj@x = -99    (* for example *)      to                   ApplySet[obj_, field_, val_]         ApplySet[obj, x, -99]   (* for example *)      `ApplySet` in turn is redirected to either a setter on the "class" or passed through to the usual _Mathematica_ handling on the basis of a conditional evaluation that checks that `obj` is a "class" or not.                    ApplySet[obj_, field_, val_] := set[obj, obj, field, val] /; MBeanQ[Head[obj]]          (* pass obj through twice, once in HoldFirst the second evaluated as the data *)          (* otherwise just pass through to normal handling for the Prefix @ *)          ApplySet[obj_, field_, val_] := obj[field] = val      This approach works well in the FrontEnd and it seemed to be able to do everything I needed and more. However, when I moved this to packages the `Notation` and related `MakeExpression`/`MakeBoxes` doesn't seem to work. I did use `Action -> PrintNotationRules` to get the the underlying `NotationMakeExpressions`/`NotationMakeBoxes`. For example, here is the `NotationMakeExpressions`:               NotationMakeExpression[       RowBox[{Notation`Private`lhs___,          RowBox[{obj_, "@", field_}], "=", val_,          Notation`Private`rhs___}], StandardForm] :=        MakeExpression[RowBox[{Notation`Private`lhs,          RowBox[{"ApplySet", "[",            RowBox[{obj, ",", field, ",", val}], "]"}],          Notation`Private`rhs}], StandardForm]         My second crack was to override the behaviour of `Set` and redirect in a similar way, testing for a "class". For example:               Set[obj_[field_], val_] := CallSet[obj, obj, field, Null, val] /; CallSetQ[Head[obj]];     Set[obj_[field_[idx_]], val_] := CallSet[obj, obj, field, idx, val] /; CallSetQ[Head[obj]];     Set[obj_, fieldUpdates__List] := CallSet[obj, obj, fieldUpdates] /; CallSetQ[Head[obj]];      This approach works well enough in both the FrontEnd and in packages, but of course it requires overriding something pretty fundamental. Even setting aside the potential performance concerns, it just doesn't seem right. I'm sure that this is documentation somewhere but I couldn't find it. Are `MakeExpression` and `MakeBoxes` really Frontend functions that aren't available in kernel to packages? Is there a smarter way to do this?


Mathematica 9 cannot solve this Integral. Mathematica 8 could. Is this a bug?

I was trying to (re)calculate a problem of an older Wolfram blog post (Problem 11457, by M. L. Glasser) with Mathematica 9.0.0.0 (on OS X 10.8.2).               Assuming[0 < a < b, Integrate[ArcCos[x/Sqrt[(a + b) x - a b]], {x, a, b}]]      Instead of the expected solution, it just returns the integral unevaluated. Is this a regression? **More details:** As pointed out in the commentes, the indefinite integral               Integrate[ArcCos[x/Sqrt[(a + b) x - a b]], x]      still gives the same result in Mathematica 8 and 9. The next two each returned ConditionalExpression in Mathematica 8 but return unevaluated in Mathematica 9:               Integrate[ArcCos[x/Sqrt[(a + b) x - a b]], {x, a, b}]     Integrate[ArcCos[x/Sqrt[(a + b) x - a b]], {x, a, b}, Assumptions -> 0 <= a <= b]      The actual problem               Integrate[ArcCos[x/Sqrt[(a + b) x - a b]], {x, a, b}, Assumptions -> 0 < a < b]      computes correctly to `((a - b)^2 \[Pi])/(4 (a + b))` in Mathematica 8 but still returns unevaulated in Mathematica 9.


What ProcessEstimator Options can I use with FractionalBrownianMotionProcess

I can generate an fBm process:               tlow = 0;     thigh = 1;     len = Sqrt[thigh];     tinc = 0.01;     hurst = 0.4;     DataZ = RandomFunction[        FractionalBrownianMotionProcess[hurst], {tlow, thigh, tinc}, 1];     dataz = Flatten[DataZ[[2, 1]]];      In the following post: Computing the Hurst exponent or fractal dimension of fractional Brownian motion it is described that you can use FindProcessParameters to estimate the Hurst exponent:               FindProcessParameters[dataz, FractionalBrownianMotionProcess[h]]      The documentation says that you can use the ProcessEstimator options... but it does not say which one you can use... I am guessing that such options would be similar to Box counting, Takens estimator, etc. What are the ProcessEstimator options that can be used with FractionalBrownianMotionProcess?


How to work with Application Project files in Wolfram Workbench?

I have figured out that in a basic project I simply have to call the main package (m file) from the notebook using               <<nameofmfile`       and then the notebook recognizes the functions I defined in the m file and I can use these function in the notebook. Unfortunately when I do the exact same thing in an application project the notebook doesn't recognize the main package (m file). I can't find proper help with this - the Workbench help doesn't seem too useful to me. I have a feeling that this problem occurs because the main package is not in the same folder as the notebook in the case of application projects. Please help!


Deleting Print results

While playing around with `$Pre` and `$Post` I created this very annoying piece of code:               $Post = If[# =!=       Null, (Print@"Are you sure you want to know the result?";       Print@Row@{Button["Yes", Print@#], Button["No", Null]}), Null] &;      I have not yet found a use for it (other than possibly playing pranks on Mma newbies) but it led me to the following question: How can one delete a certain cell that was created by `Print` (i.e. without selecting the cell manually)? And furthermore, how can one create a button that deletes itself upon being clicked (still evaluating the action)? Ultimately I want the button to delete both itself and the `"Are you sure..."` cell. I found out in the documentation that `PrintTemporary` objects can be deleted using `NotebookDelete`. Is there a similar way for `Print` cells? I think something similar to what I want could be done using `ChoiceDialog` and the like, but I'm really interested in deleting the `Print` cells.


Representation of product with exclusions

Is there a nice way to define output formatting for my expression, a product from `n = k` to `j` with `n ≠ m`? I would like to use something like this here (however _Mathematica_ doesn't evaluate it): $$\prod _{n=k,n\neq m}^j \frac{\lambda _n}{\lambda _n-\lambda _m}$$ My work around at the moment is: (adopted from Sum or Product with Exclusions) $$\prod _n^{\text{DeleteCases[Range[k, j], m]}} \frac{\lambda _n}{\lambda _n-\lambda _m}$$


How to systematically classify Mathematica expressions? I can think of using `Head[]`, `Depth[]`, `Length[]`, and some special pattern based on the problems at hand. What other key words, or functions should I consider? ## Update I mostly want to group symbols by how nested its list are, and what kinds of elements the lists have. For example               {_String, _Symbol}          {{_Integer}, _String}          _String      would be considered _three_ distinct types.


How do I save the values in a table?

I have written the following sequence. ![Sequence written with mathematica](http://i.stack.imgur.com/Q1ZeB.png) I would like to save the resulting values in a table such that I have a list of all the values at the end the For loop. How do I proceed? My goal is to sum up all the values at the end. I would like the table to look as follows: ![sample result](http://i.stack.imgur.com/g9F7G.png)


Find an equations of motion using Euler Eqution

I am a completely new to Mathematica, so my question and code may look silly. I need to find a equation of motion of a point particle of mass m moving in a potential V(x) = A abs[x]^n. (n=1,2,3,4,5,6. m=1, A=1, x(0)=2, x'(0)=0 ) I tried to find the equation using Euler method, so I made code below. I know somethings wrong with my code, but I have no idea. How can I make one equation with various n values? Can someone help me?               T = 0.5*x'[t]^2;     V = Abs[x[t]];     L = T - V     -Abs[x[t]] + 0.5 Derivative[1][x][t]^2     EulerEquations[%, x[t], t]     -Derivative[1][Abs][x[t]] - 1. (x^\[Prime]\[Prime])[t] == 0     NDSolve[{x''[t] + Abs'[x[t]] == 0, x[0] == 2, x'[0] == 0}, x, {t, 0,10}]     NDSolve::ndnum: Encountered non-numerical value for a derivative at t == 0.`. >>      And, additionally I need to plot the period as a function of n. How can I construct the plot?


Put results in multiple columns for comparison

One thing I would like to do in many instances is arrange input/output in columns for comparison. I expect that I need to use `Grid` to do this, but have not been able to figure out the right commands. For example, if I have the following type of function and two different possibilities:               Table[GCD[fun1[c^a], fun1[c^b]], {a, 1, 3}, {b, 1, 3}, {c, 1, 3}]          Table[GCD[fun2[c^a], fun2[c^b]], {a, 1, 3}, {b, 1, 3}, {c, 1, 3}]      Here, I have two custom functions `fun1` and `fun2` which take multiple inputs over ranges (27 possibilities in all). I want the output to be rearranged so I have the following columns:               a, b, c, GCD[fun1[c^a], fun1[c^b]], GCD[fun2[c^a], fun1[c^b]], difference      In otherwords I want to see the combination of inputs being used in the leftmost columns, the ouptuts from the two possible expressions, one using fun1, the other using fun2, then optionally a final column showing the difference between the two possible outputs for each of the 27 possibilities. How can I do this?


How to show values of points on surface plotted with ContourPlot3D

The help for ContourPlot3D starts with this example               ContourPlot3D[x^3 + y^2 - z^2 == 0, {x, -2, 2}, {y, -2, 2}, {z, -2, 2}]      This returns a Plots of the surface $x^2 + y^2 - z^2 = 0$: ![Surface](http://i.imgur.com/Ff4Fg.jpg). Now I have a function, and I would like to know how this function behaves on this surface. For example, take               f[x_,y_,z_] := {x^3 - 2 x y + z^2 x - 5 z^2 y^2 - 4 x y z,                      Sin[10x] + Cos[5y] + Cos[20z]}      I was thinking of making a list with some of the point that lie on this surface. Then it is easy to evaluate the function on these points. The way I would like to generate the list is to click with the mouse on a few points that I think are interesting. Is that possible? What are the alternatives to using the mouse? There most be some list available with all points that were used to draw this graph. How can I take some point of that list and add them as point to the 3D plot to visualize them? **Update** The methods of Szabolcs and Heike work fine on the example $x^3 + y^2 - z^2 =0$. Now I try to apply the same to $$ 2316 a^{12} c^6+500 a^{11} b c^5+10296 a^{10} b^2 c^4+1624 a^{10} c^5+656 a^9 b^3 c^3- \\\ \- 3856 a^9 b c^4+41 a^8 b^4 c^2+808 a^8 b^2 c^3+784 a^8 c^4+a^7 b^5 c+24 a^7 b^3 c^2- \\\ \- 176 a^7 b c^3+2 a^6 b^4 c+16 a^6 b^2 c^2+32 a^6 c^3 = 0 $$               f[a_, b_, c_] := 2 a^6 b^4 c + a^7 b^5 c + 16 a^6 b^2 c^2 + 24 a^7 b^3 c^2      + 41 a^8 b^4 c^2 + 32 a^6 c^3 - 176 a^7 b c^3 + 808 a^8 b^2 c^3      + 656 a^9 b^3 c^3 + 784 a^8 c^4 - 3856 a^9 b c^4      + 10296 a^10 b^2 c^4 + 1624 a^10 c^5 + 500 a^11 b c^5 + 2316 a^12 c^6     pts = {};      Substituting this function into Heike's solution does not work. Clicking does not result in points on the surface. Also Szabolcs's FindInstance does not work. What goes wrong here? ![Surface 2](http://i.imgur.com/MbVql.jpg).


How to write output in TraditionalForm into external text files?

I'd like to write output in TraditionalForm into external text files `ofile.txt`. I tried to use               s = OpenWrite["/home/tigerhead/log/ofile.txt", FormatType -> TraditionalForm];     $Output = s;     <run various Mathematica programs>     Close[s];      but get errors:               Intersection::normal:         Nonatomic expression expected at position 2 in          Intersection[{StandardForm, TraditionalForm}, FormatType].     Options::optnf:         FormatType is not a known option for          Intersection[OutputStream[/home/tigerhead/log/ofile.txt, 21], {OutputStream[/home/tigerhead/log/ofile.txt, 20], OutputStream[stdout, 1],            OutputStream[stderr, 2], OutputStream[/home/tigerhead/<<38>>.txt,             21], stdout, stderr}].      Any one has a clue?


How to set precision and format labeled Slider in Manipulate?

For my calculations, I need increased precision of parameter 'k' in my Manipulate:               Manipulate[      Plot[Cos[k x], {x, 0, 2 Pi}], {{k, 1}, 0, SetPrecision[4.0, 22],        SetPrecision[0.100, 22], Appearance -> "Labeled"}]      However, at the same time, for aesthetic reasons, I want the label to the right of the slider to display only couple of digits. How this could be done?


Question about Solve

I don't understand what _Mathematica_ is doing to get these solutions. I ask it to solve two equations, the left hand side of both expressions are the same, the right hand sides differ by a ± sign. I really don't think the solutions should be the same, but that is what _Mathematica_ returns, without any comment.               FullSimplify[{       Solve[1/2 E^(-((2 I l π)/k)) (-(-1 + E^(I ((4 l π)/k + δ))) Sqrt[ρ] + Sqrt[-2 E^(I ((4 l π)/k + δ)) (-2 + ρ) + ρ + E^(2 I ((4 l π)/k + δ)) ρ]) == E^(2 π I m/n), ρ],        Solve[1/2 E^(-((2 I l π)/k)) (-(-1 + E^(I ((4 l π)/k + δ))) Sqrt[ρ] + Sqrt[-2 E^(I ((4 l π)/k + δ)) (-2 + ρ) + ρ + E^(2 I ((4 l π)/k + δ)) ρ]) == -E^(2 π I m/n), ρ]     }]      _Mathematica_ returns > >     { >       {{ρ -> (-1 + Cos[(4 m π)/n - δ])/(-1 + Cos[(4 l π)/k + δ])}}, >       {{ρ -> (-1 + Cos[(4 m π)/n - δ])/(-1 + Cos[(4 l π)/k + δ])}} >     } >   Can anyone can shed some light on this, please?


Assigning Variables for Degree Distribution

So my code is divided into 3 different sections: 1) Calculating clustering coefficient, 2) Extracting degree distribution 3) Using the degree distribution to get the mean of 1000 networks.               N[GlobalClusteringCoefficient[Graph[{1\[UndirectedEdge]2, 2\[UndirectedEdge]3, 3\[UndirectedEdge]1}]]]          VertexDegree[Graph[{1\[UndirectedEdge]2, 2\[UndirectedEdge]3, 3\[UndirectedEdge]1}]]          Output: {2,2,2}      Then:               N[Mean[GlobalClusteringCoefficient/@RandomGraph[DegreeGraphDistribution[{1,2,4,3,5}],100]]]      So, I am copying and pasting the degree distribution generated in the second line into the third part. Instead of doing that, is there a way to assign a variable so it is done automatically? E.g               x = VertexDegree[Graph[{1\[UndirectedEdge]2, 2\[UndirectedEdge]3, 3\[UndirectedEdge]1}]]          N[Mean[GlobalClusteringCoefficient/@RandomGraph[DegreeGraphDistribution[{x}],100]]]      Obviously, this won't work but the idea is I save time, instead of copying and pasting the result from the output, can I make a variable assignment that automates this process?


Fixing Spline curves so as to not overlap with themselves - (Diagrams)

**Statement of the problem:** Conceptually, what I'm trying to achieve is pretty simple. I have some code that generates a set of diagrams from a list of sets of points using BSplineCurve. Certain conditions cause some of these diagrams to come out differently from what I need. With SplineDegree -> 1 the images look like: ![Spline Degree 1](http://i.imgur.com/GYuGVsE.png) and with SplineDegree -> 3 the images become: ![Spline Degree 3](http://i.imgur.com/HWiz39T.png) The problematic cases are images a7, a8 and a9, which I need to look like: ![Correct Images](http://i.imgur.com/us3oI3r.jpg) The general rule is that I need closed smooth curves through the specified points, but the curve must not lie on top of itself when the points all lie on a straight line (I also need the curves to pass directly through the points, but this is another issue that is probably fairly easily solved - I've tried clamping without much success so far). I have tried to solve this problem by implementing clunky IF statements that add additional guide points, but in addition to the fact that I struggle to make it work, it's very undesirable, because I need this to generalize to more complicated diagrams. For example, here is a preview of the higher dimensional case (the full list is very long): ![Higher Dimension Sample](http://i.imgur.com/Wjrob3N.png) The last five images are problematic and should look like ![Correct Higher Dimension Sample](http://i.imgur.com/jUPO5g3.jpg) I have also considered using Graph to try and do this, but I'm not really sure where to start. **Code:** I can't provide the full code, because the process of generating the list of points is exceptionally long. Here is the section that is relevant:               Clear[\[Delta]ToBirdTrack1];     Options[\[Delta]ToBirdTrack1] = {Background -> White, Trace -> Tr,         Scale -> 1};     \[Delta]ToBirdTrack1[expr_, A_: a, B_: b,         options___Rule] := \[Delta]ToBirdTrack1[expr, A, B, options] =         Module[{l, s, aa, bb, h, res, res1, hsep, vsep, samesep, bgcolor,       trace, scale, split},          (* options *)     bgcolor = Background /. {options} /. Options[\[Delta]ToBirdTrack1];     trace = Trace /. {options} /. Options[\[Delta]ToBirdTrack1];     scale = Scale /. {options} /. Options[\[Delta]ToBirdTrack1];          hsep = 5;     vsep = 2;     samesep = hsep/6;     l = (expr //           Cases[#, Subscript[A,  i], Infinity, Heads -> True] & //          Union // Length);     h = l*vsep;          (*line 1*)     res = (expr /.            Tr[aa__] :> m[Line[(*Append[*)aa(*,First[aa]]*)]] //.           m[aa__] m[bb__] -> m[aa, bb]) /. UP -> Sequence /.        Subscript[t, i_] -> i;          (*line 2*)     res = res // (# /. m[aa__] :> (m[aa] /. a_Line :> pos /@ a)) &;          (*line 3*)     res // (# /.           Line[aa__] :>            BSplineCurve[{aa}, SplineClosed -> True]) & // (# /.          m[aa__] :> Graphics[{aa}]) &     ];          ExplicitList[NgI[2]] //        Sum[Subscript[\[Alpha], i] #[[i]], {i,       Length[#]}] & // \[Delta]ToBirdTrack1[#] &      I can't provide the data being put into this code, again because of length, but I can however show what it looks like. At "line 1" res is being shaped into this list: ![Algebraic List](http://i.imgur.com/GAxxEit.png) At "line 2" it is shaped into this list: ![Line object list of coordinates](http://i.imgur.com/b4ALCHC.png) And at "line 3" the "aa's" that are being considered by the Spline Curve plotting look like this: ![Coordinates](http://i.imgur.com/qpGouUF.png) Any and all help would be greatly appreciated, with the most general solution being the goal.


Mathematica function intersection points with 3D grid

I need to produce a 3-dimensional equispaced grid over a given function in a way, that I can calculate intersection points of the function with the grids edges. So my first question is how to produce this grid in Mathematica. I don't really get if this is possible by modeling the grid by `Polygon`s? For this I might need some help then, too. Or can it be done by using more simple graphics objects like done here?


Export Table from Mathematica into specific cells Excel

How can I export a table to Excel - to specific cells, e.g. D1-E2? Background: I want to compare results, and it's easier to have the results on one spreadsheet. I'm using _Mathematica_ 6. This is my notebook so far:               ResultsV = Grid[{  {"result1", result1},  {"result2", result2}}]      Export["results.pdf", ResultsV]      This table should appear twice in the spreadsheet, as some parameters differ. Thanks a lot!


Count consecutive occurrences in a list above a certain value

I am trying to tally and sort the number of consecutive occurrences in a list above a certain value. For instance:               data={55.5, 65.3, 100.3, 100.1, 100.5, 98.7, 75.2, 101.3, 102.1}      The totals for this data set would be {3,2} if the tally criteria were all values greater than 100. As I have worked on this problem, I found the following code:               a = RandomInteger[1, {100}];     Cases[Split[a], {1, ___}] // Tally // Sort      Which is very close to what I am trying to do. In this case, the code provides a sorted list of consecutive integers equal to one. However, I can't seem to modify the decision criteria to only tally values above a certain criteria. How might I go about this?


Function to differentiate between date pattern and specific string format

I'd like to write a function that behaves one way when the argument is a _Mathematica_ date, such as `{2013,12,15}`, or with added hours, minutes and seconds if necessary. And the function needs to do something different with strings that will look like > 2013 Month 02 I see that I can specify List, as in `f[x_List]` and `f[x_String]` that will do what I want as long as I don't mess up the arguments. Is there way to be more specific about the patterns that are allowed?


Create continuous function from list

I have a list of data (measured per day) that I want to use as imput for another equation (say f). The problem is that the input I need for f needs to be a continuous function of time. Is it possible to change my data into a function? I would either like a function that is linear increasing or decreasing between the different timesteps (like the line you get when you use `Joined` in `ListPlot`) or a stepwise function that immediately jumps to another value the next day. I tried using `Interpolate` but then when I measured 0, I get negative values which is not possible for my measured values. Hope someone could help me. Simplified example:               tmin=1;     tmax=6;     data = {{1, 3}, {2, 0}, {3, 0}, {4, 5}, {5, 7}, {6, 10}};     ListPlot[data, AxesLabel -> {"time(day)", "data(mm)"}, Joined -> True]          f = Interpolation[data];     Plot[Evaluate[f[t]], {t, tmin, tmax}]      If you evaluate this: the first plot is the result I would prefer for my function, the second plot is not what I want as the values drop below 0. ![enter image description here](http://i.stack.imgur.com/nxFAO.png)


Why does importing a URL fail the second time and produce a FetchURL::conopen error?

I have _Mathematica_ code that uses `Import[]` to download URLs. I noticed that first time I use the `Import[]` command it works. Next time it fails. I'm using Windows 7, Mathematica 8.0.4. Here is an example. I start new sesssion of _Mathematica_ , and then type               Import["http://groups.google.com/group/comp.soft-sys.math.mathematica/about"]      No problem. Now I issue the same command again on the same URL (or different one)               Import["http://groups.google.com/group/comp.soft-sys.math.mathematica/about"]      and now this gives me an error > FetchURL::conopen: The connection to URL > http://groups.google.com/group/comp.soft-sys.math.mathematica/about cannot > be opened. If the URL is correct, you might need to configure your firewall > program, or you might need to set a proxy in the Internet connectivity tab > of the Preferences dialog (or by calling SetInternetProxy). For HTTPS > connections, you might need to inspect the authenticity of the server's SSL > certificate and choose to accept it. On the same Windows 7 PC, I start MATLAB, and type               data=urlread('http://groups.google.com/group/comp.soft-sys.math.mathematica/about')     data=urlread('http://groups.google.com/group/comp.soft-sys.math.mathematica/about')      and both work. I get the page fine the second time around. I open the browser, and type the URL, and I can see the page. This is the same PC. No proxy. home PC. Nothing special. P.S. This code used to work fine with _Mathematica_ on an earlier version (forgot which one now), becuase I used _Mathematica_ to generate this web page and all the `Import` commands I used are listed above and you can see them. I have list of many URL's that I loop over calling `Import[]` on them one by one. Again, **the problem is that I now get an error on a URL using`Import[]` and the problem seems to show up the second time I use the `Import[]`.** Any suggestions how to fix this? Is this a known issue? **update** I still have _Mathematica_ 7 and 6 installed. So I tried this on them. And I get the same problem there. This is strange, since this code worked before. I think now it is a google groups/server problem, becuase when I try different domain (i.e. not google groups), I do _not_ get this problem               data = Import["http://www.yahoo.com", "Data"];     data = Import["http://www.yahoo.com", "Data"];      No error in the second time. I do not understand why this problem (i.e. using the `Import` command again) gives an error on some URLs and not on others. **update** Thanks for everyone's help and for WReach solution. I have used WReach nice solution to bypass the problem and have just updated the currrent Mathematica code I was using to update the usenet programming languages trends charts. The updated charts are on this page if you are interested in seeing the result.


StiffnessSwitching controller for NDSolve

I have a question regarding NDSolve and StiffnessSwitching. StiffnessSwitching is a method to provide automatic means to handle switching between a stiff and nonstiff solver. The StiffnessSwitching can be activated using for example               Method -> {StiffnessSwitching, Method -> {ExplicitRungeKutta, Automatic}}      as an option to NDSolve. The inner list with the two methods is the method to use for the nonstiff and stiff solver respectively. My question is: Why can't I use the ordinary TimeIntegration methods (for example Adams) as a submethod options for the nonstiff solver. As followed by the example in the tutorial:               Needs["DifferentialEquations`NDSolveProblems`"];     Needs["DifferentialEquations`NDSolveUtilities`"];     system = GetNDSolveProblem["VanderPol"];     time = {T, 0, 10};     sol = NDSolve[system, time, Method -> {StiffnessSwitching, Method -> {Adams, Automatic}}, AccuracyGoal -> 5, PrecisionGoal -> 4]          NDSolve::mdata: An invalid NDSolve`StiffnessSwitching method data object was encountered at the point T == 0.`. >>      Is there a way to combine TimeIntegration with StiffnessSwitching?


Selecting for morphological components that do not border the edges of an image?

Is there an easy way to select for morphological components which do not border/touch the edges of an image? Taking this doodle as an example: ![enter image description here](http://i.stack.imgur.com/2fQ3j.png) We'd want to only select morphological components that stay at least some critical distance from the edges of the image.


Issue with Coefficient command

I'm trying to used the Coefficient command to extract the numerical values in front of a Chebyshev polynomial. I know that there is a numerical way to do this, presented in numerical recipes, which I have already done. But I think using the Coefficient function would be easier and possibly less prone to numerical issues. For example when I use the method from numerical recipes Mathematica thinks that some of my Chebyshev coefficients have an imaginary part, which I know they certainly do not. This is what I have so far:               test = {6.6358882978163365`, 2.12043877554564`, 7.221785806754298`, 8.556762565842575`,          0.8777943247026911`}          test2[y_] = Sum[test[[i + 1]]*ChebyshevT[i, y], {i, 0, 4}]          6.63589 + 2.12044 y + 7.22179 (-1 + 2 y^2) + 8.55676 (-3 y + 4 y^3) +      0.877794 (1 - 8 y^2 + 8 y^4)      Then I try               Table[Coefficient[test2[y], ChebyshevT[i, y]], {i, 0, 4}]      which resulted in an error, so I just trying getting the coefficients one by one to see if I could figure out the issue. Please bear with me,               In[38]:= Coefficient[test2[y], ChebyshevT[0, y]]          During evaluation of In[38]:= Coefficient::ivar: 1 is not a valid variable. >>          Out[38]= Coefficient[     6.63589 + 2.12044 y + 7.22179 (-1 + 2 y^2) +  8.55676 (-3 y + 4 y^3)      + 0.877794 (1 - 8 y^2 + 8 y^4), 1]          In[39]:= Coefficient[test2[y], ChebyshevT[1, y]]          Out[39]= -23.5498          In[40]:= Coefficient[test2[y], ChebyshevT[2, y]]          Out[40]= 7.22179          In[41]:= Coefficient[test2[y], ChebyshevT[3, y]]          Out[41]= 8.55676          In[42]:= Coefficient[test2[y], ChebyshevT[4, y]]          Out[42]= 0.877794      So, the Coefficient command is not working for the zeroth order and first order Chebyshev polynomial. I think I understand why it won't work for the zeroth order. The Coefficient function probably needs a symbolic argument and not a number like "1". Is there anyway to fix this? More confusing to me is why it fails for the first order Chebyshev polynomial. I can't figure that part out at all. * * * The code               Table[Coefficient[test2[y], z = ChebyshevT[i, y]; If[z === 1, Sequence @@ {y, 0}, z]], {i,         0, 4}]      provide by Nasser, seems to work, it gives               {0.291897, -23.5498, 7.22179, 8.55676, 0.877794}      But I'm starting to understand that there is a fundamental problem with what I'm trying to do. When I give the command               Coefficient[test2[y], ChebyshevT[1, y]]      Mathematica just interprets that as               Coefficient[test2[y], y]      and the adds together all of the numerical coefficients in front of anything that has a "y" in the term. Ideally I want Mathematica to output 2.12044, but it is adding up all of the terms that have a "y" in front of them. I guess I will just have to stick with the method found in numerical recipes.


Image's pixels GPU colour classes splitting

How can I split in color classes, the pixels of an image that I load in Mathematica? I would an output like this:               <Class1Name> 50%      <Class2Name> 30%      <Class3Name> 20%      The percentages refere to the amount of pixels of the image that are into that colour class. The definition of the classes would be something like this: `<Class1Name>` = All pixels that are into a RGB range of colours (for example from a dark green to a light green) I have tried a code like this:               Image[{List@@@DominantColors[<imagefile>, n]}, ImageSize -> 300]      But I don't know how to split the output in classes. By encreasing the value of $n$ I will have a better precision right? I would love also a plot of the normal distribution of the pixels, where in the $x$ axis lie the names of the classes and on the $y$ axis a normalized scale that go from 0 to 1. So the plot should look similar to this: ![enter image description here](http://i.stack.imgur.com/mqN8d.png) If is possible I would execute the computation of all this on the GPU or on both the CPU and GPU togheter, I would like to chose between an OpenCL and CUDA version of the code and if is not possible I would have a code optimized to perform the computation on all cores an threads of my CPU. P.S. I have used in the examples only three classes but actually I would like to choose the number of classes that I prefer every time that I run the code.


How can I get NotebookPrint to pass through the system print dialog?

As near as I can tell, `NotebookPrint` goes directly to the default printer, without employing the system standard process of opening a print dialog first. Specifically, I'd like to he able to use `NotebookPrint`, or an alternative function, `somePrintFunction` to print an arbitrary expression, `expr`, using the form               somePrintFunction[expr]      and have the standard system dialog for printing appear. Is there a way to force `NotebookPrint` to do this? Is there some other function that does?


How do I find line integrals?

For example, how can I calculate $$\int_{\left | z \right |=1}\frac{dz}{z}$$ I know that the answer is $2\pi i$ but how do I do it using _Mathematica_?


Why are my images not printing at the expected size?

I understand how (in theory) to get images to be a specific size in inches, but when I follow the documentation, all of my output seems to be scaled down by a factor of a bit less than 70% (e.g., `ImageSize -> 72x8` gives an image size of about 5.5 inches rather than 8). How do I ensure that my images print at a specified size in inches? Are there settings or additional options beyond those described in the documentation for `ImageSize` that I need to use? * * * In context, what I'm trying to do is print a generated graphic from within a Manipulate using a button using               Button["Print",  NotebookPrint[pat]]      or perhaps something like               Button["Print", NotebookPrint[Show[pat, ImageSize -> 72 patzise]]]      and I'd ideally like to apply whatever settings are needed to get a properly sized output, without messing with global or notebook level settings.


Intersection for lists of numeric data

I know that `Intersection` is a pattern matching function and will not evaluate list elements to determine if two or more list have equal elements. So my question is, what can be done to do this? Say, determine if two lists have numerically equal elements within some tolerance dx?


Maximizing functions with Which statements

I'd like to be able to find the maximum value that my Capex function (see below) generates. This is a fairly simple function so I could just add it up but I have more complex functions of a similar form that I'll need to maximize.               Capex[romSize_, CCSPsize_, washRate_, miningRate_] :=     Module[{val, rom = romSize, CCSP = CCSPsize, wash = washRate},     val = 0;     Which[CCSP > 500, val = val - 100];     Which[rom >= 200 && rom < 300, val = val - 5, rom >= 300,       val = val - 10];     Which[wash >= 1300 && wash < 1500, val = val - 10, wash >= 1500,      val = val - 20];     Which[miningRate >= 5.5 && miningRate < 5.7, val = val - 10,      miningRate >= 5.7, val = val - 20];     Return[val]     ];      The problem I have is that because it contains Which statements the Maximize function doesn't seem to work. I could spam the Capex function with values in the domain and pick the largest value but I was hoping Mathematica had some functionality to make it a little easier, kind of like Goal Seek in Excel. An example of a simple maximize call would be               Maximize[{Capex[x, 600, 1500, 6], 120 <= x <= 300}, {x}]      The max value of -240 is correct but x=300 is not


density/histogram plot for date-time data

I have date and time data and want to plot its frequency histogram. Ideally I want to be able to customize the bin size (for example, every 5 minutes or a day). Anybody has this experience?


How can I numerically solve for fractional functions and fractional derivatives?

I would like to plot fractional functions. Say $f=(\sin)^{1/2}(x)$. By that I mean that $f(f(x)) = \sin(x)$. Similarly I can define a half-derivative to be an operator such that $H[H[f(x)]] = \frac{df(x)}{dx}$. What I'd like to do, in an ideal situation, is to evaluate the function at different points and then plot it. How do I numerically solve such equations in Mathematica? Is it possible to get a Taylor series? Side question: Does Mathematica treat operators as separate entities?


ParametricPlot3D and Sphere Graphics

I'm trying to put a sphere into a 3D parametric plot, but I seem to have a strange problem. Here's the code:               ( _Gravitational Constant_ )     G = 6.672*10^-11     ( _Mass of Earth and rocket_ )     M = AstronomicalData["Earth", "Mass"]     m = 2800000     ( _Rocket thrust_ )     T = 34020000     ( _Radius of Earth_ )     r = AstronomicalData["Earth", "Radius"]     ( _Numerical solution modelling the gravitation interaction between Earth and a launching rocket_ )     ( _NOTE: Rocket mass will change over time; also, add in drag_ )     soln = NDSolve[{        x''[t] == -((G M x[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2)),        y''[t] == -((G M y[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2)) +           If[t > 1000, 0, 0.25 T/m],        z''[t] == -((G M z[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2)) +           If[t > 1000, 0, 0.75 T/m],        x[0] == 0, y[0] == 0, z[0] == r, x'[0] == 0, y'[0] == 0,         z'[0] == 0}, {x[t], y[t], z[t]}, {t, 0, 20000},        MaxSteps -> 1000000, Method -> "StiffnessSwitching"]                              Show[ParametricPlot3D[       Evaluate[{x[t], y[t], z[t]} /. soln], {t, 0, 20000},        AxesLabel -> {x, y, z}, AspectRatio -> 1, BoxRatios -> 1,        PlotStyle -> Automatic, ImageSize -> Large],       Graphics3D[{Green, Sphere[{0, 0, 0}, r]}]]      ` And this is the output that I get, not a sphere but a curved plane: ![Sphere Plot](http://i.stack.imgur.com/Z4m4m.jpg) Does anyone know what I'm doing wrong?


About multi-root search in Mathematica for transcendental equations

I have some questions for multiroot search for transcendental equations. Is there any clever solution to find all the roots for a transcendental equation in a specific range? Perhaps `FindRoot` is the most efficient way to solve transcendental equations, but it only gives one root around a specific value. For example,               FindRoot[BesselJ[1, x]^2 + BesselK[1, x]^2 - Sin[Sin[x]], {x, 10}]      Of course, one can first `Plot` the equation and then choose several start values around each root and then use `FindRoot` to get the exact value.   1. **Is there any elegant way to find all the roots at once?** Actually, I come up with this question when I solve the eigenequation for optical waveguides and I want to get the dispersion relation. I find `ContourPlot` is very useful to get the curve of the dispersion relation. For example,              ContourPlot[BesselJ[1, x]^2 + BesselK[1, x]^2 - Sin@Sin[a*x] == 0, {x, 0, 10}, {a, 0, 4}]      You can get ![enter image description here](http://i.stack.imgur.com/QMIrP.png)   2. **Is there any elegant way to get all the values in the`ContourPlot` for `x` when `a==0` ?**   3. **Is it possible to know how the`ContourPlot` gets all the points shown in the figure? Perhaps we can harness it to get all the roots for the transcendental equation.**


HighlightGraph with different styles

I want to highlight two different directed paths on a graph with two different style. I am using the following two code snippets:               HighlightGraph[      CompleteGraph[5], {PathGraph[{1, 2, 3}], PathGraph[{4, 5}]},       GraphHighlightStyle -> {"Dashed", "Thick"}]      and               HighlightGraph[      HighlightGraph[CompleteGraph[5], PathGraph[{4, 5}],        GraphHighlightStyle -> "Dashed"], PathGraph[{1, 2, 3}],       GraphHighlightStyle -> "Thick"]      But either of them results in the following plot: ![Highlighted Graph](http://i.stack.imgur.com/raJVY.png) It seems that highlighted paths use the same style (the last one applied to the graph) if we have more than one path. In addition, I want to make the highlighted paths directed, but If I add the option `DirectedEdges->True` to the path, it doesn't work.


Exporting plots with Cyrillic text elements to pdf

I'm trying to export a plot with some added notes which happen to be in Russian. Using Mathematica 8.04 and WinXP I evaluate               Export["smt.pdf", "Текст на русском", CharacterEncoding -> "WindowsCyrillic"]      Which gives nonsense as output. Is there a way to solve this?


A topoplot function for Mathematica

Matlab's EEGlab toolbox has a topoplot function: http://sccn.ucsd.edu/eeglab/ A typical topographical plot of an EEG signal is given below: ![enter image description here](http://i.stack.imgur.com/S4Dff.jpg) How can I reproduce this in Mathematica. I know that ContourPlot and ListCountourPlot provide such functionalities, however, the data is on a square grid... and I would like it on a circle like in the figure...


Counting paths of a certain length between a source and sink vertex

I have a graph $G$, which may be directed or not, and I was wondering if there was an efficient way of using, say, BreadthFirstScan[] and FindShortestPath[] to count the number of paths between some source vertex, $v(a)$, some sink vertex, $v(b)$, of a certain length $D$? As of right now, I'm simply sequentially running through all of the vertices in my graph, applying FindShortestPath[] to determine the distance of the vertex to my source and sink vertices, and then seeing if the total distance is $D$. If the total path distance is in fact $D$, I then put the path in a list which is later pruned for redundant paths or paths that revisit vertices. Assuming I have plenty of memory to spare, is there a better / faster solution? * * * Let me better specify what I'm looking for - Provided an undirected or directed graph $G$, I want to count the number of possible ordered sets, $(q_1,...,q_N)$, of all-unique vertices, $(v_{source}, ..., v_{sink}) \in q_i$, that one must visit to move from a source vertex, $v(source)$ to a sink vertex, $v(sink)$ s.t. $||q_i|| = D$ for all $q_i$, i.e. s.t. the total number of vertices along any path $q_i$ (including the source and sink) is $D$. Two paths, $(q_a, q_b)$, may have common vertices, but individual $q_i$ cannot have redundant vertices (i.e. they are not multisets). Please note, however, that I would be open to elegant/nice solutions that allow repeat vertex visits but forbid repeat edge traversals.


Compute symbolic Expectation of a summation

I am required to computed following Expectations : $E[\displaystyle\sum\limits_{i=1}^N \frac{X_{i}}{N}] = \bar{x}_{0}$ & $E[\displaystyle(\sum\limits_{i=1}^N \frac{X_{i}}{N})^2] = \frac{(N\bar{x}_{0}^2 + \sigma_{x}^2)}{N}$ with $ X_{i} \sim N(\bar{x}_{0},\sigma_{x}^2) \forall i = 1,2,\cdots,N$ & $X_{i} \bot X_{j} \forall i\not=j$ I'm looking to solve these expectation in symbolic as all these variable are unknown. Thanks for your help Alexandre


Convolution of a denstity function having a point mass with itself

My density function is as follows:               der[x_] :=Piecewise[{{E^((-4 - 4*x - x^2 - Log[2]^2)/8)/(2^(x/4)*Sqrt[Pi]*(2*Sqrt[2/E]*Erf[Log[2]/(2*Sqrt[2])]+Erfc[(-2 + Log[2])/(2*Sqrt[2])] +2*Erfc[(2 + Log[2])/(2*Sqrt[2])])), x > 0}, {0.2015152271993863, x == 0}},(2^(x/4)*E^((-4 - 4*x - x^2 - Log[2]^2)/8))/(Sqrt[Pi]*(2*Sqrt[2/E]*Erf[Log[2]/(2*Sqrt[2])]+Erfc[(-2 + Log[2])/(2*Sqrt[2])] + 2*Erfc[(2 +Log[2])/(2*Sqrt[2])]))]      This density has a point mass of               0.2015152271993863`      at $x=0$. Taking into account the point mass, I would like to calculate $P[n];$ $$P[n]=\int_{(-\infty,B)\cup (A,\infty)} q_n (x) \mathrm{d}x$$ with $$q_n(x)=\int_{B}^A q_{n-1} (\omega)f(x-\omega)\mathrm{d} \omega,\quad q_1=f,\quad n\geq 1.$$ and $f$ is some density function,which is $\mathrm{der}[x]$ here. To make these iterative calculations, I have the following code:               q[1, B_, A_, f_] := f     q[n_ /; n > 1, B_, A_, f_][x_] := Module[{\[Omega]},tempIntegrate[Evaluate[q[n - 1, B, A, f]][\[Omega]] f[x - \[Omega]], {\[Omega],B, A}]]      p[n_, B_, A_, f_] :=tempIntegrate[q[n, B, A, f][x], {x, -\[Infinity], B}] + tempIntegrate[q[n, B, A, f][x], {x,A, \[Infinity]}] //. {s_ tempIntegrate[b_,a__] :>tempIntegrate[s b, a],tempIntegrate[tempIntegrate[b_,a__], c__] :>tempIntegrate[b, a, c]} /.tempIntegrate -> NIntegrate      If the calculations are all correct, then the summation of all elements of the following table should (almost) add up to $1$               tab2 = Table[p[j, -2, 2, der], {j, 10}];      Since I cannot deal with the point mass it doesnt add upto $1$. If you want to see that it indeed adds up to $1$, you can consider for example               der[x_]:=PDF[NormalDistribution[-2, 2], x]      How can I deal with the point mass in the convolution and also in the integrations?


bulk initialization of associative array/hash implemented with function pattern matching?

I see that we can do associative arrays in Mathematica using functions that have implicit pattern arguments, as in               debyeTemperature[ "Aluminum" ] = 433 ;     debyeTemperature[ "Americium" ] = 121 ;     debyeTemperature[ "Antimony" ] = 220 ;     debyeTemperature[ "Argon" ] = 92.0 ;          debyeTemperature[ "Americium" ]      My guess is that ChemicalData[] uses something like this internally. Is there a syntax for bulk initialization of such a hash function with pairs of values, perhaps like a similar perl hash initialization:               my %debyeTemperature = ("Aluminum" => 433,                             "Americium" => 121,                             "Antimony" => 220,                             "Argon" => 92.0, ) ;          print "$debyeTemperature{'Americium'}\n" ;


Widget - GUI help

I was wondering if someone could explain me the code written below (example File Dialog from mathematica). Especially the part with `returnValue`and `InvokeMethod`. Also I want to ask how to actually save table from Table Widget(when I add Save button to the widget how to implement the method?). I really need help and any comment is appreciated.               ref = GUIRun[Widget["Panel", {Widget["Button", {"text" -> "Save File...",                         BindEvent["action",Script[         Widget["FileDialog", Name -> "saveFileDialog"];         returnValue =           InvokeMethod[{"saveFileDialog", "showSaveDialog"}, Null];         If[          returnValue ===            PropertyValue[{"saveFileDialog", "APPROVE_OPTION"}],           PropertyValue[{PropertyValue[{"saveFileDialog",               "selectedFile"}], "path"}],          Null          ]         ]]}],     Widget["Button", {"text" -> "Cancel"}]     }]       ]


Pure function inside another pure function

I have the following working expression:               In[15]:= Length[Select[IntegerPartitions[10],First[#1]==5&]]     Out[15]= 7      But, instead of using the constant 5 I want to map all values from 1 to 10 into this function. If I nest the pure function inside another it doesn't work:               In[18]:= Map[Length[Select[IntegerPartitions[10],First[#]==#&]]&,Range[10]]     Out[18]= {0,0,0,0,0,0,0,0,0,0}      What is the way to do this?


Problem enabling PlotLegends in Mathematica 8.0

I am trying to make a legend for a simple plot in _Mathematica_ 8, but does not seem to recognise the command PlotLegends. I declared beforehand `Needs["PlotLegends`"]`, and get this message: > Needs::nocont: Context PlotLegends` was not created when Needs was > evaluated. >> I also tried to install this pakage manually by going to File -> Install -> .... I am not very experienced with _Mathematica_ , so an answer for dummies will be appreciated.


Numerical simulation - getting slower the more data I have

I'm simulating the trajectory of a charged particle. I have the coordinates saved in the list $coor$ ({{0,0,0},{0.1,0.1,0.003}, etc}) as the time goes on this array is getting bigger and the computation slower. What is the usual way to solve this issue? I guess that using               coor=Append[coor,r]      is't the best way to save data on the way. Do you have any sugesstions? Thanks


How can I speed up my numerical integration?

Here is my code:               x0 = -50;      f[xe_] :=       NIntegrate[-1/(k^6 x1^4)         48 (k x1 Cos[k x1] -           Sin[k x1]) (-1/            x0^3 (-6 k x0 Cos[2 k x0 - k x1] + 3 k x1 Cos[2 k x0 - k x1] +              2 k^3 x0 x1^2 Cos[2 k x0 - k x1] +              k^3 x0^3 CosIntegral[               2 k x0] ((-3 + k^2 x1^2) Cos[k x1] - 3 k x1 Sin[k x1]) +              3 Sin[2 k x0 - k x1] + 6 k^2 x0 x1 Sin[2 k x0 - k x1] -              k^2 x1^2 Sin[2 k x0 - k x1] +              k^3 x0^3 (3 k x1 Cos[k x1] + (-3 + k^2 x1^2) Sin[                  k x1]) SinIntegral[2 k x0]) +           1/x1^3 (-3 k x1 Cos[k x1] + 2 k^3 x1^3 Cos[k x1] + 3 Sin[k x1] +              5 k^2 x1^2 Sin[k x1] +              k^3 x1^3 CosIntegral[               2 k x1] ((-3 + k^2 x1^2) Cos[k x1] - 3 k x1 Sin[k x1]) +              k^3 x1^3 (3 k x1 Cos[k x1] + (-3 + k^2 x1^2) Sin[                  k x1]) SinIntegral[2 k x1])), {x1, xe , x0},        AccuracyGoal -> 20, WorkingPrecision -> 200]     k = 1;      Plot[f[xe]/(24 Log[E, -xe]^2) , {xe, -10^-45, -10^-50}, PlotRange -> Full]      My problem is that solving and plotting takes a long time with this code. Could someone please help me to find a method to speed it up?


What should I expect for Fourier transform of Sinc?

I was expecting something I could interpret as a rect function. I don't think the Dirac delta function qualifies — for one thing, I think that would be the transform of a constant.               FourierTransform[Sinc[t], t, ω]      > >     2.50245 DiracDelta[ω] >   Is there a way to make sense of this? I'm using v.9.0 home


How to known exactly what color assign "TemperatureMap" to a particular value?

Usually               ColorData["TemperatureMap"]      is using to coloring graphs and show how near is any value to 0(Blue), 1(Red), or in the mean (White). The question is: How Can I do to obtain the RGB/CMYK code color, to a particualr value? for example,... to the value 0 is asigned BLUE=(0,0,100)%=(0,0,255)Hex but... What color-code asign the "TemperatureMap" to the value 0.123 ?, I know that it´s a close to blue, but... What exactly? I´ll use in other ranges like [0,8] or 1[12.45,45.85], not only in [0,1]