title: Why I only get 2X speedup when parallelized with 16 kernels

text: I'm trying to parallelize a function by ParallelTable, and it seems the speedup is not very good. I have 16 parallel kernels on my computer node:               $Version     (*"9.0 for Linux x86 (64-bit) (November 20, 2012)"*)          LaunchKernels[]     (*     {KernelObject[1, "local"], KernelObject[2, "local"], KernelObject[3, "local"],KernelObject[4, "local"], KernelObject[5, "local"], KernelObject[6, "local"], KernelObject[7, "local"], KernelObject[8, "local"], KernelObject[9, "local"], KernelObject[10, "local"], KernelObject[11, "local"], KernelObject[12, "local"], KernelObject[13, "local"], KernelObject[14, "local"], KernelObject[15, "local"], KernelObject[16, "local"]}     *)      And using a documentation example, I get about 16X speedup:               Table[Pause[0.5];f[i],{i,16}]//AbsoluteTiming     (*{8.003956, Null*)          ParallelTable[Pause[0.5];f[i],{i,16}]//AbsoluteTiming     (*{0.508174, Null*)      However, my code only get 2X speedup:               hz = 2*0.375*^-9; c = 2.997924580*^8; ht = hz/(1.01*c)*1.*^15; N0 = 60000; hbar = 1.0545716*^-34; ωx = 2.96265*^1; nx = 5.; Ex = 2.74*^8; Tx = 2 π/ωx; β2 = 226.161; d13 = 8.35066*^-31; Ti = 2.64516;          Ω13[t_, β1_] := Piecewise[{{((Ex*d13)/(hbar*1.*^15))*Cos[(ωx*(t - β1))/(2*nx)]^2* Sin[ωx*(t - β1)], β1 - nx*(Tx/2.) <= t <= β1 + nx*(Tx/2.)}, {0., True}}]          Ω13cf =        Compile[{{t, _Real}, {τ1, _Real}}, Evaluate@Ω13[t, τ1], RuntimeAttributes -> {Listable}];          Table[Ω13cf[t, τ1], Evaluate@{τ1, β2 - 80 Ti, β2 + 10 Ti, 0.05 Ti}, Evaluate@{t, ht, ht*N0, ht}] // Developer`PackedArrayQ // AbsoluteTiming     (*{14.805294, True}*)          Table[Ω13cf[t, τ1], Evaluate@{τ1, β2 - 80 Ti, β2 + 10 Ti, 0.05 Ti}, Evaluate@{t, ht, ht*N0, ht}] // Developer`PackedArrayQ // AbsoluteTiming     (*{14.799250, True}*)          ParallelTable[Ω13cf[t, τ1], Evaluate@{τ1, β2 - 80 Ti, β2 + 10 Ti, 0.05 Ti}, Evaluate@{t, ht, ht*N0, ht}] // Developer`PackedArrayQ // AbsoluteTiming     (*{7.714471, True}*)          ParallelTable[Ω13cf[t, τ1], Evaluate@{τ1, β2 - 80 Ti, β2 + 10 Ti, 0.05 Ti}, Evaluate@{t, ht, ht*N0, ht}] // Developer`PackedArrayQ // AbsoluteTiming     (*{3.088646, True}*)      Questions:   1. Is it possible to get about 16X speedup using ParallelTable, and how?   2. Why the second ParallelTable get a 2X speedup? **Update** Mr. Wizard suggested a very useful discussion on how to efficiently parallelize the problem. As I understand, the basic idea is to use `ParallelMap` instead of `ParallelTable`. So I tried this approach, but it turns out the result is not a PackedArray and `ParallelMap` more than 10X slower than the un-parallelized `Table`:               ls = Tuples[{Range[ht, ht*N0, ht],Range[β2 - 80 Ti, β2 + 10 Ti, 0.05 Ti]}];     Developer`PackedArrayQ[ls]     （*True*）          Map[Ω13cf @@ # &, ls] // Developer`PackedArrayQ // AbsoluteTiming     (*{181.030360,False}*)          ParallelMap[Ω13cf @@ # &, ls] // Developer`PackedArrayQ // AbsoluteTiming     (*no return before I kill it after running for 5 minutes*)


title: Programming Mathematica in plaintext, i.e. no formatting, non-notebook

text: I'm new to Mathematica and I've just begun reading Paul Wellin's _Programming in Mathematica_. The book, like many other books and online tutorials, revolves around using the notebook, with all its helpful formatting and other facilities. However, given my background as a C++ developer, mostly using vim and other "traditional" IDEs for development, Doxygen-style commenting for document generation, and Perforce, git, and svn for version control (all of which, as far as I'm aware, operate by diff-ing newline-delimited code), I'm anxious to know: **Is it possible (and more importantly, _not limiting_ ) to program Mathematica in "plaintext"? (And if so, how would one go about it, _i.e._ through a mode in Mathematica's front-end, or writing separate files and "running" them via terminal?)** For the record, I'm not at all opposed to learning a new way of doing things. I'd just like either (1) to ascertain that programming in plaintext is indeed an option and not limiting (at least, there are alternative techniques for getting around any limiting factors) or (2) to ascertain that there are clear advantages to using the notebook, in which case, I'm happy to commit to using the notebook.† Of course, it'd be _nice_ if I could touchtype Mathematica code in vim, but I'm sure there would be good reasons for preferring the notebook, if indeed it is preferred. * * * Perhaps I'm searching for answers using the wrong keywords (mainly "plaintext"), but these are some other threads I read here, on the meta, and on SO, before deciding to ask.   * http://stackoverflow.com/questions/5010346/mathematica-plain-text-notebook \- This hinted to me that it _is_ possible (and practiced) to program in plaintext, but there are no details on its merits or pitfalls, much less guidelines for doing so.   * Converting a notebook to plain text programmatically \- This again hints at plaintext programming (I think), but also again offers no insights into doing so.   * Mathematica as a normal programming language \- I _think_ this touches upon the subject but it's a bit abstract and maybe more about the language implementation rather than the _use_ of it.   * Is there an open source implementation of Mathematica-the-language? \- This is not relevant as I'm not looking for any alternative to Mathematica.   * Running a Mathematica program without Mathematica \- This is not really relevant, as I'm fine with running the kernel and MathLink-ing or whatever is necessary to program in plaintext. **If this question is defective, please help me improve my question.** I'm very much for asking only _relevant_ questions, and I'm happy to take this elsewhere, or rewrite the entire thing. * * * † The reason I'd like to ascertain one or the other is that in my current state of mind, uncommitted to _either_ style, I'm subconsciously resistant to _imagining_ myself programming in Mathematica as I read the book and online tutorials. That is, not having a clear idea of _how_ I'll be writing code, my mind seems to avoid even thinking about it! I think reading _actively_ (imagining myself applying what I'm learning) is a critical factor to learning, so I'd like to remove this mental barrier as early on as possible.


title: how to delete specific data from text file and then update it

text: I have a large text file. I read data from text file one at a time and check whether data agree with my condition. If not I want to delete that data in text file and update it. For example say my data text file is: 100 201 302 455 Suppose I want to delete second one. After deletion I want new text file to be look like 100 302 455 (without any gap between 100 and 302). Since my text file is large around 100MB, I want to read data one by one rather than loading all at once. Thanks


title: Moment central of a binary image

text: I am implementing the Hu set of invariant moments detailed here Hu set of invariant moments. I implemented the moment Image like this:                {i,j}={0,0}             m00 = Total[               Flatten[Table[                 x^i y^j ImageValue[imagetest, {x, y}], {x, 1, 800}, {y, 1, 600}]]]         {i,j}={1,0}             m10 = Total[               Flatten[Table[                 x^i y^j  ImageValue[imagetest, {x, y}], {x, 1, 800}, {y, 1,                   600}]]]     m10/m00=371.972         {i,j}={0,1}             m01 = Total[               Flatten[Table[                 x^i y^j ImageValue[imagetest, {x, y}], {x, 1, 800}, {y, 1, 600}]]]         m01/m00=472.923      I remark that the time computing is very high compared to                   {cx,cy}=Flatten[ComponentMeasurements[imagetest, "Centroid"][[All,2]]]          {cx,cy}={371.997, 473.198}      and the result is not the same. How can I reduce the time computing ? thanks! ![Hu set of invariant moments](http://i.stack.imgur.com/qZ4G5.png)


title: How to use a ConvexHull as RegionFunction?

text: I have a set of data supported over a region in 2D. I want to use RegionPlot and ContourPlot on interpolations of my data, but want to restrict the Plots to the region over which my data is supported. Paste of the supports of my data. I easily find the region with ConvexHull from the ComputationalGeometry package: > Graphics[Polygon[l2[[ConvexHull[l2]]]]] ![enter image description here](http://i.stack.imgur.com/mHv8V.jpg) Now I want to turn the information into something I can use as RegionFunction for the ContourPlots and as restrictions in RegionPlot. Can you show me a way?


title: Rounding only reals in an expression containing, reals, integers and symbols

text: I am trying to make a function that would make rounding real numbers in an expression possibly consisting of real numbers, integer numbers and symbols. An example of such an expression is below:               expr = 1.2345 + 3.2471*x + 4.3946*x^2 + 5.56789*x^3 + 3.4812*x^4 +         1.34682*x*Exp[-2.3467*x^3] + 13.25684*x^3*Exp[23.9476*x^7] +         Sin[34.876459*x^2];      What I want to achieve is the following. Let us say, I would like to have all real numbers to have not more that two figures after comma. The expression then should then look as follows:                   1.23 + 3.25 x + 1.35 E^(-2.35 x^3) x + 4.39 x^2 + 5.57 x^3 +       13.26 E^(23.95 x^7) x^3 + 3.48 x^4 + Sin[34.88 x^2]      Such a function is useful, to show dynamically and in a compact form a result obtained in the course of dynamic calculation. For example, I often fit data to a function, the both being dependent upon parameter(s). To show the fitting function dynamically in the same Panel or Manipulate window I need to cut number of figures after comma of real numbers. At present I am here:                   rnd[expr_, m_Integer] :=        Map[If[NumberQ[#],           If[Element[#, Reals], (Round[#*10^m]/10^m // N),            IntegerPart[#]], #] &, expr, {1, Depth[expr]}];      Here expr is any expression to subject the rounding, m is the integer equal to the number of figures after comma to be left. This function almost works. Its application to the expression given above yields the following:               rnd[expr, 2]              (*      1.23 + 3.25 x + 1.35 E^(-2.35 x^3.) x + 4.39 x^2. + 5.57 x^3. +           13.26 E^(23.95 x^7.) x^3. + 3.48 x^4. + Sin[34.88 x^2.]      *)      You may see that the difference between what I get and what I want is that the powers are 2., 3. and so on instead of 2, 3 and so on. I cannot understand, why these decimal points show up, and how to get rid of them.


title: How to do nor on matrices?

text: Supose I have matrices a b and c like                  a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};        b = {7, 8, 9};        c = {{1},{4},{7}};      I want to get `{{1, 2, 3}, {4, 5, 6}}` from `a` and `b`, also `{{2,3},{5,6},{8,9}}` from `a` and `c` ? In other words, I want to delete the part which is the same as `b` or `c` from `a`.


title: How to force Manipulate to use preserve control settings over successive evaluations

text: I have this Manipulate:               Manipulate[Plot[Sin[a x], {x, 0, 2 Pi}], {a, 0, 3}]      ![Sin\[a x\]](http://i.stack.imgur.com/D3IgV.png) Now, I realize I had mistyped the expression and it's actually `x^2` instead. I go back and fix it, but when I evaluate the cell again, the value of `a` reverts to default/zero. ![Mathematica graphics](http://i.stack.imgur.com/X8LE8.png) I've tried multiple things from various Q&A: adding `SaveDefinitions -> True`, saving parameter to a global variable within the `Manipulate` block, using bookmarks, but none of them achieved the effect of having the `Manipulate` start up with a previously-set control value. Interesting, I find that saving the parameter to a global variable, and then initialize the parameter with the same global variable solves the problem, i.e., `Manipulate` can remember the manipulated parameter from a previous run. If I add the option `SaveDefinitions -> True`, the value is also saved between sessions. Below is an example: `a` remains at the same value even when the expression in `Manipulate` was changed and the cell was evaluated. ![Mathematica graphics](http://i.stack.imgur.com/Dvuv3.png) ![Mathematica graphics](http://i.stack.imgur.com/yKNMJ.png) I went to the chat room to ask people if doing this is OK. I was told that I should not do this. What kind of potential issues would I have with this method? And if it's bad, is there another method to achieve the same result, i.e., preventing `Manipulate` from resetting control values after each evaluation?


title: Order of operations for the Table function

text: > **Possible Duplicate:**   >  Using pure functions in Table I have run into a situation that I do not understand when trying to generate a nested list of pure functions. I have the following code.               Table[Function[x, i*x + j], {i, 1, 3}, {j, 1, 4}]      I expected to get a nested list of pure functions, but the values for `i` and `j` are not being input. I get               {{Function[x, i x + j], Function[x, i x + j], Function[x, i x + j],        Function[x, i x + j]}, {Function[x, i x + j], Function[x, i x + j],        Function[x, i x + j], Function[x, i x + j]}, {Function[x, i x + j],        Function[x, i x + j], Function[x, i x + j], Function[x, i x + j]}}      What is making this operation fail to behave as I expected?


title: How to create list of delayed rules?

text: I am trying to make a `ButtonBar` that prints the name of the card in question. ![enter image description here](http://i.stack.imgur.com/x50De.png) What I have so far is as follows:               myHand = {{1, "Spades"}, {4, "Hearts"}, {5, "Clubs"}, {8,         "Spades"}, {9, "Hearts"}, {9, "Spades"}, {11, "Spades"}};          ButtonBar[Table[       ToString[myHand[[i, 1]]] <> " of " <> ToString[myHand[[i, 2]]] :>        Print[myHand[[i]]],       {i, Length@myHand}]      ]      However, instead of working as expected and printing out the name of the card in question, it always prints out `{9, Hearts}`. When I looked into the `FullForm` for this it made sense why:               ButtonBar[List[RuleDelayed["1 of Spades", Print[Part[myHand, i]]],       RuleDelayed["4 of Hearts", Print[Part[myHand, i]]],       RuleDelayed["5 of Clubs", Print[Part[myHand, i]]],       RuleDelayed["8 of Spades", Print[Part[myHand, i]]],       RuleDelayed["9 of Hearts", Print[Part[myHand, i]]],       RuleDelayed["9 of Spades", Print[Part[myHand, i]]],       RuleDelayed["11 of Spades", Print[Part[myHand, i]]]]]      The rule is to print out `i`, not the actual number. How can I remedy this so that my `Table` generates a list of actual rules without holding the `i`s back from being evaluated in the `Table`?


title: Appending functions to a list

text: Could someone please explain the difference between these methods, and possibly a nicer way to get the first result? (This is a toy example and in my real program I'd like to use `Do` rather than `Table` or similar as there are imperative and global things going on). Method 1 (Desired result):               In[5]:= fsum[f_]=Total@Through[f@#]&;     fs={};     Do[     AppendTo[fs,#^n1&/.n1->n];     ,{n,0,10}]     fsum[fs][a]          Out[8]= 1+a+a^2+a^3+a^4+a^5+a^6+a^7+a^8+a^9+a^10      Method 2:               In[9]:= fsum[f_]=Total@Through[f@#]&;     fs={};     Do[     AppendTo[fs,#^n&];     ,{n,0,10}]     fsum[fs][a]     Out[12]= 11 a^n      Method 3:               In[13]:= fsum[f_]=Total@Through[f@#]&;     fs={};     Do[     n1=n;     AppendTo[fs,#^n1&];     ,{n,0,10}]     fsum[fs][a]     Out[16]= 11 a^10A


title: Defining functions in a loop

text: I have a symbolic solution to a linear system with respect to some variables a[i,j] which depend on a parameter t.               sol=Solve[...,Table[a[i,j],{i,0,n},{j,0,n}]]      I would like to make functions from the solutions. Something like               a[i,j][t_]:=a[i,j]/.sol[[1]]      When I do it by hand, everything is fine. But when I try to get it in any loop, like               Do[{a[i, j][t] := a[i, j] /. sol[[1]]}, {i, 0, n}, {j, 0, n}]      it doesn't work. For example, when I'm trying to look at a[0,1][t] it gives me               a[i,j]      How can one define a family of functions in a loop?


title: How to change front end setting "Parallel Kernel Configuration" in the code?

text: I'm trying to run Mathematica parallel on multiple nodes on a HPC, and I use the remote kernel tab in the "Parallel Kernel Configuration" settings to set the communication between different nodes(detailed setup here). Since every time I would get different nodes of the HPC, each time I have to manually change the setting in the "Parallel Kernel Configuration". So is it possible to change the settings within the code? Here is the detail where I want to change: ![enter image description here](http://i.stack.imgur.com/p5HGs.png) For example, how can I enable 16 kernels on a remote host named "mike123" and 10 kernels on a remote host named "mike234"


title: How to make Mathematica save all open files, or automatically ask to save each file when closing

text: Here is the scenario: You have number of open notebooks at the same time, and made some changes in all or some of them but have not yet saved the changes. Mathematica does not have something like _save all_ that will save all and any open files that needs to be saved before closing. (At least I do not see it under `File`) So I expected that when one clicks on the close all windows on the main icon, that it will prompt one to save or not save all the open notebooks that needs this action done on them, one by one. ![Mathematica graphics](http://i.stack.imgur.com/SPAHi.png) What happens is this: It asks about the first open notebook, then when answering the question, expecting it will now ask about the next open notebook, instead it does nothing. Leaving the remaining notebooks open as is. So one have to click and click and click again on `close all windows` until all open notebooks that needs to be saved are saved. So if one has 10 open notebooks, they have to click 10 times on `close all windows` and click again to answer the question. This is 10 additional clicks. Other apps I used would ask the user for each open file in turn, or provide a _save all_ or when closing, they would ask the user if they want to save all or discard all, etc... Is there a way to get Mathematica to do this so one does not have to keep clicking on things? A palette that does _save all_ open notebooks would be great. Finally, after closing all windows, and with all those clicks, the main Mathematica icon remains there! So one has to click again to quit. (I actually do not see this splash window below at all, until I have closed all windows. It seems to be hidden somewhere during normal operations or while a notebook is open and this only shows up if all notebooks are closed, not sure) ![Mathematica graphics](http://i.stack.imgur.com/T4bGF.png)


title: Solving simultaneous exponential equations

text: In[1]: Solve[{(1 + k)^n == 0.6, (1 + k)^(n + 1) == 0.3}, {n, k}]      > Solve::ifun: Inverse functions are being used by Solve, so some solutions > may not be found; use Reduce for complete solution information. >>               Out[1]: {{n -> 0.736966, k -> -0.5}}          In[2]: Solve[{2*(1 + k)^n == 1.2, (1 + k)^(n + 1) == 0.3}, {n, k}]      > Solve::inex: Solve was unable to solve the system with inexact coefficients > or the system obtained by direct rationalization of inexact numbers present > in the system. Since many of the methods used by Solve require exact input, > providing Solve with an exact version of the system may help. >>               Out[2]: Solve[{2 (1 + k)^n == 1.2, (1 + k)^(1 + n) == 0.3}, {n, k}]      Where is the problem with Mathematica, not able to divide by 2 in first equation?


title: Autoregressive distributed lag model

text: Could someone point me in the direction of creating an autoregressive distributed lag model in mathematica?


title: Is UndirectedEdge[a,b] the same edge as UndirectedEdge[b,a]?

text: Is `UndirectedEdge[a,b]` the same edge as `UndirectedEdge[b,a]`? Then please consider this.               g = CompleteGraph[4, VertexLabels -> "Name", ImagePadding -> 10]      ![tri1](http://i.stack.imgur.com/I2VNf.png) If we ask to delete `UndirectedEdge[1,4]` or `UndirectedEdge[4,1]` gives the same result:               EdgeDelete[g, {1 \[UndirectedEdge] 4}]     EdgeDelete[g, {4 \[UndirectedEdge] 1}]      ![tri2](http://i.stack.imgur.com/4poU3.png) ![tri3](http://i.stack.imgur.com/9KLsx.png) Yet if we ask whether these edges were in the original graph, we receive different answers.               MemberQ[EdgeList[g], 1 \[UndirectedEdge] 4]     (* True *)          MemberQ[EdgeList[g], 4 \[UndirectedEdge] 1]     (* False *)      This strikes me as inconsistent. * * * **Postscript: Should`UndirectedEdge` be orderless?** @R.M 's response makes a lot of sense: `MemberQ[EdgeList[g], b \[UndirectedEdge] a]` answers True if and only if `b \[UndirectedEdge] a`, is literally in `EdgeList[g]`. It will not respond True if that edge is listed in `EdgeList[g]` as `a \[UndirectedEdge] b`. However, `EdgeQ[g, b \[UndirectedEdge] a]` will respond True whether that edge is stored in `EdgeList[g]` either as `a \[UndirectedEdge] b` or `b \[UndirectedEdge] a`. Even so, it seems to me that `UndirectedEdge` ought to be `Orderless`. Wouldn't it be preferable to behave like `Plus`? Compare `Plus` and `UndirectedEdge`:               ClearAll[x, y]     Plus[x, y]     Plus[y, x]     Attributes[Plus]     Plus[x, y] == Plus[y, x]     Plus[x, y] === Plus[y, x]      ![plus](http://i.stack.imgur.com/GttLe.png)               ClearAll[x, y]     x \[UndirectedEdge] y     y \[UndirectedEdge] x     Attributes[UndirectedEdge]     UndirectedEdge[x, y] == UndirectedEdge[y, x]     UndirectedEdge[x, y] === UndirectedEdge[y, x]      ![undirectedEdge](http://i.stack.imgur.com/yMLzl.png)


title: Export long filename truncated

text: I am seeing a weird behavior on exporting at least one type of file (here, a QuickTime movie) to files with long names. If I do this:               In[19]:= Export["Lorem-ipsum-dolor-sit-amet-consectetur-adipisicing-elit.dat", {42}]     Export["Lorem-ipsum-dolor-sit-amet-consectetur-adipisicing-elit.mov", {42}]     FileNames["Lorem*"]      it hurts:               Out[19]= "Lorem-ipsum-dolor-sit-amet-consectetur-adipisicing-elit.dat"     Out[20]= "Lorem-ipsum-dolor-sit-amet-consectetur-adipisicing-elit.mov"     Out[21]= {"Lorem-ipsum-dolor-s#123C8BE.mov", \     "Lorem-ipsum-dolor-sit-amet-consectetur-adipisicing-elit.dat"}      The `.dat` file has the correct name and the `.mov` file hasn't, even though `Export` tries to make me think it has. My questions are:   * This is not on a MS-DOS box, but with Mathematica 8.0.0.0 on Mac OS 10.7.3 (64-bit kernel). Can you comment if other versions/operating systems reproduce this issue?   * Although I find nothing with Google, is this a known bug and is there a fix?


title: Is there a TwoColoring function of Graph object?

text: The following code shows the `GraphUtilities` package makes a problem for `Graph` object. I want to use a `TwoColoring` function without using the `GraphUtilities` package. Is there a `TwoColoring` function of `Graph` object ? _Mathematica_ version is 9.0.1.0.               g1 = {1 -> 2, 2 -> 3};          GraphPlot[g1, VertexLabeling -> True, ImageSize -> 200]              Graph[g1, VertexLabels -> "Name", ImagePadding -> 20]              Needs["GraphUtilities`"]         gc = ToCombinatoricaGraph[g1]         color = TwoColoring[gc]              GraphPlot[g1,               VertexRenderingFunction -> ({Text[Framed[#2, Background -> Hue[color[[#3]]/4],               FrameStyle -> RGBColor[0.94, 0.85, 0.36]], #1]} &)]              color2 = Position[color, 2][[1]]           HighlightGraph[Graph[g1, VertexLabels -> "Name"], {2}, ImagePadding -> 20]          > >     HighlightGraph[Graph[{1 -> 2, 2 -> 3}, VertexLabels -> "Name"], {2}, >                                              ImagePadding -> 20] >   No graphics.


title: Embedding StreamPlot in Graphics3D

text: I am trying to visualise the action of the infinitesimal generator of a Lie group on the solution of a 2-ODE system drawn in the 3D space (t,y1,y2): t is time and y1,y2 are the two dependent variables. The infinitesimal generator of a Lie group is a vector field and can be visualized nicely using StreamPlot. For a system like this it would normally be a 3D vector field. In this case, however, the symmetry corresponding to the vector field is 2D and (by design) perpendicular to the time axis. Therefore, the vector field can be drawn as a vertical plane (since I am drawing the time axis horizontally). In another post I found an answer that almost works: Can 2D and 3D plots be combined so that the 2D plot is the bottom surface of the 3D plot boundary?. In my case the 2D plot is at the back and vertical, rather than at the bottom, but it was easy to modify the code in that other post to obtain this effect. Preliminaries:               Clear[y1, y2S1, y2S2, y2S3, S, R0, X0]     X0 = 1.5;     R0 = 1.5;     y1[t_, S_] := S - (S - X0) Exp[-t]     y2S1[t_] := 1 + Exp[Exp[-t] - t]*     ((R0 - 1)/E - ExpIntegralEi[-1] + ExpIntegralEi[Sinh[t] - Cosh[t]])     y2S2[t_] := 1 - (1 - R0) Exp[-t/2]     y2S3[t_] := (1/3)*Exp[-2 Exp[-t] - 4 t]*(E^2 (3 R0 - 11) + 8 ExpIntegralEi[2] +        Exp[2 Exp[-t] + t]*(4 + 2 Exp[t] + 2 Exp[2 t] + 3 Exp[3 t]) -        8 ExpIntegralEi[2 Exp[-t]])          pp3d = ParametricPlot3D[{{t, y1[t, 0.5], y2S1[t]},                 {t, y1[t, 1], y2S2[t]},                 {t, y1[t, 2], y2S3[t]}}, {t, 0, 5},     PlotStyle -> {{Thickness[.007], RGBColor[1, 0, 0]},                     {Thickness[.007], RGBColor[0, .7, 0]},                     {Thickness[.007], RGBColor[0, 0, 1]}},     BoxRatios -> {2, 1, 1},     PlotRange -> {{0, 5}, {0, 2}, {0, 2}}]      Code:               S = 2;     test = StreamPlot[{x - S, 2 x*y - S}, {x, 0, 3}, {y, 0, 3}];     Make3d[plot_, height_] := Module[{newplot},        newplot = First@Graphics[plot];        newplot = N@newplot /. {x_?AtomQ, y_?AtomQ} :> {height, x, y}];     Show[{Graphics3D[Make3d[test, 0]], pp3d}, Axes -> True]      However, I got this error:               Encountered "1." where a Graphics was expected in the value of option Arrowheads.      With corresponding graphical output: ![3D_Space_Curve_error](http://i.stack.imgur.com/DIsh7.jpg) S is a parameter. The three curves in R, G, B are three solutions for three different values of S so the vector field is not mapping between these curves. It is acting on any one of these at a time, mapping it to some other solution not shown here. But no matter. It's clear that there is something wrong with the arrows. I am guessing StreamPlot defines them as 2D and they need to be converted to a 3D spec, but I have no idea how to go about that. I can guess that the code above (which I understand only roughly) is doing this kind of conversion, but perhaps it is not reaching the arrow data structure within StreamPlot. Can anyone help? Thanks (Using MMA 9)


title: How can I decimal-align tick labels at the left?

text: I use the `CustomTicks` package, because the built-in tick labeling leaves a lot to be desired. Even just putting the tick marks on the right instead of the left is a real pain without `CustomTicks`, from what I remember. I think this would be an issue even without this package, though. Here is what I type in:               << "CustomTicks`"     Plot[Sin[x], {x, 0, 2 π},        Frame -> True, Axes -> False,        FrameTicks -> {Automatic, StripTickLabels[LinTicks], Automatic, LinTicks},       BaseStyle -> 18]      and here is what I get: ![enter image description here](http://i.stack.imgur.com/tFmfP.png) I think the tick marks on the right look awful. They would be better if aligned on the decimal rather than on the left. But how do I fix this? My current workaround is to make another version of the plot with tick labels on the left, which usually are aligned properly because they align to the right. Then I cut the labels from that image and paste them onto the image I want. Any other solution?


title: Symbolic derivative of $n$-term product

text: I want to determine the relationship that must exist between the $x_i$ and $y_i$ such that $$ \frac{\partial}{\partial\theta} \prod_{i=1}^n \frac{f(x_i,\theta)}{f(y_i,\theta)} = 0, $$ where $$ f(x,\theta) = \frac{e^{-(\theta - x)}}{(1+e^{-(\theta - x)})^2}, \;\; \forall x \in {\mathbb R}, \theta \in {\mathbb R} $$ * * * Clarification: what I'm trying to find is a condition on the $x_i$ and $y_i$ such that the derivative above (viewed as a function of $\theta$) is zero for all $\theta$ _only if_ this condition holds. Clearly, this derivative is zero for all $\theta$ if, $\forall i\in\\{1,\dots,n\\}$, the condition $x_i = y_i$ holds, since then the product in the derivative expression above is identically 1. But this condition is not necessary: the derivative will be identically zero _also_ if there is an $n$-permutation $\sigma$ such that $\forall i,\,x_i = y_{\sigma(i)}$. My problem is to prove that the derivative is identically zero (i.e. it is zero for all $\theta$) _only if_ such a $\sigma$ exists, for given $x_i$ and $y_i$. * * * So, hoping to have a look at the derivative above, I input this into Mathematica:               Block[{f, θ, x, y, i, n},      f[x_][θ_] := E^(-x + θ)/(1 + E^(-x + θ))^2;      D[Product[f[x[i]][θ]/f[y[i]][θ], {i, n}], θ]     ]      ...but Mathematically basically spits back the last formula (after replacing the various expressions in `f`):               D[Product[(E^(-x[i] + y[i])*(1 + E^(θ - y[i]))^2)/(1 + E^(θ - x[i]))^2, {i, n}], θ]      If instead of using a symbolic product (with an unspecified number of terms) I attempt the same thing with a product of three terms, namely               (f[x1][θ]/f[y1][θ]) (f[x2][θ]/f[y2][θ]) (f[x3][θ]/f[y3][θ])      ...Mathematica does compute the derivative (though the resulting expression is hairy, and I can't extract any insight from it). So my first question is > How can I get Mathematica to produce the expression for the derivative for > the general case? (After all, the derivative of an $n$-term product has a form that Mathematica should be able to express relatively easily.) In any case, the results I got for a three-term product were not encouraging. Of course, I really don't care for the derivative per se, but rather, what I'm after are the conditions on the $x_i$ and $y_i$ that make this derivative vanish. > Is there a way that Mathematica can show me the relationship between the > $x_i$ and $y_i$ when this derivative is 0?


title: List plot joined with stair steps instead of diagonal lines

text: What's a simple way to plot a list of points so that they're joined with stair steps instead of straight lines between the points? I'd imagine something like...               stairStepListPlot[{{0,0},{1,1},{2,2}}]      ...would produce a flat line from {0,0} to {1,0}, then a vertical line from {1,0} to {1,1} and so on. Can you find a concise way of producing such a plot?


title: plotting xy, yz, zx plane at

text: I have a data list in the following form,               data = {x, y, z, f}      I would like to present three kinds of subdata set as a density (or contour) plot on the respective planes at once in one 3D graph.   1. `data1 = {x, y, f}`   2. `data2 = {y, z, f}`   3. `data3 = {x, z, f}` How could I make an above kind of plot? I really appreciate if anyone help me.


title: How to abbreviate context names?

text: It's convenient to abbreviate often-used function names, eg `Dim = Dimension`. Is it possible to abbreviate long context symbols, e.g. _Combinatorica_ when the context is not inserted in the context path, like with               Block[{$ContextPath}, Needs["Combinatorica`"]]      `Com = Combinatorica` doesn't work, eg: `Com`Star[6]` is fixed by the interpreter. Is there a way to abbreviate it?


title: Recovering vertex names from Combinatorica Graph

text: According to WRI tech support: _Combinatorica functionality is not technically deprecated, though it is our hope that future versions of Mathematica will subsume it entirely by incorporating its functionality with the built-in Graphs & Networks functionality._ Leaving aside that this seems to conflict with MMA's documentation, eg:               Block[{$ContextPath}, Needs["Combinatorica`"]]      warns: _General::compat: Combinatorica Graph and Permutations functionality has been superseded by preloaded functionality. The package now being loaded may conflict with this. Please see the Compatibility Guide for details._ In the meantime, in order to use Combinatorica functionality like TransitiveClosure on built in Graphs, it's necessary to take a detour through Combinatorica, eg:               AdjacencyGraph[#, VertexLabels -> "Name"] &@      Combinatorica`ToAdjacencyMatrix@       Combinatorica`RemoveSelfLoops@        Combinatorica`TransitiveClosure@         Combinatorica`FromAdjacencyMatrix@          Normal@AdjacencyMatrix@Graph[{"E0" -> "T0", "T0" -> "E1"}]      This yields (sorry for truncation): ![enter image description here](http://i.stack.imgur.com/fcBLA.jpg) How to recover the built in Graph's vertex names? (These are extracted from XML metadata and so it's not so convenient to project them to positional indices)


title: finding anagrams

text: What I'm trying to find are the 4 letter words in the _mathematica dictionary_ that have the most anagrams and the amount of anagrams these have each. But I can't seem to find all the 4 letter words in the mathematica dictionary. My output only results in 3-8 letter words. Input is below                wordperms =Flatten[Map[DictionaryLookup,Map[StringJoin, Permutations[Characters[#]]]]] &;      words = DictionaryLookup[];      sorted = Sort[Map[Sort, Map[Characters, words]]];      Part[Select[Tally@sorted, Part[#, 2] > 4 &], All, 1];      found = Part[Select[Tally@sorted, Part[#, 2] > 4 &], All, 1];      Map[wordperms, found]


title: Placing a contourPlot under and Plot3D

text: I would like to combine a 3-dimensional graph of a function with its 2-dimensional contour-plot underneath it in a professional way. But I have no idea how to start. I have a three of these I would like to make, so I don't need a fully automated function that does this. A giant block of code would be just fine. The two plots I would like to have combined are:               potential1 =        Plot3D[-3600. h^2 + 0.02974 h^4 - 5391.90 s^2 + 0.275 h^2 s^2 + 0.125 s^4,          {h, -400, 400}, {s, -300, 300}, PlotRange -> {-1.4*10^8, 2*10^7},          ClippingStyle -> None, MeshFunctions -> {#3 &}, Mesh -> 10,         MeshStyle -> {AbsoluteThickness[1], Blue}, Lighting -> "Neutral",         MeshShading -> {{Opacity[.4], Blue}, {Opacity[.2], Blue}}, Boxed -> False,         Axes -> False]      and               contourPotentialPlot1 =        ContourPlot[-3600. h^2 + 0.02974 h^4 - 5391.90 s^2 + 0.275 h^2 s^2 + 0.125 s^4,         {h, -400, 400}, {s, -300, 300}, PlotRange -> {-1.4*10^8, 2*10^7},        Contours -> 10, ContourStyle -> {{AbsoluteThickness[1], Blue}}, Axes -> False,         PlotPoints -> 30]      These two plots look like: ![The 3-D plot](http://i.stack.imgur.com/tvjcJ.png) ![The contour plot](http://i.stack.imgur.com/hc3qA.png) I would also love it if I could get 'grids' on the sides of the box like in http://en.wikipedia.org/wiki/File:GammaAbsSmallPlot.png


title: Compile Determinant

text: I would like to determine the determinant of a 4x4 matrix with the entries `a[i,j]` being functions of $i$ and $j$. I used Compile with code: * * *               m4 = Table[a[i, j], {i, 4}, {j, 4}];          variable = Det[m4];     soln = Compile[{{a[i, j], _Real}}, Evaluate[variable]];          soln       * * * How do I declare that the function `a[i_,j_]` can be an arbitrary real number? The terms of `Det[m4]` are output correctly but Mathematica does not recognise `a[i,j] = 0` for $i=j$. Can you help, please?


title: NDSolve: EventAction list specification using Table fails

text: I have an NDSolve problem that needs a list of a large number of events that are generated programmatically. Here is a simple example that demonstrates the problem on Mathematica 7 and 8 (the versions I have access to):               NDSolve[       {y''[t] == 10, y[0] == 0, y'[0] == 0},       {y},       {t, 0, 1},       Method -> {"EventLocator",         "Event" :> {y[t] - 2, y[t] - 1},         "EventAction" :>(*{Throw[Print["i=",1],"StopIntegration"],Throw[          Print["i=",2],"StopIntegration"]}*)          Table[Throw[Print["i=", i], "StopIntegration"], {i, 3}]         }       ];      The code as it is does not work (the second event should be triggered first, and it prints `i=1`), but if I use the commented block in `EventAction`, it does work, and prints `i=2`. What is the right syntax to make this work? Thanks for any help!


title: Efficiently Constructing Rank One Approximations for a Matrix using SVD

text: Suppose I have a $m\times n$ matrix $A$ (real for simplicity). Then `SingularValueDecomposition[A]` yields 3 matrices $U$, $\Sigma$ and $V$ such that $A = U\Sigma V^\top = u_1 \sigma_1 v_1^\top + u_2 \sigma_2 v_2^\top + \cdots$, where $U = [u_1\;\; u_2 \ldots]$ (vector = column matrix). Successive approximations for $A$ are given by the rank 1 matrices $u_1 \sigma_1 v_1^\top$, etc. I wanted to make a function to compute this but found myself doing all sorts of messy manipulations due to Mathematica's matrix structure (and/or my lack of knowledge on how to use them). Here is my tentative function. It has as input any matrix A and an optional argument n saying how many rank 1 matrices should be summed. This function is not meant to be numerically fast or anything; perhaps I would use it as a educational tool to examine different approximations of A or etc. The point is in the `Sum` function where I would like to know: is there a more efficient (or perhaps cleaner) way of doing the matrix multiplications?               RankOneApprox[A_, n_: 1] := Block[{U, Sig, V},          {U, Sig, V} = SingularValueDecomposition[A];          Sum[Sig[[i,i]] ({U[[All, i]]}\[Transpose].{V[[All, i]]}), {i, 1, n}]];


title: How to align rotated tick labels?

text: How can I align tick labels so the tick label text ends centered under the data point? Of Course it works fine with a rotation of 90 Degrees, but not with 45 or similar angles. I see an example of how to do this charts but not with Plot or ListPlot http://mathematica.stackexchange.com/a/2656/388               d = Table[n, {n, 10}];     xticks = Table[{n,      Rotate["The y value is " <> ToString[n], 45 Degree]}, {n, d}];     ListPlot[d, Frame -> True,       FrameTicks -> {{Automatic, None}, {xticks, None}}]      ![Labeled list plot](http://i.stack.imgur.com/npnsK.png)


title: When to make (file.nb) instead of (file.cdf)?

text: I started with **File > New > FreeCDF** so I can save my work in a format compatible with the CDF Player. I can use Mathematica to make new cells, evaluate input and so in the CDF file. What are the differences between using **File > New > FreeCDF** and **File > New > Notebook**? I suppose there are cases when you want to use `file.nb` instead of `file.cdf` but what are they?


title: Optimizing a function involving NDSolve results in error messages

text: I want to minimize a function `f` with `NMinimize` but an error occurs that says:               f[l_] := (       kk = NDSolve[{y'[x] == 2*x + 3, y[l] == 0}, y, {x, 0, l}];       out = Evaluate[y[0] /. kk];       out[[1]])          NMinimize[{f[t], 0 <= t <= 10}, f, t]      > During evaluation of In[18]:= NDSolve::ndsv: Cannot find starting value for > the variable y. >> > > During evaluation of In[18]:= ReplaceAll::reps: > {NDSolve[{(y^[Prime])[x]==3+2 x,y[{t}]==0},y,{x,0,{t}}]} is neither a list > of replacement rules nor a valid dispatch table, and so cannot be used for > replacing. >> > > During evaluation of In[18]:= NMinimize::argrx: NMinimize called with 3 > arguments; 2 arguments are expected. >> >   >   >     Out[18]= NMinimize[{y[0], 0 <= t <= 10}, f, t] >   How can I fix the function `f` to avoid this problem?


title: Indices and variable definitions in Mathematica

text: Does anyone know how I can do this in Mathematica? Just an example.. Defining indices and variables (defined over indices), "mapping" variables and indices:               index i {NewYork,LosAngeles,Chicago}     Subindex j {NewYork,LosAngeles}     Index k {a,b,c}          variable costs = costs(i,k)     variable size = size(i)     variable biggest = biggest (j,k)      After that, I can start my calculations..               costs(i,k)=...      What about the notation package? Does it help? Thanks!!


title: Passing a variable messages list to Quiet

text: I'm trying to build a Verbose option into some code but I'm having trouble passing to a `Quiet` statement a variable list of which messages I want to suppress. My naïve try is code along the lines of               f[x_] := Module[{messageList},       messageList = {Power::infy};       Quiet[1/x, messageList]       ]     f[0]      The idea would then be to build an option `Verbose` which controls whether the assignment `messageList = {Power::infy}` is made, or whether that variable is set to `{}`, which will let the message through. However, even this bare-bones code is not working, and it returns messages of the sort               Quiet::anmlist: Argument 2 of Quiet[1/0,messageList$1303]           should be All, None, a message name, or a list of message names. >>      (though obviously the number after `messageList$` changes every time). * * * ### Edit It seems, from a discussion in the comments, that two things are important (though I don't understand why). First of all, not all error messages are treated equally (as shown e.g. by running `Evaluate[{Power::infy, FindRoot::lstol}]`) so to give a better example, here is one with the error I'm interested in, `FindRoot::lstol`:               g[a_] := Module[{verbose = True, messageList},       If[verbose,        messageList = {},        messageList = {FindRoot::lstol}        ];       Quiet[        FindRoot[x^2 + x + a, {x, 3}]        , messageList]       ]     g[1]      It is also important to me to be able to control, from within the function (and eventually with an `OptionsPattern[]` that contains `Verbose->True` or `False`) whether the message list that gets passed is `{}` or a nontrivial one. I'm not picky about how it gets there (i.e. `messageList = If[verbose, {}, {FindRoot::lstol}];` would serve just fine) but it does need to have at least that level of logic built in. * * * What is the correct way to do this?


title: Flipping x-tick-labels on custom plot

text: I'm slightly new to the world of Mathematica, so I can't assess the difficulty of my request, but anyhow, this is my question: I have 2 datasets that I want to plot with two y axes, and a reversed x axis. (as to 'why do you want a reversed x-axis': the time parameter is in thousand years before present, which decreases in value as time moves forward, such that 0 is the present day) The data is the following:               area = {{0, 443.387}, {1, 443.387}, {2, 443.387}, {3, 443.387}, {4,       443.387}, {5, 444.06}, {6, 445.406}, {7, 446.751}, {8, 447.424}, {9,      698.385}, {10, 718.57}, {11, 734.044}, {12, 772.395}, {13,       822.856}, {14, 878.7}, {15, 5933.58}, {16, 6837.85}, {17,       7254.32}, {18, 7362.65}, {19, 7458.86}, {20, 7540.94}, {21,       7621.01}}                    ;     distance = {{0, 10.3807}, {1, 10.3807}, {2, 10.3807}, {3, 10.3807}, {4,       10.0923}, {5, 10.0923}, {6, 10.0923}, {7, 10.0923}, {8,       10.0923}, {9, 9.69003}, {10, 9.65897}, {11, 9.65897}, {12,       9.35579}, {13, 8.94344}, {14, 8.22982}, {15, 7.4932}, {16,       6.66484}, {17, 5.21611}, {18, 5.21611}, {19, 4.47083}, {20,       3.94395}, {21, 3.72562}}     ;      I made a YY-plot code using this code: http://mathematica.stackexchange.com/a/647/11219, which produces: ![YY_plot-example](http://i.stack.imgur.com/wI5og.png) And then reversed the original data using the code as found here: http://mathematica.stackexchange.com/a/5717/11219, which should reverse both the data and the axis ticks. ![enter image description here](http://i.stack.imgur.com/4Ddi2.png) As I hope you can see: the data is transformed correctly, the labels on the x-axis are not. So in combining the two codes I found, I broke the Ticks on the x-axis. Is it possible to fix this? Even a manual setting of the labels is fine with me, all my plots have the same data range from 21--0. The current code is:               TwoAxisListLinePlot[{f_, g_}] :=       Module[{fgraph, ggraph, frange, grange, fticks,         gticks}, {fgraph, ggraph} =         MapIndexed[         ListLinePlot[#, Axes -> True, PlotStyle -> ColorData[1][#2[[1]]],            Mesh -> Full,           Ticks -> ({Transpose[({#[[1]],                      Reverse@#[[2]], #[[3]], #[[4]]} &@                   Transpose[Sort@#[[1, 2, 1]]])], #[[1, 2, 2]]} &@              AbsoluteOptions[ListLinePlot@#1, Ticks])           ] &, {f, g}]; {frange, grange} =         Last[PlotRange /. AbsoluteOptions[#, PlotRange]] & /@ {fgraph, ggraph};       fticks =         Last[Ticks /.            AbsoluteOptions[fgraph,             Ticks]] /. _RGBColor | _GrayLevel | _Hue :> ColorData[1][1];       gticks = (MapAt[Function[r, Rescale[r, grange, frange]], #, {1}] & /@            Last[Ticks /.              AbsoluteOptions[ggraph,               Ticks]]) /. _RGBColor | _GrayLevel | _Hue -> ColorData[1][2];       Show[fgraph,         ggraph /.          Graphics[graph_, s___] :>           Graphics[           GeometricTransformation[graph,             RescalingTransform[{{0, 1}, grange}, {{0, 1}, frange}]], s],         Axes -> False, Frame -> True,         FrameStyle -> {ColorData[1] /@ {1, 2}, {Automatic, Automatic}},         FrameLabel -> {"Years before present [ka]", "Area [km\.b2]", "",           "Isolation [km]"},        FrameTicks -> {{fticks, gticks}, {Automatic, Automatic}}]]      And then run as               k1 = Transpose@({Reverse[#[[1]]], #[[2]]} &@Transpose@area);     k2 = Transpose@({Reverse[#[[1]]], #[[2]]} &@Transpose@distance);     TwoAxisListLinePlot[{k1, k2}]


title: Determinant of a random matrix consisting of integers

text: I am trying to implement a function that finds the determinant of a random matrix consisting of integers. This is the code I have written so far, but I am stuck. Suggestions ? I want to find a solution without Det[M].               M := RandomInteger[{-10, 10}, {8, 8}]          det[M_ /; Dimensions[M][[1]] == Dimensions[M][[2]]] := Module[{i, d},     If[N == 2,     Drop[Mi, {1, 1}, {1, 1}][[1, 1]]*Drop[Mi, {1, 1}, {1, 1}][[2, 2]] -      Drop[Mi, {1, 1}, {1, 1}][[1, 2]]*      Drop[Mi, {1, 1}, {1, 1}][[2, 1]],      For[i = 1, i <= Length[M], i++,      d = d + (-1)^(1 + i) *M[[1, i]]*        Minors[Drop[M, {1, 1}, {i, i}],            Length[Drop[M, {1, 1}, {i, i}]]][[1]][[1]]]];      Return[d, Module]]     det1[Mi_ /; Dimensions[Mi][[1]] == Dimensions[Mi][[2]]] :=      Module[{det1},     det1 = Sum[     If[det1 == 1,       Break[], (-1)^(1 + j) *Mi[[1, j]]*det1[Drop[Mi, {1}, {j}]]], {j,       1, Length[Mi]}]; Return[det1 // MatrixForm, Module]]     det1[M_ /; Dimensions[M][[1]] == Dimensions[M][[2]]] :=     Module[{i, d = M},     For[i = 1, i <= Length[d], i++,     If[Length[M] == 1, Goto[end]      If[Length[M] == 2,        d = Drop[d, {1}, {1}][[1, 1]]*Drop[d, {1}, {1}][[2, 2]] -          Drop[d, {1}, {1}][[1, 2]]*Drop[d, {1}, {1}][[2, 1]];        Goto[end], d = d + (-1)^(1 + i) *d[[1, i]]*Drop[d, {1}, {i}]];     Label[end]; Return[d, Module]]]]     det1[M_ /; Dimensions[M][[1]] == Dimensions[M][[2]]] :=     Module[{i, d = M},     For[i = 1, i <= Length[d], i++,      Switch[d, 1, Goto[end], 2,      d = Drop[d, {1}, {1}][[1, 1]]*Drop[d, {1}, {1}][[2, 2]] -        Drop[d, {1}, {1}][[1, 2]]*Drop[d, {1}, {1}][[2, 1]];      Goto[end], _,     d = d + (-1)^(1 + i) *d[[1, i]]*Drop[d, {1}, {i}]];      Label[end]; Return[d, Module]]]     Return[Determinant[Mi]]


title: Saving data inside a notebook so that I don't have to run it again?

text: Piggybacking on this, I am somehow not fully convinced that I can't save data generated by a calculation in a mathematica file so that when I re-launch said file, I wouldn't have to run my calculations again. I ask because I use `NDSolve` for 4th order non linear PDEs and sometimes I need to run it for really large times (in excess of a few hours, yes that sounds crazy but I am just trying to get results for a fluid dynamics problem here and I am not all that interested in being a computer scientist to reduce run times). So after reading the linked article, I did this for an example problem:               sol = NDSolve[{D[u[t, x], t] == D[u[t, x], x, x], u[0, x] == 0,         u[t, 0] == Sin[t], u[t, 5] == 0}, u, {t, 0, 10}, {x, 0, 5}]          DumpSave["pde0.mx", sol]      Then I quit mathematica and relaunch it and load `pde0.mx` with `Get`               Get["pde0.mx"]      And when I plot,               Plot3D[Evaluate[u[t, x] /. sol], {t, 0, 10}, {x, 0, 5},       PlotRange -> All]      Voila, I get the plot as if I had run the simulation. So.. did I run the simulation again by invoking `sol` through `Get` or was my kernel state saved?


title: How to check if a 2D point is in a polygon?

text: Background: I use code from An Efficient Test For A Point To Be In A Convex Polygon Wolfram Demonstration to check if a point ( mouse pointer ) is in a ( convex ) polygon. Clearly this code fails for non-convex polygons. **Question: I am looking for an efficient routine to check if a 2D-point is in a polygon.**


title: How to judge if a point is in the interior of a closed curve or not?

text: For example:               pts = {{0, 1}, {-(Sqrt[3]/2), -(1/2)}, {Sqrt[3]/2, -(1/2)}};     trig=JoinedCurve[Line[pts], CurveClosed -> True];      Then `trig` is a closed triangle. If I have a point `p={a,b}`, how can I judge if `p` is in the interior of the triangle `trig`?


title: How to calculate the analytical result of this singular integral?

text: I'm trying to solve this integral: $I(a,b)=\displaystyle{\int_1^{\infty }\dfrac{e^{-ax}}{\sqrt{x^2-1} (1+x\sqrt{1-b^2}) (x-1/\sqrt{1-b^2})} \, dx} \,\, \,\,(a \;\textrm{real>0} \, , 0<b<1)$ by varying b from 0 to 1. Mathematica didn't calculate this integral. Maybe it is too complicated to be done. In Mathematica input form:               Integrate[Exp[-a x]/(Sqrt[x^2 - 1](1+x Sqrt[1-b^2])(x-(1/Sqrt[1-b^2]))), {x,1,Infinity}]      If I simply enter that into Mathematica, it instantly returns the same expression. How do I go about this? Is there any tricks that can be applied? Is there a way to get the a symbolic result? Thank's.


title: Is it possible to change the fontsize when printing a notebook in the working enviroment?

text: I want to print a notebook that owns syntax color,I use the Szabolcs's method               SetOptions[$FrontEndSession, PrintingStyleEnvironment -> "Working"]      Then I can achieve a PDF file shown as below: ![Working Enviroment](http://i.stack.imgur.com/CoA15.png) However,when I change the `PrintingStyleEnvironment to "Printout"`               SetOptions[$FrontEndSession, PrintingStyleEnvironment -> "Printout"]      ![Printout Enviroment](http://i.stack.imgur.com/3tM4q.png) I feel the fontsize in the `Working Enviroment` is more large than `Printout Enviroment`. So my question is: **How to make the fontsize in`Working Enviroment` be same with `Printout Enviroment`.** **I feel the fontsize in`Printout Enviroment` is very suitable.**


title: Breaking up data and finding independence

text: Suppose I have the list with elements (either 1 or 4 as the last digit) as follows:               data=     {{42, 49.11, 1}, {41, 49.32, 4}, {41, 48.21, 4}, {41, 53.08, 1}, {39,        46.22, 1}, {39, 47.06, 1}, {47, 48.87, 4}, {41, 49.64, 1}, {41,        48.44, 1}, {42, 49.98, 4}, {39, 49.04, 1}, {46, 48.73, 1}, {49,        48.33, 4}, {39, 50.95, 1}, {42, 46.05, 4}, {49, 52.52, 1}, {49,        48.81, 1}, {49, 50.75, 4}, {47, 52.39, 1}, {41, 52.56, 1}, {40,        56.01, 4}, {46, 52.77, 4}, {43, 52.81, 1}, {39, 50.37, 1}, {40,        52.38, 1}, {49, 51.31, 4}, {48, 54.26, 4}, {40, 53.3, 4}, {42,        50.62, 4}, {48, 49.66, 4}, {43, 51.39, 4}, {41, 59.23, 4}, {41,        49.07, 4}, {40, 51.43, 4}, {39, 54.47, 4}, {49, 50.4, 4}, {48,        51.04, 1}, {46, 47.95, 1}, {45, 50.52, 4}, {44, 53.18, 1}}      How do I break it into two sets with the same last digit, such that               data1={{42, 49.11, 1},  {41, 53.08, 1}, {39,        46.22, 1}, {39, 47.06, 1}, {41, 49.64, 1}, {41,        48.44, 1}, {39, 49.04, 1}, {46, 48.73, 1}, {39, 50.95, 1},       {49, 52.52, 1}, {49, 48.81, 1}...}      and               data2={{41, 49.32, 4}, {41, 48.21, 4}, {47, 48.87, 4},{42, 49.98, 4}, {49,        48.33, 4},  {42, 46.05, 4}, {49, 50.75, 4},  {40,   56.01, 4}, {46, 52.77, 4}..}      How do I test whether these two data sets are linearly independent?


title: Why does this simple program leak memory?

text: I have a simple Mathematica program which writes some plots to image files for later conversion into a movie. Unfortunately, the program leaks so much memory that it quickly exhausts all 12G of RAM on my machine. The only way out is to quit the kernel(s). I can't see why this program shouldn't use a bounded amount of memory. I've read through Debugging memory leaks which unfortunately hasn't helped - the only "heavy" symbol is 'data', whose size is fixed. I don't see what's growing! Note that the same problem occurs regardless of whether the loop is Map or Do, Parallel- or not. The problem also occurs in both Mathematica 8 and 9, both under Linux. Help?               (* number of frames *)     n = 1000;     (* just some bogus data *)     makeData[_] := Table[{{x, y} = RandomReal[{-3, 3}, {2}], {y, -x}}, {200}];     data = Array[makeData, n];     (* Export the frames *)     ParallelMap[       Export[         "movie-" <> IntegerString[#, 10, 4] <> ".png",         ListVectorPlot[data[[#]]]] &,       Range[1, n]];      **Edit** :   Some more information: after running this code (the non-parallel version), I checked the memory usage of the processes involved. The percentages are out of 12GB, so both the frontend and the kernel are consuming quite a bit of memory, while PNG.exe is almost nonexistent.                 PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND                 24575 gredner   20   0  4400  740  588 S    0  0.0   0:00.00 Mathematica             24646 gredner   20   0 3029m 2.3g  22m S    0 20.5   1:43.02 Mathematica             24655 gredner   20   0 3384m 1.6g  14m S    0 13.7   3:31.47 MathKernel              24984 gredner   20   0  387m 7364 2464 S    0  0.1   0:20.92 PNG.exe


title: PolynomialRemainder memory

text: This calculation makes the kernel crash because it needs so much memory. Thoughts on how to get around this?               PolynomialRemainder[1+x^267910657,1+x+x^20+x^32, x, Modulus->2]


title: Complex infinities in an Euler-Lagrange equation

text: I now wish to solve for $L(t)$ and $H(t)$ some ugly Lagrangian (in the code below) in configuration space, respectively the length and the height of a system. I tried running the code below, with the boundary conditions $ L(0)=\frac{2}{3},L(10)=1, H(0)=0,H(10)=1$               << VariationalMethods`     lagr = EulerEquations[(L'[t]^2 + H'[t]^2)/2 +      1/L[t]^8 (0.939047619047619 L[t]^8 +         H[t]^3 L[          t]^2 (0.008947123427519658 - 0.3461214643843182 L[t]^2 +            6.463704237990063 L[t]^4 - 112.66974752093684 L[t]^6 -            61.714285714285715 L[t]^7) +         H[t]^4 (0.0004134154745845219 - 0.017673330227199326 L[t]^2 +            0.34184835988574624 L[t]^4 - 4.255936946824733 L[t]^6 +            55.63938149182066 L[t]^8 + 27.08994708994709 L[t]^9) +         H[t]^2 L[          t]^4 (0.05911127889691029 +            L[t]^2 (-2.2077672911653297 +               L[t] (2.1333333333333333 +                  L[t] (57.725858297763935 +                     36.888888888888886 L[t]))))), {L[t], H[t]}, t];     sln = NDSolve[{lagr, L[0] == 1, L[10] == 2/3, H[0] == 1,      H[10] == 0}, {L[t], H[t]}, {t, 0, 10}]      only to get some nonsensical error messages:               Power::infy: "Infinite expression 1/0.^6 encountered."     Infinity::indet: "Indeterminate expression -338.009+ComplexInfinity+ComplexInfinity+ComplexInfinity encountered."     NDSolve::ndnum: Encountered non-numerical value for a derivative at t == 0.`.       In my mind, these messages would appear because there are complex-valued terms as well as having a point where $L = 0$, while, in fact, all coefficients are real and I would expect the solution never to cross $L=0$. However, I can't pin down what's the problem with the third message error... Perhaps I might have misunderstood the equation...


title: Have I found a big difference between using the short form and the long form of a pure function?

text: By referring to the _Mathematica_ documentation, I learned to use `##2` to represent all the arguments but the first one. This is a brief way to represent a pattern matching all arguments but the first one. However, how can I do the same thing in the long `Function[args. body]` form? For example, `{##2}& @@ f[x1, x2, x3, x4]` will give `{x2, x3, x4}`. Unfortunately, `Function[{u1, u2}, {u2}] @@ f[x1, x2, x3, x4]` only gives `{x2}`. I think this occurs because the long form does not interally contain pattern matching functionality, although I find this hard to believe. So my question is whether the long form really ignores the functionality of pattern matching? In general, are these two pure function forms identical in every aspect? That is, is the short form is just a shortcut for the long form?


title: NVCC running CUDA in Mathematica 9.01 CudaCCompiler[] fails

text: This is an old thread that received no responce but like to post again. Anyone here using Mathematica and CUDA? I have not been able to have Mathemartica detect teh CUDA able C compiler. CUDACCompiler[] returns empty. I have tried the following and no results get teh following error               CreateLibrary::target: Target system specification "TargetSystemID" -> Windows-x86-64 is not available for NVIDIA CUDA Compiler installation C:\Users\jecalderon\AppData\Roaming\Mathematica\Paclets\Repository\CUDAResources-Win64-9.0.2.0\CUDAToolkit\bin\. >>


title: Notation for numerical solutions to differential equations

text: Can somebody explain this notation to me? Using _Mathematica_ 's first example in the `NDSolve` documentation:               s = NDSolve[{y'[x] == y[x] Cos[x + y[x]], y[0] == 1}, y, {x, 0, 30}]      The output is:               {{y -> InterpolatingFunction[{{0.,30.}}, <>]}}      What do all the curly brackets and the angle signs indicate? Why is there no indication of dependence on `x`? I'm also curious why you have to use this result in what I consider to be an awkward way:               Plot[Evaluate[y[x] /. s], {x, 0, 30}, PlotRange -> All]      as opposed to simply:               Plot[s, {x, 0, 30}, PlotRange -> All]


title: Eliminate several variables between five Conic_section equations

text: I want to eliminate `x1, x2, y1, y2` between these 5 equations. I tried               Eliminate[{x1^2/a^2 + y1^2/b^2 == 1, x2^2/a^2 + y2^2/b^2 == 1,        x1 x2 + y1 y2 == 0, y2/(x2 - c) == y1/(x1 - c) == k}, {x1, x2, y1, y2}]      Mathematica takes a long time, I couldn't even wait for it to finish.Can you recommend an efficient method? **Updated:** http://en.wikipedia.org/wiki/Proportionality_(mathematics)               ForAll[{a, b}, b d != 0 && b^2 != d^2,       Equivalent[a/b == c/d,        a/b == c/d == (a - c)/(b - d) == (a + c)/(b + d)]]     Resolve[%]     (*True*)            k^2 /. Solve[          Eliminate[{x1^2/a^2 + y1^2/b^2 == 1, x2^2/a^2 + y2^2/b^2 == 1,           x1 x2 + y1 y2 == 0, y2/(x2 - c) == (y1 - y2)/(x1 - x2) == k}, {x1, x2, y1, y2}],         k] // DeleteDuplicates//Tr          (* (a^2 b^2)/(-a^2 b^2 + a^2 c^2 + b^2 c^2) *)


title: Slideshow mode: how to cycle slides automatically?

text: I'm doing a slideshow for an informative conference, so I need a slideshow running in background on some monitors. My question is: is there any way to make _Mathematica_ to cycle slides automatically? `Manipulate`, `Animate` and `SlideView` have the "Play" button by which one can set the speed. I'd need something similar for the slideshow. Any idea is welcome, also those which require the editing of notebook code.


title: Solving stochastic master equation

text: Can someone help please me in solving the following stochastic master equation for the density matrix $\rho$? ![enter image description here](http://i.stack.imgur.com/59yTx.png) where $\rho$ is the density matrix, $\sigma_i$ are the pauli matrices, $dt$ is the time, $dW$ shows the Wiener increment and ![enter image description here](http://i.stack.imgur.com/Jp1DK.png) The other parameters are constants and $[a,b]$ shows commutator of the operator $a$ and $b$


title: How to find monotonically increasing intervals of a function

text: I tried this code, but not working               Clear[f];     f[x_] := x^3 - 3 x + 2;     ForAll[{x1, x2}, x1 < x2, f[x1] < f[x2]]     Reduce[%, {x1, x2}, Reals]      I expected the result is `x<=-1 || x>=1`


How do we solve third order nonlinear differential equation f’’’+ff’-f’2-Re2 f’=0 f(0)=0,f'(0)=1,f(Infinity)=0 From the OP's comment: > >     ic1 = 0; ic2 = 0; ic3 = 1 a = 0.0; >     sol = NDSolve[{y'''[x] + y[x] y'[x] - y'[x]^2 - a^2 y'[x] == 0, >       y[0] == ic1, y'[Infinity] == ic3, y'[0] == ic2}, y[x], PlotRange]; >     Plot[y[x] /. sol, {x, 0, finish}]. >   > > I have used this code to solve using mathematica but i didnt get it


title: Only String Keys supported in Dataset's Association Query?

text: Given data:               titanic = ExampleData[{"Dataset", "Titanic"}]      This Association Query works:               titanic[All, <| "newKey" -> "age"|>]      But numeric or Symbol Keys,               titanic[All, <| 1 -> "age"|>]     titanic[All, <| newKey -> "age"|>]      fail with error: `Missing[KeyAbsent]`. Known issue? Numeric keys are especially conveninent for multiple, parametrized queries. Currently, that requires the workaround `KeyMap[ToString]` and later back `ToExpression`.


title: Is it possible to embed the Mathematica editor?

text: Is it possible to embed a Mathematica window into a .NET application? I mean not just the interop, but actually making the notebook editor window part of a .NET form. Is this possible?


How to define a function $f(x)$ such that $f(1.5)=1.5$, $f(1.)=1$, $f(0.)=0$, etc.? Namely, if $x$ is an integer with a decimal point, $f(x)$ returns the integer only, otherwise returns $x$. This will be useful in the labels of the following plots.               Table[Block[{a = aa}, Show[Plot[x^a, {x, 0, 1}, PlotLabel -> Style[Row@{"a", "=", aa}, 15]]]], {aa, 0, 2, 0.5}]


title: How can I get an exponent vector from monomials?

text: I am trying to get an exponent vector from a list of monomials. I am using the `CoefficientRules` command; however, it is returning a list that includes the coefficients of the monomial. I don't need the coefficient and need to remove it before I can use the exponent vector, however I am finding this quite difficult.               poly = x^2 + 2 x*y + y^2;     monomialList = MonomialList[poly];     alpha = CoefficientRules[monomialList]          {{{2, 0} -> 1}, {{1, 1} -> 2}, {{0, 2} -> 1}}      Is there a way to remove the -> and the value that follows it, or a better way to generate the exponent vector?


title: What is the correct way to plot a dynamically generated list of functions?

text: For example, I want to generate a list of random waves and plot them. Then I wrote               f:=Random[Real]     h:=Floor[f*20]      And then               Manipulate[Plot[Table[f Sin[h x + h t], {n, 0, 5}], {x, -5, 5}, PlotRange -> {-2, 2}], {t, 0, 10}]      But it turned out a mess. I tried to fix it with               a = Table[f Sin[ h x + h t], {n, 0, 5}]     Manipulate[Plot[a, {x, -5, 5}], {t, 0, 10}]      But no graph was generated. Finally I tried               a = Table[f Sin[ h x + h t], {n, 0, 5}]     Manipulate[Plot[a /. t -> b, {x, -5, 5}], {b, 0, 10}]      This time the graph was correct. But there are still 2 problems:   1. All functions are in the same color.   2. It lags a lot when I tried to manipulate t. These problems don't exist if you write by hand the list inside plot. So what is the correct way to solve these problems and get the desired output?


title: johansen test error in code

text: ### Cross-posted at the Wolfram community forum I have found this code on a forum, apparently it worked in a previous version of mathematica. Now when I run it, it keeps running for ages. I am not able to find the error.                ewa = FinancialData["NYSE:EWA", {{2006, 4, 4}, {2012, 4, 9}}, "Value"];      ewc = FinancialData["NYSE:EWC", {{2006, 4, 4}, {2012, 4, 9}}, "Value"];      data = Transpose@{ewa, ewc};      johansenProcedure[levels_?MatrixQ, p_Integer] /;      (Dimensions[levels][[ 1]] > (Dimensions[levels][[2]] + p)) :=      With[{N = Dimensions[levels][[1]], T = Dimensions[levels][[2]],      diff = Rest[levels - RotateLeft[levels]], ypt = Drop[levels, -p]},      Module[{x, r0t, rpt, s00, sop, cc, λ, vλ, logλ},     x = Join @@ (Drop[RotateLeft[diff, #], p - 1] & /@ Range[p]);     With[{q = Inverse[Transpose[x].x], y0t = Drop[diff, p - 1]},     r0t = y0t - x.q.Transpose[x].y0t; rpt = ypt - x.q.Transpose[x].ypt; s00 = (Transpose[r0t].r0t)/T; s0p = (Transpose[r0t].rpt)/T;     cc = Inverse[CholeskyDecomposition[(Transpose[rpt].rpt)/T]];     {λ, vλ} = Eigensystem[(cc.Transpose[s0p].Inverse[s00].s0p.Transpose[cc])];     logλ = Log[1 - λ];     {Reverse[-T* FoldList[Plus, First[logλ], Rest[logλ]]],     Reverse[-T logλ], Join[Reverse[Transpose[Transpose[cc].vλ]], s00, s0p]} ]]];          johansenProcedure[data, 10]      This is the error code               Dot::dotsh: Tensors {<<1>>} and {{0.38,0.42},{-0.21,-0.27},{0.03,0.13},{0.,-0.03},<<44>>,      {0.04,0.02},{-0.56,-0.63},<<1455>>} have incompatible shapes. Dot::dotsh: Tensors {<<1>>} and {{0.38,0.42},{-0.21,-0.27},{0.03,0.13},{0.,-0.03},<<44>>,{0.04,0.02},{-0.56,-0.63},<<1455>>} have incompatible shapes.      On guy suggested that this line was broken:               r0t = y0t - x.q.Transpose[x].y0t;      rpt = ypt - x.q.Transpose[x].ypt;       I have spent ages but are not able to figure out what to do, could someone give it a try?


title: Processing and storing a graph with a large number of vertices s.t. k-hop neighborhoods are efficiently retrievable

text: I have an unweighted, undirected graph $G$ with $(v_1, ..., v_N) \in V$ vertices, where each vertex in the lattice represents a string of some length ($\leq 200$ characters), and I need to construct $G$ from an unordered list of edges between vertices (i.e. a list saying that vertex $v_i$ is connected to vertex $v_j$ for some $i \neq j$). Here, $||V||$ is very large, on order $10^{9}$ to $10^{12}$ or so, but the degree of each vertex $v_i$ is bounded by some small integer value s.t. the maximum vertex degree is $\Delta G\approx 16$. What is a good way to store or process $G$ in Mathematica (some sort of suffix tree or hash table?) s.t. I can efficiently retrieve a list of vertices in the $k$-hop neighborhood of some vertex $v_i$? By $k$-hop neighborhood, I mean the set of vertices that can be reached from $v_i$ by traveling along at most $k$ edges. * * * To provide an example, I might start with a list of vertices corresponding to unique binary strings: $v_1 = 10101011110...$ $v_2 = 01110100101...$ ... $v_N = 00000011110...$ And an unordered list of (undirected) edges between vertices: $v_{36544} \to v_{3}$ $v_{740943} \to v_{92034}$ $v_{36544} \to v_{674}$ ... Is there a nice / efficient way to process the about lists in Mathematica s.t. I can retrieve the set of nearest-neighbors for, say, $v_{36544}$, which includes $(v_{3}, v_{674}, ...)$? The naive way to proceed is to simply specify a graph structure as: Graph[{...}], but is this efficient for very large instances of $G$? * * * Update - OK, some data. Intel Xeon CPU (X5690) 3.47 GHz 64 bit system (No attempt at parallelization) Lookup time for the $k=1$ hop neighborhood of an arbitrary vertex (using NeighborhoodGraph[G]): G = 10 x 10 integer lattice: 27.4 milliseconds G = 50 x 50 integer lattice: 0.765 seconds G = 100 x 100 integer lattice: 3.08 seconds The scaling appears exactly linear with graph size: http://www.wolframalpha.com/input/?i=%7B0.0274%2C+10%5E2%7D%2C%7B0.765%2C2500%7D%2C%7B3.08%2C100%5E2%7D This is awful, especially considering that Mathematica can draw a spring minimized graph in relatively short order for the 100 x 100 integer lattice.


title: Generate a Random Polygon

text: Does some package exist with a function that takes a parameter $n$ and generates a random 2D $n$-sided **simple polygon** (convex or non-convex), possibly within a certain bounding box? It does not suffice to simply generate $n$ random points as I would have to figure out how to connect the points in a non-intersecting manner. I am sure there are algorithms to solve this particular problem, but I would much rather use a **ready-made function** that would be guaranteed to work, rather than code my own function and introduce more bugs. I am trying to generate a large number of "random" test cases for my algorithm that is supposed to work for all polygons.


title: NDSolve for a large system of coupled (complex valued) ODEs

text: The system under consideration here is a generalization of the one I discussed in this problem. Qualitatively, I am trying to solve a system of coupled nonlinear (up to order 4 in the dep variables) ODEs which can take on complex values. The governing equation for the $n-th$ ODE is of the form: $\sum_{k=-M}^M (Q_{nk}+Q_{kn}) \ddot{a}_k -\sum_{\ell=-M}^M\sum_{k=-M}^M S_n(\ell,k) \dot{a}_{\ell} \dot{a}_k + U_n = 0 $ where $Q_{nk}=\frac{1}{2}\sum_{j=1}^MP_{jn}P_{(-j)k}$, with $P_{mn}=\frac{\sqrt{|m|}}{|n|}(a_{m-n}-\frac{a_ma_{-n}}{2})$, (and the contsraints that $a_{m-n}=0$ for $|m-n|>M$ and $a_{m-n}=0$ when $Sign(m-n)=Sign(n)$), $S_n(\ell,k)=\left(\frac{\partial Q_{k\ell}}{\partial a_n}-\frac{\partial Q_{n\ell}}{\partial a_k}-\frac{\partial Q_{\ell n}}{\partial a_{k}}\right)$ and $U_n = \frac{\partial V}{\partial a_n}$ where $V = \frac{1}{8}\left(\sum_{n=1}^M\frac{a_na_{-n}}{n}\right)^2 +\frac{1}{2}\sum_{n=1}^M\frac{a_na_{-n}}{n^2} -\frac{1}{2} \left(\sum_{n=1}^M\frac{a_na_{-n}}{n})\right)\left(\sum_{n=1}^M\frac{a_na_{-n}}{n}\right) + \sum_{i+j+k=0,(i,j,k)\neq 0}\frac{a_ia_ja_k}{4ij}$ and $M$ is the highest mode under consideration. In the limit of small $a_i$, these governing equations reduce to a system of harmonic oscillators of the form $\ddot{a}_i=-ia_i$, so I've been exploring the solutions with initial conditions that should reproduce this and give solutions of the form $a_n(t)= e^{int}$. When I set this system up in Mathematica, I can find coherent solutions for the $M=1,M=2$ cases. However, for $M=3$ the integration takes a very long time (so far more than 6 hours) so something is awry. The bottleneck seems to be occurring at the NDSolve portion of the code, as I think I've executed all HoldAll's that could be causing time issues. For the simpler system linked above (where all coefficients are real) I was able to integrate the $M=50$ cases in about 1 hour, so I'm trying to see why NDSolve would be taking longer in this case. I note that in that case the system was "treated as a system of differential-algebraic equations". The equations in this example are not treated as DAE, since this complicates finding appropriate ICs and I experience a "mconly" error. This could be one reason for large discrepancies in run time. Finally, there is a relationship between the coefficients such that $a_{-k} =a^*_k$ which I have not exploited and could potentially cut the number of dependent variables in half. Any insights into getting larger M cases to integrate, or why this is taking so long in its current state, would be greatly appreciated. Thanks, Nick               M = 3; (*Number of modes*)     cond1[r_, s_] := If[Sign[s] == Sign[r - s], 0, 1];     cond2[r_, s_] := If[Abs[r - s] > M, 0, 1];      F[n_] := If[n == 0, 1, Abs[n]];     a[0][t_] := 1;     P[m_, k_, t_] :=      Sqrt[F[m]]/     F[k]*(cond1[m, k]*cond2[m, k]*a[m - k][t] -       1/2*a[m][t]*a[-k][t]) ;       Q[k_, l_, t_] = 1/4*Sum[P[m, k, t]*P[-m, l, t], {m, 1, M}];     q[m_, k_, n_, t_] :=      Sqrt[F[m]]/     F[k]*(cond1[m, k]*cond2[m, k]* Boole[m - k == n] -       a[m][t]/2*Boole[-k == n] - a[-k][t]/2*Boole[m == n]);     SQ[k_, l_, n_, t_] :=      1/4*Sum[P[-m, l, t]*q[m, k, n, t] + P[m, k, t]*q[-m, l, n, t], {m,       1, M}];     SS[k_, l_, n_, t_] := (SQ[k, l, n, t] - SQ[n, l, k, t] - SQ[l, n, k, t]);     Fu[a_, b_, c_] := If[a + b + c == 0, 1, 0];      Fu2[a_] := If[a == 0, 0, 1];     V[t_] := Evaluate[     1/2*(Sum[-a[n][t]*a[-n][t]/(2*n), {n, 1, M}]^2 +        2*Sum[a[n][t] a[-n][t]/(4*n^2), {n, 1, M}] +        Sum[-a[n][t]*a[-n][t]/(2 n), {n, 1, M}]*        Sum[a[n][t] a[-n][t]/n, {n, 1, M}] +        Sum[Fu[n, m, o]*Fu2[n]*Fu2[m]*a[n][t]*a[m][t]*a[o][t]*         Abs[o]/(4 Abs[F[n]*F[m]*F[o]]), {n, -M, M}, {m, -M,          M}, {o, -M, M}])];      U[n_, t_] := Evaluate[D[V[t], a[n][t]]];      Gov[n_, t_] :=      Sum[a[l]''[t]*(Q[n, l, t] + Q[l, n, t]), {l, -M, M}] -      Sum[SS[k, l, n, t] a[k]'[t] a[l]'[t], {k, -M, M}, {l, -M, M}] +      U[n, t];     ao = 0.01;     eqns2 = {     Evaluate[Gov[-3, t] == 0],     Evaluate[Gov[-2, t] == 0],      Evaluate[Gov[-1, t] == 0],     Evaluate[Gov[1, t] == 0],      Evaluate[Gov[2, t] == 0],      Evaluate[Gov[3, t] == 0],     a[1][0] == a[-1][0] == ao,      a[1]'[0] == I*ao, a[-1]'[0] == -I*ao,      a[2][0] == a[-2][0] == ao^2,      a[2]'[0] == ao^2*I*2,      a[-2]'[0] == -ao^2*I*2 ,      a[3][0] == a[-3][0] == ao^3,      a[3]'[0] == 3*I*ao^3,     a[-3]'[0]==-3*I*ao^3     };     MMode = NDSolve[     eqns2, {a[-3][t],a[-2][t], a[-1][t], a[1][t], a[2][t], a[3][t]}, {t, 0, 10}, Method ->      {"EquationSimplification" -> "Solve"}]


title: The best method of constructing a product of consecutive terms

text: I am new to _Mathematica_ , I am searching for a way to create an expression with a sequence of terms such as:               (x-1)/x  (x-2)/x  (x-3)/x  (x-4)/x … (x-n)/x


title: How can I create input fields based on the user's choice from a popup menu?

text: I'm trying to create an interface with _Mathematica_. However, I need some instructions concerning the code below. This is about 10% of what I have in mind, but first I need to know how can I create `ns` `InputField`s after `ns` is defined by the user making a choice from the popup menu.               ns : number of station     sf : sound frequency     ws : width of window      * * *               CreateWindow[       DialogNotebook[       {         TextCell["Number of Stations: "],         PopupMenu[Dynamic[ns], Range[2, 8]],              TextCell["Sound Frequency (kHz): "],         InputField[Dynamic[sf], String, FieldSize -> 7],              TextCell["Window Size (ms): "],         InputField[Dynamic[ws], String, FieldSize -> 7],              TextCell["Calculation Start relative to the Window (ms): "],         InputField[Dynamic[cs], String, FieldSize -> 7],              ChoiceButtons[{DialogReturn[{retNS = ns, retSF = sf, retWS = ws, retCS = cs}]}]       },       WindowTitle -> "Fluvial Acoustic Tomography Configuration"]];


title: List all possible elements of a set

text: I have this two sets: $A = \\{\emptyset, \\{\emptyset\\}, \\{\\{\emptyset\\}, \emptyset\\}\\}$ $B = \\{\\{x, \\{x, y\\}\\} | x \in A, y \in A\\}$ Now I want to list all possible elements that are in $B$. How do I do this?


title: Convert a string to hex number?

text: How can I convert a string containing a hex number such as `"6b"` to a hex digit that _mathematica_ can use to do math with? I have tried using `ToExpression["6b"]` but that just give me another string. Note: Java's `BigInteger`class can construct hex integers from strings. Is there something like this in _mathematica_?


title: How to solve a non-linear equation?

text: I am trying to solve the following non-linear equation: $\frac{i e^{-x^2} \sqrt{\pi } x}{K^2}+\left(-0.131251-0.0379031 x^2-0.0151154 x^4-0.0100462 x^6+0.5 \left(0.00273859 +0.0400003 K^2\right) x^8+(0. +0.0000362178 i) x^9+0.5 \left(\text{6.72230790401107$\grave{ }$*${}^{\wedge}$-6}+0.000122761 K^2\right) x^{10}+(0. +\text{7.371834962565406$\grave{ }$*${}^{\wedge}$-8} i) x^{11}+0.5 \left(\text{3.049800199384706$\grave{ }$*${}^{\wedge}$-9}+\text{7.195529551699709$\grave{ }$*${}^{\wedge}$-8} K^2\right) x^{12}+(0. +\text{3.611964212904051$\grave{ }$*${}^{\wedge}$-11} i) x^{13}+0.5 \left(-\text{1.2612171276659422$\grave{ }$*${}^{\wedge}$-12}-\text{1.7472476684229308$\grave{ }$*${}^{\wedge}$-11} K^2\right) x^{14}+\text{2.7423509229173302$\grave{ }$*${}^{\wedge}$-15} K^2 x^{16}\right)/\left(0.0200001 K^2 x^8+0.0000613803 K^2 x^{10}+\text{3.5977647758498545$\grave{ }$*${}^{\wedge}$-8} K^2 x^{12}-\text{8.736238342114654$\grave{ }$*${}^{\wedge}$-12} K^2 x^{14}+\text{2.7423509229173302$\grave{ }$*${}^{\wedge}$-15} K^2 x^{16}\right)$ Here's the _Mathematica_ code I used:               Solve[(I E^-x^2 Sqrt[\[Pi]] x)/         k^2 + (-0.13125090233975123 - 0.037903065816010294 x^2 -            0.015115427229185784 x^4 - 0.010046171350985062 x^6 +            0.5 (0.0027385850487922922 +               0.04000027499878133 k^2) x^8 + (0. +               0.000036217780642055754 I) x^9 +            0.5 (6.72230790401107*10^-6 +               0.00012276053475132815 k^2) x^10 + (0. +               7.371834962565406*10^-8 I) x^11 +            0.5 (3.049800199384706*10^-9 +               7.195529551699709*10^-8 k^2) x^12 + (0. +               3.611964212904051*10^-11 I) x^13 +            0.5 (-1.2612171276659422*10^-12 -               1.7472476684229308*10^-11 k^2) x^14 +            2.7423509229173302*10^-15 k^2 x^16)/(0.020000137499390665 k^2 x^8 +               0.00006138026737566407 k^2 x^10 +            3.5977647758498545*10^-8 k^2 x^12 -            8.736238342114654*10^-12 k^2 x^14 +            2.7423509229173302*10^-15 k^2 x^16) == 0, x]      where x is a complex variable and k is a real one. I get this error message: > > Solve::nsmet : This system cannot be solved with the methods available to > Solve. >> Please, I need to find x in terms of k and plot the output x versus k. How can I use _Mathematica_ techniques to solve this equation?


title: Creating cross-version compatible documentation with Workbench

text: Wolfram Workbench allows you to create documentation for your own packages that is similar to the build-in documentation center. Integrating this type of documentation with the documentation center is possible starting from _Mathematica_ 6, and hence I would like to create packages whose documentation nicely integrates with _Mathematica_ 6, 7, 8, and 9. However, Workbench doesn't support this out of the box. Its documentation tools seem to be a spin-off from WRI own tools to create version-specific documentation, so it is no wonder creating cross-version compatible docs in Workbench is nearly impossible. So far, I've identified the following obstacles to creating cross-version compatible docs:   1. Documentation indices built with _Mathematica_ <= 8 are not compatible with _Mathematica_ 9, so docs built with <= 8 are not searchable in 9. See this workaround.   2. Documentation pages built with a given version of _Mathematica_ always give the " _This notebook was created in a more recent version of Mathematica_ " dialog warning in older versions. See this workaround.   3. The `PacletInfo.m` syntax has changed with _Mathematica_ 9; it now requires a `"Kernel"` extension. This chokes the _Mathematica_ 6 PacletManager, ruling out docs simultaneously compatible with 6 and 9. See this workaround.   4. Workbench 2 can only properly build docs with _Mathematica_ 7 or 8. _Mathematica_ 6 returns malformed notebooks (see this workaround by Simon Rochester), and 9 freezes halfway the build process for large packages.   5. Docs build with lower version look pretty bad on _Mathematica_ 9\. See this partial workaround. Points 2 and 5 are by no means deal-breakers, but 1 in combination with 4 certainly is. I've managed to find work-arounds for most of these issues, which I've posted below. If someone has identified similar issues or has better workarounds, I'm all ears!


title: Convergence and value of a complex power series

text: I've done a little math and I got the following power series expansion of $\log z$ about $z_0=-2+i$. $$\log z=\log(-2+i)+\sum_{n=1}^{\infty}\frac{(-1)^{n+1}}{n(-2+i)^n}[z-(-2+i)]^n$$ I've shown that the series converges on $|z-(-2+i)|<\sqrt5$ but I think it only agrees with $\log z$ on $|z-(-2+i)|<1$. I have:               f = Function[z, Log[-2 + I] +            Sum[(-1)^(n + 1)*(z - (-2 + I))^n/(n*(-2 + I)^n), {n, 1, Infinity}]]      The evaluation               f[-2 + I/2]      produces > log(-2 + I) + log(9/10 + I/5) I'm wondering if there is an easy way to force this to a logarithm of a single number. I'm also wondering if someone has a suggestion on how to explore the convergence on the two regions defined above.


title: Errors importing UTF8 file to mathematica

text: I'm trying to import this file:               Import["https://dl.dropboxusercontent.com/u/35192406/jarlaxxe_tweets.\     csv", CharacterEncoding -> "UTF8"]      But I am getting errors like:               $CharacterEncoding::utf8: The byte sequence {240} could not be interpreted as a character in the UTF-8 character encoding. >>      Any idea why? And any solution?


title: Could a package be composed of references?

text: Could a package be composed of references (e.g. usage messages)? Do the code for an induvidual function implemented in a package has to be physically in that package file where it is referenced (i.e. externalized)? Or can the actual function code be referenced in one package and located somewhere in another notebook?


title: How do I use Map for a function with two arguments?

text: I'm a newbie who tries to be a good boy, and use `Map` instead of writing out a list of functions. I have a table I want to `Map` onto:               ratios = Table[10^(n/10), {n, 0, 10}]        and a function               rp[x_, r_] := 1000 x (r + 1)/(r + x)      which I want to `Plot` for the 11 ratios, for `x in [0, 1]`:               Plot[Map[rp, ratios], {x, 0, 1}]      This doesn't work, and I can guess why: `rp` requires two arguments, and MMA probably doesn't know which one is the ratio. And `x` also doesn't appear as a parameter. How do I fix this?


title: Map w/ multiple arguments

text: > **Possible Duplicate:**   >  How do I use Map for a function with two arguments? If I have a function:               F[x_,y_,z_]:=x*y*z      and I want to call it with several different x values using `Map` (and y and z fixed), is there a way to do that with a one-liner? That is, for these x values               xVals = {1,2,3,4}      I want to somehow get:               {F[1,10,100], F[2,10,100], F[3,10,100],F[4,10,100]}      If I can do it with Map, it would be great, because I have many cores and want to speed this up with the parallelized Map.


title: Using Map with functions that take a parameter

text: I have a list               l={{0, 0, 0, 3}, {0, 0, 0, 3}, {0, 0, 1, 2}}      And I would like to obtain the number of zeros in each sublist:               NZ=Table[Count[l[[i]], 0], {i, Length[l]}]      which will return the list: `{3,3,2}` . Is there a way to use `Map` to accomplish this more cleanly? What I would like to do is write something like: `Map[Count, l]` which will of course fail because `Count` needs a pattern to count.


title: How to explain the behavior of Rule inside these functions

text: I'm trying to define a function that takes an expression and spits out a pure function involving a replacement rule of that function's variable. An example would be a function `f` such that `f[x^2]` returns `x^2 /. x -> # &` (let's just stick with single-variable function for simplicity's sake). I have written 2 functions, both aim to do just that. Now, their pure function outputs do work when applied to something else (see last input of block code), but they themselves don't display in the form that I'd like:               (* 1 *)         Clear[f1]     f1[expr_] := Module[{var},       var = First@Variables[expr];       expr /. var -> # &]          f1[x^2]     (* x^2 /. var$77097 -> #1 & *)               (* 2 *)     Clear[f2]     f2[expr_] := expr /. First@Variables[expr] -> # &          f2[x^2]     (* x^2 /. First[Variables[x^2]] -> #1 & *)               {f1[x^2][3], f2[x^2][3]}     (* {9, 9} *)      It seems like `Rule` holds the evaluation of the left hand side, which I don't really know why. Adding `Evaluate` to the left hand side did not help. I tried reading the documentation for `Rule` but couldn't find any relevant information on this behavior. One of its attributes is `SequenceHold`. Could that be a contribution? Also, if anyone could help me understand the result I got for each of those modules I'd really appreciate it. I'm very fuzzy on evaluation order inside `Rule` and `Module`. Lastly, how can I build such a function mentioned in the beginning of my question?


title: Complicated output from simple Eigenvalues problem

text: I have code that uses Eigenvalues on matrices of various sizes. But the output of what should be a very simple problem, namely finding the eigenvalue of a 1x1 matrix, is overly complicated.               Eigenvalues[{{1-(0.2494562342391921 Exp[-2(-0.2+x)^2]+0.769722872465748 Exp[-2x^2])/(1-x^2)}}]      returns               (3.28871*10^-17 E^(-2 (-0.2+x)^2-2 x^2) (2.3405*10^16 E^(2 (-0.2+x)^2)+7.58524*10^15 E^(2 x^2)-3.04071*10^16 E^(2 (-0.2+x)^2+2 x^2)+3.04071*10^16 E^(2 (-0.2+x)^2+2 x^2) x^2))/(-1.+x^2)      Where did those 10^-17 and 10^16 terms come from? Why can't it just give me               1-(0.2494562342391921 Exp[-2(-0.2+x)^2]+0.769722872465748 Exp[-2x^2])/(1-x^2)      ?


title: Trying to generate a list of data to plot a graph with error bars. Need help creating the looping function

text: This is the sets of data I want to put into a form which will allow me to plot error bars from the min and max data.               avg = {{10, 0.662}, {20, 0.96}, {30, 0.916}, {40, 0.787}, {50,0.621}, {60, 0.453}}     min = {{0.55`}, {0.91`}, {0.85`}, {0.72`}, {0.58`}, {0.42`}}     max = {{0.76`}, {1.02`}, {0.99`}, {0.85`}, {0.68`}, {0.51`}}      This following code worked with n=1, creating one point on the graph. How do I make it loop to n=Length[avg] to plot all the points?               errmin = min[[n]] - avg[[n, 2]]     errmax = max[[n]] - avg[[n, 2]]     err = Flatten[{errmin, errmax}]     data = {{avg[[n]], ErrorBar[err]}}          ylabel = "Voltage (V \[PlusMinus] 0.05)"     xlabel = "Blade Angle (\[Degree] \[PlusMinus] 3)"     title = "Preliminary - Altering Blade Angle"     Needs["ErrorBarPlots`"]     ErrorListPlot[data, Joined -> True, InterpolationOrder -> 2,       Mesh -> Full, PlotMarkers -> Automatic,       AxesLabel -> {xlabel, ylabel}, GridLines -> Automatic,       GridLinesStyle -> Dotted, PlotLabel -> Style[title, Bold],       LabelStyle -> (FontFamily -> "Helvetica")]      I should point out I'm new to Mathematica today so please don't be too technical.


title: How can a function with an embedded function be compiled?

text: Compile fun continues today, and I'm trying to get the function below to compile. First the function:               NewC[ymax_, xmax_] := Block[{x1, a2, a0, b0, a1, b1, c1, b2, c2, a3, b3, c3, C0, xb = 0, xe = 100, ve},       a3 = (xmax + ymax - 100)/(2*(xe - xmax)*(xe - xmax));       x1 = (200 - xmax - 2*ymax + 2*a3*xe*(xe - xmax))/(2*a3*(xe - xmax) + 1);       a2 = -(2*a3*(xe - x1) + 1)/(2*(x1 - xmax));       b2 = -2*a2*xmax;       b3 = -1 - 2*a3*xe;       a0 = -(xb + ymax)/((xmax - xb)*(xmax - xb));       b0 = -2*a0*xmax;       C0 = ymax + a0*xmax*xmax;       a1 = (100 - xe - ymax)/((xe - xmax)*(xe - xmax));       b1 = -2*a1*xmax;       c1 = ymax + a1*xmax*xmax;       c2 = ymax + a2*xmax*xmax;       c3 = a3*xe*xe + 100;       ve2[ym_, tnlr_] := If[ym <= ((100 - xmax) + (100 - xe))/2,       If[tnlr <= xmax, a0*tnlr*tnlr + b0*tnlr + xb, a1*tnlr*tnlr + b1*tnlr + c1],       If[tnlr <= x1, a2*tnlr*tnlr + b2*tnlr + c2, a3*tnlr*tnlr + b3*tnlr + c3]];       ve = Chop[Map[ve2[ymax, #[[1]]] &, $range] // N]      ]      So pretty straight forward, except for the embedded function. So I externalize the important parts and global variable, but have no idea how to handle the embedded function. Here's what I tried:               NewC = With[{$range = $range, xb = 0, xe = 100},        Compile[{{ymax, _Real, 1}, {xmax, _Real, 1}},         Block[{x1, a2, a0, b0, a1, b1, c1, b2, c2, a3, b3, c3, C0, ve,ve2},        a3 = (xmax + ymax - 100)/(2*(xe - xmax)*(xe - xmax));         x1 = (200 - xmax - 2*ymax +           2*a3*xe*(xe - xmax))/(2*a3*(xe - xmax) + 1);        a2 = -(2*a3*(xe - x1) + 1)/(2*(x1 - xmax));        b2 = -2*a2*xmax;        b3 = -1 - 2*a3*xe;        a0 = -(xb + ymax)/((xmax - xb)*(xmax - xb));        b0 = -2*a0*xmax;        C0 = ymax + a0*xmax*xmax;        a1 = (100 - xe - ymax)/((xe - xmax)*(xe - xmax));        b1 = -2*a1*xmax;        c1 = ymax + a1*xmax*xmax;        c2 = ymax + a2*xmax*xmax;        c3 = a3*xe*xe + 100;        ve2[ym_, tnlr_] := If[ym <= ((100 - xmax) + (100 - xe))/2,          If[tnlr <= xmax, a0*tnlr*tnlr + b0*tnlr + xb, a1*tnlr*tnlr + b1*tnlr + c1],          If[tnlr <= x1, a2*tnlr*tnlr + b2*tnlr + c2,a3*tnlr*tnlr + b3*tnlr + c3]];        ve = Chop[Map[ve2[ymax, #[[1]]] &, $range] // N]        ],       CompilationTarget -> "C"]];      Certainly not the winning ticket. So are there principles to follow when this type of function must be modified? Thanks!


title: Detection of horizontal lines in an image

text: Ok I'm trying to detect horizontal lines in an image. But the problem is that the line is quite obscure. So I'm not sure if it is even possible to extract that. I tried many different filters, but nothing seems promising. The image is shown below: ![enter image description here](http://i.stack.imgur.com/ZObmf.jpg) And the horizontal lines of interest are shown in the second picture: ![enter image description here](http://i.stack.imgur.com/GrDFA.jpg)


title: Importing strings in Mathematica

text: This is my first post so apologies if any obvious mistakes. I'm trying to work on a data containing names (in quotes) in _Mathematica_. The data is already saved on my system under `names.txt`. I would like to be able to sort these names in alphabetical order but I can't seem to do anything with it in _Mathematica_. None of the commands seem to be working and the file itself is not recognized as a string. I'm sure I'm making an obvious mistake in my code but would greatly appreciate any help. Here's my code below: Original file (reduced version-original file has more than 1000 names): "MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER","MARIA","SUSAN","MARGARET","DOROTHY","LISA","NANCY","KAREN","BETTY","HELEN","SANDRA","DONNA","CAROL","RUTH","SHARON"               data1 = {Import["/Users/Joeblogs/Documents/mathematica/names.txt","string"]}      the output looks like:               {"JOHN", "DAVID", "VIVIAN", "ROBERT"}      How do I sort these in alphabetical order? Thanks for your help.


title: SpeechNavigation option. What is it for?

text: Could somebody please explain what is the use for `SpeechNavigation` option found in the option inspector?


title: Use single ListPlot for multiple sets of data (on separate graphs)

text: This is the code I have working for a single set of data. Is there a way I can structure this to have multiple sets of data?               title = "Preliminary - Altering Blade Angle";     ylabel = "Voltage (V ± 0.05)";     xlabel = "Blade Angle (° ± 3)";     avg = {{10, 0.662}, {20, 0.96}, {30, 0.916}, {40, 0.787}, {50,          0.621}, {60, 0.453}};     min = {{0.55`}, {0.91`}, {0.85`}, {0.72`}, {0.58`}, {0.42`}};     max = {{0.76`}, {1.02`}, {0.99`}, {0.85`}, {0.68`}, {0.51`}};          data = MapThread[{#1,           ErrorBar[{#2[[1]] - #1[[2]], #3[[1]] - #1[[2]]}]} &, {avg, min,          max}];          Needs["ErrorBarPlots`"];     ErrorListPlot[data, Joined -> True, InterpolationOrder -> 2,       Mesh -> Full, PlotMarkers -> Automatic,       AxesLabel -> {xlabel, ylabel}, GridLines -> Automatic,       GridLinesStyle -> Dotted, PlotLabel -> Style[title, Bold],       LabelStyle -> (FontFamily -> "Helvetica"), PlotRange -> All,       ImageSize -> 600]      Maybe I could do something like this:               Needs["ErrorBarPlots`"];     title = {{"Preliminary - Altering Blade Angle"}, {"experiment 2"}};     ylabel = {{"Voltage (V ± 0.05)"}, {"ylabel 2"}};     xlabel = {{"Blade Angle (° ± 3)"}, {"xlabel 2"}};     avg = {        {{10, 0.662}, {20, 0.96}, {30, 0.916}, {40, 0.787}, {50,           0.621}, {60, 0.453}},             {{5, 0}, {10, 0.564`}, {15, 0.795`}, {20, 0.903`}, {25,           0.933`}, {30, 0.908`}, {35, 0.844}}        };     min = {        {{0.55`}, {0.91`}, {0.85`}, {0.72`}, {0.58`}, {0.42`}},        {{0}, {0.52`}, {0.74`}, {0.78`}, {0.8`}, {0.84`}, {0.78}}        };     max = {{{0.76`}, {1.02`}, {0.99`}, {0.85`}, {0.68`}, {0.51`}},        {{0}, {0.6`}, {0.84`}, {0.98`}, {1.06`}, {0.97`}, {0.92}}        };      for the first part? I'm not sure how to structure the second part.


title: Embed Code Into Image

text: I often export images(plots, matrix, arrays, etc..) from mathematica which I end up putting in word documents or uploading to the web. The problem is that I often lose the original code and I am left only with the image representing the original output. I was thinking/considering of using one of the libraries discusses here http://stackoverflow.com/questions/3335220/embed-text-into-png but was wondering what the Mathematica community new of any functionality built into Mathematica allowing to embed text(the code) into the image. ### Compatibility Table For Answers **Edit:** For documentation purposes this is the code I personally use. It varies slightly from the other answers because it embeds that data into the images pixels.


title: Paste letter grades B+ , C-, A, B into notebook and not get B+C-AB

text: I have worked for two days to find a way through this problem. I am porting my student grade records into _Mathematica_ from spreadsheets, or sometimes from my college web sites, or sometimes from my word processor. I have many different source formats as you see, but I find I can always get the data into the format where it will paste into a word processor in one or the other format sketched in my subject line above. I can deal with the _Mathematica_ end of the project once the grades are in the form `List["B+", "C-", "A", "B"]` \-- from there convert them into gpa's, points, sums, averages, whatever -- but I have not been able to operate on the data Pasted into _Mathematica_ because the pluses and minuses are interpreted as parts of incomplete expressions, which blocks execution of string functions. To get the data in, I need to use use the Windows Copy command, then Paste into _Mathematica_. The source can easily be one of the two character formats shown just below. (Or see my subject line.) But unfortunately the grades often have pluses and minuses, especially B+ or C+. But if I paste the following example straight into List in an Input cell, it is interpreted as an incomplete expression:               List[D+, F , C-, F, A-, B, A, A- ,D-, B-, C-, B, D-, D, B, D, A+, B, D, B+, F, C-, F, C+, D-, D+, B]      The same thing happens if I paste the same information in this way:               List[D + F C - F A - B A A - D - B - C - B D - D B D A + B D B + F C - F C + D - D + B]      So I need a "container" to paste into, which will eliminate white spaces, attach any pluses or minuses to the preceding character, and interpret each letter grade as a string as here: `List["B+", "C-", "A", "B"]` (By the way the only letters which appear are ABCDFWI, if that permits simplification, and the only non-letters are + and -). I feel kinda dumb asking about this, but Strings in _Mathematica_ are so crazy I'm just not there yet.


title: Explicit asterisk or @ sign in string patterns

text: What string pattern will match an explicit asterisk (*) or at-sign (@)? The obvious example, `StringMatchQ["*", "\*"]`, returns `False`. I can't find any mention of escaping them in string patterns, only in `RegularExpressions`, and that was in the advanced tutorial.


title: Importing and manipulating data in HDF format

text: I have two matrices A1 and A2 in HDF format. I use the following code to import them.               A1 = Import[       "http://www.math.mtu.edu/~struther/Courses/4610/Data/A1.hdf", "Data"];`      When I type `Dimensions[A1]` I get the output > >     {1, 12, 10} >   Now, I want to do the Singular Value Decomposition on `A1` and reconstruct it from the output matrices. I can do the SVD, but when I check the original and reconstructed matrix by inputting `A1 - U.W.Transpose[V]`, I get a shape not matching error. Also, when I see `A1` in `MatrixForm`, I see a matrix with each column as a separate vector(column matrix) inside the big matrix.               {U, W, V} = SingularValueDecomposition[A1];     Norm[A11 - U.W.Transpose[V], 2]               Here's a screenshot of A1 in MatrixForm      ![enter image description here](http://i.stack.imgur.com/tdgs1.png) I can't figure out why there are separate columns inside the matrix. Also there are 10 rows and 12 columns, but `Dimensions[A1]` outputs > >     {1, 12, 10} >   Any help would be greatly appreciated.