Exception/Error handling using returns codes

There is good explanation available for error handling on this and similar links. Here there is information on handling inappropriate input arguments and handling unprocessed functions using `$Failed`. But it is much of incomplete because I want to catch error message and according to that display some specific message. For example if I get               Integrate::idiv: Integral of E^n does not converge on {1,\[Infinity]}. >>      Than I want to display some specific message in words which is possible if I can capture this message and extract from it or if Mathematica returns some error code associated. Is there some better technique available than just using `$Failed` everywhere ?


ListPlot doesn't shows all points

I have a table: `p1 = Table[(Binomial[2000, k]*StirlingS2[1386, k]*k!)/(2000^1386), {k, 1, 1386, 1}];` I used `ListPlot[p1]` to draw a plot of this values. This is the plot, where on `Y` I have values of `p1` and on `X` I have values of `k`. But when I draw my plot, I see only points which are starting from $k \approx 560$. Why I can't see points for all values of `k`? Is this because of that values for small `k` are too small? How can I fix that?


Color inversion using ArrayPlot

I have a 3D data that I want to visualise its each slice with ArrayPlot. However, there is a problem the way it represents the data. As, > ArrayPlot by default generates grayscale output, in which zero values are > shown white, and the maximum positive or negative value is shown black. It conflicts with the general idea, cause it should represent 0 values as black, max value(if it is scaled, equals to 1) as white and the rest of the values as gray levels. I am playing with it and I wrote a code sample:               ArrayPlot[data, ColorFunctionScaling -> True, ColorRules -> {1 -> White, 0 -> Black}]      I am not sure whether it is correct. Actually, I am not satisfied with the result. Any help is appreciated.Thanks.


Computing the Hurst exponent or fractal dimension of fractional Brownian motion

The Hurst exponent is related to the fractal dimension by noticing that the fractal dimension $D$ is equal to $2-H$, where $d$ is the intrinsic dimension and $H$ is the Hurst exponent, for 1-D fractional Brownian motion. I can generate an fBm series in _Mathematica_ as follows:               tlow = 1;     thigh = 1000;     tinc = 1;     hurst = 0.4;         dataz=RandomFunction[FractionalBrownianMotionProcess[hurst], {tlow, thigh, tinc}, 1];      However, using the method described here to compute the fractal dimension, I am unable to get close to recovering the Hurst exponent used to generate the fBm. For example:               stdev[{x__}] := StandardDeviation[{x}]     stdev[{x_}] := 1     dataf = RotateRight[Mean[R /@ #/stdev /@ #] & /@ (Partition[dataz, 2^#] & /@ Range[10])]     Fit[Log[dataf], {1, x}, x]      Is this a numerical error or are there better ways to compute Hurst exponents and fractal dimension in _Mathematica_?


How to make a conditioning plot?

I'd like to make a conditioning plot just like coplot in R. Is there a pre- made solution or do I have to make a bunch of plots individually? Edit: This is an example from r screenshots. It is a way of looking at multivariate data. Each individual graph represents the respective bar in the conditioning variable or factor. In this case you see ozone vs solar for different levels of wind and temp. ![Image](http://i.stack.imgur.com/QeehJ.png) Edit2: The R-integration looks interesting. I just found a StackExchange question about returning the plot to an output cell in Mathematica, so that works. I just thought there would be a built in function as these plots seem pretty popular in statistics. In r-code I would just type coplot(a~b|c) to see a vs b for levels of c.


Plotting piecewise function with distinct colors in each section

I have a piecewise function that I would like to plot but I was wondering if it is possible that each part of the function that is plotted when its corresponding condition is true be plotted with a different color from the other parts. That is, if I have a Piecewise function `Piecewise[{{val1, cond1},{val2,cond2},{val3,cond3}}]` then I want `val1`, `val2`, and `val3` to be plotted with different colors so that I can differentiate each case in the plot.


Is Wolfram Language suitable for building web applications?

My goal is to find a technology which will afford me to build web applications (e.g. simple social networking site) as quickly as possible (with as little code as possible). I was impressed by Stephen Wolfram's video presentation: it looks like that the Wolfram Language is the tool which I sought: such that any task that I can formulate in a few words can also be implemented in the language with a line or two of code. But I've seen no explicit discussion about using Wolfram Language for building websites and web applications. Update. Let me clarity what I mean. Consider the following example. * * * Suppose I’m going to organize an event (a seminar) so I decided to make a website to communicate with participants conveniently: every potential participant will sign up and fill in a registration form; then he will be able to post questions and subscribe to other’s questions he is interested in so that he will be notified by email when such question is answered. And when I want to get some additional info from participants (e.g. an exact time of participant’s arrival to the airport), I add this additional field to the registration form and set up a procedure that will every day send an email “Please answer this additional question” to every user that has not answered it yet. So I write something like this:               mysite = CreateWebsite(     Title: "The seminar"     Authorization: {"Facebook","Twitter","Google"}     )          mysite.AddQuestionnaire(     "Name": text     "Surname": text     "Date of arrival": date     )          mysite.AddQuestionsAndAnswers(SubscribeButton = True, NotificationType = "Email")          mysite.Deploy("http://theseminar.com")      And then I get a standard-looking website with all mentioned functionality. Everything has a default, and if I want to change some details, I just specify the corresponding options explicitly. * * * It seems that this should be the right way to create websites. Such that the website creator can concentrate all his mental efforts on the conceptual design of his application without need to waste it on the low-level stuff like html and css. This looks like fitting well with the ideology of Wolfram Language. This would democratize web development, i.e. a lot of internet users who are not professional web-developers would be able to quickly create web applications tailored for their needs. There are important benefits when the user of a piece of software is himself the creator of this software — the feedback-based iteration becomes extremely fast and effective: when you-as-a- user see some possibility to improve the software, you immediately and accurately convey this vision to you-as-a-programmer who will change the software; then you-as-a-user immediately see the result and assess it; then continue such iterations until the result is perfect.


Multiple level lists

Let there be a list,               Sample={{{1, 2, 3}, {a, b, c}}, {{2, 3, 4}, {d, f, g}}}      I want to go to individual sublists and do some operation on it.I tried a few things like rule and replace.               sam /. {x_, y_} -> {x -> {a_, b_} -> {a + b}, y /. {w_, e_} -> w^e}      but I get               {{{1, 2, 3}, {a, b, c}} -> {a_, b_} -> {a + b}, {{2, 3, 4}, {d, f, g}}}      But I am not getting to individual lists. I want to use only rule or replace. **Edit** : To make my question more clear I want to specify that I am not interested in one particular list operation. My idea is to be able to traverse sublists using `Rule` or `Replace` and then work on it. My expected result is like               {{{1 + a, 2 + b, 3 + c}}, {2^d, 3^f, 4^g}}


Efficient image Import

I have several sets of 20 images I need to import. ![enter image description here](http://i.stack.imgur.com/l0yz5.png) Each time they have different categories. "Name"<>"Cat"<>"No" Electric B 1 for example. I need to create lists that contain the images for those different categories. As of now this is what i am doing :               importOne[set_, cat_, num_] :=       ImageResize[       Import[FileNameJoin[{NotebookDirectory[], set,               set <> cat <> ToString[num] <> ".png"}]], 128]                    ElectricB = importOne["Electric", "B", #] & /@ Range[6];     ElectricC = importOne["Electric", "C", #] & /@ Range[5];     ElectricN = importOne["Electric", "N", #] & /@ Range[5];     ElectricE = importOne["Electric", "E", #] & /@ Range[4];      And then, thanks to previous question/answers : ![enter image description here](http://i.stack.imgur.com/VTO9P.jpg) **What would be a more efficient mean to import automatically for different sets ?** As of now I need to repeat this operation for each set.


Which Distributions can be Compiled using RandomVariate

Recently, Oleksandr kindly showed a list of Mathematica commands that can be compiled. RandomVariate was part of that list. However, whether this can be compiled depends upon the distribution that is being sampled.               Needs["CompiledFunctionTools`"]          cf1 = Compile[{{m, _Real}, {s, _Real}},       Module[{v1, v2, v3, v4, v5, v6},        v1 = RandomVariate[NormalDistribution[m, s]];        v2 = RandomVariate[UniformDistribution[{m, s}]];        v3 = RandomVariate[GammaDistribution[m, s]];        v4 = RandomVariate[PoissonDistribution[m]];        v5 = RandomVariate[ChiSquareDistribution[m]];        v6 = RandomVariate[ExponentialDistribution[m]];        {v1, v2, v3, v4, v5, v6}        ]       ]      Using CompilePrint shows that RandomVariate can be compiled for the Normal Distribution or the Uniform Distribution and not with some others.               CompilePrint[cf1]          2 arguments             4 Integer registers             8 Real registers             1 Tensor register             Underflow checking off             Overflow checking off             Integer overflow checking on             RuntimeAttributes -> {}                  R0 = A1             R1 = A2             Result = T(R1)0          1   R2 = RandomNormal[ R0, R1]]     2   R3 = RandomReal[ R0, R1]]     3   I0 = MainEvaluate[ Function[{m, s},                   RandomVariate[GammaDistribution[m, s]]][ R0, R1]]     4   I1 = MainEvaluate[ Function[{m, s},                   RandomVariate[PoissonDistribution[m]]][ R0, R1]]     5   I2 = MainEvaluate[ Function[{m, s},                   RandomVariate[ChiSquareDistribution[m]]][ R0, R1]]     6   I3 = MainEvaluate[ Function[{m, s},                   RandomVariate[ExponentialDistribution[m]]][ R0, R1]]     7   R4 = I0     8   R5 = I1     9   R6 = I2     10  R7 = I3     11  T(R1)0 ={ R2, R3, R4, R5, R6, R7 }     12  Return      Does anyone have a list of all the distributions that can be compiled (including, PDF, CDF and RandomVariate functionality)?


Searching for phrases in a block of text

One could call this a pattern finding question with dictionary (or WolframAlpha) lookup, but let me give you some background first. I have a couple of friends who are trying to improve their English listening skills by watching TV shows in English, with English subtitles. I have access to the subtitles in text format which I can import and process as I like. Now it is easy to pick out common words from a list of words using something like `Tally`, but what I would like to do is more complicated. I want to pick out phrases (and perhaps some longer or slang-like words) that a non-native speaker may not recognize. I understand I need some sort of a lookup for this, and I thought of using WolframAlpha's `Phrase:WordData` pod, but it doesn't show up for every word, and didn't exactly do what I really wanted. I'll provide an example block of text below if anybody would like to go ahead and try it using whatever method they would like.               myStr = "Wow that must have been an awful result. That was not even close! People didn't even find out until they reviewed the footage.";     myStrList = StringCases[myStr, WordCharacter ..]      And this gives > {"Wow", "that", "must", "have", "been", "an", "awful", "result", "That", > "was", "not", "even", "close", "People", "didn", "t", "even", "find", "out", > "until", "they", "reviewed", "the", "footage"} Now I'd like an output that might look like something like > {"awful", "not even close", "find out", "reviewed", "footage"} I know this is rather vague, but I think determining search patterns and how the search would be executed would be a good start.


Integrating Squared of Interpolating Function with respect to one variable

I am interested in evaluating a two dimensional interpolating function produced by solving the wave equation. Here is the code that includes the resulting interpolating function.               pde = D[y[x, t], t, t] == D[y[x, t], x, x]          solnDerivative = NDSolve[{pde, y[x, 0] == Exp[-(x)^2], Derivative[0, 1][y][x, 0] == 0,        Derivative[1, 0][y][-50, t] == Derivative[0, 1][y][-50, t],       Derivative[1, 0][y][50, t] == - Derivative[0, 1][y][50, t]},        Derivative[0, 1][y][x, t], {x, -50, 50}, {t, 0, 130}]          ifunDerivative  = First[Derivative[0, 1][y][x, t] /. solnDerivative]      Here, I wanted to first integrate squared of `ifunDerivative` with respect to t from `{0,130}` then get a new interpolating function as a function of `x` only. The first problem I ran into is that it won't evaluate this integral and spits back out the input.               integratedFunction = Integrate[(ifunDerivative[x, t])^2, {t, 0, 130}, x]      How can I go about numerically integrating interpolating function squared with respect to `t`? Then, obtain a solution that depends only on `x`? Please help me! Thank You!


Solving a time-dependent Schroedinger equation

I want to solve the time-dependent Schroedinger equation: $$ i\partial_t \psi(t) = H(t)\psi(t) $$ for matrix, time-dependent $H(t)$ and vector $\psi$. What is an efficient way of doing this so that it efficiently scales to high- dimensional spaces?


Defining a Gaussian Distribution Fit to data

I am given a set of data and told ahead of time that the data will need to be fitted to a _Gaussian Distribution_. I know that _Mathematica_ has preset functions for linear, quadratic, and cubic fits, but how do I define a new equation to fit the data to? From this, I will need the s.d., the `x_average`, and the `A` values. The _Gaussian Distribution_ is to be defined as so:               N(x) = A/(sqrt(2*3.1416)*w)*exp(-(x-x_average)**2/(2*(w**w**2))      * * * So far I have:               Needs["ErrorBarPlots`"];          SetDirectory[];     SetDirectory["/Users/stevendang/Downloads"];          dataContent = Import["data.dat"];          dataOrganized =       Table[{{dataContent[[i, 1]], dataContent[[i, 2]]},       ErrorBar[dataContent[[i, 3]]]}, {i, 2, Length[dataContent]}];      ErrorListPlot[dataOrganized,       FrameLabel -> {"Y, X", "Gaussian Distribution"},       PlotRange -> {{0, 30}, {0, 40}}]          dataFit =       Table[{dataContent[[i, 1]], dataContent[[i, 2]]}, {i, 2, Length[dataContent]}]          FindFit[dataFit, (A/((2*3.1416)^(1/2)*w))*e^(-(x - xave)^2/(2*w^2)), {A, w, xave}, x]      Also I've tried "FindDistributionParameters" instead of FindFit but Mathematica doesn't have a built in Gaussian Distribution to work with. Any thoughts? The following isn't giving me values for A, w, xave.


ParametricPlot - Problem with ColorFunction

I am unhappy with the following mapping:               ParametricPlot[{Re@Sin[u + I v], Im@Sin[u + I v]},      {u, -Pi/2, Pi/2}, {v, -Pi/2, Pi/2},      ColorFunction -> (ColorData["DarkRainbow"][#3] &),      ImagePadding -> 20,      ImageSize -> 400,      PlotPoints -> 30]      ![enter image description here](http://i.stack.imgur.com/VwoCa.jpg) because of the distinct coloring of its left and right part. I found a certain fix with this:               ParametricPlot[{Re@Sin[u + I v], Im@Sin[u + I v]},      {u, -Pi/2, Pi/2}, {v, -Pi/2, Pi/2},      ColorFunction -> (Blend[{Red, Green, Yellow, Blue, LightBlue, Blue,            Yellow, Green, Red}, #3] &),      ImagePadding -> 20,      ImageSize -> 400,      PlotPoints -> 30]      ![enter image description here](http://i.stack.imgur.com/iY1J8.jpg) But I really would prefer to use one of the inbuilt gradients to color my figure according to its polygon size or "mesh density". Thanks in advance for your suggestions.


Wrong values at the boundary of differential equation solution

I have a second order ordinary differential equation and want to solve it numerically. Although I have specified values at the boundary, Mathematica solution does not match with boundary conditions.               h = 10.6     F = 0.001     d = 1.0     L = 100*d     phi[x_] :=       Piecewise[{{0.5*(1 - Tanh[x]),          x < L*0.5/d}, {0.5*(1 + Tanh[x - L/d]), x > L*0.5/d}}]     s = NDSolve[{u''[x] == (h)*phi[x]*phi[x]*u[x] - F*d*d*(1 - phi[x]),         u[-2.5] == 0.0, u[L + 2.5] == 0.0}, u, {x, -2.5, L + 2.5}]     vL[x_] := u[x]/(1 - phi[x])          Plot[Evaluate[{vL[x]} /. s], {x, L/d + 1.5, L/d + 2.5},       PlotRange -> All]          {u[-2.5], u[L + 2.5]} /. s      ![Mathematica graphics](http://i.stack.imgur.com/sPymr.png) > >     {{9.02944, -1.11442*10^-25}} >   What is the correct way to set the boundary conditions?


How do you put conditions on indices in a sum?

I'm relatively inexperienced with mathematica, so I apologize if this is a trivial question. I want to take a double sum over a function $f(i,j)$ of two indices, of the form $$ \sum_{i = -\infty}^\infty \sum_{j = 0\atop j\not = i}^m f(i,j). $$ That is, in the inner sum I want to sum over only those indices $j$ in my range of summation that satisfy the assumption $j \not = i$. How can I input such a sum to Mathematica?


Speeding up numerical Fourier Transform

I wrote this function `NFourierTransform`, which takes a function $f(k)$ and numerically calculates the fourier transform integral for discrete values of $k \in [k_{\text{min}},k_{\text{max}}]$, finally returning an `InterpolatingFunction` object.               NFourierTransform[f_Function, {kmin_, kmax_}] :=       Interpolation@       Table[{k, Chop@NIntegrate[f@x E^(-I k x), {x, -Infinity, Infinity}]},        {k, kmin, kmax, (kmax - kmin)/100}]      In my application (calculating the time propagation of wave functions) I need to evaluate `NFourierTransform` for a function $\psi(k,t)$, where $t$ assumes discrete values in some interval $[t_{\text{min}},t_{\text{max}}]$. So effectively I create a table of `NFourierTransform`.               TimePropagate[f_Function, kl : {kmin_, kmax_}, {tl__}] :=      Quiet@Table[        NFourierTransform[f[#] Exp[-(#^2/2) t] &, kl], {t, tl}]      Calculating a very simple example with only 2 time values, e.g. `TimePropagate[Exp[-Abs@#] &, {-3, 3}, {0, 0.1, 0.1}]` takes about 20 seconds to evaluate. Is there any way to use `Compile` to speed up the calculations? As far as I know that's only possible for numeric function arguments. What are, in your experience, suitable setings for `NIntegrate` options such as `MaxRecursion` or `AccuracyGoal`, and how do they effect evaluation time?


LibraryLink path problem

I have a library function that need to load some external data files. But it looks that the path in the default path of library function is the path that Mathematica is currently in. Is there a way to make a dynamic library that use the current path as the default path? Here is an example: Consider a library function that reads a integer from the file example.txt, which is at the same directory as the dynamic library files. The example.txt contains only one integer number in it:               cat example.txt     20      And here is the source of the library function:               #include "WolframLibrary.h"     #include <iostream>     #include <sstream>     #include <fstream>     #include <string>          using namespace std;          DLLEXPORT mint WolframLibrary_getVersion(){       return WolframLibraryVersion;     }     DLLEXPORT int WolframLibrary_initialize(WolframLibraryData libData){       return 0;     }          EXTERN_C DLLEXPORT int readstring(WolframLibraryData libData, mint Argc, MArgument* Args, MArgument Res)     {       int a;       string line;            ifstream file("example.txt");            getline(file,line);       istringstream iss(line);       iss>>a;            MArgument_setInteger(Res, a);       return LIBRARY_NO_ERROR;     }      In the above code, the `ifstream file("example.txt")` tries to load a file that at the same directory as the library file, but since the current directory is the directory of Mathematic, it cannot find the file example.txt and will crash the kernel. There are two solutions that I know:   1. Use absolute path. For example change  `ifstream file("example.txt")` to something like `ifstream file("/Users/xslittlegrass/example.txt")`   2. Change the current directory of Mathematica by something like SetDirecotory["/Users/xslittlegrass/"] before calling the library function. Question: Is there other solutions, that can somehow tell the library function to search it's current directory? Because I will use the library function in parallel, and there may be many copies of library files in different locations, so I would prefer a more clean way to call the library function, instead of manually changing the path each time I call.


Positioning ChartLabels in a horizontal stacked BarChart

I can create a `BarChart` with horizontal bars (using `BarOrigin -> Left`) and _Mathematica_ will automatically position the `ChartLabels` on the left hand side:               data1D = RandomReal[{1, 10}, 10];     labels = DictionaryLookup["D*", 10];          BarChart[data1D, BarOrigin -> Left, ChartLabels -> labels,       BaseStyle -> {FontFamily -> "Calibri", 14}]      ![enter image description here](http://i.stack.imgur.com/pP9Go.png) However, if I want to plot a stacked chart in the same way, the `ChartLabels` appear below the bars:               data2D = RandomReal[{1, 10}, {10, 2}];          BarChart[data2D, BarOrigin -> Left, ChartLayout -> "Stacked",       ChartLabels -> {labels, None},       BaseStyle -> {FontFamily -> "Calibri", 14}]      ![enter image description here](http://i.stack.imgur.com/rM2LS.png) How can I get the labels for the stacked chart to appear as they do in the simple chart?


Using SimMetrics Java Function on Mathematica

I would like to know if it's possible to use/install this java library on Mathematica. This library, named SimMetrics, has a lot of string similarity functions that I would like to test. Here is the list of functions: > Levenstein, NeedlemanWunch, SmithWaterman, SmithWatermanGotoh, > SmithWatermanGotohWindowedAffine, Jaro, JaroWinkler, ChapmanLengthDeviation, > ChapmanMeanLength, QGramsDistance, BlockDistance, CosineSimilarity, > DiceSimilarity, EuclideanDistance, JaccardSimilarity, MatchingCoefficient, > MongeElkan, OverlapCoefficient. I have no knowledge on Java and use a MAC. A thought in Leonid Java Reloader, but it's a complete .jar file, not a small class. ## Update I download the simmetrics_jar_v1_6_2_d07_02_07.jar from the link above, saved it on notebook directory and tryed:               Needs["JLink`"]     ReinstallJava[ClassPath->"/System/Library/Java/JavaVirtualMachines/:"<>NotebookDirectory[]<>"simmetrics_jar_v1_6_2_d07_02_07.jar"]          Now I have to use LoadJavaClass? How can a list the available classes? If I unzip the .jar file, the classes are inside this folder: uk/ac/shef/wit/simmetrics/similaritymetrics/ for example: Levenshtein.class


Having Mathematica solve or help solve a set of 8 equations

There is a set of DDE's that arise in leukemia dynamics and I'd like to find the equilibrium points of the system by setting all of the derivatives equal to zero. The system can be described in _Mathematica_ code as follows:               Ctotal = y0 + y1 + y2 + y3 + z0 + z1 + z2 + z3;     p[C_, T_, cn_, p0_, k_] := p0*Exp[-cn*C]*k*T;     dy0dt[ry_, u_, d0_, qC_, cn_, p0_, k_] :=        (ry (1 - u) - d0)*y0 - qC*p[Ctotal, T, cn, p0, k]*y0;     dy1dt[ay_, d1_, qC_, cn_, p0_, k_] :=        ay*y0 - d1*y1 - qC*p[Ctotal, T, cn, p0, k]*y1;     dy2dt[by_, d2_, qC_, cn_, p0_, k_] :=        by*y1 - d2*y2 - qC*p[Ctotal, T, cn, p0, k]*y2;     dy3dt[cy_, d3_, qC_, cn_, p0_, k_] :=        cy*y2 - d3*y3 - qC*p[Ctotal, T, cn, p0, k]*y3;     dz0dt[rz_, d0_, ry_, u_, qC_, cn_, p0_, k_] :=        (rz - d0)*z0 + ry*u*y0 - qC*p[Ctotal,T,cn, p0, k]*z0;     dz1dt[az_, d1_, qC_, cn_, p0_, k_] :=        az*z0 - d1*z1 - qC*p[Ctotal, T, cn, p0, k]*z1;     dz2dt[bz_, d2_, qC_, cn_, p0_, k_] :=        bz*z1 - d2*z2 - qC*p[Ctotal, T, cn, p0, k]*z2;     dz3dt[cz_, d3_, qC_, cn_, p0_, k_] :=        cz*z2 - d3*z3 - qC*p[Ctotal, T, cn, p0, k]*z3;     dTdt[sT_, dT_, n_, qT_, cn_, p0_, k_] :=        sT - dT*T - p[Ctotal, T, cn, p0, k]*Ctotal + 2^(n)*p[Ctotal, T, cn, p0, k]*qT*Ctotal;      Now, setting them all equal to zero and using `Solve` did not get me very far. I have a feeling that because there are so many equations, `Solve` having trouble finding a solution. Maybe it will find one, but it might take a long time before something happens. I have had some mild success using `FindRoot[]`, however that only gives me an approximate solution to my problem, and it is very possible that there will be more than one equilibrium point as well. I'd like to also note that I want to be able to solve for y0, y1, y2, y3, z0, z1, z2, z3,and T. Does anyone have any ideas? I know it's kind of a complex system, but there's got to be a way to get some equilibrium points here, besides the obvious solution `(0, 0, 0, 0, 0, 0, 0, 0, sT/dT)` EDIT1: Here's what I used as a solve argument               Solve[ dy0dt[ry, u, d0, qC, cn, p0, k] == 0 &&      dy1dt[ay, d1, qC, cn, p0, k] == 0 &&      dy2dt[by, d2, qC, cn, p0, k] == 0 &&      dy3dt[cy, d3, qC, cn, p0, k] == 0 &&     dz0dt[rz, d0, ry, u, qC, cn, p0, k] == 0 &&     dz1dt[az, d1, qC, cn, p0, k] == 0 &&     dz2dt[bz, d2, qC, cn, p0, k] == 0 &&     dz3dt[cz, d3, qC, cn, p0, k] == 0 &&     dTdt[sT, dT, n, qT, cn, p0, k] == 0, {y0, y1, y2, y3, z0, z1, z2, z3, T}]      If possible, I want to do it analytically. There should be at least three. Even if it did find one of the non-trivial equilibrium points it would be helpful.


PrincipalValue option of Convolve not working in 9.0.1?

The `PrincipalValue` option of `Convolve` is used in this question to define the Hilbert transform. However, in _Mathematica_ 9.0.1, the convolution version gives a wrong answer, while the Fourier transform based version still works.               (* Fourier transform version *)     hilbertTransform = Function[{f,u,t},          Module[{fp = FourierParameters -> {1, -1}, x},             FullSimplify@InverseFourierTransform[-I (2 HeavisideTheta[x] - 1)                  FourierTransform[f, u, x, fp], x, t, fp]         ]     ];     hilbertTransform[#, v, w] & /@ {Sin[v], Cos[v], 1/(1 + v^2), Sinc[v], DiracDelta[v]}          (* {-Cos[w],Sin[w],w/(1+w^2),(1-Cos[w])/w,1/(π w)} *)          (* Convolve based version which failed for DiracDelta *)         hilbertTransform2[f_, u_, t_] :=          FullSimplify[Convolve[f, 1/u, u, t, PrincipalValue -> True]/π]     hilbertTransform2[#, v, w] & /@ {Sin[v], Cos[v], 1/(1 + v^2), Sinc[v], DiracDelta[v]}          (* {-Cos[w],Sin[w],Log[(-1)^(-(1/(1+w^2))) E^(π/(-I+w))]/π,(1-Cos[w])/w,0} *)      Is this a bug?


using deletecases for twittermessages using the timestamp

I have a Excelsheet with tweetsmessages. These tweets are all written in Dutch. I would like to analyse these tweets in relation to the timestamp.               tweets = Import["E:\\mathematica\\data\\tweets_gr2014_v5.xls", {"Data", 1}];          tweets[[2 ;;, {1, 2}]]      The result is : The result is: { {"19-3-2014 23:13", "##GR2014 - Een goeie in tv commentaar: #Wilders schreeuwt wel veel, maar hij wil helemaal niet in steden regeren. Hij doet bijna nergens mee"}, {"19-3-2014 21:49", "#020kiest eerste uitslag Amsterdam zo op AT5 #GR2014 #at5"}, {"19-3-2014 22:26", "#033kiest pvda verliest veel... was wel te verwachten nietwaar? #GR2014"}.......} Then I use StringCases to split the individual words in the tweet messages.               tweets1 = Transpose@{tweets[[2 ;;, 1]],  StringCases[ToLowerCase[tweets[[2 ;;,      2]]], RegularExpression["\\w(?<!\\d)[\\w'-]*"]]};      The next step is dat I would like tot delete all stop words. Therefor I have a listing with Dutch Stop words. stopwoordenNL = { "aan", "al", "alles", "als", "altijd", "andere", "ben", "bij", "daar", "dan", "dat", "de", "der", "deze", "die", "dit", "doch", "doen", "door", "dus", "een", "eens", "en", "er", "ge", "geen", "geweest", "haar", "had", "heb", "hebben", "heeft", "hem", "het", "hier", "hij", "hoe", "hun", "iemand", "iets", "ik", "in", "is", "ja", "je", "kan", "kon", "kunnen", "maar", "me", "meer", "men", "met", "mij", "mijn", "moet", "na", "naar", "niet", "niets", "nog", "nu", "of", "om", "omdat", "onder", "ons", "ook", "op", "over", "reeds", "te", "tegen", "toch", "toen", "tot", "u", "uit", "uw", "van", "veel", "voor", "want", "waren", "was", "wat", "werd", "wezen", "wie", "wil", "worden", "wordt", "zal", "ze", "zelf", "zich", "zij", "zijn", "zo", "zonder", "zou", "ten", "per", "lid", "pagina", "toe", "indien", "alle", "den", "bent", "hebt", "nee", "ja", "wel", "mee", "ter", "zie", "aldus", "alsmede", "alsnog", "betreffende", "danwel", "derhalve", "zoals", "zowel", "hierbij", "hierboven", "hiermee", "hierna", "hiertoe", "hiervan", "hiervoor", "tenzij", "and", "for"}; Without using the timestamp I used the script:               DeleteCases[tweets[[All, 2]], w_ /; MemberQ[stopwoordenNL], ToLowerCase[w]]];      But it doesn't work when I analyse two columns. How can I delete the stop words?


Why LibraryLink function crashes at a second time?

I'm trying link one of Lapack's function to Mathematica through LibraryLink, and the Library function works great at the first execution but crashes at the second time. Here is the code (modified from here)               MMASrc="     #include <WolframLibrary.h>     #include <WolframCompileLibrary.h>          DLLEXPORT mint WolframLibrary_getVersion(){       return WolframLibraryVersion;     }     DLLEXPORT int WolframLibrary_initialize(WolframLibraryData libData){       return 0;     }          EXTERN_C void zspsv_(char* UPLO, const mint* N, mint* NRHS, mcomplex* A, mint* IPIV, mcomplex* B, mint* LDB, mint* INFO);               EXTERN_C DLLEXPORT int lpkSolveAXBS(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res){            MTensor ta=MArgument_getMTensor(Args[0]);       MTensor tb=MArgument_getMTensor(Args[1]);       mint N=*MTensor_getDimensionsMacro(tb);       mcomplex* A=MTensor_getComplexDataMacro(ta);       mcomplex* B=MTensor_getComplexDataMacro(tb);            char U='U';       mint IPIV[N];       mint NRHS=1;       mint LDA=N,LDB=N;       mint INFO;       mint i,j;            mcomplex AP[N*(N+1)/2];            for(j=0;j<N;j++)         for(i=0;i<=j;i++)           AP[i + (j+1)*j/2] = A[i*N+j];            zspsv_(&U,&N,&NRHS,AP,IPIV,B,&LDB,&INFO);            MArgument_setMTensor(Res,tb);       return LIBRARY_NO_ERROR;     }               ";     Needs["CCompilerDriver`"];          CreateLibrary[MMASrc,"lpk","Debug"->True,"TargetDirectory"->"/tmp",             "CompileOptions"->"-llapack"];          A={{1. +0. I,0. +0. I,0. -6.94908*^-13 I,0. -6.94908*^-13 I},                {0. +0. I,1. +0.0352595 I,0. -4.51893*^-11 I,0. -4.51893*^-11 I},                {0. -6.94908*^-13 I,0. -4.51893*^-11 I,1. +0.0376938 I,0. +0. I},                {0. -6.94908*^-13 I,0. -4.51893*^-11 I,0. +0. I,1. +0.0378932 I}};          B={1. +0. I,0. +0. I,0. +6.94908*^-13 I,0. +6.94908*^-13 I};          lpkSolve=LibraryFunctionLoad["/tmp/lpk.dylib","lpkSolveAXBS",             {{Complex,2},{Complex,1}},{Complex,1}]     (*LibraryFunction[<>,lpkSolveAXBS,{{Complex,2},{Complex,1}},{Complex,1}]*)          Abs[LinearSolve[A,B]-lpkSolve[A,B]]//Max     (*2.02047*10^-28*)          Table[LinearSolve[A,B],{40000}];//AbsoluteTiming     (*{0.470767,Null}*)          Table[lpkSolve[A,B],{40000}];//AbsoluteTiming     (*{0.086038,Null}*)          Table[lpkSolve[A,B],{40000}];//AbsoluteTiming      In executing `In[10]`, I hear a beep sound and then the kernel crashes and there is no output. Why the kernel crashes at the second time of invoking the LibraryLink function? How to fix that? **Update** As Todd Gayley commented under halirutan's answer, this is a bug. **Update** Still not fixed in version 10.0.


Plotting a function by converting it to a delayed differential equation

I am having a little trouble calculating the Dickman Function from scratch. I have downloaded the notebook from the above link and the have following code:               Off[      InterpolatingFunction::dmval, NDSolve::precw, Power::"infy", Less::"nord", NDSolve::"nlnum"      ];          Clear[F];     F[0][x_] = Which[x < 0, 0, 0 <= x <= 1, Exp[1 - 1/x], x > 1, 1];     With[{ε = 10^-5, n = 20},       Do[ndsol[k] =          NDSolve[{F[k]'[x] == F[k - 1][x/(1 - x)]/x, F[k][ε] == F[k - 1][ε]},            F[k], {x, ε, 1},           WorkingPrecision -> 35, MaxSteps -> 10^5, PrecisionGoal -> 18,            AccuracyGoal -> 18][[1, 1, 2]];         Print["Step ", k, "..."];         F[k][x_] =            Which[             x < 0, 0,              0 <= x <= 1, Evaluate[ndsol[k][x]/ndsol[k][2]],              x > 1, 1],         {k, n}]]     Plot[F[20][a], {a, 0, 1}, PlotRange -> All, PlotStyle -> Red]      It makes the following plot: ![enter image description here](http://i.stack.imgur.com/EXGip.gif) which is a plot of $$\rm {F}(\alpha)=\int_{0}^{\alpha}\rm {F} \bigg ( \frac{t}{1-t} \bigg)\frac{\,dt}{t}$$ I am having trouble modifying the above _Mathematica_ code so I can eventually plot $$\rm {G}(\beta)=\int_{0}^{\beta}\bigg [\rm {G} \bigg (\frac{t}{1-t} \bigg )-\rm {F} \bigg (\frac{t}{1-t} \bigg ) \bigg]\frac{\,dt}{t}$$ using the same method. Ultimately, I would like to go on to plot $$\rm {H}(\gamma)=\int_{0}^{\gamma}\bigg [\rm {H} \bigg (\frac{t}{1-t} \bigg )-\rm {G} \bigg (\frac{t}{1-t} \bigg )-\rm {F} \bigg (\frac{t}{1-t} \bigg ) \bigg]\frac{\,dt}{t}$$


SparseArray internal structure

According to the documentation: > `SparseArray` is treated as a raw object by functions like `AtomQ` and for > purposes of pattern matching. Furthermore, they have specific functions to access and format subparts (`Dimensions`, `ArrayRules`, `Normal`, etc. ), though they also have an intricate internal structure. There is however little information on what exactly certain elements mean. Some examples:               Normal@SparseArray[{2, 3, 4} -> {1, 1, 1}, {6}]     InputForm@SparseArray[{2, 3, 4} -> {1, 1, 1}, {6}]      > >      {0, 1, 1, 1, 0, 0} >      SparseArray[Automatic, {6}, 0, {1, {{0, 3}, {{2}, {3}, {4}}}, {1, 1, > 1}}] >                 x = SparseArray[{{i_, i_} -> 1, {3, 2} -> 2, {5, _} -> "x"}, {5, 4}, -1];     Normal@x           InputForm@x      > >        {{1, -1, -1, -1}, >         {-1, 1, -1, -1}, >         {-1, 2, 1, -1}, >         {-1, -1, -1, 1}, >         {"x", "x", "x", "x"}} >   >       SparseArray[Automatic, {5, 4}, -1, >            {1, {{0, 1, 2, 4, 5, 9}, {{1}, {2}, {3}, {2}, {4}, {4}, {3}, {2}, > {1}}}, >            {1, 1, 1, 2, 1, "x", "x", "x", "x"}}] >   For example, what is the purpose of the _Automatic_ at the first position and what other values can be used instead of it?


Plotting the frequency spectrum of a data series using Fourier

testData = Table[N@Sin[500 x], {x, 0, 100}];     ListLinePlot[Abs[Fourier[testData]], PlotRange -> Full]      Gives me ![enter image description here](http://i.stack.imgur.com/zM6mT.png) Which I do not expect because the Fourier Transform is `FourierTransform[Sin[500 x], x, f],` > >     I Sqrt[Pi/2] DiracDelta[-500+f]-I Sqrt[Pi/2] DiracDelta[500+f] >   I'm not saying that Mathematica's Fourier function is somehow faulty. But could someone please explain why there isn't a peak around 500? This is the frequency of the signal after all...


How can I solve this PDE with initial conditions?

I wish to solve the following second order partial differential equation $$u_{tt}=c^2 u_{xx}$$ with the initial conditions $$u(x,0)=e^x,\quad u_t(x,0)=\sin x$$ In _Mathematica_ , I evaluated the following code:               DSolve[{D[p[x, t], {t, 2}] == c^2 *(D[p[x, t], {x, 2}]),              p[x, 0] == Exp[x], D[p[x, t], t] == Sin[x]},           p[x, t], {x, t}]      _Mathematica_ responded with > DSolve::deqx: Supplied equations are not differential equations of the given > functions. I think the problem lies in the initial conditions. How can I fix this code?


How to find the distance of two lists?

I have two lists as the followings:               ab = {1, -1, -1, -1, 1, 1};     ac = {1, -1, -1,  1, 1, 1};      How I can find the difference (more precisely, the **edit distance** ) between them? In this case the result should be 1, since there is one item difference between `ab` and `ac`. Note: in my case, the list elements only take the values 1 and -1, and both lists are one dimensional of the same length, but it is always nice to see more general solutions (elements are of `Reals`, lists are matrices, etc.). Thank you.


Taking Log Transformation of unit circle using Presentations package

<< Presentations`          circle = ComplexCircle[0.1, 1/2];     domain = Draw2D[{Opacity[0.6], circle},        Frame -> True,        Axes -> True,        PlotRange -> 2,        FrameLabel -> {Re, Im},        PlotLabel -> z, ImageSize -> 200];     image = Draw2D[{Opacity[0.6], circle // ComplexMap[Log]},        Frame -> True,        Axes -> True,        PlotRange -> 4,        FrameLabel -> {Re, Im},        PlotLabel -> w,        ImageSize -> 200];     Row[{domain, image}]      The above code works, creating the following image. ![Mathematica graphics](http://i.stack.imgur.com/6ozno.png) However, if I change the center to the origin:               circle = ComplexCircle[0, 1/2];     domain = Draw2D[{Opacity[0.6], circle},        Frame -> True,        Axes -> True,        PlotRange -> 2,        FrameLabel -> {Re, Im},        PlotLabel -> z, ImageSize -> 200];     image = Draw2D[{Opacity[0.6], circle // ComplexMap[Log]},        Frame -> True,        Axes -> True,        PlotRange -> 4,        FrameLabel -> {Re, Im},        PlotLabel -> w,        ImageSize -> 200];     Row[{domain, image}]      The code fails, giving the following error message: > Coordinate {DirectedInfinity[-1], 0} should be a pair of numbers, or a > Scaled or Offset form. But this works with center at the origin:               circle = {Red, Thickness[0.02],         ComplexCurve[Exp[I t], {t, 0, 2 Pi}]};     domain = Draw2D[{Opacity[0.6], circle},        Frame -> True,        Axes -> True,        PlotRange -> 2,        FrameLabel -> {Re, Im},        PlotLabel -> z, ImageSize -> 200];     image = Draw2D[{Opacity[0.6], circle // ComplexMap[Log]},        Frame -> True,        Axes -> True,        PlotRange -> 4,        FrameLabel -> {Re, Im},        PlotLabel -> w,        ImageSize -> 200];     Row[{domain, image}]      Producing this image: ![Mathematica graphics](http://i.stack.imgur.com/E5mf7.png) What's going on?


How to Compute Aggregate Best and Worst Cases for a Large Number of Estimates?

I need to aggregate multiple estimations, but I haven't been able to find a built-in function in _Mathematica_ that aggregates multiple probablity estimations (I am specially interested in estimations based on the `PERTDistribution`) I am being told that I need to:   1. Compute the standard deviation of each estimation   2. Compute the square of each task’s standard deviation, which is known as the variance.   3. Total the variances.   4. Take the square root of the total. First of all, is that correct? And if it is, is there a function in _Mathematica_ that can do all that for me? Something like a hypotetical `AggregateDistribution` that would work like:               AggregateDistribution[PERTDistribution[{min, max}, mode], numberOfEstimatesToAggregate]      Any guidance on a function that provides this or a way to do it would be welcome.


Is it necessary to have a prior computational background or is it possible to learn Mathematica as a first programming language?

I have a background in economics and I'm very interested in learning _Mathematica_ but I'm afraid of starting out because I have seen that most programmers already have a good background in some kind of procedural language, and I don't! My goal is to start learning _Mathematica_ , and take it as my Swiss army knife. I don't want to spend time to become good in another language first, and start to study to be a good software developer in _Mathematica_ only after that. So, my question is: Is it strictly necessary to have a prior knowledge in another kind of language, or one can master, from level zero, and be a great Mathematica programmer just starting programming through _Mathematica_? It seems to me that there aren't any efforts (books, tutorials, documentation) in this sense directed to the self learner. What do you think? Is there a way?


RevolutionPlot3D: axis of revolution that doesn't pass through the origin

This is a follow up question to RevolutionPlot3D: but NOT revolving about the z axis so please check that for the context. It seems that `RevolutionAxis` requires the axis of revolution to pass thru the origin. Suppose I want to use an axis of revolution that does not pass through the origin, e.g., the line $y=-1$ in the example above. What is a good way to accomplish this? I do realize that `RegionPlot3D` may be appropriate here, but even with seemingly simple examples such as the one above, it can struggle:               Show[       RegionPlot3D[1 <= Sqrt[(y + 1)^2 + z^2] <= 1 + x^2, {x, 0, 1},          {y, -3, 3}, {z, -3, 3}, PlotRange -> All, PerformanceGoal -> "Quality",          Mesh -> False, AxesLabel -> {x, y, z}, PlotPoints -> 100,          ViewPoint -> {0.87, 0.44, 1.76}, ViewVertical -> {0.32, 0.67, 0.67}],       Graphics3D[{Thickness[.01], Black, Line[{{0, -1, 0}, {1.15, -1, 0}}]}]     ]      ![enter image description here](http://i.stack.imgur.com/c5BNm.png) Bumping `PlotPoints` up to 200, 300, 400 doesn't alleviate the problem and gets really slow.


How can I effectively performance-profile Dynamics?

How to optimize performance-wise a complex dynamic expression (like a GUI) with lots of dynamically updated components, which require different update- frequencies? I was hesitant to ask this question as it does not focus on a very specific problem, but is about general speed (and memory) improvement tricks. The gui is a primitive scrolling racer where the user has to manipulate a controller to keep an object on a winding path. I did it for a cognitive experiment for humans but it definitely has potential in the gaming market :) Also - as far as I know - _Mathematica_ was not used (and was not designed) to develop realtime platformer/racer games (or alike), so the question naturally arises: can _Mathematica_ do it? This, I think, is untrodden land worthy of exploration. Below is a toy model of a game. I tried to keep it as abstract as possible to make it general and thus applicable to a wider domain. If you still think that this question is too localized/not really a question, please say so and I remove it. **Details of the code** The code might seem too long, but I assure you, it is not complicated. If the game is started with the Start button, the function `start` initiates a `ScheduledTask` that sets the in-game timer with `updateFrequency = .05` seconds. The controller can be dragged continuously, and it generates a coordinate pair ${x_1, x_2}$, stored in `ctrl`, that is fed to the `controlFunction`, that defines the actual vertical position (`y`) of the yellow arrow (the "ship"). The responsible equation is: $$ y = y* + k_1 x_1 + k_2 x_2 $$ where $y*$ is the $y$ value of the position of the arrow in the previous timestep. Now the hard part is, that from time to time, parameters $k_1$ and $k_2$ are randomly changed (every 100 steps, using the `change` function), so the controller is changed as well. The controller background always displayes the actual gradient of ${\varDelta}y$. The different background colors in each episode indicate that the controller has changed. I did not use `Locator` or `LocatorPane`, as those seemed to be unresponsive, especially when the underlying controller is changed. While the controller is updated continuously, the actual position of the arrow is only updated via the `update` function when the running `ScheduledTask` tells so (in every 0.05 sec). Also, moving the controller produces some sounds that helps the user to learn the control gradient.               DynamicModule[{       optimumFunction = Sin[#*\[Pi]/100] &, (* defines the winding optimum zone *)       updateFrequency = .05, (* update plot every 0.05 seconds *)       xFrame = 100, (* horizontal range to show (last 100 steps) *)       yFrame = 30, (* default vertical range to show *)       maxTime = 1000, (* length of a run. Real word time is ~ 0.05 * 1000 = 50 sec *)       episodeNum = 5, (* number of different episodes: each episode lasts 200 timesteps *)            active, controlActive, ctrl, data, time, \[Theta], \[Rho], y,        yRange, xRange, gradient, crosshair, ship, episodeColors,        episodeBorders,       reset, sound, start, stop, update, change, controlFunction       },           (* Internal functions *)      reset[] := (active = False; ctrl = {0, 0}; data = {}; time = 0; y = 0; change[]; update@0);      sound[{x_, y_}, vol_] := Sound[SoundNote[Floor@Rescale[controlFunction[x, y], {-1, 1}, {-20, 40}], .3, "Strings"], SoundVolume -> vol];      start[] := (active = True; RunScheduledTask[update@(time++), {updateFrequency, \[Infinity]}]);      stop[] := (RemoveScheduledTask[ScheduledTasks[]]; active = False);      update[t_] := Block[{xAll, yAll, n = 2},        y = y + controlFunction @@ ctrl; (* update the position of the ship *)        data = Append[data, {t, y}]; (* save position of the ship *)        yRange = ({Min[Min@#, -{-1.5, 1.5}], Max[Max@#, {-1.5, 1.5}]}*1.3) &@(Last /@ Take[data, -Min[yFrame, Length@data]]); (* calculate vertical and horizontal ranges to show on the scrolling plot*)        xRange = {Max[0, time - xFrame], Max[xFrame, time]};        xAll = N@Abs@(Subtract @@ xRange); (* absolute x-range shown *)        yAll = N@Abs@(Subtract @@ yRange); (* absolute y-range shown *)        \[Theta] = Mod[ArcTan @@ #, 2 \[Pi], 0] &@ If[t < n, {1, 0}, (data[[-1]] - data[[-n]])/{xAll, yAll}]; (* rotation angle of the arrow, dependent on previous steps and the actual plot range used *)        If[0 < t < maxTime \[And] Mod[t, maxTime/episodeNum] == 0, change[]]; (* change controllers *)        If[t >= maxTime, stop[]]; (* stop run *)        ];      change[] := (        \[Rho] = RandomReal[{-.5, .5}, 2]; (* \[Rho] = {k1, k2}, the two random parameters of the gradient *)        controlFunction = {#1, #2}.\[Rho] &; (* the control function defining the gradient *)        gradient =          DensityPlot[(controlFunction[x, y]), {x, -1, 1}, {y, -1, 1},           Frame -> False, PlotRangePadding -> 0, ImagePadding -> 0,          ImageSize -> 200,           ColorFunction -> ((Lighter@               ColorData["Rainbow"][Rescale[#, {-1, 1}]]) &),           ColorFunctionScaling -> False,           PlotRange -> {{-1, 1}, {-1, 1}, {-1, 1}}, Mesh -> {{{0, Thick}}},           MeshFunctions -> {#3 &}];        );                (* Initialization *)      crosshair =        Graphics[{White, Disk[{0, 0}, 1.5], Darker@Blue, Disk[], Blue,          AbsoluteThickness@1, Circle[{0, 0}, 1.5], Line@{{0, -2}, {0, 2}},          Line@{{-2, 0}, {2, 0}}}, ImageSize -> 15];      ship = Graphics[{FaceForm@Yellow, EdgeForm@{Gray, Thick}, Polygon@{{0, -1}, {4, 0}, {0, 1}, {0, -1}}}, ImageSize -> 30];      episodeBorders = Partition[Range[0, maxTime, maxTime/episodeNum], 2, 1];      episodeColors = {Hue[.66, 1, 1], Hue[.13, .8, 1], Hue[.23, 1, .8], Hue[.5, .4, .6], Hue[.74, 1, .8]};      reset[]; (* initialize first episode *)                (* Output *)      Panel@Grid[{{          Column@{                 (* Buttons *)            Row@{              Dynamic@Button[If[active, "Stop", "Start"], If[active, stop[], start[]]],              Button["Reset", stop[]; reset[]]              },                 (* Controls *)            Framed@Dynamic[              If[! active,                Graphics[{}, Frame -> False, ImageSize -> 200,                 ImagePadding -> 5, Background -> GrayLevel@.9],               EventHandler[Dynamic[                 If[controlActive, ctrl = Clip@MousePosition@"Graphics"; EmitSound@sound[ctrl, .5]];                 Graphics[{                   Texture@gradient,                    Polygon[{{-1, -1}, {-1, 1}, {1, 1}, {1, -1}},                     VertexTextureCoordinates -> {{0, 0}, {0, 1}, {1, 1}, {1, 0}}],                   Dynamic@Inset[crosshair, ctrl]                   }, Frame -> False, ImageSize -> 200, ImagePadding -> 0],                 TrackedSymbols :> {controlActive}],                {                 "MouseDown" :> (controlActive = True;),                  "MouseUp" :> (controlActive = False;)                }]],              TrackedSymbols :> {active, gradient}]            },               (* Scrolling pane *)          Panel[Dynamic[            Show[             (* background colors *)             Graphics[MapThread[               {FaceForm@{Opacity@.2, #1}, EdgeForm@None,                  Rectangle @@ {{First@#2, -100}, {Last@#2, 100}}} &,               {episodeColors, episodeBorders}],               PlotRange -> {Automatic, yRange}],                  (* initial/terminal gray edge (before time 0 and after maxTime *)             Plot[0, {t, 0 - maxTime*.1, 0}, PlotStyle -> None, FillingStyle -> GrayLevel@.9, Filling -> {1 -> Top, 1 -> Bottom}, PlotRange -> {Automatic, yRange}],             Plot[0, {t, maxTime, maxTime*1.1}, PlotStyle -> None, FillingStyle -> GrayLevel@.9, Filling -> {1 -> Top, 1 -> Bottom}, PlotRange -> {Automatic, yRange}],                  (* desired zone (winding path) *)             Plot[{optimumFunction@t - .5, optimumFunction@t,                optimumFunction@t + .5}, {t, Max[0, time - xFrame] - 20,                Max[xFrame, time] + 100},               PlotStyle -> {None,                 Directive[GrayLevel[0, .7], AbsoluteThickness@3, Dashed],                 None}, FillingStyle -> Hue[.3, 8, .8, .5],               Filling -> {1 -> {3}}],                  (* ship & trajectory *)             Graphics[{GrayLevel@.6, AbsoluteThickness@2,                Dynamic@Line@Most@data,                Inset[Rotate[ship, \[Theta]], Last@data]}],                  (* options *)             PlotRange -> {xRange, yRange},              PlotRangePadding -> {{Scaled@.02, Scaled@.2}, 0},             ImageSize -> Full, AspectRatio -> Full,              ImagePadding -> Automatic,             Frame -> True, FrameTicks -> False, Axes -> False,              GridLines -> {Range[0, maxTime, maxTime/episodeNum], None},              Method -> {"GridLinesInFront" -> True}             ],             TrackedSymbols :> {yRange, xRange, time, y, \[Theta], active}            ], ImageSize -> {800, 400}]          }}, Alignment -> {Left, Center}]]      ![Mathematica graphics](http://i.stack.imgur.com/DmC4C.png) I know that the best advice here is that   * only update if necessary;   * only update the smallest minimum that needs to be updated. I was keeping that in mind during development. Most of the scrolling graphics are pre-generated (the sine wave and background colors as rectangles) and only the `PlotRange` is changed dynamically. Explicit `TrackedSymbols` are used to update only those symbols that should be updated. Still, the gui is lagging: the controller follows the moused with a reasonably large lag, that does not feel smooth. Also, during every episode change, there is a short pause. Now, this lagging is inacceptable: my first Commodore had only 64 KB memory, but it could run such games way smoother than _Mathematica_.   1. **How can I understand what uses up time during dynamic evaluation (considering that I do not want to print`AbsoluteTiming` values all the time)? How can I profile such a gui?**   2. **How can I improve the code further to give a smooth feeling?** Any comments/ideas are welcome. * * * I should tell here that this code uses a lot of stuff from all around Mathematica.SE, so if you run into some familiar lines, don't be surprised. Thanks for all your helpful input. Also thanks for Oleksandr for the title! * * * **EDIT at 7. 8. 2012** According to Rojo's profiling and comments in chat, here is a modified version of the scrolling output (just replace the original internal `Panel[Dynamic[Show[...]]]` with the code below. It removes the wrapping `Dynamic` around `Show` and instead uses a dynamically updated `PlotRange` (also I moved the `Dynamic`s in the ship and trajectory to the inside of `Inset` and `Line`). Now while this updates much faster, and any check on `xRange` and `yRange` indicates that they are updated correctly at every timestep, the displayed plot range is only updated when the controller is moved, meaning that if the controller is not touched, the ship will just move out of the range on the right (clearly unwanted).               Panel[Show[       Graphics[MapThread[         {FaceForm@{Opacity@.2, #1}, EdgeForm@None, Rectangle @@ {{First@#2, -100}, {Last@#2, 100}}} &,         {episodeColors, episodeBorders}]],            (* initial/terminal gray edge *)       Plot[0, {t, 0 - maxTime*.1, 0}, PlotStyle -> None, FillingStyle -> GrayLevel@.9, Filling -> {1 -> 100, 1 -> -100}],       Plot[0, {t, maxTime, maxTime*1.1}, PlotStyle -> None, FillingStyle -> GrayLevel@.9, Filling -> {1 -> 100, 1 -> -100}],            (* desired zone ("road") *)       Plot[{optimumFunction@t - .5, optimumFunction@t, optimumFunction@t + .5}, {t, 0, maxTime}, PlotStyle -> {None, Directive[GrayLevel[0, .7], AbsoluteThickness@3, Dashed], None}, FillingStyle -> Hue[.3, 8, .8, .5], Filling -> {1 -> {3}}],            (* ship & trajectory *)       Graphics[{GrayLevel@.6, AbsoluteThickness@2, Line@Dynamic@Most@data,Inset[Rotate[ship, Dynamic@\[Theta]], Dynamic@Last@data]}],            (* options *)       PlotRange -> Dynamic[{xRange, yRange}, TrackedSymbols :> {xRange, yRange}],        PlotRangePadding -> {{Scaled@.02, Scaled@.2}, 0},       ImageSize -> Full, AspectRatio -> Full, ImagePadding -> Automatic,       Frame -> True, FrameTicks -> False, Axes -> False,        GridLines -> {Range[0, maxTime, maxTime/episodeNum], None},        Method -> {"GridLinesInFront" -> True}       ], ImageSize -> {800, 400}]


How to preserve the order of terms in the output

Is there a way in which mathematica can preserve the order of operations while it evaluates an expression?, for instance: In my short example               w = f[r,Θ] ;        lapla12 = -(r/(2 μ)) (1/r D[w/r r, {r, 2}] - 1/r^2 (D[w/r, {Θ, 2}] + Cot[Θ] D[w /r, {Θ, 1}])) // ExpandAll // TraditionalForm      The output that mathematica gave me is ![enter image description here](http://i.stack.imgur.com/M6h9i.jpg) However, I know the real order is ![enter image description here](http://i.stack.imgur.com/kdznj.jpg) In my real problem, I have more than 100 terms and is quite difficult to me sort all terms to check the results. **EDITED:** For instance the first 35 terms in my real expression appears in this order and i would like that they appears in the correct order![enter image description here](http://i.stack.imgur.com/V9EeQ.jpg) I'm using the code from Jens for derivatives formatting purposes. Here is the code i'm using to obtain the above output.               ClearAll["Global`*"]     SetOptions[$FrontEndSession, PrintingStyleEnvironment -> "Condensed"]         $PrePrint = # /. {Csc[z_] :> 1/Defer@Sin[z],           Sec[z_] :> 1/Defer@Cos[z],           Cot[z_] :> Defer@Cos[z]/Defer@Sin[z]} &;               Subscript[w, 1] = f[Subscript[r, 1], Subscript[r, 2], α, β, γ, Subscript[Θ, 12]];          Set[J, -(D[Subscript[w, 1], {β, 2}] + 1/Sin[β]^2 (D[Subscript[w, 1], {α, 2}] +               D[Subscript[w, 1], {γ, 2}]) + Cot[β] D[Subscript[w, 1], β] -            2 Cot[β]/ Sin[β] D[Subscript[w, 1], α, γ])] // TraditionalForm ;          Set[Subscript[a, 1], 2 D[Subscript[w, 1], {β, 2}] + D[Subscript[w, 1], {γ, 2}] + J]          // TraditionalForm ;          Set[Subscript[a, 2],  2 Cot[β]/ Sin[β] D[Subscript[w, 1], {α, 1}] - (1 + 2 Cot[β]^2)          D[Subscript[w, 1], {γ, 1}] - 2/Sin[β] D[Subscript[w, 1], β, α] + 2 Cot[β]          D[Subscript[w, 1], β, γ]] // TraditionalForm ;          Set[Subscript[f, 1], 1/(2 Sin[Subscript[Θ, 12]]^2) (-J + Cos[Subscript[Θ, 12]]          (Sin[2 γ] Subscript[a, 2] - Cos[2 γ] Subscript[a, 1]) + Sin[Subscript[Θ, 12]]         (Sin[2 γ] Subscript[a, 1] + Cos[2 γ] Subscript[a, 2])) - D[Subscript[w, 1],          Subscript[Θ, 12], γ] - 1/2 Cot[Subscript[Θ, 12]] D[Subscript[w, 1], {γ, 1}] +         (1/4 - 1/(2 Sin[Subscript[Θ, 12]]^2)) D[Subscript[w, 1], {γ, 2}]          ] // ExpandAll // TraditionalForm ;          Set[lapla1, -(1/(2 Subscript[μ, 1])) (1/Subscript[r, 1] D[Subscript[w, 1]          Subscript[r, 1], {Subscript[r, 1], 2}] - 1/Subscript[r, 1]^2         (D[Subscript[w,  1], {Subscript[Θ, 12], 2}] + Cot[Subscript[Θ, 12]]          D[Subscript[w, 1], {Subscript[Θ, 12], 1}]) - Subscript[f, 1]/Subscript[r, 1]^2)         ] // ExpandAll // TraditionalForm      **EDITED 2** In this case the correct order is ruled by the expression for lapla1.![enter image description here](http://i.stack.imgur.com/TRGS1.png) where terms in red (radial terms) go first, then terms in purple (internal angular terms), and finally the terms in blue (coupling between the orientational angular terms and the internar angular terms). Blue terms are ruled by the expression for $f_1$ from left to right.


NDSolve: methods and step size choosing

I am looking into the documentation of `NDSolve[]`; more precisely **how this function chooses the`StepSize` and how it chooses which method to use**. * * * # Regarding `StepSize` control, it reads > NDSolve adapts its step size so that the estimated error in the solution is > just within the tolerances specified by PrecisionGoal and AccuracyGoal. **Question:** How? Does it use an adaptive step size similar to this one for instance? * * * # Regarding method choice, it reads > `NDSolve` typically solves differential equations by going through several > different stages depending on the type of equations. With `Method->{s1->m1, > s2->m2, ...}` stage is handled by method . The actual stages used and their > order are determined by `NDSolve`, based on the problem to solve. and also > Possible explicit time integration settings for the `Method` option include: > [Adams, BDF, etc] with various submethods and options. A good tutorial about method choice and stiffness detection is found here. **Questions:**   1. What is the default method choice in `NDSolve`? (I am guessing it will start by `ExplicitRungeKutta`, seeing as it is the most robust from what I've been reading, but then which?)   2. Regarding stiffness detection and method choice upon stiffness finding, I found this page that refers "Explicit modified midpoint, double-harmonic sequence, linearly implicit Euler, and sub-harmonic sequence" as possible methods. In that same page, I found how those methods seem to compute stability of the model, and use it to determine whether it should use a stiff/non-stiff method. Yet, what is again the default order of choice for those methods? Thank you for your insight.


J/Link: How to run a thread inside Mathematica

In the J/Link User Guide there is no example on how to use java.lang.Thread, from inside Mathematica. I'd like to know if is possible to start a thread from a `JavaNew` object which has a Runnable interface implemented. If I run this code from a java main class everything works fine. The Thread will run sampling bid/ask from a tcp/ip data stream and every time I need to know the bid/ask data I call the method that get me the value.               t3OpenT job01 = new t3OpenT("192.168.0.78",5333,500000,200);             job01.openConnection();             job01.setRequest("function=subscribe|item=MI.EQCON.1|schema=best_bsiz1;best_bid1;best_ask1;best_asiz1;symbol");             job01.subscribeData();          System.out.println("now start the thread 01");             Thread ntJob01 = new Thread(job01);             ntJob01.setDaemon(true);             ntJob01.setName("GENERALI");             ntJob01.start();      But if I create the objects inside the notebook using JavaNew[....] and then start the thread it will execute but it is interrupted immediately. Here is the mathematica code I use:               In[33]:= generaliGRT = t3OpenObjectT[{generaliG}]          Out[33]= {{"1", "G", JLink`Objects`vm1`JavaObject27681839799861249}}          (*Now we setup T3OpenObject to subscription:*)          In[34]:= generaliGRT[[1, 3]]@      setRequest[       "function=subscribe|item=MI.EQCON.1|schema=best_bsiz1;best_bid1;best_ask1;\     best_asiz1;symbol"]          (*subscribe the data on GENERALI stock*)          In[35]:= generaliGRT[[1, 3]]@subscribeData[];     generaliGRT[[1, 3]]@getResponse[]          Out[36]= "outcome=OK|item=MI.EQCON.1"          (*the response is OK so now we are redy to start the thread *)          In[37]:= th = JavaNew["java.lang.Thread", generaliGRT[[1, 3]]]          Out[37]= JLink`Objects`vm1`JavaObject8825827030466561          th@setDaemon[True]          In[39]:= th@setName["GENERALI"]          In[40]:= th@getName[]          Out[40]= "GENERALI"          In[41]:= th@start[]          In[42]:= th@getId[]          Out[42]= 14          (*the thread is immediately terminated *)     In[43]:= th@getState[]@toString[]          Out[43]= "TERMINATED"          (*but I can read the pusched stock date*)      In[45]:= generaliGRT[[1, 3]]@getInfo[]          Out[45]= {"MI.EQCON.1", "18387", "17.19", "17.21", "14300", "G"}      and here is the run() method of T3OpenT class:               @Override         public void run(){                  thExtSignal = false;             refThread = Thread.currentThread();                  try{                      while (true){                          try{                         //check if thread must be terminated                         if(thExtSignal == true){                             Thread.currentThread().interrupt();                         }                         if(Thread.interrupted()){                              throw new InterruptedException();                         }                         //read data from buffer                         this.pushedData = this.refBufReader.readLine();                         //get the time stamp                         dateTimeSample = dateFormat.format(cal.getTime()).toString();                         //split the response end move data in a string vector                         String responseBidAsk[] = pushedData.split("\\|", 6);                         //update only elements tha are changed                         for(int i=0 ; i<=responseBidAsk.length-1;i++){                             if(responseBidAsk[i].length()>0){                                 info[i]=responseBidAsk[i];                             }else{                                 info[i]=info[i];                             }                         }                     }catch (InterruptedException e) {                         //if the thread is interrupted then unsubscribe                         this.unsubscribe();                         // We've been interrupted: no more messages.                         return;                             }                 }             }                catch(SocketTimeoutException e){                 //if timeout unsubscribe                 response = "timeOut";                 unsubscribe();             }             catch (IOException e) {                 pushedData = "error";                  }              }


How to do DateDifference on table items containing dates

I have a `Table` with data in form `{{date}, value}`:               data= {{{2012, 6, 1}, 16}, {{2012, 6, 8}, 14.24}, {{2012, 6, 15}, 13.7},             {{2012, 6, 22}, 12.31}, {{2012, 6, 29}, 11.5}, {{2012, 7, 6}, 10.08},             {{2012, 7, 13}, 9.18}, {{2012, 7, 20}, 8.65}, {{2012, 7, 27}, 7.8},             {{2012, 8, 3}, 7.51}, {{2012, 8, 10}, 7.31}, {{2012, 8, 17}, 6.92},             {{2012, 8, 24}, 6.57}, {{2012, 8, 31}, 6.1}, {{2012, 9, 7}, 5.67},             {{2012, 9, 14}, 5.54}, {{2012, 9, 21}, 5.17}, {{2012, 9, 28}, 4.83},             {{2012, 10, 5}, 4.62}, {{2012, 10, 9}, 4.53}}      How can I know the difference (in days) between each date and the starting date `{2012, 6, 1}` and associate this new value to each row of the `Table`?


Plot 2D Vector function in 3D

I want to plot a 2D vector function such as $F(x,y) = (a(x,y),\,b(x,y))$ in a 3D graph so that the vectors are embedded in the xy plane. I tried to do the following: First I defined a piecewise function like this               g[z_] := Piecewise[{{1, z == 0}}, 0]      Then I converted the 2D vector function to a 3D one by setting the 3rd component to zero and multiplying 1st and 2nd components by `g[z]` so that the x and y components are null when `z != 0`:               f[x_, y_, z_] := {x g[z], y g[z], 0};      Plot the function:               VectorPlot3D[{x g[z], y g[z],0}, {x, -5, 5}, {y, -5, 5}, {z, -5, 5}]      The issue with this solution is that `VectorPlot3D` won't evaluate the function in the relevant points, The above example shows an empty graph, because _Mathematica_ jumps from `z = -1` to `z = 1` without evaluating `z = 0`. I tried with `RegionFunction` (which would've rendered the definition of the above-mentioned piecewise function useless), but that only accepts inequalities, and I want to evaluate the function at any coordinate `{x ,y, 0}`. I could feed it a list of vectors via `VectorPoints -> { {a, b, 0}, {c, d, 0}, ...}`, but that's not an elegant solution at all. Are there other ways to do this?


Unwanted PlotMarkers appear at non-existent places

In this simple code               ListPlot[Table[Sin[x], {x, 0, Pi, .1}], PlotRange -> {0, 0.5},      Joined -> True, PlotMarkers -> Automatic, ClippingStyle -> None, Frame -> True]      ![enter image description here](http://i.stack.imgur.com/r2nbW.png) We can see that there are two PlotMarkers appear at the clipped boundary. But actually there are not points, so they should not exist. How can we remove them? I have already used `ClippingStyle -> None`. * * * **Update** As Alexey Popkov pointed out, this is really a bug. If we play with this code               data = {Table[{x, Sin[x]}, {x, 0, 1.05 Pi, .1}], Table[{x, Sin[2 x]}, {x, 0, 1.05 Pi, .1}]};     ListPlot[data, PlotRange -> {0, 0.5}, Joined -> True, PlotMarkers -> {Automatic, Medium}]      ![enter image description here](http://i.stack.imgur.com/G7beA.png) Now, even the same plot marker will be used for all data sets at the clipped boundaries, both top and bottom.


How can I get thicker lines in the legends of a ListLinePlot?

I want to have thicker lines in the legends of this plot:               historyobjetivomejor = {10, 15, 20, 30, 35}     historyobjetivomedia = {6, 8, 10, 13, 15}     historyobjetivopeor = {6, 3, 5, 7, 8}          ListLinePlot[{historyobjetivomejor, historyobjetivomedia, historyobjetivopeor},        PlotStyle -> {Thickness[0.008]},        AxesLabel -> {"Generacion", "Objetivo"},        LabelStyle -> {24, Bold},        ImageSize -> Large,        PlotLegends -> {"Max", "Mea", "Min"},        PlotStyle -> Thickness[0.005],        AxesStyle -> Thickness[0.005]]      I was trying with options from other posts, but without good result My last attemp was               ListLinePlot[{historyobjetivomejor, historyobjetivomedia, historyobjetivopeor},         PlotStyle -> {Thickness[0.008]},        AxesLabel -> {"Generacion", "Objetivo"},        ImageSize -> Large,        PlotLegends -> [{"Max", "Mea", "Min"},        LabelStyle -> {Bold, 20},        LegendMarkerSize -> {40, 10}],        PlotStyle -> Thickness[0.005],        AxesStyle -> Thickness[0.005]]


Assign a Distribution to a group of symbolic variable

I'm looking to compute this Expectation : ![enter image description here](http://i.stack.imgur.com/5xKXu.png) "i" represent a individual and h(i) is value. I would like the compute the Expected value of his value times the mean of the groups. Everything is unknown so symbolic is conserved. Any help would be greatly appreciated Thank Alexandre


Clustering of peaks in 2D spectra

I'm having some problems clustering data in a 2D spectra and will really appreciate some help. I've been playing around with the FindClusters function but wasn't able to tune it appropriately. Maybe someone can give me a hand on how to customize the DistanceFunction option or so. A sample of my data looks like this: ![Sample data](http://i.stack.imgur.com/7J8ov.jpg) Ideally I would want the peaks to be clustered as this: ![Ideal clustering](http://i.stack.imgur.com/Y5JFW.jpg) I tried the FindClusters functions with different parameters but only got partial clusters like these: ![Partial clusters](http://i.stack.imgur.com/Sm3mJ.jpg) I believe it may be easy if I can define my own DistanceFunction but I don't understand how to use a custom function there with a threshold or so. I've seen other posts like this one, this other one and this one too but I wasn't able to successfully apply those methods. It doesn't matter if I don't get that red circle clustering like the ideal image. If I can just get to identify the whole clusters, I can reduce that set to just one point that would be the center of gravity. It would be awesome if you can point me the way on how to solve this. You can download that sample from here. Just one thing, I don't know before hand how many clusters I'll get. I believe there are 30 in this dataset but this is just a sample. Thank you!!


Removing Abs from Abs[a + Exp[I*c]b]^2

Title says it all. Mathematica produces sometimes expressions of the form               Abs[a + Exp[I*c]b]^2      where all three quantities a, b and c are positive real numbers. That expression of course reduces simply to the law of cosines               a^2 + b^2 + 2a b Cos[c]      however, I cannot get Mathematica to display it in this form. Any ideas?


How do I force all Graphics Text to be StandardForm?

I've been playing around for while trying to determine how to get all graphic objects to use StandardForm fonts. That is, I want all axes labelling, titling, legends, inserted text, etc., for 2D/3D graphics to use StandardForm. Forever and always unless explicitly overridden. I'm getting somewhat overwhelmed with all of the options in the Option Inspector and if anyone has a suggestion I would appreciate it.


Trouble with Minimize

Minimize[{t^2, 1 == 3*t + 16*u}, {t, u}, Integers]         1. It does not give the solution t = -5 and u = 1.   2. Am I missing something? The solution being known and easy, the actual question is not "how can I minimize?"; it is rather "how is it that _Mathematica_ , even version 8 or 9, can't do it?"


Adjust the results of evaluating Table so it can be used as a argument to Point

I have a list generated by `Table` as below.               Table[{a x1 + b x2 + c x3, a y1 + b y2 + c y3, a z1 + b z2 + c z3},        {a, -5, 5}, {b, -5, 5}, {c, -5, 5}]      but it can't be used as an argument to `Point`. That is,               Point[       Table[{a x1 + b x2 + c x3, a y1 + b y2 + c y3, a z1 + b z2 + c z3},          {a, -5, 5}, {b, -5, 5}, {c, -5, 5}]]      doesn't work. How do I adjust the list returned by `Table` to make compatible with `Point`?


How can I compute and plot the 95% confidence bands for a fitted logistic regression model?

I have a set of binary data that I' d like to fit a logistic regression model to and show the 95% confidence band around the fitted function. I can produce the regression model but how do I compute and show the confidence bands in plot3 ? If showing the confidence bands is not possible can the single prediction bands be shown ? Many thanks.               damagecodedata = {{53, 1}, {57, 1}, {58, 1}, {63, 1}, {66, 0}, {67, 0},                       {67, 0}, {67, 0}, {68, 0}, {69, 0}, {70, 1}, {70, 0},                       {70, 1}, {70, 0}, {72, 0}, {73, 0}, {75, 1}, {75, 0},                       {76, 0}, {76, 0}, {78, 0}, {79, 0}, {81, 0}};          plot1 = ListPlot[damagecodedata, PlotRange -> {{50, 90}, {-.1, 1.1}},                Frame -> True,               FrameStyle -> Directive[FontSize -> 13],                FrameLabel -> {Style["Temperature (deg F)", 14], Style["Coded Damage", 14]},                FrameTicks -> {Range[50, 90, 5], {0, 1}, None, None},               PlotStyle -> {PointSize[Medium], Red}, ImageSize -> 400             ]          model = LogitModelFit[damagecodedata, x, x]     Normal[model]     model["ParameterTable"]          plot2 = Plot[model[x], {x, 50, 90}];     plot3 = Show[plot1, plot2]      ![enter image description here](http://i.stack.imgur.com/rk82k.jpg)


Poor Graphics3D rendering

I am rendering a world environment simulation in _Mathematica_ with `Graphics3D` code:               Show[{     Graphics3D[{     Lighting -> "Neutral",     Green,      Polygon[{{-10, -10, 0}, {-10, 10, 0}, {10, 10, 0}, {10, -10,         0}}],     Red, Cone[{{0, 0, 0}, {0, 0, .1}}, 1/2],     White,      Table[Sphere[        Table[{0, 0, 10} + {rx, ry, rz} + {r, r, r/3} /.           r :> RandomReal[]*4, {5}],         2] /. {rx -> RandomReal[{-20, 20}],         ry -> RandomReal[{-20, 20}], rz -> RandomReal[{-1, 3}]}, {30}]     }, Boxed -> False, Background -> Blue,      ImageSize -> {900, 900*41/54}, SphericalRegion -> True],     ContourPlot3D[     x^2 + y^2 == 10^2, {x, -10, 10}, {y, -10, 10}, {z, 0, .6},      Mesh -> None, Lighting -> "Neutral",      ContourStyle -> Darker[Green]]     }]      If the camera is positioned far away from the scene so that everything is in view range, it renders fine: ![somewhat cloudy](http://i.stack.imgur.com/rtbM4.png) However, when I specify the desired camera parameters:               ViewVector -> {{0, 0, .1}, {0, 1, .1}}, ViewAngle -> 54 \[Degree]      The rendering becomes weird: ![weird rendering](http://i.stack.imgur.com/q02aw.png) The bottom part of the green rectangle is cut off and the blue background is displayed instead, and the red cone is very weird as well. Is there a way to display this scene properly? edit: **Solved** with               ViewRange -> {0.1, 100}      This is not optimal, because it does not take `0` or `Automatic` for a minimum value, `All` causes the cut-off in the above example, and it does not take `Infinity` or `Automatic` for a maximum value.


Significant platform-dependent efficiency when importing data?

I'm curious, as I understand that answer this way: > If you are using a Linux derivative or something like cygwin on Windows, > then this is an efficient solution for reading only the third field from > your files ( assumes whitespace separated data, other delimiters can be > specified ).               data= ReadList["!head --lines=-2 " <>#<> " | tail --lines=+39 | cut -f 3 "]& /@ FileNames[]      If one deals with data files in the 2 digit GB range, and often only some columns of the data are needed for further evaluation in experimental science, should one think about running mathematica on Linux, cygwin,... Is the efficiency boost for importing data small, big, huge? Do I have more options to select specific data elements in files?


Solving a system of equations

Mathematica doesn't want to solve my exact system with 3 equations and 3 variables.               AdjustPar20[x_] := a x^b Exp[c x]     Solve[AdjustPar20[0.05] == 9.37126 && AdjustPar20'[0.05] == 0 &&        AdjustPar20[0] == 0, {a, b, c}]      As an explanations why this cannot be solved the program replies:               {}     Solve::ifun: Inverse functions are being used by Solve, so some solutions may not be found;                   use Reduce for complete solution information. >>      Any ideas?


How to collect terms with positive powers in polynomial

I am trying to collect all terms with non-negative powers of $x$ in polynomials like $\frac{1}{x^2}\left(a x^2+x^{\pi }+x+z\right)^2$ First expand the polynomial               Expand[1/x^2 (x + x^π + a x^2 + z)^2, x]      This gives $a^2 x^2+2 a x^{\pi }+2 a x+2 a z+2 x^{\pi -2} z+x^{2 \pi -2}+2 x^{\pi -1}+\frac{z^2}{x^2}+\frac{2 z}{x}+1$. Now try to select those terms with positive or zero powers of x. My best guess is               Plus@@Cases[%, (Times[___, Power[x, g_.], ___] /; g >= 0)]      However, this only yields the term $a^2 x^2$. And why does this not work for the other terms? How can I collect the other terms with positive or zero powers of x?


how to superimpose two best-fit graphs

I have a couple of best fit curves. All I want to do is superimpose them, to see if they are shaped differently. (I can eyeball them but I want to be sure, as it were). On to what I am asking: I have a couple of data sets. I graphed them both with the following and all was well:               IntData = {{0.05`, 2.835`}, {0.1`, 2.84`}, {0.2`, 2.845`}, {0.3`, 2.85`},                {0.4`, 2.865`}, {0.5`, 2.88`}, {0.6`, 2.9`}};     Fit[IntData, {1, amp, amp^2}, amp]     Plot[2.84 - 0.00005*amp + 0.176*amp^2, {amp, 0, 0.6},       AxesLabel -> {"Amplitude", "Period"}, AxesOrigin -> {0, 2.84}]      I did it again with a second data set. Everything looks the same except the numbers are different: ˚ IntData = Table[{amplitude[n], period[n]}, {n, 0, 6}]; Fit[IntData, {1, amp, amp^2}, amp] Plot[4.02 - 0.00698*amp + 0.271*amp^2, {amp, 0, 0.6}, AxesLabel -> {"Amplitude", "Period"}, AxesOrigin -> {0, 4.02}] Both sets generated nice curves. I wanted to have the curves superimposed so I tried setting up both data sets again with variables named differently:               amplitude1[0] = 0.05; period1[0] = 2.835;     amplitude1[1] = 0.10; period1[1] = 2.840;     amplitude1[2] = 0.20; period1[2] = 2.845;     amplitude1[3] = 0.30; period1[3] = 2.850;     amplitude1[4] = 0.40; period1[4] = 2.865;     amplitude1[5] = 0.50; period1[5] = 2.880;     amplitude1[6] = 0.60; period1[6] = 2.900;     IntData = Table[{amplitude1[n], period1[n]}, {n, 0, 6}];     Fit[IntData, {1, amp1, amp1^2}, amp1]       and               amplitude2[0] = 0.05; period2[0] = 4.010;     amplitude2[1] = 0.10; period2[1] = 4.015;     amplitude2[2] = 0.20; period2[2] = 4.02;     amplitude2[3] = 0.30; period2[3] = 4.035;     amplitude2[4] = 0.40; period2[4] = 4.05;     amplitude2[5] = 0.50; period2[5] = 4.075;     amplitude2[6] = 0.60; period2[6] = 4.105;     IntData = Table[{amplitude2[n], period2[n]}, {n, 0, 6}];     Fit[IntData, {1, amp2, amp2^2}, amp2]      and then tried this:               Plot[4.02 - 0.00698*amp2 + 0.271*amp2^2, {amp2, 0, 0.6},       AxesOrigin -> {0, 0},       2.84 - 0.00005*amp1 + 0.176*amp1^2, {amp1, 0, 0.6},       AxesLabel -> {"Amplitude", "Period"}, AxesOrigin -> {0, 0}]      thinking that would pu them both on the same graph, but I got an error message:               Plot::nonopt: Options expected (instead of {amp1,0,0.6}) beyond position 3 in Plot[4.02 -0.00698 amp2+0.271 amp2^2,{amp2,0,0.6},AxesOrigin->{0,0},2.84 -0.00005 amp1+0.176 amp1^2,{amp1,0,0.6},AxesLabel->{Amplitude,Period},AxesOrigin->{0,0}]. An option must be a rule or a list of rules. >>      Which I can sort-of-decipher but not really. So I am asking here what I did wrong. It's probably something obvious to many people here, but I am a rank beginner with Mathematica and am hoping that someone here can give me the kind of explanation they'd give to their grandmother. :-) No, I am not smarter than a 5th grader in this context. I hope this isn't too long a post. I'm just trying to get this done and offer my sincere thanks to those that answer. (And maybe this will help other newbies too, I can't be the only one)


What ways are there to convert an Integer to a list of digits?

How can I convert an `Integer` to list of numbers? For example:               781049 ==> {7, 8, 1, 0, 4, 9}      What are the possible ways of doing this? How well they compare performance- wise? Is a compiled version faster than `IntegerDigits`? How to convert huge amounts of large integers to digit form?


How to Open Kernel?

My MathKernel.exe resides in the following path: C:\Program Files\Wolfram Research\MathKernel.exe. I built a webMathematica application named "WebMathematica" and placed my entire application folder under the "Web-Apps" folder of Apache Geronimo. It's working fine. My Mathkernel was initialized using "mspConfiguration.xml" in the following way.               <KernelPool>       <KernelPoolName>General</KernelPoolName>         <KernelExecutable>C:\Program Files\Wolfram Research\MathKernel.exe</KernelExecutable>         <URLPattern>/*</URLPattern>     </KernelPool>      After this, I copied this entire folder and pasted it in I:\Projects. I opened the command prompt (cmd) and converted my application into a ".war" file. ![enter image description here](http://i.stack.imgur.com/iKYjj.jpg) Finally, I got a WebMathematica.war file. I then deployed this file in Apache Geronimo. I started my application server, and here I observed that Mathkernel wasn't initialized, so my application was not working as well. The problem was the kernel path, the one that I list in the "MSPCOnfiguration.xml" file. I believe that once a`.war` file has been created, we can't access outside paths. My question is how to fix this. I never use any `IDE`.


strange output from ToExpression

I want to set constraints to my parameters, e.g., "m", but Mma gives nonsensical output. How could I avoid this phenomenon by using another but "equivalent expression"? Or, is this just in my computer (i.e. a non- reproducible problem)? case 1. output is as expected:               ToExpression[      ToString[2.] <> ToString[">"] <> ToString["m"] <> ">=" <>        ToString[1.]]      > >     2. > m >= 1. >   case 2. output is unexpected:               ToExpression[      ToString[0.10465923419974825] <> ToString[">"] <> ToString["m"] <>        ">=" <> ToString[-6.0857416503171394*^-6]]      > >     -60.8574 >


Runge-Kutta-2 on System

After spending some time using the Mathematica documentation and this Mathematica.SE _answer_, I implemented the Runge-Kutta-2 routines. I am hoping someone can validate what I did and tell me that it is correct (especially the Butcher Tableau I used) and the step size $h = 0.1$.                 ClassicalRungeKuttaCoefficients[4, prec_] :=         With[{amat = {{1/2}}, bvec = {0, 1}, cvec = {1/2}},          N[{amat, bvec, cvec}, prec]]            {xf, yf} = {x, y} /.          First@NDSolve[{x'[t] == -y[t], y'[t] == x[t], x[0] == 1,           y[0] == 0}, {x, y}, {t, 0, 6},           Method -> {"ExplicitRungeKutta", "DifferenceOrder" -> 4,          "Coefficients" -> ClassicalRungeKuttaCoefficients},           StartingStepSize -> 1/10];            xl = MapThread[Append, {xf["Grid"], xf["ValuesOnGrid"]}]            yl = MapThread[Append, {yf["Grid"], yf["ValuesOnGrid"]}]      We can find a closed form solution to this problem as:                 s = DSolve[{x'[t] == -y[t], y'[t] == x[t], x[0] == 1, y[0] == 0}, {x, y}, t]      Lastly, is there an automated way to update and step through each variant of RK-2, RK-3, RK-4, ... without having to manually enter the Butcher values (in other words, I want to step through each variant of RK-n and compare the errors (a table of that would be great))? There is a hint of this at _Wolfram's Reference page_. Note: I am embarrassed to say that I did not totally understand ClassicalRungeKuttaCoefficients (other than the coefficients).


Problem with NIntegrate when WorkingPrecision is specified

I am trying to evaluate this integral numerically: $$ \int_0^{\infty } m \exp (-m) J_1(m){}^2 \, dm $$ Everything is OK when only the integration method is specified:               NIntegrate[-m Exp[-m] BesselJ[1, m]^2, {m, 0, Infinity}, Method -> "ClenshawCurtisRule"]      but when I specify the `WorkingPrecision`, the integral remains unevaluated:               NIntegrate[-m Exp[-m] BesselJ[1, m]^2, {m, 0, Infinity}, Method -> "ClenshawCurtisRule",       WorkingPrecision -> 10]      What is wrong with this code? I am using _Mathematica_ v9.0.1 **UPDATE** This bug is still present in version 10.0.0.0.


How can I stop DiscreteMarkovProcess[] from relabeling vertices?

I'm attempting to calculate the mean first passage time between two vertices, $v_1$ and $v_2$, provided some undirected graph $G$. However, I noticed that running the following script:               DMPG = DiscreteMarkovProcess[1, G];     Print[Mean[FirstPassageTimeDistribution[DMPG,2]]      Returns a value for the mean first passage time between $v_1$ and some $v_i$ (instead of the desired $v_2$) due to a vertex name reassignment by DiscreteMarkovProcess[]. How can I stop this, or find the mapping between vertices in $G$ and nodes in the Markov chain generated by DiscreteMarkovProcess[]?


Alternative to using global variables in functions?

Often times I find myself using unevaluated variables (i.e. they show up blue) as dummy variables in whatever I'm returning such that I can evaluate them as needed later on. A simple example is as follows. Consider we have a function that returns a collection of monomials with 'x' as the independent variable.               getFns[n_] := Array[x^# &, n];      In this function, 'x' is simply a dummy (global) variable. Then suppose we have a function that returns a list of values corresponding to the list of monomials evaluated at specified coordinates:               useFns[fns_, coords_] := Array[fns[[#]] /. x -> coords &, Length[fns]];      Here is some sample input:               myFns = getFns[3]; (* {x, x^2, x^3} *)     myCoords = {1, 2, 3, 4};     useFns[myFns, myCoords]      which returns (as expected):               {{1, 2, 3, 4}, {1, 4, 9, 16}, {1, 8, 27, 64}}      The problem with this approach is that if the initial dummy variable is changed, it needs to be changed each time the list of functions is evaluated at specific points which can be tedious. Is there a better way to implement this?


Replacing a function in defined expressions

I'm having a little trouble with substituting functions into an expression. A minimal example is as follows:               diffy := D[U[z], z];     Unevaluated[diffy]/. U[z] :> Exp[-I*k*z]         Derivative[1][U][z]      Instead I want to do this:               Unevaluated[D[U[z], z]] /. U[z] :> Exp[-I*k*z]         -I E^(-I k z) k      but obviously I can't do the latter because my practical "diffy" expression is a result of many steps and consists of many lines of functions and derivatives of U[z]. Is there a way _Mathematica_ can take a function, substitute it into an expression such as "diffy" and evaluate it? I tried enclosing my expression above in "Evaluate[]" but that did not work. **Update:** The solution provided works for the above prototype, but when I add another level, it all breaks down. This is a minimum example:               U0 := U[z];     diffy1 := Hold[D[U0, z]];     diffy1 /. U[z] :> Exp[-I*k*z] // ReleaseHold         Derivative[1][U][z]      I have tried holding the first expression, releasing the hold in the definition of the second one and then holding again - and many other combinations of holding/releasing but nothing has worked so far. Is there a fundamental reason why this is not working? Maybe I'm not thinking of Mathematica correctly but I don't understand why this does not work immediately.


Select elements in a list when the firsts two items are the same (no matter order) and its third element is lower

I'm trying to solve a heuristic search in Mathematica 9. I get a list of succesor nodes called open with two nodes and a heuristic value, e.g.,               open={{node1,node2,H1},...,{node2,node1,Hi},...,{noden,noden,Hn}}      I need to select only when the two firts elements are the same (no matter order) but where the heuristic is lower. Following the code that I used for sort the elements by the first item               Sort[open, #1[[1]] < #2[[1]] &]      I try to select cases when the same first and second numbers and the heuristic value where lower:               Select[open, #1[[1]]==#2[[1]] &&  #1[[2]] == #2[[2]] && #1[[3]]< #2[[3]] &]      But, returns `{}`... My list               open = {{1, 2, 3}, {2, 1, 5}, {1, 2, 2}, {3, 4, 5}, {4, 3, 2}};      Between `{1, 2, 3}`, `{1, 2, 2}`, and `{2, 1, 5}` then choose `{1, 2, 2}` that has the lower heuristic. And, between `{3, 4, 5}` and `{4, 3, 2}` then `{4, 3, 2}`...               {{1, 2, 2},{4, 3, 2}}      Thanks,


Accessing Draw Tools objects with notebook commands

In a notebook I would like to be able to access and modify the properties of draw tools objects after I've drawn them on a graph by hand. For example, if make a plot and, with draw tools, make a circle, is it possible now to access the circle Graphics object and its properties with commands in the notebook?


How to create a 'shortest-path link matrix'?

I am currently struggling with a problem in _Mathematica_. I have a randomly generated weighted Barabasi-Albert graph and a corresponding demand matrix of the same size. I'm generating the graph with the following code:               generateBarabasiAlbertGraph[n_, l_] /; n >= 3 :=       Module[{g = CycleGraph[3], vc, vl, el},      Do[      vc = VertexCount[g];      vl = VertexList[g];      el = EdgeList[g];      ec = EdgeCount[g];      wl = RandomInteger[{5, 20}, {ec}];      graph = Graph[el, EdgeWeight -> wl, EdgeWeight -> "EdgeWeight"];      el = Map[UndirectedEdge[vc + 1, #] &,         RandomSample[VertexDegree[g] -> vl, Min[l, vc]]        ];      g = Graph[Join[EdgeList[g], el],         VertexLabels -> Placed["Name", Before]], {n - 3}];        g;      ];     v = RandomInteger[{5, 10}];     l = RandomInteger[{1, 2}];     generateBarabasiAlbertGraph[v, l];      I then calculate the shortest path from each vertex `a` to vertex `b` if vertex `a` has a demand from vertex `b`. Now I would like to create a _shortest-path link matrix_ for all shortest paths in the graph. (A similar graph appears in this paper by Kelly). This is what I already figured out:               TableForm[Array[0 &, {EdgeCount[graph], 1}], TableHeadings -> {EdgeList[graph], {sp}}]      ![enter image description here](http://i.stack.imgur.com/Eh87P.png) As you can see, I have the shortest-path 3-1-4 and need to replace the 0 at the corresponding row if this edge is used in the shortest path. So in this case I need a `1` in row 3 and 4 Any ideas? Best, Julian


3D Plot from 3 Polynomial Equations

Here is my code:               f0[\[Lambda]0_, y0_, y1_, x_, k_] :=-(-y0 + k*x*y1 + (1 - k*x^2)*\[Lambda]0^2)^2 + 4*x^2*(1 - k^2*x)*\[Lambda]0^2*Abs[-(k*y0) + y1 + k*\[Lambda]0^2 - x*\[Lambda]0^2]          f1[\[Lambda]1_, y0_, y1_, x_, k_] := -(x*y0 - y1 + (1 - k*x^2)*\[Lambda]1^2)^2 + 4*x^2*(-k + x)*\[Lambda]1^2*Abs[-(k*y0) + y1 - \[Lambda]1^2 + k^2*x*\[Lambda]1^2]          f2[\[Lambda]0_, \[Lambda]1_, x_, k_] :=-1/27 + \[Lambda]0^3 + 3*x*\[Lambda]0^2*\[Lambda]1 + 3*k*x*\[Lambda]0*\[Lambda]1^2 + \[Lambda]1^3      $k$ is some positive number which can be chosen freely for example $k=1$ or $k=3/2$ or $k=2/3$. $f_0$ is only a function of $\lambda_0$, likewise $f_1$ is only a function of $\lambda_1$. If I would insert $\lambda_0$ from $f_0$ into $f_2$ and insert $\lambda_1$ from $f_1$ into $f_2$ then $f_2$ will be a function of only $x,k,y_0,y_1$. In this case I would like to have a 3D plot with x axis =$y_0$, y-axis=$y_1$, and z-axis =$x$ for $7/81<y_0<1/9$ and $7/81<y_1<1/9$, for some known $k$ as mentioned above and $x$ must be eventually in $0<x<1$, by positivity condition. Is it doable? how can I do that? **EDIT:** I obtain the polynomials via equating them to $0$. Namely, $f_0=0$, $f_1=0$ and $f_2=0$ are all given and known. Thank you very much.


Scripting a visual comparison between the derivative and some finite scheme

I want to make an application where I can specify a function $f:\mathbb R\to \mathbb R$ and a dynamic value $n$ and get the function $\frac{f(x+\frac{1}{n})-f(x)}{\frac{1}{n}}$. I moreover want to compare it to $f'(x)$, i.e. plot it in the same graph. I first tried it with $f(x):=x^m, m=2$ and used Listplot, but even here I got into some obsticles. Here is my attempt:               Table[((x+1/n)^m)-x^m)/(1/n),{m,1000,100}]          Function[x,#][Rangle[10]]&/@%          %/.{n->3}//N          Show[     Plot[3 x^2,{x,0,10}]     ListPlot[#]&/@%     ]      If I do just _ListPlot[#] &/@%_ instead of the last line, the I get all the plots, however it doesn't compare. I'd also like to get away from $x^m$ and make an abstraction w.r.t. $f$, but my tries with Function fails. Is there a difference between _Function[$x$,term]_ and _$\lambda x.$term_ ?.


making a function of fit results

I have 13*25 datasets consisting each of around 40 points. They are all linear I can easily fit them using fit function but my problem is when I want to call them I want them to be functions. I want to define a function using fit results something like               Radius[s1,s2,o,i]=Fit[data[s1,s2,o],{1,x},x]      Do you have any idea how can I make this function? any ideas? Edit: My data is a set data of radius, {i,r(i)} what are s1,s2 and o, Here it come in details if you are interested ![Molecules](http://i.stack.imgur.com/GEjtR.jpg) s1 is site one on molecule one and s2 is site2 on molecule 2 an o is orientation meaning the way molecules can approach each other anyways in each case we will have different radiuses between these molecules and data[s1,s2,o] is a set of 40 points for example the picture is orientation one, data[1,7,1] will be 40 points of distance between atom 1 in molecule 1 and atom 7 in molecule 2.               {{1, 6.44479}, {2, 6.34609}, {3, 6.24742}, {4, 6.1488}, {5,     6.05023}, {6, 5.9517}, {7, 5.85322}, {8, 5.7548}, {9, 5.65642}, {10,     5.55811}, {11, 5.45986}, {12, 5.36167}, {13, 5.26356}, {14,     5.16551}, {15, 5.06754}, {16, 4.96965}, {17, 4.87185}, {18,     4.77414}, {19, 4.67652}, {20, 4.57901}, {21, 4.48161}, {22,     4.38432}, {23, 4.28716}, {24, 4.19013}, {25, 4.09325}, {26,     3.99652}, {27, 3.89995}, {28, 3.80356}, {29, 3.70736}, {30,     3.61137}}      the first iterator is the step number, meaning by each step molecules get closer to each other. Thanks for your attention


How to prevent Mathematica combining similar terms?

For example, given: `x + 2 x y - x y + y` I need to put it in this form: `x (1 + 2 y) - y (x - 1)`. But _Mathematica_ will simplify (automatically) `x + 2 x y - x y + y -> x + x y + y` and I will not be able to group this expression as I need (I need to factor `(1 + 2 y)`). The main question is how to prevent _Mathematica_ simplifying, _or_ how to factor out `x (1 + 2 y)` from this expression: `x + x y + y`? Alternatively, how to put `x + x y + y` into `x (1 + 2 y) - y (x - 1)`?