title: Writing intelligent replacement rules for symbols

text: I am learning about quaternions right now, and I wanted to play around with some concepts I am learning. e.g. take rotation of a point about an axis with specified angle.               th = 3.4;     v  = Sqrt[1/3.0]*(i + j + k)     q    = Cos[th] + Sin[th]*v;     qinv =  Cos[th] - Sin[th]*v;          p = 2*i + 3*j + 4*k;          r = q * p *qinv // Expand     r = r//.{ i*i->-1, j*j->-1,k*k->-1,                i*j->k , j*i->-k,                j*k->i,  k*j->-i,                k*i->j,  i*k->-j}      Here I want to rotate the point _p_ in three dimensions by the angle _th_ with the axis given by the unit vector _v_. So for that I basically just need to use replacement rules like did above. The result I get is               0.391808 + 2.26121 i - 0.0435342 i^3 + 3.1959 j - 0.0653013 j^3 +       4.1306 k - 0.0870683 k^3      How do I tell Mathematica to replace **'i^3'** etc. by **'-i'**? I would have thought Mathematica would be smart enough to use my 'i^2=-1' rule to figure this out. Generalizing this question, if I am manipulating symbols (not just quaternions) how do I specify replacements so that the final answer is as 'simple' as possible?


title: How to create a rectangle wave (duty cycle $\ne$ 50 %)?

text: I'm trying to use phase-shifted `SquareWave[]` functions to create a rectangle wave:               SquareWave[{0, 1}, x/100] * SquareWave[{0, 1}, x/100 - offsetx]      Two things:   1. This only allows for duty cycles less than 50 %.    2. While it's handy (it's always the phase shift $0\dots 1$, regardless of horizontal scale), I'm confused that `offsetx` isn't a function of the `x` scaling Is there a general function to create rectangle waves with duty cycles from 0 % to 100 %?


title: Accept Infinity as an Integer argument

text: I have the following function, albeit contrived:               Foo[x_Integer] :=       Module[{i},        i = 1;        While[i <= x && i <= 10, i++];        i - 1        ];      I am looking for the following               Foo[1] = 1     .     .     .     Foo[10] = 10     Foo[11] = 10     Foo[Infinity] = 10      However `Foo[Infinity]` returns `Foo[\\[Infinity]]` and not `10` . Is there an something that I can do, short of: `Foo[Infinity] = 10;` to get `Foo[Infinity]` to return `10` ? The problem is `i <= 10` is static in my contrived example, but will be dynamic in practice.


title: How do I solve N simultaneous equations for N variables?

text: I have a function:               f[x_] := x + 31 x^3 + 5 x^25      Which I want to find an expansion for:               ex[x_, a_, b_, c_, d_] := a + b x + c x^3 + d x^25      I do this by solving to find the coefficients a,b,c,d by setting the expansion equal to the function at the appropriate number of points:               sol = Solve[{ex[1, a, b, c, d] == f[1], ex[3, a, b, c, d] == f[3],      ex[2, a, b, c, d] == f[2], ex[4, a, b, c, d] == f[4]}]      This works fine, but its ugly. I've only used this to illustrate what I want to do... but actually I want to find an expansion involving 'N' expansion coefficients, and perform solve at N different points to find what they are. However, I don't understand how to do that without having functions with N+1 arguments and so on. If I haven't expressed myself clearly let me know and I'll add more. EDIT: Perhaps I'll add that really the expansion I'm looking for is something like (though how I put the coefficients into the function argument I don't know):               ex[x_,a[i]_,b[i]_,N_,M_]:= Sum[a[n] ChebyshevT[n,x],{n,0,N}] + Sum[b[n] * y[n,x],{n,1,M}]      Where the functions y[n,x] are some other functions which is not orthogonal to the Chebyshev polynomials.


title: My donut has holes in it!

text: More than one hole, I mean… I’m trying to export from Mathematica into the X3D format, with the longer term goal of generating 3D figures for PDF inclusion. But I'm stuck at the first step:               p = ParametricPlot3D[{(2 + Cos[v]) Sin[u], (2 + Cos[v]) Cos[u],          Sin[v]}, {u, 0, 2 Pi}, {v, 0, 2 Pi}, PlotStyle -> Red];     Export["test.x3d", p];      The donut thus generated has holes in it (as visualized here with FreeWRL): ![enter image description here](http://i.stack.imgur.com/ccppQ.png) ![enter image description here](http://i.stack.imgur.com/y5RE6.png) and the same is true for every 3D surface I've tried to export. MeshLab complains that the file contains “4 degenerated faces”, but I doubt it's the same issue, as there are a lot more than 4 holes! I am not a 3D format expert, so I don't really know where to go. Exporting to VRML gives the same issue, so I suspect something generic is going on, but I don't really know how to investigate. I tried importing back the files into Mathematica, but 3D graphics formats are apparently write-only. So, how do you advise me to tackle the issue? Do you have any experience in this kind of export?


title: Printing exported PDF graphics fails (version 8)

text: When I export even simple graphics, say, a `DateListPlot` to PDF under Windows, it refuses to print on any of the printers at work.   ![enter image description here](http://i.stack.imgur.com/f3RGx.png) Acrobat (Reader X) throws three modal dialogs in succession: "The document could not be printed", "There were no pages selected to print" and (sometimes) "There was a drawing error". Strangely, simple graphics (i.e. not a `GraphicsGrid`) will print correctly if you choose "Save Selection As..." or right-click and choose "Save Graphics As..." and save as a PDF. However PDFs produced using the `Export` command, or by saving some more complex `Grid`s of graphics, have this printing issue. I cannot see anything different in the properties of the PDFs produced with `Export` that might cause them not to print, when those produced using the various versions of "Save As..." do print. There is a work-around, which is to go into the Advanced tab of the print dialog and choose "Print as image". Since the intention is that colleagues will be running notebooks that automatically update and export PDF-format graphics, I am reluctant to use this work-around. People will forget what to do and blame me. I have already had problems sending graphics to colleagues that they then can't print. Other than manually exporting things all the time using "Save Selection As" and educating people on print settings, is there anything I can do to avoid printing errors? System: Windows XP, Mathematica 8.0.4. We're going to Windows 7 very soon, so maybe that will help. **EDIT**   I have now uploaded:   1. The file that does not print (produced using `Export`)   2. The file that does print As you can see, they look identical but there are about 100 extra bytes in the `Export`ed version. **EDIT 2** This bug seems to have been fixed in version 9.


title: Generate list of strings from a list of assigned variables

text: How do I generate a list of strings from a list of assigned variables? Eg. Convert               var1 = 10;     var2 = 11;     var3 = 17;     var4 = 5;          compvar = {var1, var2, var3, var4}; (*all variables assigned*)      into,               compvarstr = {"var1", "var2", "var3", "var4"};      Using `ToString` obviously converts the variables assignments into strings e.g.               compvarstr = ToString[#] & /@ compvar      gives, > {"10", "11", "17", "5"} i'm after the unassigned variable names as strings e.g. > {"var1", "var2", "var3", "var4"}; Apologies if this is a duplicate - I had a bit of a look and nothing seemed to answer it.


title: Devising a sparse array rule

text: Suppose I have a matrix               A={{1, 2}, {3, 4}}      that defines the positions of non-zero values in a sparse array:               S=SparseArray[Table[p1 = A[[i, 1]]; p2 = A[[i, 2]]; {p1, p2} -> 77, {i, Dimensions[A][[1]]}]];     ArrayRules@S     {{1, 2} -> 77, {3, 4} -> 77, {_, _} -> 0}      Is it possible to construct such a sparse array without explicitly building the table of correspondence, by using a single rule that extracts the positions of non-zero elements from matrix A? Mathematica documentation shows examples of such rules, e.g.               SparseArray[{{i_, j_} /; Abs[i - j] <= 1 -> -2 + 3 Abs[i - j]}, {5,5}]      How should a similar rule be devised for my case? Thank you!


title: Stationarity tests

text: I have the Time Series package and Mathematica 8. In the package, there is the function 'StationaryQ' to test the stationarity of a known model. Is there any function in Mathematica to test the stationarity of a given list of data?


title: Plotting Time Series with call to Wolfram Alpha

text: I am trying to plot stocks showing some of the local maxima. As an exercise I first tried to load Apple's stock data from Wolfram Alpha with the following code:               appledata =TimeSeries[WolframAlpha["AAPL", {{"History", 1}, "ComputableData"}][[1]]];       Show[DateListPlot[appledata],DateListPlot[FindPeaks[TimeSeriesResample[appledata], 12],        Joined -> False,PlotStyle -> Directive[PointSize[0.03], Red]]]       However, I am returning the following errors:               DateListPlot::ldata: TimeSeries[NotAvailable] is not a valid dataset or list of datasets. >>     FindPeaks::arg: The argument TimeSeriesResample[TimeSeries[NotAvailable]] at position 1 is not a consistent list of real values. >>     DateListPlot::ldata: FindPeaks[TimeSeriesResample[TimeSeries[NotAvailable]],12] is not a valid dataset or list of datasets. >>     Show::gcomb: Could not combine the graphics objects in Show[DateListPlot[TimeSeries[NotAvailable]],DateListPlot[FindPeaks[TimeSeriesResample[TimeSeries[NotAvailable]],12],Joined->False,PlotStyle->Directive[PointSize[0.03],\!\(\*GraphicsBox[{{GrayLevel[0], RectangleBox[{0, 0}]},{GrayLevel[0], RectangleBox[{1, -1}]},{RGBColor[1, 0, 0], RectangleBox[{0, -1}, {2, 1}]}},AspectRatio->1,Frame->True,FrameStyle-RGBColor[0.6666666666666666, 0., 0.],FrameTicks->None,ImageSize->{Automatic, 10.8},PlotRangePadding->None]\)]]]. >>      I'd like to move beyond just searching stocks such as Apple and be able to search tickers, maybe something like https://www.google.com/webhp?sourceid=chrome- instant&rlz=1C1LENP_enUS562US562&ion=1&espv=2&ie=UTF-8#q=ugaz&safe=off


title: Generating $n$ random samples every time

text: Is it possible to generate $n$ random samples, and always ensure that $n$ samples are generated? eg For $n=5$:               n=5; {n1, n2, n3, n4, n5} = (While[Total[set = Reverse@Sort@Round     [(tmp = RandomInteger[100, n])/Total@tmp 100]] != 100]; set);     s = Reverse[Sort[{n1, n2, n3, n4, n5}]];     a = rs[[1]]; b = s[[2]]; c = s[[3]]; d = s[[4]]; e = s[[5]];     PieChart[{a, b, c, d, e}, ImageSize -> 200,      ChartLabels -> {Style[StringForm["A:``%", a], 10],      Style[StringForm["B:``%", b], 10],      Style[StringForm["C:``%", c], 10],      Style[StringForm["D:``%", d], 10],      Style[StringForm["E:``%", e], 10]}]      is ok, but for large enough $n$ the numbers are often "used up" before the last few get a chance to sample (so, in the example of the above pie chart, "E" often doesn't feature). Is it possible to avoid the samples reaching $0$ before last $n$ is reached? (Obviously, by the time $n=100$, each sample should have value of $1$.)


title: Calculating average distance

text: I have a program that gives the average distance as the output. When I tried to repeat finding the average distance 100 times using Table, It failed to generate the output. This is the program.               Xarray = A @@@ Tuples[Range[0, 4], 3];     Table[M = RandomSample[Xarray, 7];     energies = RandomVariate[ExponentialDistribution[1.5], {7}];     f = {#, First@Pick[energies, M, #]} &;     list = Map[f, M]     c = Subsets[Range[Length@list], {2}];     d = Length@%          distanceBetween[{n_, m_}] :=        Norm[List @@ list[[n, 1]] - List @@ list[[m, 1]]]          Map[distanceBetween, c]     ans = % // N;          Total[%/d], {i, 100}]      The program is like this. I created an array of let say 500 elements and assigned energy to it. Next I choose a coordinate from the list and find the distance from other coordinates using the norm equation. Next I sum up that distances in the list and take the average of the distance. The Problem comes when I am trying to do this process 100 times using Table or Do command.


title: Memory Leak in RowReduce?

text: Recently I tried to do what I thought was a fairly small (relative to the 6 GB of RAM that I have on my machine) row reduction calculation on a matrix representing an undetermined linear system and was very surprised by how much trouble I had with it. The 2590 X 12155 matrix, `A` (available for download via Mediafire), takes a little over 17 MB to store, has rational entries, and is very sparse (~3% of the entries non-zero). The data structure I used to store `A` is _Mathematica_ 's rule-based representation for sparse arrays on a row-by-row basis (if this is unclear please see the example matrix from my last post). Curiously, I find that using `RowReduce` to find a row echelon form for `A` leaves a huge memory footprint well beyond what _Mathematica_ reports with `MemoryInUse`. I was able to observe this effect without leaving _Mathematica_ in an (to me miraculous) allegedly platform-independent way by using the answer that @WReach gave here in response to a question about memory monitoring. I began with               In[1] := $HistoryLength = 0;      to turn off caching and then set up a pair of commands which give respectively my machine's and _Mathematica_ 's estimates of how much memory is currently in use using the ideas of @WReach:               In[2] := Needs["JLink`"]              InstallJava[];              LoadJavaClass["java.lang.management.ManagementFactory"];          In[5] := temp = JavaBlock[{#,java`lang`management`ManagementFactory              `getOperatingSystemMXBean[]              @#[]} & /@ {getFreePhysicalMemorySize,               getTotalPhysicalMemorySize}]; memstart1 =               temp[[2, 2]] - temp[[1, 2]]          Out[5] := 3096420352          In[6] := memstart2 = MemoryInUse[]          Out[6] := 18286664          In[7] := temp = JavaBlock[{#,               java`lang`management`ManagementFactory`getOperatingSystemMXBean[]              @#[]} & /@ {getFreePhysicalMemorySize,               getTotalPhysicalMemorySize}]; memnow1 =               temp[[2, 2]] - temp[[1, 2]] - memstart1          Out[7] := 94208          In[8] := memnow2 = MemoryInUse[] - memstart2          Out[8] := 1808      I've found that copying and running the preceding two lines of code wherever I want a memory sanity-check seems to give a fairly consistent way to compare how much memory _Mathematica_ has actually used since the start of the session and how much memory _Mathematica thinks_ it has used since the start of the session (the numbers 94208 and 1808 from the initialization above should be thought of as being effectively zero). Although it is probably obvious, I have of course assumed that the amount of RAM used by all other programs is constant throughout the session (which should be approximately correct if they are just running idly in the background). Now I read in the file containing the matrix and assign it to `A`:               In[9] :=  f = OpenRead["rrdemo"];               A = Read[f];               Close[f];      I also go ahead and define an array that will be used momentarily (recall that 12155 is the number of columns in `A`)               In[12] := W = Array[w, 12155];      Actually, although it's a bit off-topic, it's worth pointing out that there already seems to be some missing memory associated with the process of reading in the file `"rrdemo"` (in a separate session I checked that there is no missing memory associated with the definition of `W`):               In[13] := temp = JavaBlock[{#,                java`lang`management`ManagementFactory`getOperatingSystemMXBean[]               @#[]} & /@ {getFreePhysicalMemorySize,                getTotalPhysicalMemorySize}]; memnow1 =                temp[[2, 2]] - temp[[1, 2]] - memstart1          Out[13] := 425725952          In[14] := memnow2 = MemoryInUse[] - memstart2          Out[14] := 268374384      This is actually nothing at all compared to what happens with `RowReduce`. To obtain a row echelon form for my matrix I use `RowReduce` in a straightforward way on a sparse array. To show that the problem is not with my generation of the sparse array, I first check the memory footprint of that step of the calculation:               In[15] := AbsoluteTiming[C1 = CoefficientArrays[Plus @@@ (#[[2]] w @@                #[[1]] & /@ # & /@ A), W][[2]];]          Out[15] := {5.447995, Null}          In[16] := temp = JavaBlock[{#,java`lang`management`ManagementFactory               `getOperatingSystemMXBean[]@#[]} & /@ {getFreePhysicalMemorySize,                getTotalPhysicalMemorySize}]; memnow1 =                temp[[2, 2]] - temp[[1, 2]] - memstart1          Out[16] := 539504640          In[17] := memnow2 = MemoryInUse[] - memstart2          Out[17] := 385560664          In[18] := ByteCount[C1]          Out[18] := 100604400      The performance of _Mathematica_ here seems reasonable. The actual and reported memory usage go up from what they were before in proportion to the `ByteCount` of `C1`. Now look what happens if we `RowReduce` `C1`:               In[19] := AbsoluteTiming[C2 = Drop[ArrayRules[#], -1] & /@                RowReduce[C1, Method -> "OneStepRowReduction"];]          Out[19] := {402.172945, Null}          In[20] := temp = JavaBlock[{#,                java`lang`management`ManagementFactory`getOperatingSystemMXBean[]               @#[]} & /@ {getFreePhysicalMemorySize,                getTotalPhysicalMemorySize}]; memnow1 =                temp[[2, 2]] - temp[[1, 2]] - memstart1          Out[20] := 2461675520          In[21] := memnow2 = MemoryInUse[] - memstart2          Out[21] := 731499200          In[22] := ByteCount[C2]          Out[22] := 280479264      Something seems to be seriously wrong here. The `ByteCount` of `C2` is only ~ 280 Mb and this is close to the increase in the total memory usage reported by _Mathematica_. But the actual memory usage is ~3.3 times what _Mathematica_ thinks it is! I'm forced to conclude that _Mathematica_ fails to garbage collect more than 1.5 Gb of memory at the end of the calculation. In summary, I have a couple of related questions. Does anybody have any insights into the anomalous behavior of `RowReduce` that I just illustrated? Am I doing something wrong? More generally, does anybody have any idea as to whether or not _Mathematica_ has special algorithms for symbolic sparse linear algebra? Memory issues aside, it makes me suspicious that `RowReduce` takes so long to process `C1` (I have a 2.5 GHz processor) and that it returns a result that is no longer a sparse array. At this point I'm wondering whether _Mathematica_ is even the right tool for the job (symbolic linear algebra on large, very sparse undetermined linear systems). Any advice from more experienced users would be greatly appreciated. If it makes any difference, I'm using 64 bit Linux and am running _Mathematica_ v.8.0.4.


title: ListInterpolation causing .cdf security problems?

text: I've made a simple `.cdf` that makes a function from a list of data I've provided in table form (using `ListInterpolation`) and plots it on a graph (no importing, exporting or conversion of data from string) and I still get a grey block when I try to post it online, indicating that I'm violating some security rule. It works with the `{fullscreen: 'true'}` workaround, but I don't know what I'm doing that necessitates this. Advice? Thanks


title: Configuring Mathematica to send email from a notebook

text: I can't get my email settings set properly such that I can use `SendMail[]` to email directly from Mathematica. I have opened "Preferences", clicked on the tab "Internet Connectivity" and filled in all the settings to match those in my Apple Mail accounts settings. These include:   * Server   * Port Number   * Encryption Protocol   * Username   * From Address   * Full Name   * Reply To Odd that no setting exists for "Password"? The "Preference" window's "Test Internet Connectivity" tells me "Test succeeded..." Apple Mail has a setting to "Use default ports (25, 465, 587)" so I thought this might confuse the Mathematica settings, so I've tried setting the Apple Mail settings to "Use Custom Port" and specified each of the the default ports specifically. None of those settings worked either. I have also attempted to specify **all** available options for `SendMail[]` specifically also trying each of the 3 possible "default" ports described above.                SendMail[      "From" -> "myemail@myisp.com",      "To" -> "recipientemail@isp.com",      "Subject" -> "Example Message",      "Body" -> "Test",      "Server" -> "smtpout.secureserver.net",      "EncryptionProtocol" -> "SSL",      "FullName" -> "MyUserName",      "Password" -> "myPassword",      "PortNumber" -> 25 (* I also tried 465, 587 *),      "ReplyTo" -> None,      "ServerAuthentication" -> Automatic,      "UserName" -> "myUserName"      ]      Again `SendMail[]` gives me the same message: `$Failed`. Also, in the "Preferences" window under the "Proxy Settings" tab I have tried selecting both "User proxy settings from my system or browser" and "Direct connection to the Internet". The "Troubleshooting Internet Connectivity Problems - Wolfram Mathematica" in the "Document Center" suggests checking proxy settings. Given what mine look like in Snow Leopard's "Preferences" >> "Network" >> "Proxies" ![Proxies](http://i.stack.imgur.com/Nu6q4.png) I don't think I have much to help. I have no Firewall Setting on the computer. This has me stumped. Does anyone have an idea of what else I can try.


title: Splitting a list

text: Please consider the following list:               data={1, 0, 0, 0, 2, 5, 2, 3, 0, 0, 3};      Now I would like to split the list into 0-sequences and Not-0-sequences as following:               {{1}, {0, 0, 0}, {2, 5, 2, 3}, {0, 0}, {3}}      All numbers are non-negative `Integer`s, if that helps.


title: Defining symbol shortcuts in the Front End

text: I was wondering (because I could not find any documentation on this) if it is possible to do shorthand abbreviations for domains or could one define them? E.g. > In[1]:= Element[p,Complexes]   >  Out[1]= p $\in$ Complexes to instead do something of the following: > In[1]:= p `esc` elem `esc` `esc`CC `esc`   >  Out[1]= p$\in\mathbb{C}$ And similarly for others: $ \begin{align} \text{Algebraics}: &\text{esc AA esc} \,\mapsto\mathbb{A} \\ \text{Rationals}: &\text{esc QQ esc} \,\mapsto\mathbb{Q} \\ \text{Booleans}: &\text{esc BB esc} \,\mapsto\mathbb{B} \\ %%\text{Naturals}: &\text{esc NN esc} \,\mapsto\mathbb{N} \\ \text{Integers}: &\text{esc ZZ esc} \,\mapsto\mathbb{Z} \\ \text{Primes}: &\text{esc PP esc} \,\mapsto\mathbb{P} \\ \text{Reals}: &\text{esc RR esc} \,\mapsto\mathbb{R} \\ \end{align} $


title: TimeConstrained[] not taking full amount of time

text: I am using Mathematica to evaluate an integral within a given time constraint. Note that I have read in values of 'BigList' or `BL` from a file. If the file has a value for `(l,m)` of zero, then I evaluate the integral, otherwise, I read in the value of the integral from the file. The idea is to continually allow more and more time and 'knock out' the easiest integrals each time, instead of having the script run for hours before stopping when it would get to 'easier' integrals later. My problem is that, for the integrals which evaluate to zero, the output happens far too quickly. The integrals will ONLY evaluate to zero if the time constraint is met, these integrals will _never_ be zero on their own, so I know that if I get an output of zero, that it did not evaluate the integral in the time constraint allowed. The output, however, prints `(l) (m) 0` (where `(l)` and `(m)` are actual numerical values of l and m) almost within less than a second of each other. This tells me that it is not spending the full time (15 seconds in the example below) on the integral. Does Mathematica somehow know that it will take longer and give up or is something else going on? Shouldn't it work for 15 seconds before stopping and resulting in zero?               29 (* total time for each integral allowed *)     30 tt = 15;     31 (* loop through NeedList and assign values *)     32 (* Print["BLsize = ", BLsize]; *)     33 For[i=1, i<=BLsize, i++,     34   If[BL[[i]][[3]]==0,     35     l=BL[[i]][[1]];     36     m=BL[[i]][[2]];     37     (* Assign Jm to be Integrate[Abs[Sin[m*theta],{theta,0,2*pi}]] *)     38     If[m==0,Jm=2*Pi,Jm=4];     39     Ilm=TimeConstrained[Integrate[Abs[LegendreP[l,Abs[m],z]],{z,-1,1}],tt,0];     40     If[Ilm==0, BL[[i]]={l,m,0},     41       If[l==0, BL[[i]]={l,m,1/(Ilm*Jm)}, BL[[i]]={l,m,2/(Ilm*Jm)}];     42     ];     43     (*Print[FortranForm[N[BL[[i]][[3]]]]];*)     44     Print[BL[[i]][[1]], " ", BL[[i]][[2]], " ", FortranForm[N[BL[[i]][[3]]]]];     45   ]     46 ];      EDIT: here is a full working example ...               finp = OpenRead["dens_coefs"];     (* BigList *)     BL = ReadList[finp,{Number,Number,Number}]     Close[finp];     BLsize = Length[BL];          (* total time for each integral allowed *)     tt = 20;     (* loop through NeedList and assign values *)     For[i=1, i<=BLsize, i++,       If[BL[[i]][[3]]==0,         l=BL[[i]][[1]];         m=BL[[i]][[2]];         (* Assign Jm to be Integrate[Abs[Sin[m*theta],{theta,0,2*pi}]] *)         If[m==0,Jm=2*Pi,Jm=4];         Ilm=TimeConstrained[Integrate[Abs[LegendreP[l,Abs[m],z]],{z,-1,1}],tt,0];         If[Ilm==0, BL[[i]]={l,m,0},           If[l==0, BL[[i]]={l,m,1/(Ilm*Jm)}, BL[[i]]={l,m,2/(Ilm*Jm)}];         ];         Print[BL[[i]][[1]], " ", BL[[i]][[2]], " ", FortranForm[N[BL[[i]][[3]]]]];       ]     ];      an example of an input file might be:               3 -3 0.02829421210522584     3 -2 0.06666666666666667     3 -1 0.5706901657772195     3 0 0.     3 1 0.5706901657772195     3 2 0.06666666666666667     3 3 0.02829421210522584     4 -4 0.004464285714285714     4 -3 0.011904761904761904     4 -2 0.1361783763047951     4 -1 0.     4 0 0.     4 1 0.     4 2 0.1361783763047951     4 3 0.011904761904761904     4 4 0.004464285714285714      the program _should_ read these numbers in, figure out which ones are zero (in this case, {3,0}, {4,-1}, {4,0}, {4,1}) and attempt to produce the corresponding integrals. it should take no more than 20 seconds, but if it returns 'zero' then it should take AT LEAST 20 seconds (very close to 20 seconds, maybe a few clock cycles over). for what it is worth, i am running this from a command line script on a linux machine. i have tried `TimeConstrained` arguments in a Mathematica notebook (though not the _exact_ same thing) and it waits, as it should, in the notebook, but it is not waiting the full 20 seconds in the script. EDIT(2): for what it's worth, this seems to work as intended when running it from a notebook interface. it is only when running the script from command line that it gives me problems. any idea why that would happen?


title: Can't get DynamicModule[{..},..EventHandler[] ] working

text: This makes a slider to control the number of points. Click in the `Graphics` and the points slide over to where you click.               Manipulate[     DynamicModule[{points,oldPoints,centerG,oldCenterG,finalPnts,mousePosn},     points=Map[{10,12}+#&,Table[{Cos[2.0 Pi k/n],Sin[2.0 Pi k/n]},{k,1,n}]];     oldPoints=finalPnts=points;     oldCenterG=centerG=Mean/@Transpose[points];          Dynamic[EventHandler[Framed[Graphics[{PointSize[0.02],Point[     If[TrueQ[points==finalPnts],     oldCenterG=centerG;     oldPoints=points,     (* else *)     points=MapThread[     With[{mag=Norm[#2-#1]},If[TrueQ[mag<=0.02],#2,#1+0.04(#2-#1)/mag]]&,     {points,finalPnts}]     ]     ]},PlotRange->{{-15,15},{-15,15}},ImageSize->{600,600}]],     {"MouseDown":>(     mousePosn=MousePosition["Graphics"];     centerG=Mean/@Transpose[points];     finalPnts=Map[(#+mousePosn-oldCenterG)&,oldPoints]) ,     "MouseUp":>(centerG=mousePosn)     }]]      ],{{n,3},3,8,1}]      The problem is that my real application doesn't allow use of `Manipulate`. I thought the code below would work, but it breaks when you click in the `Graphics`. How to get the second version working?               DynamicModule[{points, oldPoints, centerG, oldCenterG, finalPnts,        mousePosn, n},           points =        Dynamic[Map[{10, 12} + # &,          Table[{Cos[2.0 Pi k/n], Sin[2.0 Pi k/n]}, {k, 1, n}]]];      oldPoints = finalPnts = points;      oldCenterG = centerG = Mean /@ Transpose[points];           Column[{        Slider[Dynamic[n], {3, 8, 1}],        Dynamic[EventHandler[Framed[Graphics[{PointSize[0.02], Point[              If[TrueQ[points == finalPnts],               oldCenterG = centerG;               oldPoints = points,               (* else *)               points = MapThread[                      With[{mag = Norm[#2 - #1]},                    If[TrueQ[mag <= 0.02], #2, #1 + 0.04 (#2 - #1)/mag]] &,                 {points, finalPnts}]               ]              ]}, PlotRange -> {{-15, 15}, {-15, 15}},             ImageSize -> {400, 400}]],          {"MouseDown" :> (             mousePosn = MousePosition["Graphics"];             centerG = Mean /@ Transpose[points];             finalPnts = Map[(# + mousePosn - oldCenterG) &, oldPoints]) ,           "MouseUp" :> (centerG = mousePosn)           }]]}]]


title: Turning evaluation off

text: I am making a directed graph, but Mathematica keeps trying to evaluate my labels. I know that I can just use " ", but I have a lot of input. Is there a way to turn evaluation off?               LayeredGraphPlot[{"C1.4.4" -> "T1.5.7", "1.23" -> "L1.5.4",        "P1.4.3" -> "C1.4.4", "P1.4.3" -> "C1.1.4", "P1.1.9" -> "P1.5.2",        "P1.1.9" -> "L1.5.3", "P1.5.2" -> "T1.5.7", "L1.5.3" -> "T1.5.7",        "L1.5.4" -> "T1.5.7", "P1.5.5" -> "T1.5.7", "L1.4.6" -> "L1.4.7"},       VertexLabeling -> True]


title: Precision problem while evaluating RegionMember or Element in V10

text: I'll try to give you a background on where the problem occured. The problem itself is defined near the end of the post. I'm running a sort of a simulation of a particle in a box. I finally got my hands on Mathematica10 so I decided to use new built-in mechanisms such as regions. Long story short: I need to determine the point at which the particle hits the bounding region. I defined my box by:               {X, Y, Z} = {.05, .05, .3};     ip1 = InfinitePlane[{{0, 0, 0}, {0, Y, 0}, {0, Y, Z}}];     ip2 = InfinitePlane[{{X, 0, 0}, {X, Y, 0}, {X, Y, Z}}];     ip3 = InfinitePlane[{{0, 0, 0}, {X, 0, 0}, {X, 0, Z}}];     ip4 = InfinitePlane[{{0, Y, 0}, {X, Y, 0}, {X, Y, Z}}];     ip5 = InfinitePlane[{{0, 0, 0}, {0, Y, 0}, {X, Y, 0}}];     ip6 = InfinitePlane[{{0, 0, Z}, {0, Y, Z}, {X, Y, Z}}];     reg = RegionIntersection[Cuboid[{0, 0, 0}, {X, Y, Z}], RegionUnion[ip1, ip2, ip3, ip4, ip5, ip6]];      I generate the initial position and velocity of the particle as random numbers, then draw a `HalfLine` from the position of particle along the velocity vector. Finally, I check the intersection of the `HalfLine` and the bounding region `reg` with `RegionIntersection`. Then I can extract the coordinates of the bouncing point and calculate the new velocity vector, define a new `HalfLine`, find the intersection, and so on... **The Problem** At some point, however, I get an error caused by the point not being a member (or element, both functions do the same in this case) of my bounding region (sounds ridiculously, because it's supposed to be the intersection of the region and the halfline). When I print the coordinates of that point, I get:               In: p1     Out: {0.0000316867, 0.00969779, 0.3}      So everything looks fine, but doesn't work. I checked it with `Manipulate` - I entered these coordinates manually and `RegionMember[reg,{0.0000316867, 0.00969779, 0.3}]` evaluated to `True`. Then I copied the coordinates of p1 from the output above and found out that they were in fact:               {0.00003168673646693154`, 0.009697790214128308`, 0.29999999999999993`}      The last coordinate was at fault. Is this a bug in the new functions? Any ideas how to get around it? **EDIT: Computing p1:** @user21               line = HalfLine[r + v/10^8, v];     p1 = RegionBounds[RegionIntersection[line, reg]][[All, 1]];      If `line` would start on the wall, `RegionIntersection` would consist of two points. To avoid that, I translate the origin of the `HalfLine` along v a bit. **EDIT 2: I've found a way around, but it doesn't answer the question about precision** Okay, instead of defining `p1` as an element of `RegionBounds` I used `RegionCentroid`:               old: p1 = RegionBounds[RegionIntersection[line, reg]][[All, 1]];     new: p1 = RegionCentroid[RegionIntersection[line, reg]]      And it seems to have solved the problem. But I have no idea why, because for a single point both `RegionCentroid` and `RegionBounds` should give the same result. I tried both functions on a "buggy" (i.e. found by `RegionBounds`) point and here's what I got:               In: RegionBounds[RegionIntersection[line, reg]]     Out: {{0.0494424, 0.0494424}, {0.0341449, 0.0341449}, {0.3, 0.3}}      And after copy-pasting the output:               {{0.04944240524519992`, 0.04944240524519992`}, {0.03414494309476567`, 0.03414494309476567`}, {0.30000000000000004`, 0.30000000000000004`}}      And for RegionCentroid:               In: RegionCentroid[RegionIntersection[line, reg]]     Out: {0.0494424, 0.0341449, 0.3}      Copy & paste:               {0.04944240524519991`, 0.03414494309476552`, 0.3`}      Well, I can imagine that it's due to internal functions used, but I'm still somehow confused that the results do not "converge" for this case.


title: Deploy a custom function to the cloud

text: Following my previous topic on how to optimize a complex function, I decided to write a custom algorithm because I need this task to be run locally and on machines with no access to _Mathematica_. Unfortunately the performance differences between my _java_ code and the _Mathematica_ 's one are really huge and I need another solution. I've just discovered _Wolfram Cloud_ and this seems the best way to make everything work because I can just execute my _Mathematica_ 's notebook, so I subscribed to the free tier to give it a try. Here's what I'm trying:               optimize[d_, p_] := Module[{n, m, q, k, A, b, result},         n=Length[d];          m=Dimensions[p][[2]];          vec[m_]:=Flatten[m\[Transpose]];          mat[v_]:=Partition[v,n]\[Transpose];          j[k_]:=ConstantArray[1,k];          q=j[m];          k=vec[p (d\[TensorProduct]q)];          A=ArrayFlatten[{IdentityMatrix[m]\[TensorProduct]j[n]}];          b=j[m]\[TensorProduct]{1,0};          result = mat[LinearProgramming[k,A,b]];          result      ];      CloudDeploy[APIFunction[{"d" -> "List", "p" -> "List"}, optimize[#d, #p] &, "String"]]      I'm using `List` as a parameter because `d` and `p` are like               d={7,5,11,3};     p=({{5,2,5,3,7,1,1,5,2,5,3,7,1,1},{2,8,3,2,7,2,3,2,8,3,2,7,2,3},{3,6,4,5,9,1,1,3,6,4,5,9,1,1},{4,6,2,8,14,8,4,4,6,2,8,14,8,4}});      Now, the function works fine in my local notebook and hitting evaluate actually makes the deploy. The problem is that the API doesn't return what I expect. While I expect a `string` that contains the result matrix, it outputs: > > Transpose[LinearProgramming[LinearProgramming[Transpose[{{{5,2,5,3,7,1,1,5,2,5,3,7,1,1},{2,8,3,2,7,2,3,2,8,3,2,7,2,3},{3,6,4,5,9,1,1,3,6,4,5,9,1,1},{4,6,2,8,14,8,4,4,6,2,8,14,8,4}} > {{7,5,11,3}} ? ConstantArray[1, {1}[[2]]]}]], > LinearProgramming[ArrayFlatten[{IdentityMatrix[{1}[[2]]] ? {1}}]], > LinearProgramming[ConstantArray[1, {1}[[2]]] ? {1, 0}]]] and I don't understand why. Do you know what the problem is? Their documentation is not that helpful and I'm quite clueless.


title: Multiplication sign in TeXForm?

text: How do I get Mathematica to produce TeX output that does not omit the multiplication signs ? For example, this expression:               (z03*z14*z32 + z01*z12*z43 + z14*(z01 + z03 + z12 + z32)*z43)      displays in Mathematica as:               (z14 z43 (z01+z03+z12+z32)+z01 z12 z43+z03 z14 z32)      And the output of TeXForm look like this: $$ \text{z14} \text{z43} (\text{z01}+\text{z03}+\text{z12}+\text{z32})+\text{z01} \text{z12} \text{z43}+\text{z03} \text{z14} \text{z32} $$ which is really hard to read because the spaces get ignored. How do I get TeXForm to produce this instead ?: $$ \text{z14}\times\text{z43}\times(\text{z01}+\text{z03}+\text{z12}+\text{z32})+\text{z01}\times\text{z12}\times\text{z43}+\text{z03}\times\text{z14}\times\text{z32} $$ Even better would be: $$ \text{z14}.\text{z43}.(\text{z01}+\text{z03}+\text{z12}+\text{z32})+\text{z01}.\text{z12}.\text{z43}+\text{z03}.\text{z14}.\text{z32} $$ Worse come to worse, I could even settle for something like this: $$ \text{z14}\;\text{z43}\;(\text{z01}+\text{z03}+\text{z12}+\text{z32})+\text{z01}\;\text{z12}\;\text{z43}+\text{z03}\;\text{z14}\;\text{z32} $$


title: Graphic using manipulate runs too slow

text: Here is a naive coding of a projection of a point on a sphere. It runs very slow. Can it be changed to run faster without losing its essential analytic character?               Magnify[Manipulate[       Show[ParametricPlot3D[{{x, 0, 1}, {0, y, 1}, {x, y, 1}, {x, x^2,            1}, {x*w, x*w^2, x}, {x, y, Sqrt[1 - x^2 - y^2]}, {x,            y, -Sqrt[1 - x^2 - y^2]}, {x/Sqrt[x^2 + (x^2)^2 + 1], (x^2)/            Sqrt[x^2 + (x^2)^2 + 1],            1/Sqrt[x^2 + (x^2)^2 + 1]}, {-x/Sqrt[x^2 + (x^2)^2 + 1], -(x^2)/            Sqrt[x^2 + (x^2)^2 + 1], -1/Sqrt[x^2 + (x^2)^2 + 1]}}, {x, -5,           5}, {y, -5, 5}, Axes -> False, Boxed -> False,          Mesh -> {{-5, 5}, {-5, 5}},          RegionFunction -> Function[{x, y, z}, 0 < x^2 + y^2 < 16],          SphericalRegion -> True, (*RotationAction->"Clip",*)         PlotStyle -> {Black, Black,            Directive[Opacity[0.5], Blue, Specularity[White, 50]],            Directive[ Red], Directive[ Red],            Directive[Opacity[0.5], Orange, Specularity[White, 50],             Mesh -> None],            Directive[Opacity[0.5], Orange, Specularity[White, 50],             Mesh -> None], Directive[Black], Directive[ Black]}],         Graphics3D[{Red, PointSize[.01],           Point[{{w/Sqrt[w^2 + (w^2)^2 + 1], (w^2)/Sqrt[w^2 + (w^2)^2 + 1],              1/Sqrt[w^2 + (w^2)^2 + 1]}, {-w/Sqrt[              w^2 + (w^2)^2 + 1], -(w^2)/Sqrt[w^2 + (w^2)^2 + 1], -1/Sqrt[              w^2 + (w^2)^2 + 1]}, {w, w^2, 1}}]}]], {{w, 1.086}, 0.01,         3}], 1.7]


title: Do a gauge transformation for a Chern-Simons theory?

text: Suppose we have the following Lagrangian density: $$ L=\epsilon^{\mu\nu\rho}\big(\sum_a A^a_{\mu}(x) \partial_\nu A^a_{\rho}(x)-\sum_{a,b,c}\frac{1}{3} f^{bca} A^a_{\mu}(x) A^b_{\nu}(x) A^c_{\rho}(x)\big) $$ under this infinitesimal transformation + $\dots$ $$ A^a_\mu(x) \to {A^a_\mu}'(x)\equiv (A^a_\mu(x) + f^{abc} \alpha^b(x) A^c_\mu(x) + \partial_\mu \alpha^a(x) +\dots) $$ where $x\equiv(t,x_1,x_2)$, $\epsilon^{\mu\nu\rho}$ is anti-symmetric and cyclic, $f^{abc}$ is anti- symmetric, but may not be cyclic in general. We end up with $L \to L'$ under $A^a_\mu \to {A^a_\mu}'$. And my question is: How to obtain a **well-simplified** $L'$ using _Mathematica_ ? The key point is: **without knowing the detailed structure $f^{abc}$, but only implement $f^{abc}$'s property to simplify the answer $L'$.** ps. I just took a glimpse at this post -how-to-manipulate-gauge-theory-in- mathematica, but I wonder whether there is a simpler way, since I am only doing **pure algebra?**


title: Mesh inside Plot legend

text: I have a plot for which I would like to create an legend that is black and white printer friendly. I have seen Jen's legendmaker but I don't know how to adapt it. I need help in making the legend for the exit region to appear meshed. The graph is incomplete right now and I will add more stuff to it.. like J and V etc etc but for now I want the exit regions and their legends to be black and white printer friendly. What can I do to get a mesh to appear in the legend for the exit region. Thanks **EDIT: Gaps in code fixed.** ![enter image description here](http://i.stack.imgur.com/5Ix9Z.jpg)               I1 = 15;     I2 = 8;     f1[x_] := I1;     f2[x_] := I2;     hddd = 20;     h00d = 60;     h00s = 150;     hsss = 180;         pl1 = Plot[{f1[x]}, {x, 0, 200}, AxesOrigin -> {0, 0},             PlotRange -> {-1, 20}, Epilog -> {              Inset[               Grid[{{Text[Style["J", "Garamond", 16]],                   Text[Style["First Function", "Garamond", 16]]}, {Text[                   Style["V", "Garamond", 16]],                   Text[Style["Second Function", "Garamond", 16]]}}], {h00s,                 I1 + 3}],              Inset[               Grid[{{Item["",                    Background -> RGBColor[0.35082, 0.595178, .853742],                    Frame -> True, FrameStyle -> AbsoluteThickness[1]],                   Style["Continuation Region", "Garamond", 16]}, {Item["",                    Background -> RGBColor[1, 1, .4], Frame -> True,                    FrameStyle -> AbsoluteThickness[1]],                   Style["Exit Region", "Garamond", 16]}}]], Dashed,               Arrowheads[Small], Arrow[{{h00s, I1}, {h00s, 0}}],               Arrowheads[Small], Arrow[{{h00d, I1}, {h00d, 0}}],               Arrowheads[Small], Arrow[{{hddd, I1}, {hddd, 0}}],               Arrowheads[Small], Arrow[{{hsss, I2}, {hsss, 0}}],               Inset[Style["Down Boundaries", "Garamond",                 16], {(hddd + h00d)/2, (I1 + I2)/2}],              Inset[               Style["Top Boundaries", "Garamond",                 16], {(hsss + h00s)/2, (I1 + I2)/2}],              }, Ticks -> {{{hddd, Text[Style["HDD", "Garamond", 20]]}, {h00d,                 Text[Style["H0D", "Garamond", 20]]}, {h00s,                 Text[Style["H0S", "Garamond", 20]]}, {hsss,                 Text[Style["HSS", "Garamond", 20]]}}, {{I1,                 Text[Style["High", "Garamond", 20]]}, {I2,                 Text[Style["Low", "Garamond", 20]]}}},             AxesLabel -> {Text[Style["Variable X", "Garamond", 20]],               Text[Style["Variable Y", "Garamond", 20]]}];         pl2 = Plot[{f2[x]}, {x, 0, 200}, AxesOrigin -> {0, 0},             PlotRange -> {-1, 20}];         ptd = ListPlot[{{h00d, I2}, {hddd, I1}},             PlotStyle -> {Directive[Red, PointSize[Large]]},             AxesOrigin -> {0, 0}, PlotRange -> {-1, 20}];         pts = ListPlot[{{h00s, I1}, {hsss, I2}},             PlotStyle -> {Directive[Green, PointSize[Large]]},             AxesOrigin -> {0, 0}, PlotRange -> {-1, 20}];         r1 = RegionPlot[            f1[x] > 0, {x, 0, hddd - 1}, {y, I1 - 0.15, I1 + 0.15},             PlotStyle -> RGBColor[1, 1, .4], Mesh -> 2];         r2 = RegionPlot[            f1[x] > 0, {x, h00s + 1, 200}, {y, I1 - 0.15, I1 + 0.15},             PlotStyle -> RGBColor[1, 1, .4], Mesh -> 2];         r3 = RegionPlot[            f1[x] > 0, {x, 0, h00d - 1}, {y, I2 - 0.15, I2 + 0.15},             PlotStyle -> RGBColor[1, 1, .4], Mesh -> 2];         r4 = RegionPlot[            f1[x] > 0, {x, hsss + 1, 200}, {y, I2 - 0.15, I2 + 0.15},             PlotStyle -> RGBColor[1, 1, .4], Mesh -> 2];         r5 = RegionPlot[            f1[x] > 0, {x, h00d + 1, hsss - 1}, {y, I2 - 0.1, I2 + 0.1},             PlotStyle -> RGBColor[0.35082, 0.595178, .853742]];         r6 = RegionPlot[            f1[x] > 0, {x, hddd + 1, h00s - 1}, {y, I1 - 0.1, I1 + 0.1},             PlotStyle -> RGBColor[0.35082, 0.595178, .853742]];         Show[pl1, pl2, ptd, pts, r1, r2, r3, r4, r5, r6]


title: Is it possible to manipulate FindFit

text: I was wondering if it is possible to manipulate a `FindFit[]` function. As a basic example, if I had an equation $ax^2+bx+c$ and a set of data, would it be possible to manipulate the `c` value, while _Mathematica_ outputs the best fit values for `a` and `b` for that `c` value?


title: Precision of number not maintained when saved via Export

text: Assume that the output of my calculation is `a` and is a number such as: > `a = 100.1252135246354847;` `N[a]` gives me `100.125` However, when I try to save my data, `a` via export such as : > `Export["/path/to/file/with/extension/dat", N[a]]` My eventual filename.dat has `100.12521352463548` and not `100.125`. So is the precision of digits/most significant digits for display only? I also tried `NumberForm[a,6]` and I get `NumberForm[100.1252135246354847`18.000543455259304, 6]` in my data file! What am I doing wrong? ## Edit (possible solution): Replacing `N[a]` with `SetPrecision[a,5]` helped. I wasn't sure if I should have this in the ANSWER section because the solution may be quite trivial and may not warrant being in the answer section. Any thoughts on that (whether or not I should answer this question or let the solution remain as an appended "edit")


title: StringJoin/FileNameJoin doesn't quite work in script

text: My mathematica script is as follows:               #!/usr/local/bin/MathematicaScript -script          $HistoryLength=0;         $pwf=FileNameJoin[{NotebookDirectory[],FileBaseName[NotebookFileName[]]}];     $parameterfile=StringJoin[$pwf,".dat"];      Export["testcase.dat", {0.333, 100,0, 0, 35.1, 7.02, 0, 2, 1, 5, 10000}];     Export[$parameterfile, {0.333, 100, 0, 0, 35.1, 7.02, 0, 2, 1, 5, 10000}];      * * * ## It is also uploaded **here** All it does is creates a file name from the `NotebookDirectory` and `NotebookFileName` and saves a bunch of data `{0.333, 100,0, 0, 35.1, 7.02, 0, 2, 1, 5, 10000}` to file with generated filename. It runs fine with the front end. However, it doesn't run from a unix terminal which defeats the purpose of having this script. The error that I get is:               > FrontEndObject::notavail: A front end is not available; certain     > operations require a front end.     >      > FrontEndObject::notavail: A front end is not available; certain     > operations require a front end.     >      > StringJoin::string: String expected at position 1 in     > FileNameJoin[{NotebookDirectory[$Failed],         > FileBaseName[NotebookFileName[$Failed]]}]<>.dat.     >      > Export::chtype: First argument     > FileNameJoin[{NotebookDirectory[$Failed],         > FileBaseName[NotebookFileName[$Failed]]}]<>.dat is not a valid file     > specification.      Am I to understand that I will HAVE to use the front end for when I have `StringJoin` operations? The reason I find `StringJoin` useful is that I have 150 different cases varying in parameters and easily identified by file name. If I can have a script to run all these mathematica cases, it would save a lot of trouble. Any help would be appreciated.


title: How do I interpret the following syntax?

text: I have been given some code with the following line               PeriodicExtension[g_, x_] := If[Abs[x] < Pi, g[x], PeriodicExtension[g, x - 2 Sign[x] Pi]]      I do not understand the syntax. I would appreciate if someone can explain what this code does for different values of `x`.


title: Find sublists of a list match conditions (2)

text: Needs["TetGenLink`"];         Needs["ComputationalGeometry`"];              long = 100;         broad = 100;         height = 100;              pts = {{0, 0, 0}, {long, 0, 0}, {long, broad, 0}, {0, broad, 0},            {0, 0, height}, {long, 0, height}, {long, broad, height}, {0,              broad, height}};         facets = {{{1, 2, 3, 4}}, {{5, 6, 7, 8}}, {{1, 5, 6, 2}}, {{2, 6, 7,               3}}, {{3, 7, 8, 4}}, {{4, 8, 5, 1}}};              inst = TetGenCreate[];         TetGenSetPoints[inst, pts];         TetGenSetFacets[inst, facets];              inst1 = TetGenTetrahedralize[inst, "pq1.414a4"];         ElemPtsCoord = TetGenGetPoints[inst1];         ElemFacesMadeofPtsIndex = TetGenGetFaces[inst1];         ElemElemsMadeofPtsIndex = TetGenGetElements[inst1];              Graphics3D[GraphicsComplex[ElemPtsCoord, Polygon[ElemFacesMadeofPtsIndex]]]              ElemPtsCoordandIndex = ElemPtsCoord;         Do[PrependTo[ElemPtsCoordandIndex[[i]], i], {i, 1,             Length[ElemPtsCoordandIndex]}           ];              ElemElemsMadeofPtsIndexandIdex = ElemElemsMadeofPtsIndex;         Do[PrependTo[ElemElemsMadeofPtsIndexandIdex[[i]], i], {i, 1,             Length[ElemElemsMadeofPtsIndexandIdex]}           ];             RetainElementsIndex=Range[1,Length[ElemElemsMadeofPtsIndexandIdex]];             ProjectedElemsIndex[ElemPtsCoord_, ElemElemsMadeofPtsIndexandIdex_,        Acen_, Bcen_, Ccen_, R1_, RetainElementsIndex_] := Module[       {RetainElemsMadeofPtsIndexandIndex, ClassifiedElements,         ProjectedElementsIndex},            RetainElemsMadeofPtsIndexandIndex =         ElemElemsMadeofPtsIndexandIdex[[RetainElementsIndex]];            ClassifiedElements = GatherBy[         RetainElemsMadeofPtsIndexandIndex,         Volume[            RegionIntersection[             Ball[{Acen, Bcen, Ccen}, R1],             Simplex[              ElemPtsCoord[[  Delete[#1, 1]  ]]              ]             ]            ] != 0 &];            ProjectedElementsIndex = If[         Volume[           RegionIntersection[            Ball[{Acen, Bcen, Ccen}, R1],            Simplex[             ElemPtsCoord[[  Delete[ClassifiedElements[[1, 1]], 1]  ]]             ]            ]           ] != 0,              ClassifiedElements[[1]],              ClassifiedElements[[2]]         ];       ProjectedElementsIndex =         Union[Flatten[          Take[ProjectedElementsIndex, Length[ProjectedElementsIndex], 1]]];            ProjectedElementsIndex            ]               ProjectedElemsIndex[ElemPtsCoord, ElemElemsMadeofPtsIndexandIdex,       62.84752406439229, 28.984094217780612, 72.55554474676572, 12.5, RetainElementsIndex]      Questions Background: I have a cube sized 100*100*100, I have meshed it with fine meshes. So the mesh elements set is `ElemElemsMadeofPtsIndex`, The mesh points set is `ElemPtsCoord`. And because `ElemElemsMadeofPtsIndex` and `ElemPtsCoord` do not tell us elements(points)' oder. So I add the points(elements) a order number to the first of the sublists: ElemElemsMadeofPtsIndex-> ElemElemsMadeofPtsIndexandIdex ElemPtsCoord-> ElemPtsCoordandIndex. Math Problem: A sphere(ball): the center is located at (Acen, Bcen, Ccen) and radius is R1). and I want to find which elements belong(located in the ball or intersected with the ball) to the zone of the ball. so the problem become to find sublists of list `ElemElemsMadeofPtsIndexandIdex`, which the volume of region which mesh tetrahedron and the ball intersected is not null.


title: Order of Evaluate for Map

text: I would like to get a list of variable names as strings. For example,               x = 1;     y = 2;     Map[SymbolName, Unevaluated /@ Unevaluated@{x, y}]      > {"x", "y"} This works well. However, if I use               Map[SymbolName @* Unevaluated, Unevaluated@{x, y}]      It does not work and drops an error message > SymbolName::sym: Argument 1 at position 1 is expected to be a symbol. What's the difference between the two?


title: Use NDSolve to solve a PDE

text: I have the following PDE (a master equation, and $P$ is probability density, $0\le x\le1$ and $0\le y\le1$): $$ \partial_t P(x,y,t)=x\partial_xP(x,y,t)+(1-y)\partial_yP(x,y,t)+2P(x,y,t) $$ The initial conditions are $P(x,y,t=0)=\delta(x-0.05,y-0.85)$. For the boundary conditions, if the probability density is going to flow through the boundary, I won't do anything to stop it. ( **How to express the BC in Mathematica?** ) I used the following command:               NDSolve[{D[P[x, y, t], t] ==      x D[P[x, y, t], x] + (1 - y) D[P[x, y, t], y] + 2 P[x, y, t],      P[x, y, 0] == DiracDelta[x - 0.05, y - 0.85]}, P,      {t, 0, 2}, {x, 0, 1}, {y, 0, 1}]      First, Mathematica gave the following warning:               Warning: an insufficient number of boundary conditions have been specified for the direction of      independent variable y. Artificial boundary effects may be present in the solution. >>      Moreover, the result it gave obviously is wrong:               Plot3D[Evaluate[(P[x, y, t] /. %) /. {t -> 0}], {x, 0, 1}, {y, 0, 1}]      ![enter image description here](http://i.stack.imgur.com/dHIrn.png) **My question is** : 1) How can I express the boundary conditions I mentioned 2) How can I make the `NDSolve` work?


title: DSolve breaks when the ordering of independent variables aren't proper?

text: I encountered this when trying to solve this problem with `DSolve`:               DSolve[D[p[x, y, t], t] ==             x D[p[x, y, t], x] + (1 - y) D[p[x, y, t], y] + 2 p[x, y, t], p, {t, x, y}]      > DSolve::deqx: Supplied equations are not differential equations of the given > functions. >   >   >     (* Input returned *) >   It's not surprising to see `DSolve` fails in solving PDEs… but why this warning? Even more shocking:               DSolve[D[p[x, y, t], t] ==             x D[p[x, y, t], x] + (1 - y) D[p[x, y, t], y] + 2 p[x, y, t], p, {x, y, t}]      > >     {{p -> Function[{x, y, t}, C[1][x (-1 + y), t + Log[x]]/x^2]}} >   The result changed just because I reordered the independent variables (from `{t, x, y}` to `{x, y, t}`). Is this a bug? Tested in _v9.0.1, Windows Vista 32bit_ and _Wolfram Programming Cloud_.


title: Getting cdf content from nice Wolfram info graphic

text: There is a very nice cdf info graphic on the Wolfram Webpage (http://www.wolfram.com/cdf/uses-examples/infographics-full-example.html). I'd like to have a look at the code as I'd like to do something similar. However, they only provide the cdf. Is it possible to extract the code from this? – Thanks.


title: Where can I get detailed information on how the Plot command works?

text: The command               Plot[x^2, {x, -3, 3}, PlotStyle -> Arrowheads[{-.025, .025}]] /.Line -> Arrow      produces this output. ![enter image description here](http://i.stack.imgur.com/0WN0q.jpg) What I don't understand is what `Line` has to do with anything. It must be the case that the `Plot` command produces `Line` objects that can be replaced with `Arrow`. I haven't seen anything in the documentation for `Plot` that suggests this is the case. Without `/.Line->Arrow` the plot won't have arrowheads at the ends of the graph of the function.


title: Wavelets: Relative error vs compression ratio

text: I need to plot the relative error vs compression ratio diagram of a discrete wavelet transform on an image, but no luck so far .. Here's the problem in short:   1. random_image.jpg   2. compress the image   3. plot the relative error vs compression ratio diagram Here's the code and below is the link I am using as a reference:               cumulativeEnergy[data_] :=       Module[{c = Sort[Flatten[data]^2, Greater]}, Accumulate[c]/Total[c]]          data = (* insert random image*)          wtdata = DiscreteWaveletTransform[data]          wtE = cumulativeEnergy[Last /@ wtdata[Automatic]];          ListLinePlot[Sqrt[1 - wtE]]      The problem is I don't get a curve like in the example.. Tutorial used as a reference Thank you !


title: Is there an equivalent to MATLAB's linspace?

text: Does _Mathematica_ have an equivalent to Matlab's `linspace`? I want to make a list with "start", "stop" and "number of points". What is the neatest way of doing this?


title: Strange Behavior with RegionPlot

text: Consider the following code.               RegionPlot[Print[{x, y}], {x, -2, 2}, {y, -2, 2}, PlotPoints -> 2]      > >     {-1.996,-1.996} >     {Region`Private`RegionVar[1],Region`Private`RegionVar[2]} >     {-2.,-2.} >     {2.,-2.} >     {-2.,2.} >     {2.,2.} >   My question is: what is `RegionPlot` doing to create the first two lines of output? I do not understand why the first sample point is `{-1.996, -1.996}` and why the second sample point is `{Region`Private`RegionVar[1],Region`Private`RegionVar[2]}`. I am running this in _Mathematica_ 9. I do not recall this happening in an earlier version. **Edit:** I changed the code above to give a better minimal working example. I leave below the code I first gave along with its truncated output.               myFunc[pt_] := Module[ {bool},       bool = Sin[ pt[[1]] ] > 0;       Print[pt, bool];       If[ bool, Return[True], Return[False] ];     ];          RegionPlot[myFunc[ {x, y} ], {x, -2, 2}, {y, -2, 2}, PlotPoints -> 2]      > >     {-1.996,-1.996}False >   > > {Region`Private`RegionVar[1],Region`Private`RegionVar[2]}Sin[Region`Private`RegionVar[1]]>0 >   >     {-2.,-2.}False >   >     {2.,-2.}True >


title: String to File removing quotation marks

text: If I print a string to a file it also adds quotation marks to the string. Here is an example:               a = "test \t test"     a >> file     FilePrint["file"]      How can I remove those? And is it possible to use `\t` for a tabulator?


title: Dynamic Graph visualization

text: I'm working on a C++ library that will be used to construct and study certain graphs (as in a set of connected vertices, not a function plot). These graphs will be dynamic in nature (and can potentially be very large) and I'm looking for ways to visualize them. I looked at a few solutions such as Gephi which can visualize dynamic graphs, but then decided that this should be something that _Mathematica_ would do well. My C++ library keeps track of a 'lifetime' for each vertex and edge and I can output the graph data any way I need to. Although I've visualized a lot of graphs in Mathematica with `GraphPlot` and `GraphPlot3D` I'm not sure what's the best way to visualize a dynamic graph? I've used `Dynamic` and `Manipulate` extensively and I've been able to use Manipulate to draw a series of successive 'snapshots' of a graph at each time step. The problem with this approach is that you're redrawing the entire graph each time even though only one vertex or edge has changed. Also when you redraw the entire graph there's no guarantee that the vertices will be put in similar places, so adding one edge causes the picture to totally change. This kills the ability to animate the changing graph. What seems to be needed is the ability to change the graph slightly and then locally recompute the graph drawing forces without redrawing the graph from scratch. Is this possible? Something like a hypothetical `GraphPlotDynamic[]`. **Edit** Here is a contrived example showing the problem. The format for each edge is.               {source, target, begin, end}      This creates the graph connectivity.               dynamicGraph =         {{0, 1, 0, 20}, {1, 2, 1, Infinity}, {2, 3, 2, 21}, {3, 4, 3, 22},          {4, 5, 4, Infinity}, {5, 6, 5, Infinity}, {6, 7, 6, 26}, {7, 8, 7, 25},              {8, 9, 8, Infinity}, {9, 10, 9, 24}, {0, 6, 10, 27}, {1, 6, 11, Infinity},          {1, 5, 12, Infinity}, {2, 5, 13, Infinity}, {2, 4, 14, Infinity},          {6, 8, 15, Infinity}, {5, 8, 16, Infinity}, {5, 9, 17, Infinity},          {4, 9, 18, Infinity}, {4, 10, 19, 23}};      Now the graph is rendered with `GraphPlot`. The edges are selected based on whether `t` is within the edge's lifetime.               Manipulate[        GraphPlot[#1 -> #2 & @@@ Select[dynamicGraph, #[[3]] <= t <= #[[4]] &],           VertexRenderingFunction -> (Text[#2, #1] &)], {t, 0, 31, 1}]      This graph has a relatively natural progression of adding nodes in a line then connecting the line by folding it back on itself twice. Then all the outside edges are deleted and you are left with hexagon with all vertices connected to one vertex at the center. But when clicking through the `Manipulate` the graph jumps around at each step so it's hard to keep track of what is being added and taken away. **Edit** Here is an example video of what I'm talking about. This is from Ubigraph and does more than what I'm asking for since it does fancy camera angles and rotations as the graph is being constructed. But what's important is that as the vertices and edges are being added the force directed algorithm is continuously running so the graph is constantly updated. http://ubietylab.net/ubigraph/content/Demos/Animation.html


title: Transformation rule on a list of non-negative integers

text: I am trying to create a transformation rule that takes a list of non-negative integer values of any length, finds a non-zero entry in the list, adds 1 to all preceding numbers, subtracts 1 from the chosen non-zero entry, and keeps the subsequent values untouched. As an example, `{0,1,0,2,3,0}` could be transformed into `{1,0,0,2,3,0}`, `{1,2,1,1,3,0}` or `{1,2,1,3,2,0}`. I'm looking for a transformation rule, let's call it say `desiredrule`, such that `ReplaceList[{0, 1, 0, 2, 3, 0}, desiredrule]` yields those three lists above. My (failed) attempt at this was along these lines:               ReplaceList[{0, 1, 0, 2, 3, 0}, {x___, y_ /; y > 0, z___} -> {x + 1, y - 1, z}]      which results in:               {{1, 0, 0, 2, 3, 0}, {2, 1, 3, 0}, {4, 2, 0}}      The key issue is obviously the `x + 1` but I'm not sure how to correct this. I know of other ways to achieve this same result without using `ReplaceList`; I know I could, for example, do the following:               transform[list_] :=       Module[{nonzeropositions, numberoftransformations},        nonzeropositions = Flatten@Position[list, x_ /; x > 0];        numberoftransformations = Length[nonzeropositions];        Table[list[[i]] + If[i < nonzeropositions[[j]], 1, 0] +          If[i == nonzeropositions[[j]], -1, 0], {j,          numberoftransformations}, {i, Length[list]}]]      But I'm specifically interested to learn how I could achieve this result via the transformation rule approach I outlined initially.


title: FindSelectedFunction for packages - how to make it work?

text: The _Mathematica_ help menu contains an entry _Find Selected Function_ (`Cmd`+`Shift`+`F` on OSX). If you are working with say `Transpose` and want to look up its _reference page_ , you just select `Transpose` with the mouse, hit `Cmd`+`Shift`+`F` and _Mathematica_ opens the _reference page_ for `Transpose`. Works beautifully. **Question:** How to get this to work for your own packages? So, suppose your package is correctly built, and it has its own functions:               MySuperFunc     FunkyMonkey     FunkMeister2      and the documentation pages are correctly created, correctly defined and correctly installed for each of those functions. You select `MySuperFunc` with the mouse, select _Find Selected Function_ , expecting _Mathematica_ to open the _reference page_ for that function but it doesn't work. Instead, _Mathematica_ opens up something akin to a Google search on "MySuperFunc", providing a list to anything it can find on that name. But that's not what I want. And it's also not what that menu function is supposed to be doing: Find SELECTED Function! Not a google-type search. Just open the _reference page_ for the selected Function. Anyone have some tips on how to make this work as advertised? * * * Addendum: If one enters:                ?MySuperFunc      ... you get the usual Help blurb on the function, such as:               MySuperFunc[b] returns blah given b. >>      ... and if you then click on those two little `>>` arrows, _Mathematica_ opens the Help _Reference_ page for `MySuperFunc` PERFECTLY, which is exactly what FindSelectedFunction _should_ be doing, but is not doing. And if it works perfectly for the `>>` info blurb, why can't it work just as perfectly for FindSelectedFunction?


title: How can I name "a[[i]]" the parts of Table "a"? Or how to make Table "a" grow inside FindMinimum?

text: Let's say I want to minimize a function that uses a `Table` named `a` with the Conjugate Gradient Method of `FindMinimum`. _Instinctively_ I do the following :               FindMinimum[(Sum[a[[i]]*Cos[1.3], {i, 1, 2}])^2, {a, {0, 0}}, Method -> "ConjugateGradient"]      But I obviously get the following messages and results : > During evaluation of In[135]:= Part::partd: Part specification a[[1]] is > longer than depth of object. >>   >  During evaluation of In[135]:= Part::partd: Part specification a[[2]] is > longer than depth of object. >> > > {0., {a -> {0., 0.}}} So, to overcome this _little_ difficulty, I tried the following :               a = {a1, a2};     FindMinimum[(Sum[a[[i]]*Cos[1.3], {i, 1, 2}])^2, {a, {0, 0}}, Method -> "ConjugateGradient"]      > During evaluation of In[136]:= Part::partd: Part specification a[[1]] is > longer than depth of object. >>   >  During evaluation of In[136]:= Part::partd: Part specification a[[2]] is > longer than depth of object. >> > > {0., {{a1, a2} -> {0., 0.}}} and again I obtain the same error messages. So I came down to the _dirty_ manner:               FindMinimum[(a1*Cos[1.3] + a2*Cos[1.3])^2, {{a1, 2}, {a2, 0}},        Method -> "ConjugateGradient"]      which this time provided me with actual results :               {2.86222*10^-17, {a1 -> 1., a2 -> -1.}}      Now, while this last alternative works for this simple example and for a Table containing only two values, It will become impossible if I had to do for example:               FindMinimum[(Sum[a[[i]]*Cos[1.3], {i, 1, 1000}])^2, {a, {0, 0}},        Method -> "ConjugateGradient"]      How can I sort this out? I'm aware that there might something wrong with my approach, but I can't find another manner to set this up.


title: Animate a position change along the curve for every iteration

text: I've only had few previous experiences on Mathematica before. So basically an entry-level question that harasses a rookie like me. I made the following attempt using bisection method to calculate the real root for the function $f(x)=-x^3+2x^2-2$ with basic while loop and if: ` a = -5; b = 5; m = (a + b)/2; While [ Abs[f[m]] > 0.000001, If[f[m]*f[a] < 0, b = m, a = m]; m = (a + b)/2]` The answer turns out to be $-(14080895/16777216)$ that is correct. Then, I wanted to create a animation that shows the change of position of a dot along the function curve for each iteration of the bisection method. But I tried several times with different codes that all fails to do so. One confusion is I am not sure how to set up a stepsize here which involves not a constant number but "While" and "If". Would you please help me animate the iteration with while and if?


title: Creating a version of SequenceAlignment that accepts patterns

text: `SequenceAlignment` seems like a function that is not (yet?) fully integrated into Mathematica. I want a function that accepts general patterns instead. I naively fed a `StringPattern` instead of a literal string to `SequenceAlignment` and met silence, though `MatchQ` is positive:               {StringMatchQ["A", Alternatives["A", "B"]], SequenceAlignment["A", Alternatives["A", "B"]]}     (* Out= {True, SequenceAlignment["A", "A" | "B"]} *)      One approach would be to write out all alternatives and repeatedly feed them to `SequenceAlignment`. The question is strongly related to this one: How to generally match, unify and merge patterns?. **Background:** I want to answer questions like _"What DNA sequences give rise to a given protein sequence and where can you find them?"._ Then one naturally stumbles across `Alternatives`. For example, a transmembrane protein that is supposed to selectively filter K ions contains an amino acid sequence "TVGYG". I want to find all its DNA parents, ie DNA code of all proteins that may contain such a filter. Due to the redundancy of the genetic code, that subsequence can be coded by a diversity of DNA sequences, giving rise to a `StringExpression` with alternatives:               In[80]:= StringReplace["TVGYG", backlist]         Out[80]= "ACA" | "ACC" | "ACG" | "ACT" ~~ "GTA" | "GTC" | "GTG" | "GTT" ~~       "GGA" | "GGC" | "GGG" | "GGT" ~~ "TAC" | "TAT" ~~       "GGA" | "GGC" | "GGG" | "GGT"      The first residue, `"T"` for Threonine, may thus be coded by either `"ACA"` or `"ACC"` or `"ACG"` or `"ACT"`, etc.


title: ListPlot style and axes

text: I have this list saved in matrix 6x2: \begin{array}{cc} 0 & 1.216 \\ \frac{\pi }{3} & 0 \\ \frac{2 \pi }{3} & 0.1351 \\ \pi & 0 \\ \frac{4 \pi }{3} & 0.04863 \\ \frac{5 \pi }{3} & 0 \\ \end{array} Now i have saved this matrix in a variable called myList: { { 0 , 1.215 } , { π/3 , 0 } , { (2π)/3, 0.1351 } , { π , 0 } , { (4π)/3 , 0.04863 } , { (5π)/3 , 0 } }    if i use the comand:               ListPlot[myList, AxesLabel -> {\[Omega], Subscript[C, n]},       Filling -> Axis]<br>      the result is this:   ![enter image description here](http://i.stack.imgur.com/No8nt.png) The problem 1 is:   i would like to see the blue points and the line under them with RED color.      The problem 2 is:   I don't see the first coordinate on the plot `{0,1.1215}`   there is a way to set the range of y for example (from 0 to 2) and of x for example (from0 to 5) ??? in this way i can see all points.      The problem 3 is:   i would like to see the $\omega$ axe with the Trigonometric value instead of the natural number.   thanks


title: Using a List in PlotLabel which goes beyond width of ImageSize

text: My `PlotLabel` goes beyond the width of the `ImageSize`. The label is generated into a `List` form by my program. I hope to allow my `PlotLabel` to go to a second, third, fourth (...) line if it reaches beyond the boundaries. My problem in simplified, working code:               testList = {1.1`, 1.2100000000000002`, 1.4641000000000004`,         2.143588810000001`, 4.594972986357221`, 21.1137767453526`,         445.7915684525922`, 198730.12250342217`, 3.949366159022518`*^10,         1.5597493058032278`*^21, 2.432817896953651`*^42,         5.918602919737985`*^84, 3.5029860521531003`*^169,         1.22709112815791634686748164742131068419446205954341`15.\     653559774527023*^339,         1.50575263680386788043945221511499961813146`15.352529778863042*^\     678, 2.2672910032418008565810795918131168775255956636`15.\     051499783199061*^1356,         5.1406084933812118223464178513329285`14.75046978753508*^2712,         2.64258556822230525123173280428744040060801405497404`14.\     449439791871098*^5425,         6.98325848537680392124060228920952089211156`14.148409796207117*^\     10850, 4.8765899073587133585511396520327915438254972718`13.\     847379800543136*^21701};     Plot[x^2, {x, -3, 3},       PlotLabel -> StringForm["The orbit of x=1.1 is\n``\n", testList ],       ImageSize -> {600, 600}]      ![enter image description here](http://i.stack.imgur.com/uXs1k.png)


title: Understanding output of multivariable integration

text: I'm new to Mathematica and I'm trying to integrate this function:               K = Function[{x,theta},       ((b - x^3 (d/(Cos[theta])^2 - b/x)^3) (e - 2 b/x)^3/(((b - x^3 (e - 2 b/x)^3)       (d/(Cos[theta])^2 - b/x)^3))) Sin[theta]]       from $\theta = 0$ to $\theta = \pi$ and from $x = c$ to $x = \frac{f \cos^2(\theta)}{a + \cos^2(\theta)}$ by executing this command:               Integrate[K, {theta, 0, Pi}, {x, c, f((Cos[theta])^2)/(a + (Cos[theta])^2)}].      However, when I do this, the output is $\pi \left(-\left(\left(\sqrt{\frac{a}{a+1}}-1\right) f+c\right)\right) Function\left(\{x,\text{theta}\},\frac{\sin (\text{theta}) \left(\left(e-\frac{2 b}{x}\right)^3 \left(b-x^3 \left(\frac{d}{\cos ^2(\text{theta})}-\frac{b}{x}\right)^3\right)\right)}{\left(b-x^3 \left(e-\frac{2 b}{x}\right)^3\right) \left(\frac{d}{\cos ^2(\text{theta})}-\frac{b}{x}\right)^3}\right)$ What is the meaning of the `Function` part of this result? The result seems like it's a product of the constants and the function itself, but this doesn't make sense because I clearly specified integration limits.


title: Is there a way to stop evaluation immediately?

text: Sometimes I'll have a loop that I accidentally made too big. I'll evaluate, and MM will try to run through the entire loop. The program itself doesn't actually seem frozen... I can go to Evaluation-> Abort/Interrupt evaluation, but they don't do anything. I can even save while it's doing this! What seems to kind of work is saving, closing the file, and then going to Evaluation->Quit kernel. But that's a little ridiculous. Is there really no 'hard kill'? Thank you!


title: Optimization problem test suites

text: _Mathematica_ provides nonlinear, unconstrained test problems here:               Needs["Optimization`UnconstrainedProblems`"]      and LP test problems here:               ExampleData["LinearProgramming"]      Does anyone know a good source of constrained nonlinear problems in _Mathematica_ format? Also nice to have, but not essential, would be mixed integer linear and nonlinear test problems.


title: Parametric plot of multiple graphs on the same axes

text: I'm trying to plot on a single axes system multiple graphs but ran into a problem when tryinf to label my graphs. Here's what I've used so far Mathematica code:               r1 = 0.5;     r2 = 1;     r3 = 2;     r4 = 2.5;     z[r_, t_] = {r ^2 Cos[2 t] - 2 r Sin[t], 2 r Cos[t] + r^2 Sin[2 t]};     zz[t_] = Table[z[r, t], {r, 0.1, 4, 0.5}];     ParametricPlot[{z[r1, t], z[r2, t], z[r3, t], z[r4, t]}, {t, 0,        2 \[Pi]}, PlotRange -> Full, PlotStyle -> {Thick},       AxesLabel -> {"Re(z)", "Im(z)"},       LabelStyle -> Directive[Bold, Large]]      Now, I can't seem to get the legends show, I simply want a number next to each color, say, 0.5 - (green) etc.. Ideally I would like a more elegant solution than having to manually set r1,r2,... Thanks!


title: Arrow pointing upwards in a Graphics3D

text: I am trying to write a code for an arrow that points upwards from the center of the circle in a `Graphics3D`.               Manipulate[     Plot3D[RandomReal[{-0.5, 0.5}]*     UnitStep[(x - a)^2 + (y - b)^2 - 1.5^2], {x, -3, 3}, {y, -3, 3},      PlotRange -> All], {a, -1, 1}, {b, -1, 1}]      ![](http://i.stack.imgur.com/1kQfU.png) I want an arrow to point perpendicular from the center of this circle, how can I do that ?


title: Finding integral points on a surface

text: Suppose I have a dimension formula (for a Lie algebra representation) that is as follows: $$ d(a,b) = {(a+1)(b+1)(a+b+2) \over 2} $$ Now consider the surface $F(a,b,n) = 0 = d(a,b) -n$ where $n \in \Bbb N$. Is there a Mathematica function that would allow me to find triples $(a,b,n) \in \Bbb N^3$ on this surface?


title: Mapping the imaginary axis of the complex (s) plane

text: In this problem is very difficult to analyze the roots s. Firstly I thought that the problem is in precision, but I am not sure. The criterion which I want to obtain is that one of these roots has a positive real part. Characteristic equation has the following form: $$\frac{2 \pi }{\int_{-\infty }^{\infty } \frac{1}{\text{D1}(k,s)} \, dk}+\text{a6} s^2+\text{k0}=0$$ The imaginary axis of the complex s-plane can be parametrized by conidering s=i*r (i=sqrt(-1)). So the equation has new form for consideration                 k0 = a6 r^2 - (1/(2 Pi)       NIntegrate[1/(       a1 a3 k^4 - a2 a4 (-k a5 + r)^2), {k, -\[Infinity], \[Infinity]}])^-1      where               a1 = 2*10^11;     a2 = 7.687*10^-3;     a3 = 3.055*10^-5;     a4 = 7849;     a5 = 500;     a6 = 70;     \[Alpha] = Sqrt[(a1 a3)/(a4 a2)];     c = Sqrt[k0/a6];          a5 > < Sqrt[4 \[Alpha] c];      The mapping rule follows from the characteristic equation, which should be rewritten to express the chosen parameter explicitly. Once the mapping is accomplished, a mapped line is obtained, which divides the parameter plane into domains with different number of roots s* possessing a positive real part. Every line is normally shaded from the side, which is related to the right-hand side of the imaginary axis of the (s)-plane now. Obviously, crossing a decomposition curve in the direction of the shading, one extra root with a positive real part is gained. This curve (rule) should be obtained for parameter r from -Infinity to +Infinity for discuss. So I need two separately diagrams for a5 > Sqrt[4 [Alpha] c] or a5 < Sqrt[4 [Alpha] c]. I am completely not sure how to obtain curves from the equation                 k0 = a6 r^2 - (1/(2 Pi)       NIntegrate[1/(       a1 a3 k^4 - a2 a4 (-k a5 + r)^2), {k, -\[Infinity], \[Infinity]}])^-1      presented here ![enter image description here](http://i.stack.imgur.com/urHhH.jpg) where N is number of roots in the region


title: How to match a cyclically repeating sequence?

text: I have run across several times recently where I must match a sequence that is cyclically repeating. For example, with the sequence,               Sequence[a, b, c]      how would I write a pattern that matched against               a     a, b     a, b, c     a, b, c, a      etc., but not any of the surrounding elements? For a two element sequence comprising the entire list, this is straightforward, if a bit verbose:               MatchQ[#, {a | PatternSequence[a, b] .., a | PatternSequence[]}] & /@       {{a}, {a, b}, {a, b, a}, {a, b, a, b, a, b, a}}     (* {True, True, True, True} *)      But, this does not work when the sequence is part of a bigger list, e.g.               Cases[      {q, r, a, b, a, b, a, s, e, f, a},       x : PatternSequence[a|(PatternSequence[a, b] ..), a | PatternSequence[]] :> {x},       Infinity     ]     (* {{a}, {a}, {a}, {a}} *)      Even reversing the initial element to `(PatternSequence[a, b] ..)|a` returns the same thing. So, my questions are:   1. How can I write the pattern so it extracts parts of larger lists that may contain other elements?   2. How can I generalize the pattern to match against larger cyclically repeating sequences?


title: Mapping multiple functions

text: This question was part of a course on Mathematica written in 1998. > Each of the functions f1, f2, and f3 defined below has a root near x=2. Map > an anonymous function involving FindRoot[] onto the list {f1,f2,f3} to find > all three roots.                f1[x_]= 2x-17Cos[x]         f2[x_]= x^2-3Sin[x]         f3[x_]= 2Sin[x]^2-x         Plot[{f1[x],f2[x],f3[x]},{x,0,5}]      Which produced the output: > Out[242]= 2 x - 17 Cos[x] > > Out[243]= x^2 - 3 Sin[x] > > Out[244]= -x + 2 Sin[x]^2 ![enter image description here](http://i.stack.imgur.com/9GhD2.png) And then proceeds to draw a nice graph, showing that all of these functions have a root between @1.5 and 1.8. I then individually evaluated the roots (near two) for each function so that I would know if the answers to the "mapped" functions were correct. FindRoot[f1, {2}] > Out[287]= {1.40477}               FindRoot[f2, {2}]      > Out[284]= {1.72213}                FindRoot[f3, {2}]      > Out[285]= {1.84908} Here are some of my attempts to answer the question using `Map` and `FindRoot` along with the error messages and output that each produced. (* Note that I attempted about half a dozen other solutions, but did not want to make this post too long*)                Map[FindRoot, {f1, f2, f3}, {1}]      > During evaluation of In[296]:= FindRoot::argmu: FindRoot called with 1 > argument; 2 or more arguments are expected. >> > > During evaluation of In[296]:= FindRoot::argmu: FindRoot called with 1 > argument; 2 or more arguments are expected. >> > > During evaluation of In[296]:= FindRoot::argmu: FindRoot called with 1 > argument; 2 or more arguments are expected. >> > > During evaluation of In[296]:= General::stop: Further output of > FindRoot::argmu will be suppressed during this calculation. >> > > Out[296]= {FindRoot[f1], FindRoot[f2], FindRoot[f3]}                    Map[FindRoot, {[f1, {2}], [f2, {2}], [f3, {2}]}]      > During evaluation of In[303]:= Syntax::sntxf: "{" cannot be followed by > "[f1,{2}],[f2,{2}],[f3,{2}]}". > > During evaluation of In[303]:= Syntax::tsntxi: "[f1,{2}]" is incomplete; > more input is needed. > > During evaluation of In[303]:= Syntax::sntxi: Incomplete expression; more > input is needed .                    Map[FindRoot, {{f1, {2}}, {f2, {2}}, {f3, {2}}}]      > During evaluation of In[303]:= FindRoot::argmu: FindRoot called with 1 > argument; 2 or more arguments are expected. >> > > During evaluation of In[303]:= FindRoot::argmu: FindRoot called with 1 > argument; 2 or more arguments are expected. >> > > During evaluation of In[303]:= FindRoot::argmu: FindRoot called with 1 > argument; 2 or more arguments are expected. >> > > During evaluation of In[303]:= General::stop: Further output of > FindRoot::argmu will be suppressed during this calculation. >> > > Out[303]= {FindRoot[{f1, {2}}], FindRoot[{f2, {2}}], FindRoot[{f3, {2}}]} I have read the documentation on `Map`, `FindRoot`, `Listable`, `Fold` and `Function`. None of these gave me an idea of how to answer this question. In addition I ran a search of this site(and also looked at each of the threads that were linked when I filled in the subject), the "comp.soft- sys.math.mathematica" site, as well as a general Internet search for "Mapping multiple functions in Mathematica", and didn't find anything that gave me an idea of how to answer the question. I would appreciate someone pointing me in the right direction.


title: Differential operator squared

text: I defined a one-dimensional momentum operator $\hat{p}=-i\hbar\frac{\partial}{\partial{x}}$ in Mathematica               p = -I * h * D[#, x]&      and I want to get the kinetic energy operator $\hat{T}=\hat{p}^2/2m=-\frac{\hbar^2}{2m}\frac{\partial^2}{\partial x^2}$ from it, so               T = p^2/(2m)      but it gives the wrong result What can I do about it? Do I have to derive the operators by hand?


title: Wrapping a function in count

text: I am working through the _Programming Paradigms via Mathematica (A First Course)_ and am attempting to answer the following: > Use recursion to count how many times the argument can have its square root > taken before the result is less than 2: "manySqrt[x_Real]" should report how > many times the "Sqrt[]" function has to be applied to "x" before the result > is less than 2. For instance, Sqrt[81.0] is 9.0, Sqrt[9.0] is 3.0 and > Sqrt[3.0] is less than 2 so, "manySqrt[81.0]" is 3. Of course, don't use a > logarithm. Additionally: > First, use of a repetition function ("Map[]", "MapThread[]", "Nest[]", > "NestList[]", "Fold[]", "FoldList[]", "Table[]", "Apply[]", and so on, being > our "adverbs") will generally disqualify a method as purely recursive, for > the repetition is accomplished externally from the nested function calls. > Also, repetition accomplished with a loop structure, such as a "While[]", a > "Do[]", or some other repetition command, is explicitly forbidden. My strategy is to make a list of 'Real' values and then count the 'Real' values in the list. I can get the following to work:               Clear[manySqrt]     manySqrt[x_Real] := If[x >= 2, Flatten[Append[{x}, manySqrt[Sqrt[x]]]]]           manySqrt[81.]          (* {81., 9., 3., Null} *)           Count[%, _Real]          (* 3 *)      However I get an erroneous answer when I try to wrap `Count` as follows:               Clear[manySqrt]     manySqrt[x_Real] :=       If[x >= 2, Count[Flatten[Append[{x}, manySqrt[Sqrt[x]]]], _Real]]           manySqrt[81.]           (* 1 *)      I would appreciate a point in the right direction.


title: Every second evaluation in notebook front end is slow

text: I'm having a rather baffling problem that Wolfram was unable to help me diagnose, and I'm hoping one of you geniuses in residence here can figure it out. (I don't get access to the Technical Support folks at Wolfram because of the fact that mine is a home license.) If I open a new notebook and run `Factorial[10]//AbsoluteTiming` I will get the expected results for my machine: `{0.000024, 3 628 800}`. However, if I execute it again, the notebook reports "Running" for 3-5 minutes before giving nearly the same output. During that period, the Mathkernel process is cranking with 100% CPU usage, however the actual time reported in the output to perform the evaluation is tiny. There is a pattern. After either canceling the hanging evaluation or letting it run through to its tardy completion, the next evaluation runs normally (i.e. quickly). However, the next evaluation AFTER that hangs again. And the pattern continues indefinitely as far as I have tested it: every other evaluation hangs for 3-5 minutes. My setup: 2012 Macbook Pro Retina running OS X 10.8.3, with Mathematica version 9.0.1.0. I have 8 GB RAM, and plenty of space on my 250GB SSD. 2.3 GHz Intel Core i7. What I have tried: Sleep --> Wake, Restart, Shut Down and Reboot, uninstalling and reinstalling Mathematica, including deactivating and reactivating it. What might be causing this mysterious problem? All other software on the machine is performing normally and I ran the Apple Hardware Diagnostics, which turned up nothing. _UPDATE_ More clues: -Invoking Mathkernel from the terminal to execute an m file works fine. (I haven't tested keeping a Mathkernel alive from the terminal and sending commands one at a time, like you might in the front end.) -If I leave Mathematica and do something else for a few minutes and come back, the first evaluation always works fine and the second hangs. -If I press command+'.' (abort evaluation) before evaluating, it always works. What the....? -If I run Factorial[10]//Timing a few times successfully, the typical response is actually `{6.x10-6, 3 628 800}`


title: Elliptic curve cryptography in Mathematica

text: I can find no resources for doing elliptic curve cryptography. I have used the finite field package, but I find it cumbersome and it does not seem to have any builtin methods for ECC. How can I get started doing ECC in _Mathematica_?


title: Correct use of Mathlink's MLGetRealList

text: I am attempting to use Mathlink from C. I have managed to return single values from mathlink to my c program, but I am having trouble with lists. Consider the Mathematica operation:               NSolve[{x^2 + 4 x + y == 0, y == x + 2}, {x, y}]      This gives us:               {{x -> -0.438447, y -> 1.56155}, {x -> -4.56155, y -> -2.56155}}      Say I wanted to return to my C program a list containing only the second solution i.e. I want {-4.56155,-2.56155}}. I could do this                List[NSolve[{x^2 + 4 x + y == 0, y == x + 2}, {x, y}][[2]][[1]][[2]],       NSolve[{x^2 + 4 x + y == 0, y == x + 2}, {x, y}][[2]][[2]][[2]]]      In mathematica, this gives me:               {-4.56155, -2.56155}      All very well, but I worried mathematica is doing Nsolve twice. When I try to replicate this through C like this:               MLPutFunction(link, "EvaluatePacket", 1);         MLPutFunction(link, "ToExpression", 1);         MLPutString(link, (const char *)"List[NSolve[{x^2 + 4 x + y == 0, y == x + 2}, {x, y}][[2]][[2]][[2]], NSolve[{x^2 + 4 x + y == 0, y == x + 2}, {x, y}][[2]][[1]][[2]]]");         MLEndPacket(link);              while (MLNextPacket(link) != RETURNPKT)         {              MLNewPacket(link);         }              double *list;         long length;              MLGetRealList(link, &list, &length);              std::cout<<list[0]<<std::cout;              MLDisownRealList(link, list, length);      EDIT: The program sort of completes, but I thin kit is crashing at the end. Now when I print out list[0] and list[1] I get the right answer followed by a hex value. E.g.:               -4.561550x7fff7986fb68      1) How can I return a list of numbers in an elegant fashion through Mathlink? 2) Why is it crashing? Thanks


title: Redefining built in input aliases

text: Which file would you need to modify to change the built in definition of the alias [escape] dt [escape] to include parentheses after the partial derivative operator?


title: Point style in ListPointPlot3D

text: In `ListPointPlot3D`, it seems the only point style available is the default, because there is no `PlotMarkers` option for this function. Is there a way to change the point style? For example, what if I want to draw the points as small cubes?


title: Quoting definition explicitly

text: I'm trying to quote a definition using `DownValues`, `OwnValues`, etc. Everything seems to be fine, except for temporary symbols' annoying appearance in recursive definitions: compare               In[1]:= With[{g = f}, {HoldPattern@g@x_ :> 2 + x}]     Out[1]= {HoldPattern[f[x_]] :> 2 + x}      and               In[2]:= With[{g = f}, {HoldPattern@g@x_ :> 2 + g@x}]     Out[2]= {HoldPattern[f[x$_]] :> 2 + f[x$]}      Here is my version of quoting a definition:               In[3]:= SetAttributes[InheritDefinition, HoldAll];          InheritDefinition[f_Symbol, g_Symbol, rules_:{}] :=     { ClearAll@f     (*, InheritOptions[f, g]*)     , (#@f = With[{g = f}, Evaluate[#@g /. rules]])& /@       {DownValues, OwnValues, SubValues, UpValues}     , FullDefinition@f } // Last      I don't see any need for temporary symbols here at all, since `RuleDelayed` is `HoldRest`, and `HoldPattern` is `HoldAll`. So, `x$` is a dependency that seems totally unnecessary.               In[4]:= ClearAll /@ HoldComplete[oldF, newF] // ReleaseHold;          In[5]:= oldF@x_ := 2 - oldF[2 + x]          In[6]:= newF = "Will be overwritten";          In[7]:= InheritDefinition[newF, oldF]     Out[7]= newF[x$_] := 2 - newF[2 + x$]                  Attributes[x$] = {Temporary}      1) How to quote definitions without temporary symbols? 2) Why exactly is there a difference between `In[1]` and `In[2]`? Is it really because of recursion?


title: Why is this code in functional style is slower than procedural style?

text: I know that in Mathematica a functional programming style is often more efficient than procedural style programming using `For` loops. But the code shown below seems to be an exception, How to explain this?               del[ls_, k_] := Delete[ls, List /@ Range[k, Length@ls, k]]          max = 10^5;     r1 = Range[max];     For[i = 2, i <= Length[r1], i++, r1 = del[r1, i]]; // Timing          r2 = Range[max];     Do[r2 = del[r2, i], {i, 2, Length@r2}]; // Timing          r3 = Fold[del, Range[max], Range[2, max]]; // Timing          r1 == r2 == r3      Out:               {0.031200, Null}          {0.889206, Null}          {0.577204, Null}          True


title: Importing colors from file

text: I just tried something straightforward (for me):               dummy = Import["http://pastebin.com/raw.php?i=g8D7NprC", "List"] & /@ col;     colors = dummy[[1]];     ToExpression@colors;     Graphics[{colors, Rectangle[{0, 0}]}]      Is it not possible to import color data from a file?


title: Steady states and eigenvalues for a non-linear system:

text: I am trying to understand a non-linear system of equations, and find their steady states and dynamics. I am noob to understanding _Mathematica_ (I am using version 6, but I have access to the latest versions in the lab), and I wondered if some kind soul would be able to help me with some of the code. The system is below:               Clear[PBC];     PBC = {       d'[t] == (1/z) (α - β (d[t]/Y[t]) - γ L[t] - δ ψ[t]  - τ Y[t]) + ε (d[t]/ Y[t]) d[t],       L'[t] == (j (Y[t]/f) - e)/N,       ψ'[t] == p L[t] - \[Xi],       Y[t] == (v + b + α - β ( d[t]/Y[t]) - γ L[t] - δ ψ[t])          (ψ[t] + (1 - s) (1 - ψ[t]) - m z)/(1 - (1 - τ))     }     Clear[PBCSS];      PBCSS = Solve[PBC[[1 ;; 3]] /. {g_'[t] -> 0, g_[t] -> g}, {d, L, ψ}] // Simplify     Clear[PBCEigenSystem];     PBCEigenSystem = D[Transpose[PBCSS][[2, 1 ;; 3]], {{d, L, ψ}}] // Simplify) // MatrixForm      I know that I have done some no-no's (already edited in the code above I think), but the code seems to work. However, I am getting some problems with the output. For one, it does not solve all the system. I included some parameters for a numerical solution, but even if you take away the parametrization, it gives the same error as it does not solve for all variables (I have more choppy code to get some solutions for a large n number of iterations, I do not get it for steady states). Furthermore, I seem to be getting an error when I try to get the eigenvalues of the matrix. Also I have been trying to put a Manipulate handle on the steady states and eigenvalue estimation to see where the bifurcations are but I get errors. Any help will be most appreciated!


title: Using the LQGRegulator to build a human operator model

text: I'm trying to build a human operator model using an optimal control model in Mathematica: ![Human operator model](http://i.stack.imgur.com/OonUR.png) The vehicle dynamics are given by               a = {{-2, 0}, {1, 0}};     b = {{0}, {1}};     c = {{0, 1}, {1, 0}};     d = {{0}, {1}};      with noise and cost weightings               w = {{4}};     v = {{0.0025}};     q = {{0, 0}, {0, 1}};     r = {{1}};      I generated the state space model and added the time delay ($T_d = 0.2s$) using               ssm = StateSpaceModel[{a, b, c, d}]     td = TransferFunctionModel[SystemsModelDelay[.2]];     ssmWithDelay = SystemsModelSeriesConnect[td, ssm];      Now I am trying model the Kalman estimator and gains ($-l^*$) using a LQG regulator               k = LQGRegulator[{ssm, 1, 1}, {w, v}, {q, r}] // StateSpaceModel      which results in the error               The number of columns in {{},{}} is not equal to the length of {{4}}      I think my problem must be with the noise and cost weightings, but I'm not sure where I went wrong?


title: Integrating a list of functions

text: For the purpose of this minimal example, let's say we have a list of functions, like this:               f[y_?NumericQ] := {NIntegrate[z*y, {z, 0, 1}], a y}      I want to integrate an expression involving `f`, say               NDSolve[{y'[t] == f[y[t]][[1]], y[0] == 1}, y[t], {t, 0, 5}]      Now, the problem is that this doesn't return the expected result, because `f[y[t]][[1]]` evaluates to `y[t]` inside the `NDSolve`. How can this be done correctly?


title: Using an ellipse as a threshold for Nearest function

text: The `Nearest` function can receive as a threshold parameter a radius to look for elements inside that. From the documentation: > >     Nearest[data,x,{n,r}] give up to the n nearest elements to x within a > radius r >   What about if instead of a circle I want to use an ellipse as a threshold? So I would have an X and Y limit for the `Nearest` function. I know that `Nearest` can receive a `DistanceFunction` as a parameter but I can't think of how to use that for this purpose. Any ideas?


title: Number theory: Problem involving rational numbers

text: Use `RandomRat` to test whether `((-1)^(1/Denominator[q]))^Numerator[q]` is identical with `(-1)^q`. Use `25000` rational numbers between `1` and `500000`. Use `Delta =10^-10` and `Map` it to a large list of random rational numbers. If you always get `True` you have evidence for the identity. Then, show that               ((-1)^Numerator[q])^(1/Denominator[q])==(-1)^q      is not an identity. * * * So far this is what I have:               RandomRat := ((-1)^(1/Denominator[q]))^(Numerator[q])     (-1)^q == RandomRat      I'm not sure if that's correct so far because I think I'd have to use pure functions and then how would I use the `25000` rational numbers between `1` and `500000` from here?


title: How can I randomly color Graphics3D objects?

text: I have a set of Graphics3D primitives (here, spheres) which I would like to assign either: (1) One of a subset of colors, e.g. {Green, Red} (2) A random color over some RGB interval Writing something like:               Graphics3D[{RGBColor[RandomInteger[{0, 1}], RandomInteger[{0, 1}], RandomInteger[{0, 1}]],Sphere[{#[[1]], #[[2]], #[[3]]}, #[[4]]] & /@ SphereList...      Appears to only assign one random color to all of the spheres. I can force this to work by generating a string that explicitly specifies a random color for each sphere, but is there a simple way to make this work?


title: Why won't Mathematica work with quantities or Quantity[]?

text: As you can see in the screenshot below, Mathematica is simply not evaluating any quantities. It is simply listing them as I wrote them. Could anybody give me a pointer as to why this may be? ![enter image description here](http://i.stack.imgur.com/KbG0S.png)


title: How does parallelization of LibraryLink function call work?

text: I'm trying to call a C function in parallel through LibraryLink. Here is an example kind of demonstrates that library function can be used in parallel. My question is what happened in the library function call? Does each kernel have its own copy of the library function? Are there some pitfalls we need to watch out when using library functions in parallel?               Needs["CCompilerDriver`"];          src = "       #include \"WolframLibrary.h\"       #include \"time.h\"            DLLEXPORT mint WolframLibrary_getVersion(){         return WolframLibraryVersion;       }       DLLEXPORT int WolframLibrary_initialize( WolframLibraryData libData){         return 0;       }            DLLEXPORT int pause(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res) {         timer(MArgument_getReal(Args[0]));         return 0;       }            void timer(double seconds)       {         clock_t x;         x=clock()+seconds*CLOCKS_PER_SEC;         while(clock()<x){}       }            ";          test1 = CreateLibrary[src, "test1"];     pauseLib = LibraryFunctionLoad[test1, "pause", {Real}, Integer];          Table[pauseLib[1.],{8}];//AbsoluteTiming     (* {8.021739,Null} *)     ParallelTable[pauseLib[1.],{8}];//AbsoluteTiming     (* {2.350266,Null} *)


title: Check for holomorphy of a function

text: Given a (rather complicated) function `H(z)`, what is the best approach to check symbolically whether it is holomorphic? What I tried is checking explicitly the Cauchy-Riemann equations(*):               z = a + I b          H = E^-Sqrt[z^2] / (Sqrt[z^2] + Sqrt[z^2] Cosh[Sqrt[z^2]] + Sqrt[z^2] Sinh[Sqrt[z^2]])          HRe = FullSimplify[ComplexExpand[Re[H]], (a | b) ∈ Reals]     HIm = FullSimplify[ComplexExpand[Im[H]], (a | b) ∈ Reals]     HReA = Assuming[(a | b) ∈ Reals, D[HRe, a]]     HReA = Simplify[HReA, (a | b) ∈ Reals]     HImB = Assuming[(a | b) ∈ Reals, D[HIm, b]]     HImB = Simplify[HImB, (a | b) ∈ Reals]     Simplify[HReA == HImB, (a | b) ∈ Reals]      What I would expect as a result is either just `True` or some equation that `a` and `b` need to satisfy in order for the _CR_ equations to be fulfilled. This would mean that my function is not holomorphic everywhere in the complex plane. The problem that I encounter is that the call to `Simplify` does not complete computation in a reasonable amount of time (> 1 hour, then I aborted it). Checking whether `HRe` and `HIm` are harmonic (which is a necessary condition for `H` to be holomorphic) did not seem to be any easier, with the second derivatives of `H` being even longer. Is there a way to speed this up, or even a completely different approach? The derivatives are so long that a manual inspection is not an option. (*) Note that as correctly pointed out by murray below, the Cauchy-Riemann DEs being fulfilled alone does not already imply holomorphy. Additional properties need to be given, e.g. continuity of H or continuity of its derivatives.