title: How do you deal with very large datasets in Mathematica?

text: This question is in two related parts. The first is about dataset size, the second data wrangling. Part 1: I've built a naive Bayesian classifier on Mathematica. It uses `KernelMixtureDistribution` to train on a large (2mm row) dataset. About 200 fields, of which 30 are used. Two separate classes are trained. Unfortunately, when I try to load 2mm rows into _Mathematica_ I get a Java out of heap space error. This is not the end of the world, I can load each column individually, compute the distribution and save it. Then load up all the distributions separately without the training data later. The problem comes in, with the prediction part of the process. I have a 300Mb (400K rows) CSV file, and can't load it. In more traditional environments, I'd either read a row at at time (slow), do a prediction and write it out to a separate file. Or read in some block of rows at a time. I can't see a way to do this in Mathematica. Import seems to only import whole files, and runs out of memory. (4Gig) How are people working with large datasets that won't fit into memory? Part2: I'm dealing with data that mostly has the same columns, but can be shifted about a bit, sometimes have extra columns added. Mathematica, doesn't seem to have a record or structure type, only lists and matrices. How are people dealing with this? I've taken to loading my data into an SQL database, but even this is suboptimal - for my classifier I have to make sure I select the same fields, in the same order, in the same offset in a list. Edit: It looks like Mathematica supports a sort of cursor called result sets. This looks to be slow (400K records, one at a time), but computer time is cheap, person time isn't. I'm going to attempt to train my classifier per normal, then use result sets to individually classify each sample row. If this works out, I'll post an answer to this question detail how I did it. I am making one huge presumption here, that MMA/Java database link will free up memory after each row is no longer needed. As long as that's the case, this approach might stand a chance of working. http://reference.wolfram.com/mathematica/DatabaseLink/ref/SQLResultSetRead.html Edit2: After some playing around, I found Mathematica's result sets acts the same as a standard select would - it loads the entire dataset into JDBC and Mathematica's memory. So that approach runs out of memory just like a standard Import or Select would. I hit on another approach relying on my database (PostgresQL) to do the lifting for me using cursors. This approach only works if you can process your data sequentially. For me, that's an acceptable limitation. First I declared a cursor predRows, and made sure it would persist outside of a transaction (The hold part): SQLExecute[dbconn, "declare predRows cursor with hold for select * from myTable;"] Next, I fetch a row from the cursor - this will iterate over all my ~400K rows one at a time for each request. I can also ask for more rows say 1000 at a time if I'd like. (* Fetch one row at a time *) SQLExecute[dbconn, "fetch 1 from predRows;"] (* Fetch 1000 rows at a ttime *) SQLExecute[dbconn, "fetch 1000 from predRows;"] This does mean I have to program in a imperative manner, but I'll learn to live with myself. Postgres documentation on cursors: http://www.postgresql.org/docs/current/interactive/sql-declare.html


title: Implementing Position

text: As an assignment I need to re-implement `Position`. I've managed to do this except for one small thing, the resulting list is not in the current format. The following piece of code is what I have so far.               findPosition[lst_, x_] :=       Module[{output = {}, index = 1},         For[index = 1, index <= Length[lst], index++,           If[lst[[index]] == x,             AppendTo[output, {index}],             False,             If[MemberQ[lst[[index]], x],               AppendTo[output, Map[{index, #} &, findPosition[lst[[index]], x]]];               False             ]; (* If *)           ] (* If *)         ]; (* For *)         Return[output]       ] (* Module *)      This gives the following output:               findPosition[{1, 2, {3, 2, 1}, {1, {4, 2, 1}, 2, {2, 6}}, {2, 6}}, 2]     {{2}, {{3, {2}}}, {{4, {{2, {2}}}}, {4, {3}}, {4, {{4, {1}}}}}, {{5, {1}}}}      While the original gives:               Position[{1, 2, {3, 2, 1}, {1, {4, 2, 1}, 2, {2, 6}}, {2, 6}}, 2]     {{2}, {3, 2}, {4, 2, 2}, {4, 3}, {4, 4, 1}, {5, 1}}      **Am I doing something wrong or is there a way to make my result match the one from the original?** I've tried things using `Flatten`, but it's hard to control what is flattened and what is not. The closest I've come to is `{{2}, {{3, 2}}, {{4, 2, 2}, {4, 3}, {4, 4, 1}}, {{5, 1}}}` using               AppendTo[output, Map[Flatten[{index, #}] &, FindPosition[lst[[index]], x]]];


title: How to set font color for display formula to be same as the cell in which the display formula resides?

text: I have a stylesheet that works as expected in _Mathematica_ 8\. It does not work as expected in _Mathematica_ 9\. In the stylesheet I have set FontColor to `RGBColor[0.501961, 0, 0]` for ItemParagraph. DisplayFormula and InlineFormula have FontColor set to `Automatic` (I've also tried `Inherited`). When I press `Ctrl`+`(` to start a formula from within an ItemParagraph the color is the same as for my Text cell (black). The FontColor option for Text is Automatic. Interesting behavior. When I type `Esc``intt``Esc` the font color is `RGBColor[0.501961, 0, 0]` and it creates an inline formula region (or is it displayformula?). When I type `Ctrl`+`/` it creates an inline formula region but the color is black. I have both _Mathematica_ 8 and _Mathematica_ 9 installed and the behavior does not exist on _Mathematica_ 8.


title: Setting boundary values of a second order differential equation

text: Not sure what is wrong with the boundary conditions for this problem:               NDSolve[{D[u[x, y], x, x] + D[u[x, y], y, y] -          u[x, y] == -DiracDelta[x, y], u[10, y] == 0, u[x, 10] == 0,        u[-10, y] == 0}, u, {x, 0, 10}, {y, 0, 10}].      The error message is: > NDSolve::ivone: Boundary values may only be specified for one independent > variable. Initial values may only be specified at one value of the other > independent variable.


title: How to make a simple tree yourself with defined distances for each generation?

text: I'm trying to make a function that generates a tree for spin spin analysis in spectroscopy. I though it would be pretty easy, but I'm totally stocked. The tree should look something like this: ![Spin Spin analysis](http://i.stack.imgur.com/62ZXp.jpg) where the listed frequencies are the distance between the "generations". I have tried with this: `FoldList[{#1 + #2, #1 - #2} &, 0, {jad,jab,jac}]` where I get the right x-values, but rearranging these values to give me the right lines is where is where it all stops for me. What should I do?


title: How can I improve this trial division procedure?

text: My background is procedural programming, so I find this construction quite natural. Is there a way to get rid of the `While`?               gd[n_, k_] := Block[{d = k + 1}, While[0 != Mod[n, --d]]; d]     gd[n_, d_List] :=            Block[{j = Length[d] + 1}, While[0 != Mod[n, d[[--j]]]]; d[[j]]]            k = 4; n = 25;     gd[n, k]     gd[n, Range[1, k]]     d = Join[{1}, Table[Prime[j], {j, 1, PrimePi[k]}]];     gd[n, d]        My trial division requires the greatest divisor $\leq$ the square root. The $n$ mod $1$ is the terminating step. Whatever the final format, I will need to describe it for a math paper. **Edit** The revised functions as recursions:               gd[n_, k_] := If[Mod[n, k] == 0, k, gd[n, k - 1]]     fd[n_, d_List] := If[Mod[n, d[[1]]] == 0, d[[1]], fd[n, Delete[d, 1]]]        **Edit** The second function as it will be described in my paper: $$f(n,D)\text{:=} \begin{array}{ll} \lbrace & \begin{array}{ll} n \bmod d_{1}=0 & d_{1} \\\ n \bmod d_{1}\neq 0 & f(n,\text{Delete}(D,1)) \\\ \end{array} \\\ \end{array} $$


title: Functional programming and Do loops

text: I'm writing a Monte Carlo simulation. I'm using a `Do` loop to create the different simulations, iterating over different `SeedRandom[]` parameters in my pseudorandom number generator. I'm trying to formulate it as a function that returns a list of correlations that I can then manipulate. I expect there is a very simple solution, but I have to admit that I'm pretty new to _Mathematica_ so I'm having problems. The _Mathematica_ documentation seems to conveniently dodge this issue whenever it comes up! This might be a little complicated, so I'll explain what my code does first, then I'll describe the problem precisely. _First I make a list with the parameters of each of my random variables (I want them to have different means):_               varparams = Table[i, {i, 0.1, 0.9, 0.1}];      _Then I define my random variables:_               var[i_]:=RandomChoice[{varparams[[i]],1-varparams[[i]]}->{1,0},10]      _(I'm generating [for argument's sake] a set of 10 values for each run of the simulation)._ _Now, I define the function that iterates over different SeedRandom[] values, so as to generate different data sets. I want to calculate a list of correlations:_               corrlist = {};     corrcheck[i_, j_, n_] := Do[       SeedRandom[k];       AppendTo[corrlist, Correlation[var[i], var[j]]];       , {k, n}]      _(`n` is the number of different runs of the simulation)._ Now this sort of works, in the sense that I can run `corrcheck[i,j,n]` and then work with the `corrlist` that is produced, but what I want is for `corrcheck[i,j,n]` **itself** to be a list, so that I can make tables and other manipulations of `corrcheck` for different values of `i` and `j`. I hope this makes sense. To reiterate: I want the function `corrcheck`, which consists of a `Do` loop, to produce a unique list for each set of `i,j,n`, so that I can do things like:               Table[corrcheck[i,j,100],{i,10},{j,10}]      and manipulations thereof. The answer has to be obvious. I just can't see it! Thank you very much in advance.


title: How to prevent the loss of Tooltip when using ListLinePlot?

text: Version 9, windows 7: When I use `ListLinePlot` Tooltip does not work any more. It seems to have been lost somewhere. With same data, Tooltip works ok using `ListPlot`.               data = Table[Tooltip[{x, x^2}], {x, 0, 10, .1}];     ListPlot[data]     (* Tooltip shows ok *)          ListLinePlot[data]     (* Tooltip does not show up *)      ![enter image description here](http://i.stack.imgur.com/6BFH7.png) Looked at possible issues for `ListLinePlot` and do not seen mention of this. question: How to make Tooltip work with `ListLinePlot` thanks


title: Solving set of non-linear simultaneous equations gives PolynomialGCD::lgrexp error - what next?

text: I'm trying to solve a set of six simultaneous non-linear equations to get a numerical answer using `NSolve`:               NSolve[{-0.5547005383792517 +          0.8082903768654761/E^(0.08452994616207483*(0.10136907301545368 +                         beta1/0.3^alpha)) ==         a, -0.3147005383792517 + 0.669726312259966/               E^(0.08452994616207483*(0.10136907301545368 +                beta1/0.45^alpha)) == a,           -0.13470053837925167 +          0.5658032638058333/          E^(0.08452994616207483*(0.10136907301545368 +                beta1/0.55^alpha)) ==             a, -0.540774588761456 +          0.805711228582561/          E^(0.0779225411238544*(0.10136907301545368 + beta2/0.3^alpha)) ==             a, -0.420774588761456 +          0.7324647532568737/          E^(0.0779225411238544*(0.10136907301545368 + beta2/0.45^alpha)) ==             a, -0.160774588761456 +          0.5737640567178843/          E^(0.0779225411238544*(0.10136907301545368 + beta2/0.55^alpha)) ==             a}, {alpha, beta1, beta2, a}, Reals]      (I'm not very experienced with Mathematica - so I hope that is the correct way to paste code in here so that others can copy into Mathematica and try running it) I get the following errors:               PolynomialGCD::lrgexp: Exponent is out of bounds for function PolynomialGCD.      This seems to suggest that Mathematica can't deal with the large values used as the exponents in the equations given - but as far as I can see the values aren't particularly large. I do know roughly what sort of ranges the results for each of the variables should have (eg. `a` should be between 0 and 1) but I can't seem to find a way to specify this extra knowledge as an option to `NSolve`. I'm not sure where to progress from here, now that I've got these errors. Does anyone have any ideas? I am taking the equations from a paper that I am trying to reimplement, but I'm pretty sure the equations are how they're meant to be. I may be doing something silly in Mathematica though.


title: Use Results from Manipulate Plot NDSolve to create another plot versus variable used in DE

text: I created my plot using using this input:               Manipulate[solution[t_] = NDSolve[{          Derivative[1][w][t] == - k1  S w[t] + k2   x[t] -                    k7 H  w[t] + k8  y[t],           Derivative[1][x][t] == - k2  x[t] + k1 S w[t] - k3 H x[t] +                    k4  z[t],           Derivative[1][y][t] == -k8  y[t] + k7 H w[t] - k5  S y[t] +                    k6 z[t],           Derivative[1][z][t] == - k4  z[t] + k3 H  x[t] - k6  z[t] +                    k5 S y[t], w[0] == 1, x[0] == 0, y[0] == 0,           z[0] == 0}, {w [t],                x [t], y [t], z [t]}, {t, 0, 10}][[1, All, 2]];        Plot[solution[t], {t, 0, 10}], {{k1, 1}, 0.01, 5,          Appearance -> "Labeled"}        , {{k2, 1}, 0.01, 5, Appearance -> "Labeled"}        , {{k3, 1}, 0.01, 5, Appearance -> "Labeled"}        , {{k4, 1}, 0.01, 5, Appearance -> "Labeled"} , {{k5, 1}, 0.01, 5,          Appearance -> "Labeled"} , {{k6, 1}, 0.01, 5,          Appearance -> "Labeled"} , {{k7, 1}, 0.01, 5,          Appearance -> "Labeled"} , {{k8, 1}, 0.01, 5,          Appearance -> "Labeled"} , {{H, 1}, 0.1, 5,          Appearance -> "Labeled"}, {{S, 1}, 0.01, 5,          Appearance -> "Labeled"} ,        TrackedSymbols :> {k1, k2, k3, k4, k5, k6,  k7, k8, H, S}]      I now want to plot the solutions function versus S. Any suggestions?


title: Graphics and panel size

text: Consider the following snippet:                 DynamicModule[{},        Manipulate[         Graphics[          Translate[           GeometricTransformation[            {Blue, Polygon[{{0, 0}, {1, 0}, {1, 1}, {0, 1}}]},            {{scx, 0}, {0, scy}}],           Tuples[{Range[wi], Range[he]}] - 1]],         {{scx, 1, "x scale"}, 0, 1},         {{scy, 1, "y scale"}, 0, 1},         {{wi, 1, "width"}, 1, 5, 1},         {{he, 1, "heigth"}, 1, 5, 1}]]      ![Mathematica graphics](http://i.stack.imgur.com/VPcuI.png) I want a stable, fixed, panel in which the polygons are displayed, thus independent from the slider values. Applying the `PlotRange-> option` to the `Graphics` function in the example above doesn't work as expected. **Question: How should I set and fix the panel size?**


title: Functions that creates symbol in a specific context

text: I'm trying to make a function `f` that takes a symbol, a value, and a context, and creates the symbol in the requested context and assigns it the passed value. The obvious doesn't work. I.e.:               Attributes[f]={HoldAllComplete};     f[symbol_,value_,context_]:=(Begin[context];Set[symbol,value];End[])      Creates the symbol in the current context, as opposed to the one that is passed as an argument. This seems to happen because the FrontEnd, as soon as it sees `f` getting evaluated, creates the symbol in the current context despite `HoldAllComplete`. I tried adding `Remove[symbol]` to the function but that doesn't work. Any thoughts?


title: Custom functions by delegating options in a specific way and using core functions

text: I'd like to create a custom function that does essentially the same as a core function of mathematica but uses different default settings. Example: I want a Plot function that uses Mathematica's core `Plot` function but uses different default settings. I don't want to use `SetOptions[Plot, ...]` because I don't want to override anything for the core Plot function. Instead of this I want to build a custom function `PlotFramed[x^2,{x,-5,5}]` that points to `Plot[x^2, {x,-5,5}, Frame->True, GridLines->Automatic]`. I also want the function to be able to override my default settings. So `PlotFramed[x^2, {x,-5,5}, GridLines->None]` should return the results from `Plot[x^2, {x,-5,5}, Frame->True, GridLines->None]`. And I want to use additional options that are not set by default as in the normal Plot function. So `PlotFramed[x^2, {x,-5,5}, PlotStyle->Dashed]` should point to `Plot[x^2, {x,-5,5}, Frame->True, GridLines->Automatic, PlotStyle->Dashed]`. The reason for this is that when writing reports (in LaTeX) I have to add several options to the plot function to make the font-size bigger, add a grid, etc pp. Using the idea above I could write a custom Plot function that I can use when generating output for the report and otherwise use Mathematica's core function since everything is fine with it when working inside Mathematica. Can anyone tell me how to do this? This would be awesome. Thanks in advance!


title: Mathematica Parellelization on HPC

text: I'm currently using _Mathematica_ on a High Performance Cluster (HPC) which consists of many compute nodes each with around 16 cores. I currently run my _Mathematica_ script on 20 of the nodes that invokes 10 cores and 10 of the subkernels licenses in Parallel, meaning I use 20 Mathkernel licenses and 200 subkernel licenses. The problem is we have limited Mathkernel licenses (36, and for me to be using 20 of them is unfair on everyone else!) although ample subkernel licenses (288). Is there a way I can just use a single (or at least fewer) Mathkernel licenses to invoke the 200 subkernels I need? Currently in each of the 20 scripts I just have               LaunchKernels[10];     ParellelTable[....];      which launches the 10 local subkernels on each node, but could I specify different nodes to launch subkernels on perhaps? Thereby I would only need to launch one Mathkernel which could invoke the 200 subkernels spread across the compute nodes.


title: Integral with HeavisideTheta takes too long to evaluate

text: I tried to compute $$\int_{-1}^1 d x_1 \int_{-1}^1 d x_2 \int_{-1}^1 d y_1 \int_{-1}^1 d y_2 \theta(x_1 x_2 + y_1 y_2)\,$$ where $\theta$ is Heaviside's step function, by using               Integrate[HeavisideTheta[x1 x2+y1 y2],{x1,-1,1},{x2,-1,1},{y1,-1,1},{y2,-1,1}]      but it took forever to evaluate. I didn't have the patience to wait until the end. However,               Integrate[Boole[x1 x2+y1 y2 >= 0],{x1,-1,1},{x2,-1,1},{y1,-1,1},{y2,-1,1}]      was very quick. Can anybody explain this strange behavior?


title: Check homework integration in Mathematica

text: Given in my homework I have to compute (by hand) $$\iint\limits_{x^2+y^2\leq 1}(x^2+y^2)\,\mathrm dx\,\,\mathrm dy.$$ My solution so far: Let $f(x,y)=x^2+y^2$ and $K=\\{(x,y)\in\mathbb{R}^2:x^2+y^2\leq 1\\}$. With the transformation of polar coordinates $\varphi:(r,\phi)\mapsto(r\cdot\cos\phi,r\cdot\sin\phi)=(x,y)$ and the determinant of the Jacobian matrix $|\det D_\varphi|=r$ we can rewrite the set as $K=\\{(r\cdot\cos\phi,r\cdot\sin\phi):r\in[0,1],\phi\in[0,2\pi]\\}$ and our integrand too as $f(x,y)=x^2+y^2=r^2$. $$\iint\limits_K f(x,y)\,\mathrm dx\,\mathrm dy=\int\limits_0^1\int\limits_0^{2\pi}r^2\cdot |\det D_\varphi|\,\mathrm d\phi\,\mathrm dr=2\pi\int\limits_0^1r^3\,\mathrm dr=\left.2\pi\cdot\frac{1}{4}r^4\right|_0^1=\frac{\pi}{2}.$$ I now want to check the result with a CAS. I am pretty new to Mathematica so I just didn't found any clue on how to enter such an integral for computation. Any help out there?


title: More elegant/efficient solution to browse through an array

text: I have an array of lists and want to correlate every list with each other like this:               Table[Table[Correlation[list[[y]], list[[x]]], {x, 1, Length[list]}], {y,1, Length[list]}];      I take the first list and correlate it with all others asf. I pretty much assume, this is not a very elegant and efficient code, so I wanted to ask for some alternatives. How would you guys do it?


title: How to convert from base 2 to base n?

text: I'm trying to use baseform to convert numbers in base 10 to base n, how can I make the convertion between, say base 2 to base n? Baseform seems to always think that the base in expr `BaseForm[Expr, n]` is always 10.


title: Selecting a specific complex number from a list

text: I have a formula which is producing a large (hundreds of elements) list of complex numbers of the simple form $x+iy$. However I'm only interested in the one value which satisfies the conditions:   1. The imaginary part is the _least negative_ value in the list   2. The real part is positive.  What can write that will pick out this value and display it for me?


title: Will aliasing the Quantity and UnitConvert functions to "in" and "to" create problems?

text: It seems that there is a lot of interest in enhancing the use of units in Mathematica; various solutions in the name of brevity, correctness, and general utility have been demonstrated. I've begun treating unit conversions in a very simple manner as listed below. My question: what problems might I run into making conversions in this manner? (It saves a little typing and seems somewhat easier to read to me, at the expense of defining "in" and "to" aliases.) (Mathematica v.9.0.1.0)               in = Quantity; to = UnitConvert;          Express x "in" feet:            x = 100.0~in~"Feet"          100. ft          Convert "to" yards:          x~to~"Yards"          33.3333 yd          Convert to SI units:          x // to          30.48 m          "One stop shop" conversion:          x = 1.0~in~"kg"~to~"lb"          2.20462 lb


title: Optimizing Monte Carlo simulation of a Pred-Prey model

text: **My assignment and code** As part of an assignment for one of my classes, I'm trying to run a "massive" Monte Carlo simulation in Parallel on the follow model:               {H'[t] == r (1 - H[t]/k) - d H[t] P[t],       P'[t] == -s P[t] + e H[t] P[t],       H[0] == H0, P[0] == P0}      I've been given values for d, s and e but am required to use distributions for r, k, H0 and P0. I've implemented this as follows:               If[Kernels[] == {}, LaunchKernels[]];          kdis = RandomVariate[NormalDistribution[150, 20], 10];      rdis = RandomVariate[NormalDistribution[0.4, 0.003], 10];     H0dis = RandomVariate[UniformDistribution[{50, 200}], 10];     P0dis = RandomVariate[UniformDistribution[{20, 70}], 10];     d = 0.01;     s = 0.3;     e = 0.02;     SetSharedVariable[d, s, e];          distr = Tuples[{kdis, rdis, H0dis, P0dis}];          Eqs[{k_, r_, H0_, P0_}] :=       NDSolve[{H'[t] == r (1 - H[t]/k) - d H[t] P[t],                P'[t] == -s P[t] + e H[t] P[t],                H[0] == H0, P[0] == P0}, {H, P}, {t, 0, 600}]     DistributeDefinitions[Eqs];          AbsoluteTiming[solset = ParallelMap[Eqs, distr];]      To display the results I create an envelope enclosing all runs for both predator and prey populations:               Envelope[n_] =       Map[{Min@#, Max@#} &,         Transpose[Map[Flatten[{H[n], P[n]} /. #] &, solset]]];     DistributeDefinitions[Envelope];          AbsoluteTiming[plotset = ParallelMap[Envelope, Range[0, 600, 1]];]          plotsetH = plotset[[All, 1]];     plotsetP = plotset[[All, 2]];     Show[ListPlot[{plotsetH[[All, 1]], plotsetH[[All, 2]]},                     Joined -> True, PlotRange -> {{0, 600}, {0, 25}}],          ListPlot[{plotsetP[[All, 1]], plotsetP[[All, 2]]},                     Joined -> True, PlotRange -> {{0, 600}, {0, 25}}]]      The result looks decent: ![The result](http://i.imgur.com/DPZIt6y.jpg) **The problem** Now my issue is that I'm currently hardly using proper distributions, but only 10 values per variable, which I doubt is what my instructor meant when he asked for a massive Monte Carlo simulation. The notebook takes about 2 minutes to evaluate and eats up almost all of the memory 8gb memory I have available in that time. Using 11 instead of 10 values per variable results in an error about kernels appearing dead, which I assume is caused by my memory running out. Are there any ways to optimize this kind of code, or to decrease memory usage? Thanks in advance!


title: Partitioning a list by recursion (Programming Paradigms via Mathematica (A First Course))

text: I am working through the course _Programming Paradigms via Mathematica_. One of the homework exercises for the section _Recursion I: Passing the Buck_ is as follows: > Use recursion to partition a list: "recurPartition[L_List,k_Integer]" should > return the same thing as "Partition[L,k]". Of course, don't use > "Partition[]". The following additional limitations are also applied: > First, use of a repetition function ("Map[]", "MapThread[]", "Nest[]", > "NestList[]", "Fold[]", "FoldList[]", "Table[]", "Apply[]", and so on, being > our "adverbs") will generally disqualify a method as purely recursive, for > the repetition is accomplished externally from the nested function calls. > Also, repetition accomplished with a loop structure, such as a "While[]", a > "Do[]", or some other repetition command, is explicitly forbidden. Here was my code, following many edits:               Clear[recurPartition]     recurPartition[{}, k_] := {}     recurPartition[L_List, k_Integer] :=       If[Length[L] >= k, {Take[L, k], recurPartition[Drop[L, k], k]}]     recurPartition[{1, 2, 3, 4, 5, 6}, 2]      Which produced the following output: > {{1, 2}, {{3, 4}, {{5, 6}, {}}}} By contrast `Partition[{1, 2, 3, 4, 5, 6}, 2]` would produce: > {{1, 2}, {3, 4}, {5, 6}} I can't figure out what I should have done differently and would appreciate some guidance.


title: Disk is displayed distorted in plot

text: What is the problem with my plot? I want to get a disk shape.               Plot[Table[-x + k, {k, -2, 2, .1}], {x, -5 ,5},        RegionFunction -> Function[{x, y}, (x^2 + y^2) < 1]]      ![enter image description here](http://i.stack.imgur.com/Wx0h9.jpg)


title: Extract Graphics properties using EventHandler

text: One can find primitives' properties such as the radius, the center or the color of a `Disk` using `Cases` by using:               g = Graphics[{Red, Disk[{0, 0}, 1], Black, Disk[{10, 0}, 5], Blue, Disk[{30, 0}, 3]}]     Cases[g, Disk[_, y_] :> y, Infinity]     Cases[g, Disk[x_, _] :> x, Infinity]     Cases[g, _RGBColor | _Hue | _GrayLevel, Infinity]      yielding the right values. How can the same functions be applied to an `EventHandler`? Consider for instance the following code:               DynamicModule[{list = {{0, 0}, {2, 0}}},      Graphics[       EventHandler[        {Red, Dynamic@Disk[#, 1] & /@ list},       {"MouseClicked" :> {(* the appropriate function *)}}]]]      The aim would be the extract the radius/center/color of the clicked primitive.


title: space lost when converting inline cell to tex

text: > Sample Cell 1 words with spaces in one inline cell               Cell[TextData[Cell[BoxData[\(TraditionalForm\`\(Y\ =\ \(\({\(x\ \[Element]\ \([\(a,\ b\)]\)\)\ :\ \(there\ is\ a\ finite\ subcover\ in\ \(\[Sum]\ \(of\ the\ \(interval\ [\(a,\ x\)]\)\)\)\)}\) .\ \)\)\)], "InlineFormula", FormatType -> "TraditionalForm"]], "Text"]      * * * When saving it as Tex, or `Copy As Latex`, the spaces between words will lost, What's the right and good method to deal with such thing? The worst is each time this happen, I modify it in Tex Editor. * * * As Silva's answer suggested, creating text cell for inline words block. What occurred in my mind is to develop some palletes like this post(my prevous quesion) to do the similar thing. How to make AutoAction take effect only one time? * * * As you see in the picture, I'm handling the `InlineFormula` with blue color. In the biggest blue block, there are two words block`there is a finite subcover in` and `of the interval`. Consider one possible situation, there are five or more words block in the inline cell with depth 2. ![enter image description here](http://i.stack.imgur.com/Twaft.png)


title: How to define a function or procedure that includes multiple steps?

text: I would like to define a procedure or function that takes as input an integer, s, and gives as output two nested lists. I have written code (shown below) that does this for one particular value of s, but I don't know how to generalize it. I would like to be able to get the nested lists for different input values without having to define and re-define s. Any help or suggestions would be much appreciated!                   s = 4;         popIndicies = Range[s^2];         list = Table[Table[Partition[popIndicies, s], {3}], {3}];         test = list;         output = {};         Do[temp2 = {};           Do[            temp1 = {};            Do[             temp0 = {};     Do[AppendTo[temp0, test[[l, i, k, j]]], {j, s}];     AppendTo[temp1, temp0], {i, 3}];            row = Flatten[temp1];            AppendTo[temp2, row], {k, s}];           AppendTo[output, temp2], {l, 3}];         output = Flatten[output, 1];         Partition[output, s*3];         latticeWthPadding = {};         Do[AppendTo[latticeWthPadding, output[[s + i, s ;; 2*s + 1]]], {i, 0,             s + 1}];         neighborhoods = {};         Do[          Do[AppendTo[            neighborhoods, {latticeWthPadding[[i, j]],              latticeWthPadding[[i, j - 1]], latticeWthPadding[[i, j + 1]],              latticeWthPadding[[i - 1, j]],              latticeWthPadding[[i + 1, j]]}], {j, 2, s + 1}], {i, 2, s + 1}]         latticeWthPadding // TableForm         neighborhoods // TableForm


title: How to get a list of days from July 4th to Oct 4th over a range of years

text: I'd like to create a list with days from the 4th of July to the 4th of October starting in July 1970 to the current date. I tried to use `DateRange`, but I'm a bit confused cause the documentation is't very clear on this point. What should I do? Have you ever tried to do such a thing?


title: How to extract only real solutions from the result of Solve

text: For Example, I have the following polynomial equations: $$ \left\\{ \begin{array}{ll} \dfrac{2025 (208 x+5 (y-3446))}{52 (y+90)^2}+\dfrac{300 (8 x-21 y+1920) (y-80)}{7 (x+30)^3}+\frac{300 (80 x-21 z+4500) (z-100)}{7 (x+30)^3}-\dfrac{1521 (-539 x+50 z+15425)}{539 (z+39)^2} =0\\\\[30pt] \frac{2025 (445 y-208 z+49410) (z-45)}{52 (y+90)^3}-\dfrac{2025 (x-85) (208 x+5 (y-3446))}{52 (y+90)^3}-\frac{300 (8 x-21 y+1920)}{7 (x+30)^2}-\frac{1521 (-539 y+90 z+19680)}{539 (z+39)^2} =0\\\\[30pt] \frac{2025 (445 y-208 z+49410)}{52 (y+90)^2}+\frac{300 (80 x-21 z+4500)}{7 (x+30)^2}+\frac{1521 (x-25) (539 x-25 (2 z+617))}{539 (z+39)^3}+\frac{1521 (y-30) (539 y-30 (3 z+656))}{539 (z+39)^3}=0 \\\ \end{array} \right.$$ The mathematica expression:               {{(300 (1920 + 8 x - 21 y) (-80 + y))/(7 (30 + x)^3) + (        2025 (208 x + 5 (-3446 + y)))/(52 (90 + y)^2) + (        300 (4500 + 80 x - 21 z) (-100 + z))/(7 (30 + x)^3) - (        1521 (15425 - 539 x + 50 z))/(        539 (39 + z)^2)}, {-((300 (1920 + 8 x - 21 y))/(7 (30 + x)^2)) - (        2025 (-85 + x) (208 x + 5 (-3446 + y)))/(52 (90 + y)^3) + (        2025 (49410 + 445 y - 208 z) (-45 + z))/(52 (90 + y)^3) - (        1521 (19680 - 539 y + 90 z))/(        539 (39 + z)^2)}, {-((2025 (49410 + 445 y - 208 z))/(         52 (90 + y)^2)) - (300 (4500 + 80 x - 21 z))/(7 (30 + x)^2) - (        1521 (-25 + x) (539 x - 25 (617 + 2 z)))/(539 (39 + z)^3) - (        1521 (-30 + y) (539 y - 30 (656 + 3 z)))/(539 (39 + z)^3)}}      How to extract only those real solutions as new Rule? I mean a general approach to such solutions with mixed real and complex solutions in a rule.


title: A problem with parallelize

text: I am experimenting with `Parallelize` and `ParallelTable` This is the code I am using:               K[a_, b_, r_] = a*Exp[-r/b]/r;          T = D[K[10^5, 10^9, s], s]/299792^2 /. s -> 7.6          R = Range[0, 7, 0.01];     \[Theta] = Range[0, 2*Pi, 0.05];          RcG[d_, t_] = Sqrt[7.6^2 + d^2 - 2*7.6*d*Cos[t]];     f[a_?NumberQ, b_?NumberQ] :=        1/299792^2*NIntegrate[K[10^5, 10^9, x], {x, 7.6 - a, b}];          tab = Parallelize[        Table[1/299792^2*           d*(K[10^5, 10^9, RcG[d, t]] - K[10^5, 10^9, 7.6] - d*T) +           f[d, RcG[d, t]], {d, R}, {t, \[Theta]}]];     p1 = ListPlot3D[tab, InterpolationOrder -> 4]      I want make a 3d plot using the complicated function defined in the table. When computing, Mathem. gives this error a lot of times:               NIntegrate::inumr: The integrand K[100000,1000000000,x] has evaluated to non-numerical values for all sampling points in the region with boundaries {{7.3,7.30039}}.      It doesn't happen without the `Parallelize`, so this means that I am using it wrongly, but I don't get where. I also used `ParallelTable`, with the same result.


title: Convert an expression's symbols of form a$x to a[x]

text: I want a function that takes expressions of the following form: `a$x` and converts them to `a[x]`. In particular, consider the following test cases               exp = a$x + b$x$y + a$x[d] + a$x[d$y]      Should become, with some `ToFunctionNotation`:               ToFunctionNotation[exp] == a[x] + b[x][y] + a[x][d] + a[x][d[y]]      Note: I want to keep this as an expression for further processing. I tried using matches with `SymbolName` and string patterns, but couldn't figure it out.


title: Clearing arguments passed to a Module

text: Is there a possible way to clear the arguments passed to a module to release some memory. I believe that arguments passed to modules are passed by value rather than pass by reference. e.g. I have the following module               DoSomething[arglist_,arglist2_]:=Module[{localvar},     Some long computations...     (*Clear arglist here*)     Some further long computations...     (*Is it possible to reassign some other value to arglist here? e.g. arglist={1,2}*)     ];      I've tried to use Clear[arglist] but i've got the following Clear::ssym error, however Clear[localvar] was fine. All I wan't is to release some memory because my arglist_ is a list of million sublists and tens of elements in each sublist. Secondly Is it possible to reassign some other value to arglist here? e.g. arglist={1,2} within a module. Thanks in advance for the help.


title: How can I change the size of the plot markers

text: I use `ListPlot` in order to plot four sets of data and also insert legends in my plot. Here is the Mathematica code               data1 = {{0, 48}, {50, 59}, {100, 69}, {150, 78}, {200, 86}, {250,      87}, {300, 88}, {350, 88.5}, {400, 89}, {450, 89.5}, {500, 90}};     data2 = {{0, 50}, {21, 57}, {45, 65}, {69, 73}, {100, 82}, {150,      86}, {200, 90}, {250, 90.5}, {300, 91}, {350, 92}, {400,      93}, {450, 93.5}, {500, 94}};     data3 = {{0, 55}, {50, 60}, {100, 65}, {150, 72}, {200, 80}, {250,      84}, {300, 87}, {350, 89}, {400, 91}, {450, 91.5}, {500, 92}};     data4 = {{0, 63}, {50, 66}, {100, 69}, {150, 72}, {200, 74.5}, {250,      77}, {300, 79}, {350, 81}, {400, 83}, {450, 85}, {500, 87}};          col = {Blue, Darker[Green], Red, Magenta};     leg = {"\!\(\*SubscriptBox[\(L\), \(z\)]\) = 5",      "\!\(\*SubscriptBox[\(L\), \(z\)]\) = 20",      "\!\(\*SubscriptBox[\(L\), \(z\)]\) = 40",      "\!\(\*SubscriptBox[\(L\), \(z\)]\) = 60"};     plrange = {45, 100};          P0 = ListPlot[{data1, data2, data3, data4}, Frame -> True,      PlotStyle -> Table[{Thickness[0.003], col[[i]]}, {i, 1, 4}],      Joined -> True, PlotMarkers -> {Automatic, 12},      FrameLabel -> {Subscript["M", "n"],      "Percentage of chaotic orbits (%)"},      FrameStyle -> Directive[FontSize -> 17, FontFamily -> "Helvetica"],      PlotRange -> plrange, Axes -> False, ImageSize -> 600,      PlotLegends ->      LineLegend[leg, LegendMarkers -> Automatic,      LegendMarkerSize -> {{20, 25}},      LabelStyle ->       Directive[FontSize -> 15, FontFamily -> "Helvetica"]]]      which produces the following output using version 9 ![enter image description here](http://i.stack.imgur.com/MkdPR.jpg) My main issue is how to increase the size of the plot markers in the legend. Inside the main plot, I can control the size of the markers by `PlotMarkers -> {Automatic, 12}`. On the other hand, even though I tried a lot, I cannot do the same regarding the markers in the legend. Any ideas? Many thanks in advance.


title: Command to get License Management Monitor info

text: Using Netlink, when we have more users than _Mathematica_ licenses (used in a pool), we get messages such as: > Error code: 11. Connected MathLink program has closed the link, but there > might still be data underway, that I translate into a more user friendly message. There's a Wolfram License Management Monitor on a server and it generates these reports: Ref: http://uczelnia.mazovia.edu.pl/info/mathematica.html ![enter image description here](http://i.stack.imgur.com/j7zf2.png) Unfortunately the License Server is locked down (its still in the network unlike this: How to access Mathematica license server (being outside of the local network)) and I can't install IIS or a Windows Service to retrieve the License Report on demand. Is there a command that can be used in _Mathematica_ (via Netlink or Front- End) to get this information? ### Update As per http://reference.wolfram.com/mathematica/ref/program/monitorlm.html, I can't get this command to work:               monitorlm  "servername"


title: How to manipulate a Fourier sine series?

text: I would like to plot the Fourier sine series for $f(x) = x$. I would like to manipulate the parameter `n` from $0$ to $10$ and plot the sine waves over $(0,1)$. My code below does not work; what is wrong?               Manipulate[Plot[FourierSinSeries[x, x, n], {x, 0, 1}], {n, 0, 10}]


title: Create a Figure with a sequence of Balanced Binary Trees

text: I would like make the attached image by Mathematica. someone who could help me? Thank!![enter image description here](http://i.stack.imgur.com/j7A1g.jpg)


title: Code for solving numerically an integro-differential equation

text: First of all, I want to greet the community. This is my first question, but I hope I will be able to help answering others members questions, although I am quite new working with Mathematica. I would like to work out the numerical solution of this integro-differential equation: $$\partial_t P(t)=-\frac{1}{\hbar^2}\int_0^tg(t,\tau)P(\tau) e^{\frac{i}{\hbar}k(t-\tau)}d\tau$$ where $k$ is a constant. The function is defined as $$g(t,\tau)=\frac{\hbar^4}{4}\sum_{n=1}^N|\alpha_n|^2\exp[-i \omega_n\cdot(t-\tau)]=F_1(t-\tau)+iF_2(t-\tau)$$ Before deciding to solve numerically, I applied the Laplace transform to my equation (having in mind that I have a convolution product) and got $P(s)$ but I can't go any further because to restore $P(t)=\mathcal{L}^{-1}[P(s)]$ I need to solve the Bromwich integral and finding the poles of my function has no analytical solution. Again, at certain point I should use numerical methods so I prefer to start solving the equation numerically from the beginning and learn how to do that. To be honest, this is my first try in Mathematica and I would appreciate any help, comments focused on code writing. Thank you very much.


title: 2d heat conduction equation: Boundary and initial conditions are inconsistent

text: I have the following code for a 2d heat c equation:                soln = NDSolve[{        D[y[r, f, t], r, r] +                         (1/r)*D[y[r, f, t], r] +                      (1/r^2)*D[y[r, f, t], f, f] ==                                      (1/1.27*10^-4)*D[y[r, f, t], t],                y[r, f, 0] == 0,                y[10^-2, f, t] == 0,               (D[y[r, f, t], r] /.                     r -> 2*10^-6) == -(1/(3.14*10^-8))*(1 + Sin[2*2*3.14*t/2]),                (D[y[r, f, t], f] /. f -> 0) == -(10/238)*y[r, 0, t],                (D[y[r, f, t], f] /. f -> 3.14/2) == 0},                          y, {r, 2*10^-6, 10^-2}, {f, 0, 3.14/2}, {t, 0, 1}]      and I'm getting the two following error messages: NDSolve::ibcinc:   Warning: Boundary and initial conditions are inconsistent NDSolve::mxst:Maximim number of 10000 steps reached at the point t==1.629*10^-10 NDSolve::eerr:Scaled local spatial error estimate of 4203.0461 at t=1.840*10^-8 in the direction of independent variable r is much greater than prescribed error tolerance. Grid spacing with 51 points may be too large to achieve the desired accuracy or precision. A singularity may have formed or you may want to specify a smaller grid spacing using the MaxStepSize or MinPoints method options I saw an answer for the first one so i'm pretty ok with that but the second one is giving me trouble limitting the useful time domain.I cannot figure out why I'm getting this. Any help will be greatly appreciated! Claudiu


title: Save open Mathematica Notebook from command line or second Notebook to avoid data loss

text: I was executing a long Mathematica Notebook over night. The Mathematica instance is running on a Linux workstation (in a vnc server session to be precise). Now I cannot access this session anymore, which means that I likely loose the output data which was produced during the run. I can still login on the workstation as the same user and run Mathematica there. I know from the process list that Mathematica is still running, but I cannot access the GUI anymore. So, if there would be a remote control for Mathematica from command line or a second worksheet, which allows me to save the worksheet, I could prevent the data loss. I already tried to run a second instance of Mathematica but it seems that I cannot even see the Kernels there. Any ideas? It would save my day.


title: Manipulate slider unresponsive after suspend in Linux

text: I've tested Linux Mathematica versions 7-9 on various Linux distributions, with identical problem: after suspend/resume cycle my Manipulate controls (i.e. sliders&buttons) appear unresponsive, though I can enter the values manually. This looks much like this question, but before suspend I can use the controls normally, and if they stop working, restarting Mathematica also helps (killing and restarting math kernel doesn't help). Easy way to test this would be using this code:                 Manipulate[Plot[a x, {x, -3, 3}, PlotRange -> {-1, 1}], {a, -1, 1}]      Then making the machine suspend to RAM, waiting 5 seconds and resuming it. If the controls still work (I rarely encounter such situation), second suspend does kill them. Does anyone reproduce this problem? Are there any better workarounds than restarting Mathematica UI?


title: Working with a database

text: I just started to work with a database through _Mathematica_. I have a large data set. I use an `.mx` file to store my data. Now I have to store the data in a database, I have installed Microsoft SQL server 2012 in my system. My problem is I don't know how I should store my big list of data in the database. My options seem to be   1. store the mx file in database and retrieve it using SQL command in _Mathematica_   2. create a column in a database table and insert an element from my data list into each row. I tried the SQL route to insert the `.mx` file into the database, since I thought that would be better than inserting the list element-by-element.               insert into test select * from openrowset(bulk 'I:\MsSql\test.mx', single_blob) as test1       I executed the above line in Microsoft SQL server 2012. It appeared to work, but when I tried to retrieve my data set from the database table through _Mathematica_ , I got results that look like a big sublist containing some random numbers and characters. > {{282A546869732069732061......}} I have googled it, but I couldn't find a useful answer. Please explain what I did wrong or refer to me to good material I can learn from.


title: Find all permutations with a condition

text: How can I find all the permutations of `{a, b, c}` where `a + b + c = n`? For instance: if `n = 3` the permutations I seel are:   * `Permutations[{3, 0, 0}]`   * `Permutations[{2, 1, 0}]`   * `{1, 1, 1}`


title: CoordinateTransform from Cartesian to Spherical

text: I have a set of coordinates on the sphere in terms of cartesian coordinates. I would like to convert them to spherical data points. However, when I try to convert the point {0, 0, 1} it tells me that the solution is indeterminate. Why is this?               CoordinateTransform[ "Cartesian" -> "Spherical", {0, 0, 1}]      > ArcTan::indet: Indeterminate expression ArcTan[0,0] encountered. >> Best, Andy


title: How to test if all the elements in a list are Integers?

text: Consider a list such as `s={1,2,3,3,5,6,3}` With `IntegerQ[number]` , you know if `number` is an `Integer`, the result is `True`, and if not, the result is `False`. But... How to do this without visiting each element with a `Do[...,{i,1,Length[.]}]`?


title: How to show error messages in current notebook?

text: I would like Mathematica to print error messages in current notebook together with output. This is default option in Mathematica, but recently I turned it off somehow. Now, I am getting output in the notebook, and all cells with style Message go to this other window called Messages. How to set this option back?


title: Timing enclosed by Manipulate not working

text: **Manipulate[Timing[Show** [somegraphs[[1 ;; i]]]], {i, 1, 500, 1}] (in Mathematica 8) This is the last line of my function **f[x_]:= Module[....]**. I am trying to combine a list of graphs into a single graph. I want to test its performance so I add an Timing function within the Manipulate function. I want to find out the time it takes when I change the value of _i_. However, the output doesn't change as I change _i_ while clearly the time taken is increased.


title: Cumulative frequency plot

text: I have the following data:               data = {{0, 0}, {20, 1.4}, {25, 9.8}, {30, 32.2}, {35, 38.2}, {40, 15.6}, {45, 2.7}, {50, 0.1}};      where the second coordinates are frequencies measured as percent of total (adding, therefore, to $100$). I would like to produce a cumulative frequency plot. What would be the neatest way to do so?


title: Compare C++ Standard Library's Mersenne Twister with Mathematica's Mersenne Twister

text: The C++ standard library does contain a set of random distribution classes, among other things a Mersenne Twister engine. What I'd like to do is to generate the same random number distribution, using the same seed for C++ and Mathematica. For instance, generate 10 random numbers using the mersenne twister engine (C++):               std::vector<size_t> a1( 10 );     std::mt19937 gen(42);     std::generate(a1.begin(), a1.end(), gen);          /* {1608637542, 3421126067, 4083286876, 787846414, 3143890026, 3348747335,          2571218620, 2563451924, 670094950, 1914837113} */      and now I generate 10 random integers in _Mathematica_ using the MersenneTwister engine:               BlockRandom[SeedRandom[42, Method -> "MersenneTwister"]     RandomInteger[{0, 2^32 - 1}, 10]]          (* {3012359023, 1649004928, 188383571, 1935467488, 3494372723, 668236121,          1292572136, 98984411, 2487091843, 3121826951} *)      Apparently not the same. The mersenne twister in the C++ standard library uses the following default settings to generate the distribution: ![enter image description here](http://i.stack.imgur.com/cC5iN.png) The question is now: **How much influence do I have on _Mathematica's_ random number generator, so that I can overwrite some specific settings to generate the same set of numbers for a given seed**? EDIT: MathLink implementation MT19937Range: The .tm file:               :Begin:     :Function:      mersenneRange     :Pattern:       MT19937Range[seed_, len_]     :Arguments:     { seed, len }     :ArgumentTypes: { Integer, LongInteger }     :ReturnType:    Manual     :End:          :Evaluate:      MT19937Range::usage = ""      The .cpp file:               #include <random>          using namespace std;          void mersenneRange( int seed, long length )     {         mt19937 gen(seed);              MLNewPacket(stdlink);         MLPutFunction(stdlink, "List", length);             for(long x = 1; x <= length; x++)             MLPutLongInteger(stdlink, gen());     }      MLPutFunction expects as a third argument a int. So implicit conversion here with loss of precision. Is there a better alternative? The Mathematica side:               link = Install["wherever the binary is...",  LinkMode -> Launch]          MT19937Range[42, 10]          (* {1608637542, 3421126067, 4083286876, 787846414, 3143890026, 3348747335, 2571218620,        2563451924, 670094950, 1914837113} *)          Uninstall[link]


title: Image processing: Floor plan - detecting rooms' borders (area) and room names' texts

text: ![here is a simple building floor plan](http://i.stack.imgur.com/qDhl7.jpg) Here is a simple building floor plan. I would like to derive the _rooms as (rectangular) components and the names of the rooms_. This is very common representation of building floor plans. **The problem** So far I could clean up the floor plan. However, only the walls are left as one component but I would like to derive the _rooms as rectangular components_. In the solution - The rooms may have polygonal shapes as well as rectangles with small rectangular components called circulation areas, corridors or an other function name... alternatively they could added to living room or any other near function. My Question is how to proceed from here? **Code to start with**               img = Import["http://i.stack.imgur.com/qDhl7.jpg"]     nsc = DeleteSmallComponents[Binarize[img, {0, .2}]];     m = MorphologicalTransform[nsc, {"Min", "Max"}]      **Cleaned up floor plan** ![Cleaned up floor plan](http://i.stack.imgur.com/9ywgs.png) **EDIT 1** Some further information about the image. The image contains 2 types of information.   1. The geometric   2. The Spatial The Spatial information; it is important to abstract the room names for defining adjacency of spaces. The door and windows helps to define the adjacency matrix. The adjacency matrix with the geometric information can be used to calculate areas or boundaries. For example : ![Layout](http://i.stack.imgur.com/S6j4F.png)


title: How to simplify a complicated Sum in terms of power Sums?

text: For example, I have: $a=\sum _{r=1}^n x_r \left(\left(\sum _{i=1}^n x_i-x_r\right){}^2-\sum _{i=1}^n x_i^2\right)$               a =        Sum[Subscript[x, r]*          ((Sum[Subscript[x, i], {i, 1, n}] - Subscript[x, r])^2 -             Sum[Subscript[x, i]^2,  {i, 1, n}]),         {r, 1, n}]      and $\sum _{i=1}^n x_i=s_1, \sum _{i=1}^n x_i^2=s_2, \sum _{i=1}^n x_i^3=s_3$                c2 = Sum[Subscript[x, i]^2, {i, 1, n}] == s2      I would like to represent $a$ by $s_1, s_2, s_3$, e.g. $a=s_1^3+s_3-3s_1s_2$ . How should I do it? I tried `Solve` or `Eliminate`, but couldn't find a way.


title: Compiler stack overflow

text: I tried to compile a huge function. I used these options:               "RuntimeOptions" -> {"EvaluateSymbolically" ->         False}, CompilationOptions -> {"InlineCompiledFunctions" ->         True}, CompilationTarget -> "C", Parallelization -> True      After 700 seconds it returned this error: > CreateLibrary::cmperr: Compile error: > C:\Users\myusername\AppData\Roaming\Mathematica\ApplicationData\CCompilerDriver\BuildFolder\mypcname-6828\Working- > mypcname-6828-4884-1\compiledFunction0.c(1703108) : fatal error C1063: > compiler limit : compiler stack overflow >> > > Compile::nogen: A library could not be generated from the compiled function. > >> How can I diagnose the problem? I feel this is because of the C compiler limitation.


title: How to randomly erode a 3D distribution of points with Mma 7.0?

text: Suppose we have a 3D distribution of points, like the spherical ball example below :               Ball[num_]:=Table[     {         #1 Sqrt[1-#2^2]Cos[#3],         #1 Sqrt[1-#2^2]Sin[#3],         #1 #2     }          &[         Random[NormalDistribution[1, 0.5]],         Random[Real,{-1,1}],         Random[Real,{0,2Pi}]     ],{num}]          Graphics3D[{AbsolutePointSize[2],Point[Ball[10000]]},Boxed->True,BoxRatios->{1,1,1},ImageSize->800,SphericalRegion->True]      This code produces the ball shown here : ![A spherical distribution of points in 3D space](http://i.stack.imgur.com/ONB8Q.jpg) Obviously, this ball has a spherical symmetry and could be considered as a "smooth" distribution (under the limit of an infinite set of points). Now, I would like to randomly "erode" the distribution, to get something that look a bit like a fractal shape (think about how an eroded mountain could be obtain from a smooth hill). How can I do that ? What Mathematica procedures could modify the Ball distribution that act like a random eroding process ? To me, "eroding" mean _removing a randomly selected point, and several of its neighbors, then repeat the process several times_. Please, the suggestions should be compatible with **_Mathematica 7.0_**.


title: Empirical Cumulative Distribution Function

text: I have a data set of the form $d=\\{(y_1,x_1),(y_2,x_2)...(y_n,x_n)\\}$ for a large $n$. A non-parametric plot of this data (a scatter plot where all observations are sorted along $x$ and joined with a line in the $y-x$ plane) looks like this: ![enter image description here](http://i.stack.imgur.com/WdMXQ.jpg) I want to know how to construct (or define) an empirical distribution, for which the CDF corresponds to this plot. I know that the function `EmpiricalDistribution` could create a distribution function from $d$. The question, however, is how to generate in Mathematica a function from an empirical CDF.


title: Why does simplification in Mathematica depend on variable names

text: _Mathematica_ fails to put the following into an obvious simplest form:                  numerator = C2p D2 (C1y N1x - C1x N1y - C1y N2x + N1y N2x + C1x N2y - N1x N2y) +      C1p D1 (-(C2y N1x) + C2x N1y + C2y N2x - N1y N2x - C2x N2y + N1x N2y)          numerator = Simplify[numerator]        produces               C2p D2 (-(C1x N1y) + C1y (N1x - N2x) + N1y N2x + C1x N2y - N1x N2y) +      C1p D1 (C2x N1y - N1y N2x + C2y (-N1x + N2x) - C2x N2y + N1x N2y)        which has obvious simplification failures If I change the name of a variable it succeeds.               numerator = ReplaceAll[numerator,{N2y -> aN2y}]     numerator = Simplify[numerator]          C2p D2 (aN2y (C1x - N1x) + C1y (N1x - N2x) + N1y (-C1x + N2x)) +      C1p D1 (aN2y (-C2x + N1x) + N1y (C2x - N2x) + C2y (-N1x + N2x))          numerator = ReplaceAll[numerator,{aN2y -> N2y}]              C2p D2 (C1y (N1x - N2x) + N1y (-C1x + N2x) + (C1x - N1x) N2y) +      C1p D1 (N1y (C2x - N2x) + C2y (-N1x + N2x) + (-C2x + N1x) N2y)      Once one knows that success depends on the variable names, possibly an alphabetic sort order in the sum somewhere, one knows what to do in order to simplify, but I am concerned about much bigger expressions where you don't know that you need to trick it. Is there any way to get _Mathematica_ to get past this variable name dependence? `FullSimplify` does not help here.


title: Fortran kind of matrix creation

text: I want to create the matrix H of dimensions nxn and matrix elements H(i,j). Because of the physical problem I am dealing with, it is necessary to build it in the following not trivial way. I know how to do it in Fortran, but this time I have not been able to figure out how to do it in Wolfram Mathematica. FORTRAN WAY:                 do iy=1,n               do ix=1,n                  do jy=1,n                     do jx=1,n                      i = ix+(iy-1)*n                      j = jx+(jy-1)*n               (Now I give a list of "If" about i and j, and give values to my matrix elemnts H(i,j))                      enddo             enddo         enddo     enddo      Does anybody know how to do this in Wolfram Mathematica?


title: How to apply a permutation to a symmetric square matrix?

text: Given a symmetric square matrix, how can I apply a permutation to the rows and columns (i.e. the same permutation to both the rows and the columns) such a way that the new structure of the matrix should follow the new row and column order? Consider an order of rows/columns, according to which the elements of a set are arranged in a matrix:               order = Range[5];     matrix = Table[Subscript[a, i, j], {i, 5}, {j, 5}];     TableForm[matrix, TableHeadings -> {order, order}]      ![Mathematica graphics](http://i.stack.imgur.com/l9T57.png) Now take a permutation of the row/column order:               newOrder = RandomSample[order]     (*        ==> {1, 4, 5, 2, 3}     *)      `FindPermutation` finds the appropriate permutation cycle for the new order:               permutation = FindPermutation[order, newOrder]     Permute[order, permutation]     (*        ==> Cycles[{{2, 4}, {3, 5}}]        ==> {1, 4, 5, 2, 3}     *)      Now the question is: **How to easily and elegantly apply the above permutation (preferably in its`Cycles` form) to the matrix to yield the following one**: ![Mathematica graphics](http://i.stack.imgur.com/1wQrV.png) Some notes:   * The `matrix` is always square and symmetric.   * Column and head orders are always identical.   * Bear in mind that `order`, and consequently `matrix`, can be big (e.g. `4^8` for `order`)   * Since `matrix` can be big, I'm looking for a method, that applies the permutation 'locally', that is without reconstructing the whole table every time, or without applying replacements/functions enumerating each element, thus no dispatch table should be used. This is rather important, as it could be that the new order only swaps two columns/rows, and nothing else.


title: About high dimensional integrals

text: I want to be able to do high dimensional integrals like, (..naively I wrote it as this..)               Nc = 12; Nn = 12;      f [x_] := (Sin[x])^2;     g[n_, x_] := Cos[n*(x)];     Integrate[ (Times @@          Flatten@Table[           f[(a[i] - a[j])/2], {i, 1, Nc - 1}, {j, i + 1, Nc}])*       SeriesCoefficient [         Series [          Exp[ Plus @@            Flatten@Table [   ((4)/(n (x^(-n/2) + x^(n/2))))*(Plus @@                 Flatten@                 Table[g[n, a[i] - a[j]], {i, 1, Nc}, {j, 1, Nc}]), {n, 1,               Nn}] ], {x, 0, 1}], 1/2], {a[1], -\[Pi], \[Pi]} , {a[        2], -\[Pi], \[Pi]}  , {a[3], -\[Pi], \[Pi]} , {a[        4], -\[Pi], \[Pi]}, {a[5], -\[Pi], \[Pi]}, {a[        6], -\[Pi], \[Pi]}, {a[7], -\[Pi], \[Pi]}, {a[        8], -\[Pi], \[Pi]}, {a[9], -\[Pi], \[Pi]} , {a[        10], -\[Pi], \[Pi]}, {a[11], -\[Pi], \[Pi]}, {a[12], -\[Pi], \[Pi]}]      But the above has been like running for ages without an output. I would like to know how I can optimize this work so that I can push this to higher levels. For instance I would like to extract higher powers of $x$ rather than $1/2$ as in the above example and also to more variables than $12$ as above.


title: What's fastest way of defining 10^5 down values?

text: I want to define               isGood[___] = False;          isGood[#] = True & /@ list      where `list` is a list of several million integers. What's the fastest way of doing this?


title: LogPlot of the calculated data in For Loop in Mathematica

text: I have the following loop, for calculating a data for different values of inputs. How I can plot the result at the end of For loop? Its not matter if the plot is inside or outside the loop, I just want to plot the results.               Clear["Global`*"];     b = 10^4;     s = b/2;     tx = ((2*RandomInteger[1, s])-1) + (I*((2*RandomInteger[1, s]) - 1));     For[i = 0, i <= 20, i++, snrdb = i;      snr = 10^(0.1*snrdb);      sd = 1/Sqrt[snr/2];      noise = 1/Sqrt[2]*(RandomReal[NormalDistribution[], {s, 1}] + I*RandomReal[NormalDistribution[], {s, 1}]);      y = tx + (sd*noise);      rx = Flatten[Sign[Re[y]]+I*Sign[Im[y]]];      error = Unitize[tx-rx];      ber = Total[error]/b;      Print["Total number of errors: ",Total[error]];      Print["Error rate: ",N[ber]];      ]     LogPlot[{ber, 10^-4, 10^0}, {snrdb, 0, 20}]      * * * Thanks All, Both techniques was useful. Sorry b is the same as bits, I made a mistake I corrected later. I need the continous line not discrete. how to change the y axis to be from 10^-4 to 10^1? Note: for the purpose of accuracy I increased b to 10^6.               Clear["Global`*"];     b = 10^6;     sym = b/2; tx = ((2*RandomInteger[1, sym]) -          1) + (I*((2*RandomInteger[1, sym]) - 1));     bervals = Reap[         For[i = 0, i < 21, i++, snrdb = i;          snr = 10^(0.1*snrdb);          sd = 1/Sqrt[snr/2];           noise = 1/             Sqrt[2]*(RandomReal[NormalDistribution[], {sym, 1}] +               I*RandomReal[NormalDistribution[], {sym, 1}]);           y = tx + (sd*noise); rx = Flatten[Sign[Re[y]] + I*Sign[Im[y]]];           error = Unitize[tx - rx];          Sow[ber = Total[error]/b];          ]][[2, 1]];     ListLogPlot[bervals, Joined -> True]


title: CurveGraphics for 3D System of DEQs

text: I am using the _CurveGraphics6_ NB to try and do some 3D related phase portraits and graphics. The following works and produces an animation.               pic = NDSolve[( {        {x'[t] == 2 y[t] (z[t] + 1)},        {y'[t] == -x[t] (z[t] + 1)},        {z'[t] == -(z[t])^3},        {x[0] == z[0] == 0},        {y[0] == 1}} ),         {x, y, z}, {t, -9, 9}, Animate -> True, PlotPoints -> 600,       ImageSize -> 300, HeadLength3D -> 1/30, DefaultDuration -> 40] // Last      I then attempt:                 Export["temp.gif", pic]      It exports the gif, but not the animation. What am I doing wrong? I also welcome if anyone has ideas on how to better show this in 3D. I do not see how to use the nice 3D Phase Portrait on the system above and maybe someone will be kind enough to provide guidance (as that is what I was really after).


title: Shaving the last 50 ms off NMinimize

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


title: How does one draw a parallelepiped in Mathematica?

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


title: Grid rows height & SpanFromAbove issue

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


title: Write any positive integer as a sum of squares

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


title: Remote Kernel and CUDALink

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


title: Counting the zeros in a factorial expansion

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


title: How do I re-direct FilePrint's output?

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


title: Convert coefficients of polynomials into a matrix

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


title: How do I plot a U- form cylinder

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


title: Color linear interpolation of ParametricPlot3D

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


title: Help with Reduce, quadratic system of inequalities

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


title: Few quick Mathematica questions about Dictionary

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


title: Using KalmanFilter or KalmanEstimator

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


title: How can I get the style of selected cells?

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


title: Trouble using If[] within TabView Manipulate control

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


title: StringCases using RegularExpression fails when there is missing data

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


title: Applying a function with the HoldAll attribute inside NestList

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


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


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

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


title: Connecting a vertex to middle of an edge with GraphPlot?

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


title: Replace interior of matrix with zeros

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


title: Dashboard TV with CDF Player

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


title: Problem with ParametricPlot of multiple Curves

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


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

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


title: Finding critical points of a function

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


title: Spherical harmonic derivative

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


title: Better Autocompelete for the Front-End

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


title: Calculating an exact orthogonal modal matrix in Mathematica

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


title: Generation function of recurrence sequence

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


title: How to distinguish between lists and values?

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


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

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


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

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


title: Lesser and greater symbols in the axeslabels

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


title: DSolve solves PDE only without boundary condition, but fails otherwise

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