title: How to extract structured array data from DefineDLLFunction in Mathematica

text: I want to use my Bluechip PCI-ADC acquisition card in Mathematica via his dynamic link library “Bcdll32.dll”; (used to access functions on my PCI data acquisition cards). My problem is the function “BCTGetBoardId” that will open a Board by providing a board type (integer 19 to my card) and a board number (integer 0 to my card). By considering VB.Net programming language, the BCTGetBoardId function is defined as:               Public Declare Function BCTGetBoardId Lib "BCDLL32.DLL"            (ByRef pBoardID As BCT_BOARD_ID, ByVal nDevType As Short, ByVal nBoard As Short) As Integer      where the variable pBoardID is a BCT_BOARD_ID type; in VB.Net this type is defined as:               <StructLayout(LayoutKind.Sequential)> _         Public Structure BCT_BOARD_ID                  Dim Handle As Integer             Dim SerialNo As Integer             <MarshalAs(UnmanagedType.ByValArray, SizeConst:=30, ArraySubType:=UnmanagedType.AsAny)> _             Dim DevName() As Byte             <MarshalAs(UnmanagedType.ByValArray, SizeConst:=30, ArraySubType:=UnmanagedType.AsAny)> _             Dim Clock0Name() As Byte             <MarshalAs(UnmanagedType.ByValArray, SizeConst:=30, ArraySubType:=UnmanagedType.AsAny)> _             Dim Clock1Name() As Byte             <MarshalAs(UnmanagedType.ByValArray, SizeConst:=30, ArraySubType:=UnmanagedType.AsAny)> _             Dim Clock2Name() As Byte             Dim hClock0 As BCT_HANDLE             Dim hClock1 As BCT_HANDLE             Dim hClock2 As BCT_HANDLE             Dim Index As Integer             Dim DeviceType As Integer         End Structure      According the “BLUECHIP.vb” file that allows access to DLL library functions IN VB.Net programs, in the case of the BCT_BOARD_ID structure described above, ” In VB.NET, we cannot declare a dimensioned array from within the structure. Instead, we use the 'MarshalAs Attribute' class to handle each array data.” To obtain the data contained in pBoardID variable and by using the help offered by (How can multiple null terminated strings be handled in a DLL-function result?) I used a Mathematica program as follows:               Needs["NETLink`"]     path="c:\\WINDOWS\\system32\\Bcdll32.dll"; (*my Bcdll32.dll  path*)     codgbi=DefineDLLFunction["BCTGetBoardId",path,"short",{"IntPtr","System.Int16","System.Byte"}];     $maxBufLen=1000;          LoadNETType["System.Runtime.InteropServices.Marshal"];          buf=Marshal`AllocHGlobal[$maxBufLen];           codergbi=codgbi[buf,19,0]          managedArray=NETNew["System.Byte[]",$maxBufLen];          Marshal`Copy[buf,managedArray,0,$maxBufLen];          bytes=NETObjectToExpression[managedArray];          FromCharacterCode[DeleteCases[SplitBy[bytes, # != 0 &], {0 ..}]]      I obtained the following confuse answer: > Out[18] 0 (*the value codergbi=0 indicate a correct function syntax *) > > Out[22] {"à.02", "D0.10", "\\\\.\PCIADC0_0000", > \"4B-B1DA-6F7CA\\\\.\PCIADC0_5400", "\\\\.\PCIADC0_5401", > \"\\\\.\PCIADC0_5402", "+", "Realtek PCIe GBE Family Controller - \Packet > Scheduler Miniport", ".06", ".08`no.b4", ".02", ".06", \"", "192.168.1.120", > "255.255.255.0", ".02", "192.168.1.1", \"0.0.0.0", "192.168.1.1", "0.0.0.0", > "0.0.0.0", "0.0.0.0", "0.0.0.0", \"ÞÂR^ÝÃR"} It is clear that I am not mastered the subtleties of programming in NET. Framework. Please, any help to extract in Mathematica all the correct form of the data contained in the structure “buf” from the function codgbi[buf,19,0]! * * * First of all, many thanks Alexey Popkov for your sugestion “calling a dll- function that returns a structure and many, many thanks Todd Gayley, for the superb examples presented in the same MathGroups thread above. Please ignore the last line of my first code, which splits up the bytes of the structure; this was a stupid trial inspired by “How can multiple null terminated strings be handled in a DLL-function result?” and bad adapted by me. To understand how to solve my problem I rebuilt and corrected some small errors (sign == bad placed due to the publisher of the site), the didactic examples offered by Todd Gayley . My second problem is that I deal with a nested structure: the BCT_BOARD_ID structure presented above use the BCT_HANDLE structure and the last use OVERLAPPED structure as follows:                  Structure OVERLAPPED         Dim Internal As Integer         Dim InternalHigh As Integer         Dim Offset As Integer         Dim OffsetHigh As Integer         Dim hEvent As Integer     End Structure                Public Structure BCT_HANDLE         Dim Handle As Integer         Dim Overlap As OVERLAPPED         Dim DeviceType As Integer         Dim BoardType As Integer         Dim nPort As Short         Dim LastError As Integer         Dim NextTime As Integer     End Structure      After analyzing the material on nested structures (pinvoke.net and others) I suggested the following DefineDLLFunction:               path = "c:\\WINDOWS\\system32\\Bcdll32.dll";          bctboardid = DefineDLLFunction[     "           public struct OVERLAPPED        {                public System.Int16 Internal;           public System.Int16 InternalHigh;             public System.Int16 Offset;             public System.Int16 OffsetHigh;             public System.Int16 hEvent;       }                 Public struct BCT_HANDLE            {            public System.Int16 Handle;            public OVERLAPPED Overlap;             public System.Int16 DeviceType;            public System.Int16 BoardType;            public System.Byte nPort;            public System.Int16 LastError;            public System.Int16 NextTime;       }                      [StructLayout(LayoutKind.Sequential)]                 public struct BCT_BOARD_ID            {                    public System.Int16 Handle;                    public System.Int16 SerialNo;                 [MarshalAs(UnmanagedType.ByValArray, SizeConst=30, ArraySubType=UnmanagedType.AsAny)]                    public System.Byte DevName();                 [MarshalAs(UnmanagedType.ByValArray, SizeConst=30, ArraySubType=UnmanagedType.AsAny)]                    public System.Byte Clock0Name();                  [MarshalAs(UnmanagedType.ByValArray, SizeConst=30, ArraySubType=UnmanagedType.AsAny)]                    public System.Byte Clock1Name();                  [MarshalAs(UnmanagedType.ByValArray, SizeConst=30, ArraySubType=UnmanagedType.AsAny)]                    public System.Byte Clock2Name();                    public BCT_HANDLE hClock0;                    public BCT_HANDLE hClock1;                    public BCT_HANDLE hClock2;                    public System.Int16 Index;                    public System.Int16 DeviceType;       }            [return: MarshalAs(UnmanagedType.Byte)]            [DllImport(path, CallingConvention = CallingConvention.StdCall,CharSet = CharSet.Auto, SetLastError = true)]                     public static extern short        BCTGetBoardId([In, Out] BCT_BOARD_ID pBoardId,System.Int16 nDevType,System.Int16 nBoard );"]      Unfortunately I received the message: > DefineDLLFunction::compileerr: "The compiler reported errors in your DLL > function declaration: "Invalid token 'struct' in class, struct, or interface > member declaration ". Please, help me identify the error!


title: Can I evaluated a cell in a notebook in a background process?

text: I currently run my _Mathematica_ on a linux computer through Putty and Xming. Xming provides a graphical display for _Mathematica_ windows running on a remote linux computer. But recently, the network has become quite unstable. A disadvantage of using Xming is the graphical display will disappear immediately as soon as the network goes down. When the graphical display disappears, all the evaluation that is running stops and is lost. **So I wonder if there is a way to control to make notebook cell evaluations run in the background when I use the graphical display to run _Mathematica_ remotely.** I expect that code running in the background will not be affected by the shutdown of the graphical display.


title: Zooming into animated plot

text: Let's say I have the following animation:               Animate[ParametricPlot[{Cos[a t], Sin[a t]}, {t, 0, 1}], {a, 0,        2Pi}, AnimationRate -> 0.1]      Is there a way to somehow zoom into the moving point of the animated plot at a preselected xy-coordinate or time; such as being able to zoom into the animated moving point after 3 seconds or when the moving point reaches {x,y}={-1,0}? Any help would be appreciated.


title: DSolve cannot solve for certain branches of the solution

text: Could somebody please tell me, why I am always getting an error message when trying to run the following code:               DSolve[y'[x] == c*(d - y[x]) - b*(d - y[x])*y[x] && y[0] == y0, y, x]      The error message:               DSolve::bvfail: For some branches of the general solution, unable to solve the     conditions.


title: Symbolically solve a system of coupled second order differential equations

text: I have posted a similar question in another forum where the general consensus seems to suggest that it is not possible to symbolic solve a system of coupled second order differential equations with damping (dissipation) and driving forces. However, I have found in many papers and books writing out analytical formula of the solutions to such coupled equations. So, it must be possible. I just do not know how. Attached is the system I am trying to solve. Although solving this sort of equation with two masses, no damping (dissipation) and with only one driving force is simple enough, even by hand, it is impossible to do the same for a system with two different damping constants and two driving forces. I have been trying for two weeks now, but could not figure out the solution. Of course, I could get the numeric solution, but I could not get the same result obtained from Eq. 5. So, I was wondering if someone could help me how to solve this analytically. Any solution to this problem would be of interest. I am completely new to _Mathematica_ , so any example worksheets on this sort of equation would be gratefully appreciated! ![Coupled second order diff eqn](http://i.stack.imgur.com/y91t6.jpg)


title: Pass Options to Export[]

text: I'm working with Options to change the look and feel of some generated Graphics by passing Options to several functions, one of them being `Export[]`. For example:               Options[myPlot] := {Resolution -> 325, Size -> 12, FileName -> "A",        PlotStyle -> Automatic};          myPlot[f_, opts : OptionsPattern[myPlot]] := Block[{fig},     (* ... some calculations here *)     fig = Plot[f[x], {x, -\[Pi], \[Pi]},          Evaluate[FilterRules[{opts}, Options[Plot]]]];     fig = Show[fig, ImageSize -> OptionValue[Size]*72/2.54];+     Export[OptionValue[FileName] <> ".png", fig,  FilterRules[{opts}, Options[Export]]];     Print[fig];     ]      And using `f[x_] := x^2` use the function as                myPlot[f, Resolution -> 120, PlotStyle -> Red]      The Option to plot the function in `Red` is passed correctly to `Plot` but `Resolution` is not passed to `Export`. This is of course due to the fact that `Options[Export] = {}`. My question is: _How can I still pass Options to`Export` (i.e. how to determine, which are available, if they are not written in `Options[Export]`?_ And closely related: _How to do that on your own, i.e. now I defined`PlotStyle` to be an Option of `myPlot`, though it's only passed on, how can I pass Options, that I haven't given myself, without getting the message_ > OptionValue::nodef: "Unknown option PlotStyle for ...


title: Two questions about drawing tool

text: In _Mathematica_ , Ctrl+1 inserts a new picture. Using the drawing tool, we can draw many things. It seems to me that there is no way to control the drawing angle. So here are my questions:   1. How to draw a regular polygon quickly and accurately? (e.g. a hexagon)   2. How to draw a straight line with an accurate angle relative to the horizontal line? Or rotate an existing horizontal line for an angle (e.g. 60 degrees)?


title: Plotting a complicated vector field

text: If we consider the vector $\left ( A \cdot \nabla \right) \: B$, we have in Cartesian coordinates $$\left ( A \cdot \nabla \right) \: B = \left ( A \cdot \nabla B_x \right ) e_x + \left ( A \cdot \nabla B_y \right ) e_y + \left ( A \cdot \nabla B_z \right ) e_z,$$ which gives in full writing: $$\left ( A \cdot \nabla \right) \: B = \left (A_x \frac{\partial \: B_x}{\partial \: x} + A_y \frac{\partial \: B_x}{\partial \: y} + A_z \frac{\partial \: B_x}{\partial \: z} \right )e_x + \left (A_x \frac{\partial \: B_y}{\partial \: x} + A_y \frac{\partial \: B_y}{\partial \: y} + A_z \frac{\partial \: B_y}{\partial \: z} \right )e_y + \left (A_x \frac{\partial \: B_z}{\partial \: x} + A_y \frac{\partial \: B_z}{\partial \: y} + A_z \frac{\partial \: B_z}{\partial \: z} \right )e_z$$ Now, say $B=A$ and $A=\left (10 \: x, \: 20 \, y^3, \: 30 \:z \right )$. I would like to plot the field of $A$ and of $\left ( A \cdot \nabla \right) \: A$ in Mathematica. How to go about? (My objective in this exercise is to know which direction the vector $\left ( A \cdot \nabla \right) \: A$ lies with respect to $A$ and also test for different vectors $A$ when the lines of $\left ( A \cdot \nabla \right) \: A$ are straight or are curved.) Thanks a lot...


title: How Do I Plot A Binomial to the Right of the Origin?

text: I'm having a seven element binomial distribution: BinomialDistribution[7, 0.5], x],{x, 0, 8}] I would like to locate to any arbitrary point on the X axis. Mathematica will let me have eight columns on the X axis ranging from -0.5 on up to 7.5. How do I shift the binomial on up to say, from 5.5 to 13.5?


title: How can I hold UpValues but evaluate other expressions?

text: Consider these definitions:               own = "OwnValue";     down[_] = "DownValue";     sub[_][_] = "SubValue";     N[n] = 3.14;     _[___, up, ___] ^= "UpValue";      The attribute `HoldAllComplete` holds an UpValue but it also holds the other Values as well. Without advance knowledge of the symbol `up` how can I evaluate everything but the UpValue? `Set` and related functions appear to have this evaluation property internally:               f[own, down[1], sub[1][2], N[n], up] = 1;          Definition[f]      > >     f["OwnValue", "DownValue", "SubValue", 3.14, up] = 1 >   * * * The first idea that comes to mind is to test if a symbol has an UpValue and skip evaluation if it does, but this proves problematic. First, a symbol can have both an OwnValue and an UpValue, and the OwnValue should be used if possible:               x[up3] ^= 2;     up3 = 1;          f[up3]      > >     f[1] (* desired output *) >   Second, testing for an UpValue can be difficult:               _[___, up4, ___] ^= {};          UpValues[up4] === UpValues[Plus]      > True * * * To clarify, it is not my intent to return `f[. . ., up]` as output, which would require `Defer` or similar. Rather I would like to handle the expression `f[. . ., up]` as an argument like `Set` does, or define a function `f[args___] := . . .` (with attribute `HoldAllComplete`) that returns e.g. `{"OwnValue", "DownValue", "SubValue", 3.14, HoldComplete[up]}` How can this be achieved?


title: RecurrenceTable with a recurrence function of two variables

text: I have to calculate the cool down process of a regenerative heat exchanger. I solved the problem in Excel before, but now I want to do it with _Mathematica_. I want to create a table with the variables t and z. For `t = 0`, there is a function which gives the temperature for each layer z. For `z = 0`, there is another function which gives the temperature for the first layer for each t. the rest of the table should be calculated layer by layer, so that z is constant while t goes form `t0` to `tend`, then z should increase 1 step and so on. I tried out some simple code, but it didn't work. What's worng? Are there any other ways to solve my problem?               RecurrenceTable[{       T[t + 1, z + 1] == T[t, z + 1] + T[t + 1, z],        T[t + 1, 0] == T[t, 0]/2,        T[0, z] == z + 2       },        T, {t, 0, 6}, {z, 0, 4}] // Grid


title: Plotting a dynamical NonlinearModelFit Function

text: Currently I'm playing around with dynamics and the `NonlinearModelFit` function. To be precise, I want to fit a function the data, which range I want to specify dynamically. This is not a problem and works fine. But when it comes to plotting, Mathematica refuses to show me anything. Here's an example code (the testdata consists of 100 values. The variable min gives the lower bound for the fit to begin. ) * * *               min = 50;          testdata = Table[{x*RandomReal[{0.95, 1.05}], 3 x^2 + 4 x}, {x, 0, 10, 0.1}];          fit = Dynamic[NonlinearModelFit[testdata[[min ;;]], a x^2 + b x, {a, b}, x]];          Dynamic[Plot[fit[x], {x, 0, 4}]];      * * * Do you have an idea, how to overcome this problem? Thanks in advance, Juergen


title: How to detect if a sequence of integers is consecutive

text: I'm not a math-guy really (a programmer actually) and this is my first question. And excuse me if I can not explain my problem good. The problem is I have a sequence of integers and I want to detect if they are consecutive or not. e.g.               a1 = {1, 2, 3, 4} (* consecutive *)          a2 = {0, 1} (* consecutive *)          a3 = {0, 1, 2, 4} (* non-consecutive *)          a4 = {3, 4, 5, 6} (* consecutive *)          a5 = {3, 5, 6, 7} (* non-consecutive *)          a6 = {2, 3, 4} (* consecutive *)      The numbers come from a list's indexes that a user selected in UI. Actually I want to see if he selects a consecutive rows or not. Is there any way (sure there is :)) to check this without walking through all items in the list? I mean for example by using the first and last number in the list etc? Update: **Note:** The numbers:   1. they are integers,    2. they are ascending,    3. no repeats


title: Plotting boundary value expression against a parameter

text: I am very new to _Mathematica_ and have a question regarding plotting a ODE boundary value problem. Let say I have an ODE               alpha = 1/2;     beta = -5;     eq = beta*f'''[x] + alpha*f[x]*f'[x] == 0     bc = {f[0] == 0, f'[0] == 0, f'[10] == 1};      NDSolve[{eq, bc}, f[x], {x, 0, 10}]      I want to plot `alpha*f''[0] + (f''[0])^3` vs `beta`. In the plot, `beta` should take the range [-5, 5]. `NDSolve` should use shooting method for the numerical solution. Also, how I can extract data from that plot as a .txt file.


title: MapThread over large graph

text: I am trying to build a very large graph with approximately $16\,000\,000$ edges, each being a two-dimensional integer vector. I have a list of edges in the form $\\{\\{e_{11}, e_{12}\\}, \\{e_{21}, e_{22}\\}, \dotsc\\}$, where $e_{11} = \\{n, m\\}$, etc. To convert it into a usable edge-list I need to turn every element of this list into a rule:               edgeList = MapThread[Rule, Transpose[edgelist]];      This works fast enough when there are $3\,000\,000$ edges but is too slow for $16\,000\,000$. What is the best way to speed up the threading?


title: Using Mathematica to find Derivatives

text: I am given a system first order differential equations: $x'=y$ and $y'=6x^2-a/2$, where $a$ is a constant and $'$ denotes $t$-derivatives. I then make the substitution $(x,y)=(x_1y_1,y_1)$. This implies that $x_1=\frac{x}{y}$ and $y_1=y$. The $t$-derivatives are $$x_{1}'=\left(\frac{x}{y}\right)'=\frac{yx'-xy'}{y^2}=1-x_{1}y_{1}^{-1}(6x_{1}^2y_{1}^2-a/2)$$ and $$y_{1}'=6x_{1}^2y_{1}^2-a/2.$$ I need to continue in this fashion, that is, in the next step, for example, we let $(x_{1},y_{1})=(x_{2}y_{2},y_{2})$ and then find $x_{2}'$, $y_{2}'$, etc. Is there a way I can compute the derivatives in Mathematica? For instance, how would I find $x_{1}'$ in Mathematica. Thanks, Radz.


title: Numerically solving an ODE for a parameter

text: My equation is as follows:               sol =        ParametricNDSolve[{(f'[r]^2 - 1) f'[r] r == 6.2 (f'[1])^2/1000, f[1] == a},          {f}, {r, 1, 3}, {a}]      where the function `f[r]` needs to satisfies a constraint `6.2 (f'[1])^2/1000 = 6 (f'[3])^2/1000` Then I plot `f[r]`               Plot[Evaluate[{(f'[a])^2[1],6(f'[a])^2[3]/6.2} /. sol], {a, 0, 2}]      I am getting the message > ParametricNDSolve::litarg: To avoid possible ambiguity, the arguments of the > dependent variable in {r (NDSolve`f$1$1^\[Prime])[r] > (-1+(NDSolve`f$1$1^[Prime])[r]^2)==0.0062 NDSolve`f$1$1[1]^2,2 r > (NDSolve`f$1$1^[Prime])[r]^2 (NDSolve`f$1$2^\[Prime])[r]+r (-1+ > (NDSolve`f$1$1^[Prime])[r]^2) (NDSolve`f$1$2^\[Prime])[r]==0.0124 > NDSolve`f$1$1[1] NDSolve`f$1$2[1]} should literally match the independent > variables. >> I do not know how to avoid the error message and solve the function `f[r]`


title: Generation of Sliders via Tables/For loops

text: I have a list named data that contains lists of arbitrary size,               data={{0.5, 0.5}, {}, {0.5, 0.5, 0.5}, {}, {}, {}, {}, {}, {}, {}}      I now want to generate for each sub-list the appropriate number of sliders (for the empty sets none, ~~though I believe they are easy to skip~~ ). However, I am not sure if this is even possible. In my quest I stumbled upon this thread, Manipulate with a variable number of sliders, which allows me to generate sliders for one sub-list,               Dynamic[Grid[     Table[With[{i = i}, {Slider[Dynamic[data[[1]][[i]]]],       Dynamic[data[[1]][[i]]]}], {i, Length[data[[1]]]}]]]       This works perfectly fine if I use a constant as an index for `data`, in this case 1. However, if I want to extend this by using a for loop or a table to make that index variable, say               Table[Dynamic[Grid[     Table[With[{i = i}, {Slider[Dynamic[data[[k]][[i]]]],       Dynamic[data[[k]][[i]]]}], {i, Length[data[[k]]]}]]],{k,1,1}]      the `k` gets marked red and the code fails. Is it even possible to generate sliders this way? I imagine the reason that the code fails is that Dynamic requires the object under consideration to remain constant, but is there a way around this?


title: Transition matrix of order n

text: I am doing a work about Markov Chains and I have as task to determine, either by induction or by spectral methods, the form of the higher order transition matrix of the model. My transition matrix (P) is:               transitionmatrix = {{17/72, 3/72, 5/72, 0, 0}, {5/72, 5/72, 7/72, 1/72, 0}, {4/72,9/72,     4/72, 0, 4/72}, {0, 0, 3/72, 1/72, 0}, {3/72, 1/72, 0, 0, 0}}            By spectral method P=MDM^-1 :               In[6]:= eigenvalues = Eigenvalues[transitionmatrix] // N     Out[6]= {0.297046, 0.113193, -0.0215001 + 0.0136874 I, -0.0215001 - 0.0136874 I,         0.00776109}          In[7]:= eigenvectors = Eigenvectors[transitionmatrix] // N     Out[7]= {{6.03283, 3.28881, 3.32027, 0.48858, 1.}, {4.22247, -4.51749, -4.76335,      -1.99863, 1.}, {-0.171634 + 0.124637 I, -1.0331 + 0.61158 I, 1.23199 - 0.86313 I,          -1.60369  + 0.395985 I, 1.}, {-0.171634 - 0.124637 I, -1.0331 - 0.61158 I, 1.23199 +      0.86313 I, -1.60369 - 0.395985 I, 1.}, {0.280052, -0.281356, -0.752063, 5.11374, 1.}}          In[18]:= M = Transpose[eigenvectors]     Out[18]= {{6.03283,      4.22247, -0.171634 + 0.124637 I, -0.171634 - 0.124637 I,      0.280052}, {3.28881, -4.51749, -1.0331 + 0.61158 I, -1.0331 -      0.61158 I, -0.281356}, {3.32027, -4.76335, 1.23199 - 0.86313 I,      1.23199 + 0.86313 I, -0.752063}, {0.48858, -1.99863, -1.60369 +      0.395985 I, -1.60369 - 0.395985 I, 5.11374}, {1., 1., 1., 1., 1.}}          In[16]:= Diag = DiagonalMatrix[eigenvalues]     Out[16]= {{0.297046 + 0. I, 0. + 0. I, 0. + 0. I, 0. + 0. I,      0. + 0. I}, {0. + 0. I, 0.113193 + 0. I, 0. + 0. I, 0. + 0. I,      0. + 0. I}, {0. + 0. I, 0. + 0. I, -0.0215001 + 0.0136874 I,      0. + 0. I, 0. + 0. I}, {0. + 0. I, 0. + 0. I,      0. + 0. I, -0.0215001 - 0.0136874 I, 0. + 0. I}, {0. + 0. I,      0. + 0. I, 0. + 0. I, 0. + 0. I, 0.00776109 + 0. I}}          In[17]:= Minver = Inverse[M]     Out[17]= {{0.109069 + 7.70366*10^-19 I, 0.0487956 + 6.50521*10^-19 I,      0.0514224 - 9.72945*10^-19 I, 0.00239343 + 5.5971*10^-19 I,      0.00961738 - 3.82994*10^-18 I}, {0.0828826 -      4.20783*10^-18 I, -0.0865795 + 1.0842*10^-17 I, -0.0549339 -      8.27329*10^-18 I, -0.0121092 - 4.07692*10^-18 I, -0.0269617 +      1.91893*10^-17 I}, {-0.0897774 + 0.141661 I,      0.0551552 - 0.443078 I, -0.00936235 + 0.351851 I, -0.0773342 +      0.143982 I, 0.429087 - 0.636007 I}, {-0.0897774 - 0.141661 I,      0.0551552 + 0.443078 I, -0.00936235 - 0.351851 I, -0.0773342 -      0.143982 I,      0.429087 + 0.636007 I}, {-0.0123972 -      4.92909*10^-18 I, -0.0725264 + 1.38778*10^-17 I,      0.0222361 - 1.0567*10^-17 I, 0.164384 - 5.62511*10^-18 I,      0.159171 + 2.19287*10^-17 I}}      But when i do               M.Diag.Minver      i dont get my transition matrix i get:               In[14]:= M.Diag.Minver          Out[14]= {{0.236111 - 7.80878*10^-19 I, 0.0416667 + 6.58726*10^-18 I,      0.0694444 - 5.94759*10^-18 I, -3.43324*10^-18 - 8.88005*10^-19 I,      4.15626*10^-17 + 2.63492*10^-18 I}, {0.0694444 + 2.15757*10^-18 I,      0.0694444 - 3.80299*10^-18 I, 0.0972222 + 2.07205*10^-18 I,      0.0138889 + 3.02264*10^-18 I,      1.88651*10^-17 - 1.20859*10^-17 I}, {0.0555556 + 4.03989*10^-18 I,      0.125 - 6.75901*10^-18 I,      0.0555556 + 5.16039*10^-18 I, -1.15614*10^-17 + 2.29187*10^-18 I,      0.0555556 - 1.62182*10^-17 I}, {-2.1617*10^-15 +      2.2484*10^-20 I, -9.09499*10^-16 - 5.39346*10^-19 I,      0.0416667 - 6.27859*10^-20 I,      0.0138889 + 1.20315*10^-18 I, -2.11264*10^-16 -      2.33486*10^-18 I}, {0.0416667 + 9.43055*10^-20 I,      0.0138889 + 9.58975*10^-19 I, -1.44261*10^-17 -      6.90605*10^-19 I, -2.78314*10^-18 - 5.28583*10^-19 I,      1.27434*10^-17 + 4.46324*10^-19 I}}      Please could u help me, i dont know what i am doing wrong. And could u help me finding the higher transition matriz by induction? My teacher gave this code, but i dont understand it, so i wouldnt like to use.               POTtrMx[0] = IdentityMatrix[Length[StSp]];      POTtrMx[n_Integer] := POTtrMx[n] = Dot[POTtrMx[n - 1], trMx]


title: Change number from real to integer

text: > **Possible Duplicate:**   >  Is this the most efficient way to round approximate integers to integers > while leaving other Reals untouched? Please consider the following:               data={123.,56.,45.};     Head/@data     (*result: {Real,Real,Real}*)      How do I change the numbers in `data` into integers, so:               dataConv=MyFunction/@data;     Head/@dataConv     (*result: {Integer,Integer,Integer}*)      **EDIT** Also interesting could be to change "real" reals like `{12.3,10.555}` into integers by returning only the numbers before the decimal separator `(*result: {12,10}*)`.


title: A dot appearing after a zero, and making the entries of a matrix into fractions

text: > For more info about the difference between 0. and 0 I am a self-taught Mathematica user and I have some elementary questions-- perhaps too elementary for this site, but here they are. ![Matrix](http://i.stack.imgur.com/XFQkd.jpg)   1. If you look at the identity matrix, you'll see a "dot" in each entry in the upper triangular portion of the matrix. Why are they there? Is it because those entries are not really zeros?    2. How do I get the entries in MatrixForm[Inverse[M]] to appear as fractions?  Thanks everyone! So I just found this link: Expressing a decimal as a fraction in lowest terms and tried the following: ![Matrix2](http://i.stack.imgur.com/cJfBZ.jpg) Isn't there a way to tell Mathematica to not show entries like -9.71445146547012`*^-17 (up to 17th decimal place)?


title: Returning Replacement Rules in a function and using it later on

text: I would like a function which returns replacement rules as some internal mathematica functions are doing and use the results in other functions. I could not find any information on that and I'm wondering if it is a good idea after all. I'm not sure how this is done in a good way. Here is an example:               Clear[f, f2, H, imax, res]     f[imax_] :=       Block[{H}, H = Table[Random[], {i, 1, imax}];        Return[{H -> H, imax -> imax}]]     f[5]      with the result               {{0.855859, 0.656278, 0.793888, 0.275233, 0.751709} -> {0.855859,       0.656278, 0.793888, 0.275233, 0.751709}, 5 -> 5}      Yes this is obvious but I would like to use the name H internally and also in the returned replacement rule. So I do this instead:               f2[imax_] :=       Block[{H}, H = Table[Random[], {i, 1, imax}];        Return[{"H" -> H, "imax" -> imax}]]     res = Table[f2[imax], {imax, 5, 7}]     (*now i want to invesgate the result with imax=6*)     p = First @Flatten[Position[res, "imax" -> 6]]     res[[p]]     Head["H"] /. res[[p]]      with the result:               {{"H" -> {0.486493, 0.60306, 0.666644, 0.148913, 0.598069},      "imax" ->       5}, {"H" -> {0.873354, 0.98408, 0.0392209, 0.428918, 0.485521,      0.710918},      "imax" ->      6}, {"H" -> {0.198376, 0.385448, 0.438549, 0.818111, 0.314781,      0.533971, 0.955322}, "imax" -> 7}}          2          {"H" -> {0.873354, 0.98408, 0.0392209, 0.428918, 0.485521, 0.710918},       "imax" -> 6}          String      So the Problem is that Head["H"] /. res[[p]] results in a string and ListPlot["H"] /. res[[p]] would complain but plot the result. A good thing tough is that it is possible to search in the results and it is more flexible and readable than returning a List. So what is the best way to do this? So that I can use H and imax internally in the function and in the Return?


title: Rearrangement of the list

text: I have the following list:                m = {{x == 0, y == 0.29264681456942615},            {x == 30, y == 0.2419119568894183},            {x == 50, y == 0.1485164898707659},            {x == 70, y == 0.05437093382683481},            {x == 90 , y == 1.}}      I would like to convert it to the form `{{0,0.29264681456942615},{30, 0.2419119568894183}, ... }` (extracting only the numbers form the list). How can I do this?


title: How to resolve Start up error 502?

text: My Mathematica is not launching properly (I run it on Ubuntu 12.04 LTS). Here is the screenshot of the error message. ![enter image description here](http://i.stack.imgur.com/XZmIy.png) I've tried the following suggestions :               i) -cleanstart     ii) ~/.mathematica and even      iii) reinstalled it.      But none of the above is woking. Can anyone please help me?


title: How to extract a possible closed form from WolframAlpha[] output

text: To find a possible closed form of a number, I can use the function               WolframAlpha["6.38905609893065", IncludePods -> "PossibleClosedForm"]      It returns a result in the following form: ![Possible closed forms](http://i.stack.imgur.com/DkQw8.png) The `InputForm` of this result displays quite a large expression containing pods and cells represented as `XMLElement`s. > Is there an easy way to extract the first suggested closed form as a normal > expression (in this case, `E^2 - 1`)?


title: Showing "updating..." message while Manipulate is re-evaluating

text: Is it possible to show a fixed text such as _"updating..."_ instead of the last result shown, when `Manipulate` is re-evaluating an expression (in a slow evaluation context)? How to do it? More precisely, I have a `Button` element in the set of controls, and it is the action triggered by the button the one that slows down the process, and _not_ the results shown in the `Manipulate` sentence themselves. This could be a MWE for what I mean:               Manipulate[result,      {{x, 5}, 0, 10, 1, Appearance -> {"Labeled"}, AppearanceElements -> None},      {{y, 5}, 0, 10, 1, Appearance -> {"Labeled"}, AppearanceElements -> None},      Button["Calculate", Pause[2]; result = x + y],      TrackedSymbols :> {result},      Initialization -> Clear[result, x, y]]      In this example, the values for two integer numbers `x` and `y` are selected using their respective slider controls, and then a button is used to perform some calculations based on them. Finally, results based on those calculations are shown using `Manipulate`. So, regarding this example, my question is: how can I show the text _"updating..."_ while the button is _thinking_? If you think there would be an easier solution in case it was not the button but the expression to be shown by `Manipulate` the one that takes some long time to be executed, I think I could also modify my real problem to be like that. The MWE could be like this:               Manipulate[Pause[2]; parameters[[1]] + parameters[[2]],      {{a, 5}, 0, 10, 1, Appearance -> {"Labeled"}, AppearanceElements -> None},      {{b, 5}, 0, 10, 1, Appearance -> {"Labeled"}, AppearanceElements -> None},      Button["Calculate", parameters = {a, b}],       TrackedSymbols :> {parameters},       Initialization -> (Clear[a, b, parameters]; parameters = {5, 5})]      It would be also OK if the text _"updating..."_ appeared _in the button_ , temporarily replacing the _"Calculate"_ text. It would be a little bit strange, but also valid. I look forward to your solutions.


title: How to declare a function of variable?

text: In my program, there are many functions relying on spatial coordinates: x, y, and z, which are also functions of time t, i.e., composite function. I need to differentiate some functions for example f:                   D[f[x[t], y[t], z[t]], t]      But because those coordinates appear so frequently, when I write x[t] instead of x my program becomes lengthy and lacks readability. So, how can I declare those coordinates as functions of time t at the start to tell _Mathematica_ that the differentiation is relative to t, so I can use x, y , and z, afterwards as an abbreviation.


title: Creation of name.m Package

text: I have a structure of folders.   1. Main Directory( has init.m, and name.m files)   2. Subfolders under Main directory      1. library ( has the packages, pacakge1.m, package2.m)     2. Data (some xcel sheets and other data files) The init.m has the following commands `Get[FileNameJoin[{NotebookDirectory[],"library", "Package1.m"}]]; Get[FileNameJoin[{NotebookDirectory[],"library", "Package2.m"}]];` Package1 has `function1` and `function2` definitions. Package2 has `function3` and `function4` definitions. The Names.m file has the following the commands               Get[FileNameJoin[{NotebookDirectory[],"init.m"}]];     DeclarePackage["Package1`",{"function1", "function2"}];     DeclarePackage["Package2`",{"function3", "function4"}]      After evaluating the name.m file, I was expecting that calling `function1` should execute the `Package1`function1`. However it is not happening. This is what I understand of _Mathematica_ so far. I don't want to touch the init.m file in the Autoload folder of the userbase directory as I don't want to modify the contents. I just want my init.m in the local folder to run. Workarounds anyone?


title: Problem evaluating a complicated integral

text: Apologies for stating my problem poorly in the first instance, thank you for the help in narrowing down the issue. **Problem** For those interested, it's for the exact unbiased inverse of the generalized Anscombe Transform, as given in this paper: http://dx.doi.org/10.1109/TIP.2012.2202675. I'm trying to integrate, for a given value of $y$ and $\sigma$, the function $$ \int_{-\infty}^{+\infty} f_{\sigma}\left ( z \right ) \sum_{k=0}^{\infty}\left ( \frac{y^{k}\mathrm{e}^{-y}}{k!\sqrt{2\pi \sigma^{2}}} \mathrm{e}^{-\frac{\left ( z-k \right )^{2}}{2\sigma^{2}}} \right ) \mathrm{d}z $$ where $$ f_{\sigma}\left ( z \right ) = \left\\{\begin{matrix} 2\sqrt{z+\frac{3}{8}+\sigma^{2}}, & z > -\frac{3}{8}-\sigma^{2}\\\ 0, & z \leq -\frac{3}{8}-\sigma^{2} \end{matrix}\right. $$ which gives the equation in the reference below: $$ \int_{-\infty}^{+\infty} 2\sqrt{z+\frac{3}{8}+\sigma ^{2}}\sum_{k=0}^{\infty}\left ( \frac{y^{k}\mathrm{e}^{-y}}{k!\sqrt{2\pi \sigma^{2}}} \mathrm{e}^{-\frac{\left ( z-k \right )^{2}}{2\sigma^{2}}} \right ) \mathrm{d}z $$ In the reference, the values of the above function are tabulated, presumably in Matlab, for $\sigma \in \left \\{ 0.01,...,50 \right \\}$ and $y \in \left \\{0,...,200 \right \\}$. The authors have made this table available for download, but I want to do it myself. However, I can't get it to work - Mathematica won't evaluate it:               func[z_, y_, sig_] :=       Piecewise[{{2 Sqrt[z + 3/8 + sig^2],z > -3/8 - sig^2}},0.]*       Sum[((y^k )* Exp[-y])/(k! * Sqrt[2 \[Pi] sig^2]) *          Exp[-((z - k)^2) / (2 sig^2)], {k, 0, Infinity}]     NIntegrate[func[z, 5, 2], {z, -Infinity, Infinity}]      Have I made a mistake somewhere? Or misunderstood the integral/problem as given? **Update** A suggestion is to replace the infinite sum with an upper limit of ~50 as it converges quickly. This does allow Mathematica to now evaluate the integral.


title: Mathematica sporadically crashes on open

text: Sometimes, when I open Mathematica, while the opening splash screen still says "Initializing Kernel Connections", Windows will tell me that "Wolfram Mathematica 9 has stopped working". This will happen every time I try to open Mathematica for a while, but then just as randomly as it started, it will stop, and I'll be able to open Mathematica again with no problems. When it stops working, I'm given the option to Debug it, but all I can tell is that it's a segmentation fault that seems to be caused by dereferencing a null pointer. Interestingly, MathKernel still runs fine even when Mathematica is refusing to launch. Does anyone know how I can start fixing/investigating the cause of this? Edit:   Version: Mathematica Version 9.0.1.0, Microsoft Windows 64-bit   OS: Windows 8


title: Rearranging a matrix

text: I would like to convert a matrix which has a structure like this:               {{"A", 10, "D", 1},{"B", 3, "A", 2},{"C", 7, "B", 3},{"D", 6, "C", 4}}//MatrixForm//Print;      into one that looks like this:               {{"A", 10, "A", 2},{"B", 3, "B", 3},{"C", 7, "C", 4},{"D", 6, "D", 1}}//MatrixForm//Print;      Is there a way to do this that still works when column 1 is not in alphabetical order.


title: How can I set different opacity values for the background of a ListPlot

text: In the following example:               ListPlot[{1, 2, 3}, Background -> Green]      how can I set the `Opacity[]` for the background such that the opacity increases from top to bottom?


title: Take part of image under locator

text: How to create Manipulator with Locator to take part of an image? ![enter image description here](http://i.stack.imgur.com/Db9AG.png)


title: Complex line integral

text: Can someone recommend an online article or introductory tutorial that will show me how to do real and complex line integrals using _Mathematica_?


title: Porting code from MATLAB

text: I'd like to switch from MATLAB to Mathematica for my research in digital signal processing. I used Mathematica a lot during the '90s but I haven't used it since then, so I might as well be a complete newbie. As a first experiment I tried to port the following MATLAB function (a slow implementation of CQT):               function cq= slowQ(x, minFreq, maxFreq, bins, fs) % x must be a row vector          Q = 1/(2^(1/bins)-1);     maxK = ceil(bins*log2(maxFreq/minFreq));     maxN = ceil(Q*fs/minFreq);     if size(x,2) < maxN         x(end+1:maxN) = 0;     end          for k=1:maxK         fk = minFreq * 2^((k-1)/bins);        N = ceil(Q*fs/fk);        cq(k) = x(1:N) * (hamming(N) .* exp( -2*pi*i*Q*(0:N-1)'/N)) / N;      end          end      This is the code I came up with, which not only looks horrible but is also horribly slow (several orders of magnitude slower than MATLAB):               slowCQT[x_, minFreq_, maxFreq_, bins_, fs_] :=         Module[{Q, maxK, maxN, k, fk, Ncq, cqt},             Q = 1/(2^(1/bins) - 1);             maxK = Ceiling[bins*Log2[maxFreq/minFreq]];             maxN = Ceiling[Q*fs/minFreq];             If[Length[x] < maxN,                  x = Join[x, ConstantArray[0, maxN - Length[x]]]];             cqt = ConstantArray[0, maxK];             For[k = 1, k < maxK, k++,                 fk = minFreq*2^((k - 1)/bins);                 Ncq = Ceiling[Q*fs/fk];                 cqt[[k]] =                  N[x[[1 ;; Ncq]].(N[HammingWindow[Range[-1/2, 1/2, 1/(Ncq - 1)]]] *                      N[Exp[-2*Pi*I*Q*Range[0, Ncq - 1]/Ncq]])/Ncq];];             cqt]      Any suggestions or pointers to improve it? EDIT: Example usage MATLAB               fs = 44100;     T = (0:2*fs)/fs;     x=sin(2*pi*440*T);     tic; cqt = slowQ(x,27.5,880,24,fs); toc          Elapsed time is 0.305124 seconds.      Mathematica               fs = 44100;     T = N[Range[0, 2*fs]/fs];     x = N[Sin[2 Pi 440 * T]];     tic = AbsoluteTime[];     cqt = slowCQT[x, 27.5, 880, 24, fs];     AbsoluteTime[] - tic          89.755638


title: RecurrenceTable not evaluated: mathematica just echoes input

text: Forgive the newbie question... I am trying to create a table of the following system, following the Stirling example in the documentation, but Mathematica just echoes my input. What am I doing wrong?               RecurrenceTable[        {s1[n, k] == s1[n, k - 1] + s1[n - 1, k - 1],          s1[0, k] == 1, s1[n, 0] == Boole[n == 0], s1[n, 1] == Boole[n <= 2]},         s1, {n, 0, 6}, {k, 0, 4}     ] // Grid


title: Converting from TableForm to Grid

text: I wonder if there is an easy way to convert from TableForm to Grid. I have an existing data format that uses the Table function that I’d like to prettify…. Let’s setup a nested table as follows:               params = {"A", "B", "C", "D"};  (*example, can be more *);     axes = {"x", "y", "z”}; (*fixed number*) ;     mean = {l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12}; (*example data, maybe more*);     stdev = {m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12};     stat = {n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12};     labels = {"params", "axes", "mean\[PlusMinus]stdev", "other stat"};      My data format is as follows:               expr = MapThread[{#1, {#2, #3}, #4} &, {Flatten@      Table[axes, {i, 1, Length@params}], mean, stdev, stat}];     mytable = MapThread[{#1, #2} & , {params, Partition[expr, 3]}];      Visualizing the table:               TableForm[mytable]       ![TableForm output](http://i.stack.imgur.com/13Qt0.png) I’ve been banging my head on how to format this table using Grid while maintaining the general structure of the table. Q1. **What is the best way to convert this from TableForm to a Grid.** Q2. **Is there a better data structure I could use that would allow me to use TableForm or Grid interchangeably?** Related Question: Grid - sizing and spacing problems with spanning cells


title: Single Legend for a Table of Plots

text: For this toy problem               Needs["PlotLegends`"]          GraphicsGrid[      Partition[       Table[ListPlot[         Table[{x, f[x]}, {f, {Sin, Cos}}, {x, 0, Pi, Pi/10.}],          PlotRange -> {{0, Pi}, {-1, 1}},          PlotLegend -> {"Sine", "Cosine",}, LegendPosition -> {1.1, -0.4},          PlotMarkers -> Automatic], {k, 1, 6, 1}], 3], Spacings -> 0,       ImageSize -> 700]      I was trying to make a single legend (precisely the legend you see here four times) for the entire `GraphicsGrid` rather than the same legend four times. How do I do so? * * * **Edit:** Same question but now with v9 code that doesn't require loading any package:               GraphicsGrid[      Partition[       Table[ListPlot[{Sqrt[Range[50]], Power[Range[50], (3)^-1]},          PlotLegends ->           PointLegend[Automatic, {"one", "two"}, LegendFunction -> "Frame",            LegendLabel -> "datasets"]], {k, 1, 6}], 3], ImageSize -> 800]      ![enter image description here](http://i.stack.imgur.com/Xh3Ww.png)


title: InterpolatingFunction with growing Domain

text: I want to find roots of a function that is very slow to calculate (the function itself involves a bunch of FindMaxima) so I interpolate the function in a region where I think it likely the the root is, since I have very little certainty where the root is I have to interpolate an absurdly large region. Is there a way to have InterpolatingFunction remember the original function and expand its domain when evaluation is attempted outside it?


title: Unencoding encoded URLs in a function

text: Is there a built-in function for decoding encoded URLs in _Mathematica_? I would like to convert an encoded URL, for example `https%3A%2F%2Fwww.google.co.uk%2Fimages%2Fsrpr%2Flogo4w.png` into `https://www.google.co.uk/images/srpr/logo4w.png` as attempting to directly access the encoded URL with `Import[]` fails.


title: Twirl Image Transformation

text: I am looking to reproduce the functionality of Photoshop's "Twirl" filter, which twists an image that originally looks like this (pulled from this page): ![enter image description here](http://i.stack.imgur.com/Di28d.png) Into this: ![enter image description here](http://i.stack.imgur.com/IBjxt.png) Ideally, I'd like it to approximate the way the Photoshop Twirl filter behaves as much as possible, or at least be flexible enough to be able to reproduce the way the filter works.


title: How to get state of checkbox?

text: Please explain how to get state of checkbox for its usage in further calculations. And I want to keep the selection from session to session without external savings. Thanks in advance


title: How to style and position VerticalCallouts and RadialCallouts

text: Here is a pie chart with a labels placed with a "VerticalCallout"               PieChart[Range[10],      PerformanceGoal -> "Speed",      ChartLabels ->        Placed[Range[10], "VerticalCallout", Style[#, Red, Bold, 14] &],      SectorOrigin -> {Automatic, 1}]      ![enter image description here](http://i.stack.imgur.com/3ycE2.png) I was trying to figure out what, if any, options control the colour and thickness of the "call out" lines and disk. So Q1. Are there built in options to change this styling? I was able to alter the styling via a rule replacement:               PieChart[Range[10],       PerformanceGoal -> "Speed",       ChartLabels ->         Placed[Range[10], "VerticalCallout", Style[#, Red, Bold, 14] &],       SectorOrigin -> {Automatic, 1}] /. {{x_Thickness, _GrayLevel,          y_Opacity, z__} :> {AbsoluteThickness[1], Red, y,          z}, {_GrayLevel, _Opacity, Disk[x_List, _]} :> {Red,          Disk[x, 0.05]}}      ![enter image description here](http://i.stack.imgur.com/BE2FE.png) But... Q2. Is there a way to specify the vertical positioning of the labels (for "VerticalCallout"? That is, to specify how far left and right from pie chart that they are positioned? By default they appear to align at the "image boundary" but if I set image padding or alter the plot range the label positions don't alter. **Edit** ok I have figured out Q2 via rule replacements as well but would still like to know if this can be controlled via built in options.               PieChart[Range[10],        PerformanceGoal -> "Speed",        PlotRangePadding -> 0,        ImagePadding -> 0,        ImageSize -> 600,        PlotRange -> {{-4.5, 4.5}, {-4.5, 4.5}},        ChartLabels ->          Placed[Range[10], "VerticalCallout", Style[#, Red, Bold, 14] &],        SectorOrigin -> {Automatic, 1}] /. {Text[x_, {a_, b_}, z_] :>          Text[x, {a*1.8, b}, z], {x_Thickness, _GrayLevel, y_Opacity,           z__} :> {AbsoluteThickness[1], Red, y, z}, {_GrayLevel, _Opacity,           Disk[x_List, _]} :> {Red, Disk[x, 0.05]}} /.       Line[{{x_, y_}, {z_, y_}}] :> Line[{{x, y}, {z*1.8, y}}]      ![enter image description here](http://i.stack.imgur.com/SfE17.png)


title: Calculating morphometric properties

text: Is it possible to calculate segment length, segment diameter and branch angles for three dimensional geometry. Geometry contains vertex points and polygon surfaces as                 file = "http://i.stack.imgur.com/N6RYT.png";       Import[file, "Graphics3D"]      ![enter image description here](http://i.stack.imgur.com/N6RYT.png)                 data = Import[file, "VertexData"];       polysurface = Import[file, "PolygonData"];       Graphics3D[Point@data]


title: How can I obtain Wolfram Alpha's "alternative forms" of an expression inside Mathematica?

text: When I type in Wolfram Alpha, say,               cos(a+b)      or               cos(a+b)^2      or (OK this next one can easily be obtained in Mathematica, still, I have run into Bessel function expressions that cannot be simplified by Mathematica, but get a decent "alternative expression" through W|A)               D[A^mu BesselK[mu, A r], A]      I get several alternative forms of these, but I cannot seem to obtain them simply from **pure** Mathematica (i.e. no W|A integration stuff). Am I missing something or is Wolfram Alpha just smarter in these things? The alternative expressions have helped me quite a lot, so it would be nice to have them in my toolbox without having to access Alpha.


title: Implementing the Farey sequence efficiently

text: There is of course the silly implementation:               FareySequence[n_] := Union[Flatten[Table[j/i, {i, 1, n}, {j, 0, i}]]]      However, there are numerous properties and confinements of Farey sequences (that can be used, **potentially** , in an indirect manner). This calls for a very simple, and, very efficient recurring/functional implementation, exhibiting _Superiority_. But I'm new to _Mathematica_ and can't find the right combination of built-in functions, and pure functions.. Ideas?


title: Refresh dynamic variable when used with Get

text: I came across this issue with a more complicated program I was working on. Suppose we have a volatile variable `data`:               In[1]:= data = RandomReal[{0,1},{10}];      As this cell is evaluated,               In[2]:= Dynamic@data      refreshes as expected. However, if we want to save a certain instance of data and later load it in:               In[3]:= DumpSave["filepath.mx",data]      (change value of `data` to something else)               In[4]:= <<"filepath.mx"      the dynamic cell (`In[2]`) isn't updated (unless you evaluate it again). It can be forced to update on the loading of the .mx file by using a `Refresh[...,UpdateInterval->time]`, but it seems odd that re-evaluating `In[1]` instantly changes the dynamic cell while redefining `data` with the .mx file doesn't. Any explanation for this? And is using the `Refresh` method a good solution here?


title: How to convert the symbol $d$ in Integrate into $\mathrm{d}$?

text: I used               TeXForm[HoldForm[Integrate[x^2, {x, 1, 2}]]]      to convert the integral $$\int_1^2 x^2 \, dx$$ How to get $$\int_1^2 x^2 \, \mathrm{d}x ?$$


title: Excluding a Region in ParametricPlot3D

text: Suppose I have a torus and a closed path on said torus:               r = 1;     R = 2.5*r;     a = .8;     b = .4;      path = ParametricPlot3D[{{(R + r Cos[a Sin@w]) Cos[b Cos@w], (R + r Cos[a Sin@w]) Sin[b Cos@w], r Sin[a Sin@w]}}, {w, 0, 2 π},  PlotStyle -> {Black, Thickness[0.008]}];     patch = ParametricPlot3D[{{(R + r Cos@v) Cos@u, (R + r Cos@v) Sin@u, r Sin@v}}, {u, 0, 2 π}, {v, 0, 2 π}, Mesh -> False, PlotStyle -> Opacity[0.75]];     Show[patch, path, Boxed -> False, BoxRatios -> Automatic]      ![torus with path](http://i.stack.imgur.com/xOgU9.gif) What I want to know is: Is there some way of plotting my torus without the part that is cut out by the path? I'm sure there is an easy way to do this with something like "Eliminate" but it seems just outside of my skill.


title: RegionPlot (or FillingStyle) using hash lines?

text: > **Possible Duplicate:**   >  Filling a polygon with a pattern of insets I have a RegionPlot (and sometimes a regular Plot) where I'd like to shade two different parts of it two different ways. Since the final output will be printed in black and white, I'd really like to do this in an old fashioned way: with hash lines. I was mainly wondering if there is some built in way to do this without developing it from scratch.


title: How to show an exclusion limit

text: I would like to show an exclusion plot, by having a filling made of parallel tilted lines. Any ideas? Something along these lines ![enter image description here](http://i.stack.imgur.com/y82aW.gif)


title: Output of NonlinearModelFit differs from the correct result

text: I'm having a bad time dealing with the `NonlinearModelFit` in Mathematica 8, since the result given is a bit imprecise. An example is given on potential regression, as follows:               data = {{0.9, 1.1}, {2, 2}, {6, 4.1}, {6.9, 4.5}, {9.9, 5.5},              {10.7, 5.9}, {14, 6.7}, {15.9, 7.3}}          NonlinearModelFit[data, b*t^a, {a, b}, t]      The result I get is: `1.34232*t^0.615024`, however it should be `1.23...*t^0.6548`. What am I doing wrong? I experience the same thing when I try to do a exponential regression (like this: `NonlinearModelFit[data, b*a^t, {a, b}, t]`).


title: Error message LinkObject::linkd when calling TextRecognize

text: I am getting the message > LinkObject::linkd: "Unable to communicate with closed link > LinkObject["E:\Program Files\Wolfram > Research\Mathematica\9.0\SystemFiles\Converters\Binaries\Windows\Tesseract.exe", > 134, 7] This is what is did As Mathematica's version of Tesseract was not recognizing text correctly, I installed `tesseract-ocr-setup-3.02.02.exe` in another directory. But my efforts were in vain. Therefore, I uninstalled that setup and, then, when I tried the following code it gave me the error message quoted above. Maybe I messed up somewhere.               x = Import["http://i.stack.imgur.com/AqSqO.jpg"];     TextRecognize[x];      Please, can anyone help me to solve this problem. ![enter image description here](http://i.stack.imgur.com/AqSqO.jpg)


title: Extract the left channel from an mp3 file

text: I'm trying to control where a sound is going to be heard, in the left For example, when I import an mp3 file, and I want to hear it only from the left ear, what should I do? I've never worked with sounds before, so I didn't know where to start. The **Documentation Center** seems very undocumented on this topic.


title: Travelling salesman with start and end points for 30 points

text: I am doing a route optimisation for delivery vehicles and failing dismally. Please see problem statement below. My current solution uses FindShortestTour, but this does not have defined start and end points. Data is received from the calling application in the following format: {"Unique Identifier used by server", Original order, Task locked, Latitude, Longitude} The first point will always have the unique identifier "00000000-0000-0000-0000-000000000000" and represents the depot. This point will always have an order of 1 and always be locked. A number of tasks may be locked in their given order at the beginning of the list. The Task locked is a boolean represented by 1 - locked, 0 - unlocked. These locked tasks are not included in the optimisation as they are fixed in their given order at the beginning of the scheduled. The route is to be optimised finding the shortest path starting at the last locked point and ending back at the depot, traversing all other unlocked points. Depot is always locked and will be used if there are no other locked tasks. The output is to be in the following format: {"Unique Identifier used by server", Original order, Distance to Next Task in km} and is to be arranged in the optimal order. The order will always start with the depot the traverse locked Tasks in their given order. This will be followed by unlocked tasks optimised from the last locked to the depot. This list will not contain the final depot point as the distance returned is the distance to next task. i.e. The last ordered task distance will be the distance from itself to the depot. The calculation needs to be able to handle the optimisation of 30 points in under a minute as accurately as possible.               input = {{"00000000-0000-0000-0000-000000000000", 1.,          1., -26.17132739,          28.21375807}, {"817463b3-e330-4405-9008-e21821e6c121", 2.,          1., -26.2055333333333,          28.420565}, {"36418378-a9ef-49d7-be5a-3a54264a8479", 3.,          0., -25.99202013,          27.53309061}, {"49595197-11e5-463a-8f7b-6cd294c33f43", 4.,          0., -26.14895194,          27.92271447}, {"83fd029b-0313-4519-a785-ff7b9843c85c", 5.,          0., -26.169355,          28.2079083333333}, {"612bf08a-1679-4feb-8fee-d12deb49803a", 6.,          0., -25.6755766666667,          28.0820533333333}, {"382f1997-5efe-42c1-99f5-bcb8da30e1c8", 7.,          0., -26.8742866666667,          28.25047}, {"883d68f2-b50f-48ca-b065-febfc6ea9546", 8.,          0., -26.0938733333333,          28.1937966666667}, {"1bf089bf-acae-4a41-8c4b-e120cef8a148", 9.,          0., -25.9877716666667,          28.0691433333333}, {"6958e90b-d42a-4c13-b6ec-78bbdd301aba", 10.,          0., -25.7661166666667,          28.2811033333333}, {"2f2c5d25-c1de-449e-b779-dd95699d83ed", 11.,          0., -26.0474216666667,          28.0060766666667}, {"a11feb01-f067-49aa-b99d-50879229c423", 12.,          0., -25.7949916666667,          28.29928}, {"729b8bfb-029a-483a-814a-1575a6fe47bc", 13.,          0., -26.0258616666667,          28.0692033333333}, {"732771dd-55fd-4074-a097-2665686f67d8", 14.,          0., -26.772045,          28.49977}, {"0690914d-ba34-4086-b5ae-feda7ed6d22b", 15.,          0., -26.044905,          28.0346666666667}, {"5de23f0e-9a05-40af-8e1e-f887d5a06452", 16.,          0., -26.4070083333333,          28.138515}, {"3e95a2ac-9985-4753-a4cc-5372ca44ed12", 17.,          0., -25.64392423,          28.13148167}, {"d2e0bce2-8061-4b57-b983-aa409c1532fe", 18.,          0., -26.42138814,          28.1074221}, {"0259d54a-0782-4ac8-a5f6-42af6e3edbc3", 19.,          0., -25.78637, 28.28066}, {"f686b23a-de85-4004-ae70-8d2703336b5d",          20., 0., -26.043795,          28.1197816666667}, {"e8bca7d4-69ad-4477-8791-9daedbc563c9", 21.,          0., -26.2624883333333, 28.17859}};               outputReturned = {{"00000000-0000-0000-0000-000000000000", 1.,         21.020}, {"817463b3-e330-4405-9008-e21821e6c121", 2.,         26.772045}, {"732771dd-55fd-4074-a097-2665686f67d8", 14.,         63.26}, {"382f1997-5efe-42c1-99f5-bcb8da30e1c8", 7.,         27.24}, ..., {"83fd029b-0313-4519-a785-ff7b9843c85c", 5., 0.62}}      Current poor solution here: https://dl.dropbox.com/u/9666857/Schedule.m **Edit** The requirement boils down to a traveling salesman path problem. I have a fixed start and end point with a list of intermediate points which need to be visited exactly once in an optimal order. I have a working solution here


title: A math function similar to "LatticeReduce" for finding linear independent basis

text: We would like to ask a math function similar to "LatticeReduce" for finding linear independent basis. The input is a list of vectors $M=\\{v_1,v_2,v_3,\dots\\}$, with the following property: There is a subset $O=\\{w_1,w_2,w_3,\dots\\}\subset M$, such that $O$ is a basis, i.e. linearly independent and span $M$, $$ v_i=\sum_a c_{ia} w_a.$$ Moreover, the coefficients $c_{ia}$ are **non-negative integers**. An explicit example is the following: $$M=\left( \begin{array}{ccccc} 1 & 1 & 1 & 1 & 1 \\\ 1 & 1 & -1 & -1 & 1 \\\ 1 & 1 & -1 & 1 & -1 \\\ 1 & 1 & 1 & -1 & -1 \\\ 2 & -2 & 0 & 0 & 0 \\\ 2 & 2 & 2 & 0 & 0 \\\ 2 & 2 & 0 & 2 & 0 \\\ 2 & 2 & 0 & 0 & 2 \\\ 2 & 2 & -2 & 0 & 0 \\\ 2 & 2 & 0 & -2 & 0 \\\ 2 & 2 & 0 & 0 & -2 \end{array} \right),\quad O=\left( \begin{array}{ccccc} 1 & 1 & 1 & 1 & 1 \\\ 1 & 1 & -1 & -1 & 1 \\\ 1 & 1 & -1 & 1 & -1 \\\ 1 & 1 & 1 & -1 & -1 \\\ 2 & -2 & 0 & 0 & 0 \end{array} \right), $$ where $O$ is the first 5 rows of $M$ and $$M[[6]]=O[[1]]+O[[4]],\, M[[7]]=O[[1]]+O[[3]],\,\dots$$ In Mathematica form, the example is               m = {{1,  1,  1,  1,  1},          {1,  1, -1, -1,  1},          {1,  1, -1,  1, -1},          {1,  1,  1, -1, -1},          {2, -2,  0,  0,  0},          {2,  2,  2,  0,  0},          {2,  2,  0,  2,  0},          {2,  2,  0,  0,  2},          {2,  2, -2,  0,  0},          {2,  2,  0, -2,  0},          {2,  2,  0,  0, -2}};      May we know that how to write a function/program such that inputting such $M$, the program will output the desired $O$. _For this example the built-in function LatticeReduce works well. But we are not sure it always works._


title: How to set PageWidth when using PutAppend to append expressions to a file?

text: Do[       PutAppend[Table[i, {RandomInteger[100]}], "./file.m"],       {i, 100}     ]      I'd like each inner list to always appear on the same line, but not automatically wrapped at 68th character. How to achieve that? I wonder where and how the PageWidth option should be set for the InputStream used by the PutAppend.               #!/usr/bin/env bash          sed -e '         /.* $/ {             N             /\n .*$/ {                 s/\(.*\) \n \(.*\)/\1 \2/             }         }     ' $1      will fix the broken lines.


title: How to create a simple interface to get file path and execute some code on it?

text: I need to create a simple user interface to choose one file in the notebook directory, import it and execute some functions on the imported data. For the first version I created this code:               Button["get File Path",      fileData = Import@SystemDialogInput["FileOpen", NotebookDirectory[]];      ];      function[fileData]      Now I want it to be a little bit more error proof, so if you cancel your selection, you don't get an error, and the rest of your code is not executed.               Button["get File Path",     fileData=Quiet@Check[Import@SystemDialogInput["FileOpen",NotebookDirectory[]],$Canceled]         ]         If[fileData!=$Canceled,function[fileData]]      I don't feel that it is the best practice for this kind of situation. Some clue to make the code more intelligent? Maybe with `Module`, `DynamicModule`, `Return` or something else?


title: Opening a notebook from command line in an existing front end instance

text: I am using Linux, and I would like to be able to programmatically open notebooks in a running Mathematica instance from the command line. Currently, doing something like /opt/Wolfram/Mathematica/8.0/Executables/Mathematica foo.nb launches a new kernel/frontend instance. Is it possible to re-use a running frontend for opening notebooks (short of enforcing single-instance behavior, for which I believe there is a command line option)?


title: Interpolation with boundary conditions

text: I'm working on a sales projection, trying to create some flexibility in handle the forecast using locators. The toy code is something like this:               DynamicModule[{pts={{1,1},{2,1}}}         ,LocatorPane[             Dynamic[pts]            ,Dynamic@Plot[Piecewise[{{InterpolatingPolynomial[{{0,1},Sequence@@pts,{3,5}},x],x<3},{5,x>3}}],{x,0,5},PlotRange->{{0,5},{0,6}}]         ]     ]      ![plot](http://i.stack.imgur.com/IdyQl.png) Where I can change the locators position in order to change the curve. **The question is, assuming my plot functions as`f[x]`**   1. How to define `f'[3]=0` to don't get the slop break in `{3,5}`?   2. How to define `f'[0]>0` to don't get a initial down slope? So I could control the polinomial order to get these conditions met, still using locators. Maybe using `NDSolve` together with `LinearModelFit`? Or is there a simpler way? **Update** The first condition was solved by @kguler and @belisarius. Tks to both. Some clue for the second?


title: Mathematica usage (success stories) for financial back-ends

text: I've been working for about 5 years in Java, developing financial back-offices (web-services, business logic, report generation etc.). I think Mathematica is very suitable for such calculations and business logic development and am wondering if there are any success stories for its usage in such systems. I also think that it can be pretty to use Mathematica with JLink in my web- application to delegate calculations.   * **Does anyone have such an experience or know-how ?** **UPD 1:** Removed some questions (they have relation to Wolfram Workbench): What about unit-testing in Mathematica ? How to organize Mathematica code if it would be very large ?


title: How to calculate FDCT

text: I'm new to Mathemtica and I'm trying to calculate Discrete Cosine Transformation FDCT. I found the FourierDCT built-in function, but not DCT, so I need to implement it. I have tried couple of ideas but no luck yet. Any ideas that can get me started will be really appreciated. ![enter image description here](http://i.stack.imgur.com/oGSwG.png) Edit 1 **_*_ ** _*_ ** _*_ ** _*_ ** _*_ ** _*_ ** _*_ ** _*_ ** _*_ ** _*_ **** This is the result of FourierDCT on the same Matrix from the Wikipedia link above, and the values are different. I need Forward Discrete Cosine Trasnformation, not the FourierDCT: ![enter image description here](http://i.stack.imgur.com/pCkUu.png) From Wikipedia: "A DCT is **similar** to a Fourier transform in the sense that it produces a kind of spatial frequency spectrum." Edit 2 **_*_ ** _*_ ** _*_ ** _*_ ** _*_ ** _*_ ** _*_ ** _*_ ** _*_ ** _*_ **** This is the matrix I'm using as input in Mathemtica: b = {{52, 55, 61, 66, 70, 61, 64, 73}, {63, 59, 55, 90, 109, 85, 69, 72}, {62, 59, 68, 113, 144, 104, 66, 73}, {63, 58, 71, 122, 154, 106, 70, 69}, {67, 61, 68, 104, 126, 88, 68, 70}, {79, 65, 60, 70, 77, 68, 58, 75}, {85, 71, 64, 59, 55, 61, 65, 83}, {87, 79, 69, 68, 65, 76, 78, 94} }


title: Visualizing the output of a Voronoi diagram computation

text: I need to plot a graph (to be specific: Fortune Algorithm output) with given vertex coordinates and a few unconnected vertices. I am thinking of using Mathematica for that. `GraphPlot` does much of the task with `VertexCordinateRules` option but does not plot unconnected points.   1. So is there any way to do this?   And it would be even nicer if that graph comes with 2-D Axes. I was thinking to use `ListLinePlot` and `Point` commands but they give two different graphs as output.   2. Is there any option for combining output from two graphs? (The `Show` command didn't help.)


title: Unsupervised Machine Learning Algorithm for Autonomous Image Processing and Tracking

text: I am trying to prototype a Mathematica application that will enable Autonomous Intruder & Anomalous Event Detection, Tracking and Alarm to web users those who want to autonomously and asynchronously monitor their private spaces such as homes, offices as well as outdoor spaces such as backyards, roads and recreation facilities using inexpensive commercial Internet-connected IP-cams and webcams. I want to employ a proven and tested unsupervised algorithm that will help me accomplish my goal. Any idea which one would be the best? What are the Mathematica functions that will help me customize such an algorithm? I am using network license of Mathematica-8.


title: Colorize a 3D distribution of points according to density

text: Suppose we have some random 3D distribution of points. I'll use the spherical ball defined below as an example and a starting point for the discussion here :               Ball[num_]:=Table[     {         #1 Sqrt[1-#2^2]Cos[#3],         #1 Sqrt[1-#2^2]Sin[#3],         #1 #2     }          &[         Random[NormalDistribution[1, 0.5]],         Random[Real,{-1,1}],         Random[Real,{0,2Pi}]     ],{num}]          Graphics3D[{AbsolutePointSize[2],Point[Ball[10000]]},Boxed->True,BoxRatios->{1,1,1},ImageSize->800,SphericalRegion->True]      This code produces the ball shown here : ![A spherical distribution of points in 3D space](http://i.stack.imgur.com/ONB8Q.jpg) I would like to colorize the whole distribution with a color shade defined on the density of points, from **_color1_** (highest density of points) to **_color2_** (lowest density of points). Adding more colors to the shade is a desirable option ( ** _color1_** to **_color2_** to **_color3_** ... to **_colorN_** ). How can I do that ? What Mathematica code could do this ? Please, the suggestions should be compatible with **_Mathematica 7.0_**.


title: Changing variables algebraically

text: Suppose one has two functions, $y(x)$ and $z(x)$, and one seeks to obtain $y(z)$ by substituting $x(z)$ into $y(x)$. Can this be done in a single step? Or must $z(x)$ first be inverted independently? For the sake of illustration, suppose the functions consist of transcendental functions combined by the elementary operations of addition, subtraction, multiplication, division, and exponentiation. For instance, $y(x) = a\ln x + \displaystyle\frac{\exp(bx)}{c+x}$ $z(x) = \ln x \cdot \left(1 - \cos x \exp(a^2x) \right)^{r}$


title: Running some code every time a new notebook is opened

text: **Is it possible to automatically execute some code every time a new notebook is opened?** So for example I would like to print a message "New notebook" every time a new notebook is opened. This question was prompted by this answer about fixing indentation when moving to a new line. The "fix" requires that some code is applied to the notebook every time it is opened. But I think this question in interesting enough to stand on it own. I even have some working code, but it based on polling, so I would like to avoid that if possible. (also is it possible to get rid of the global variable `$OldNotebooks`?)               Clear[GetNewNotebooks, $OldNotebooks];         $OldNotebooks = Notebooks[];     GetNewNotebooks[] :=        Module[{new},         new = Complement[Notebooks[], $OldNotebooks]; $OldNotebooks =          Notebooks[]; new];     (*new=GetNewNotebooks[];*)          NBHistory = {}; Dynamic[NBHistory]          StartScheduledTask@       CreateScheduledTask[NBHistory = NBHistory~Join~GetNewNotebooks[]];      Now every time you open a new notebook, it will get added to the list of NBHistory and displayed.               (*When you had enough:) *)     RemoveScheduledTask[ScheduledTasks[]]


title: Symbolic integration in the complex plane

text: **Context** While answering this question, I defined (symbolic and numerical) path integrations as follows                ContourIntegrate[f_, par : (z_ -> g_), {t_, a_, b_}] :=             Integrate[Evaluate[(f /. par) D[g, t]], {t, a, b}]           NContourIntegrate[f_, par : (z_ -> g_), {t_, a_, b_}] :=             NIntegrate[Evaluate[D[g, t] (f /. par) /. t -> t1], {t1, a, b}]      I also defined a piecewise contour               Clear[pw];      pw[t_, a_: 1] = Piecewise[{{a Exp[I t], t < Pi}, {-a + 2 a (t - Pi)/Pi, t >= Pi}}]     ParametricPlot[pw[t] // {Re[#], Im[#]} &, {t, 0, 2 Pi}]      ![Mathematica graphics](http://i.stack.imgur.com/9JnzU.png) While checking these routines on wikipedia examples, I tried numerically                Table[NContourIntegrate[Exp[I i x]/(x^2 + 1), x -> pw[t, 2], {t, 0, 2 Pi}], {i, 2, 5}] // Chop          (* {0.425168,0.156411,0.0575403,0.0211679} *)      which corresponds accurately to (see example II for Cauchy distributions)               Table[Exp[-i] Pi, {i, 2, 5}] // N      On the other hand, the symbolic integration               ContourIntegrate[Exp[I x]/(x^2 + 1), x -> pw[t, 2], {t, 0, 2 Pi}] // FullSimplify      returns 0. **Question** What am I doing wrong? **Attempts** Example I and III work ;-)               ContourIntegrate[1/(x^2 + 1)^2, x -> pw[ t, 2], {t, 0, 2 Pi}] // FullSimplify     NContourIntegrate[1/(x^2 + 1)^2, x -> pw[ t, 2], {t, 0, 2 Pi}] // Chop          (* Pi/2  1.5708 *)      and               NContourIntegrate[1/I/x/(1 + 3 ((x + 1/x)/2)^2), x -> Exp[I t], {t, 0, 2 Pi}]//Chop     ContourIntegrate[1/I/x/(1 + 3 ((x + 1/x)/2)^2), x -> Exp[I t], {t, 0, 2 Pi}]          (* 3.14159  Pi *)


title: Defining a recursive sequence

text: I want to define a recursive sequence and then ask Mathematica to print a specific value: ![enter image description here](http://i.stack.imgur.com/2wC22.png) Am I doing something wrong?


title: How to find the period of an arbitrary mathematical function?

text: Is there a function to find the period of an arbitrary (possibly complex) function in _Mathematica_?


title: How to stop V10 asking to continue with updated styling each time I open a new notebook

text: Each time I open a new notebook, using File->New->Notebook, I get this message ![Mathematica graphics](http://i.stack.imgur.com/J0LeN.png) Then I check on the "Do this for all notebooks". But when I repeat this and want to create a new notebook, it asks again. Restarted M and still no change. Any idea what can cause this and how to resolve it? ![enter image description here](http://i.stack.imgur.com/hYfjF.gif) I am on window 7, 64 bit. Version 10.


title: How do I plot a function over a subset of the displayed interval?

text: I want to plot `f1[x]` over `0 < x < L/2` and `f2[x]` over `L/2 < x < L` (i.e. so that `f1[x]` isn't displayed over`L/2 < x < L`, etc.). How do I do this?


title: Some Problem with WhenEvent!

text: Anyone knows what's the problem with the following code and how can I fix it? I am not sure that I wrote the WhenEvent section correctly. By the way, I want to solve the equations and then plot y vs. y' when x goes to zero (it is obvious that it's an interval :) ). Thanks               tmax = 300;     {{sol1}, {ps}} = Reap[     NDSolve[      {x'[t] == -(x[t] + 2 x[t] y[t]),       y'[t] == -x[t] x[t] + y[t] (y[t] - 1),       x[0] == 0.1, y[0] == 0.1,       WhenEvent[Limit[x[t], x[t] -> 0], Sow[t]]},      {x, y},          {t, 0, tmax}]]


title: Way to find color at a point in a Graphics?

text: I need to figure out a way to find out the RGB color value at a certain coordinate in a Graphics object. The Graphics object I am dealing with is continually Dynamically updated, so it is made of moving objects. How can I find the color at a certain point in this moving graphics object. There is a function, for Image type, called ImageValue which will give color at the given point, but then I have to somehow convert the Graphics to a Image each time I want to check the color at a point, since the Graphics is changing. I have the following code to do that, but it takes much too long to do so, and causes a visible pause. I replace the Dynamic type of the Graphics with Image.               image = screen /. Dynamic -> Image      The above calculation takes too long, when I checked the timing of it. What I am asking for is a faster, easier way to make a Dynamic Graphic an Image so I can take color like that, or a way to take color at a certain point in Graphics. Please help, A frustrated student. Code except:               screen = Dynamic[Show[{backdrop, carsList}];     image = screen /. Dynamic -> Image;     points = ImageValue[image, {newX, newY}];         For[i = 1, i < Length[points], i++,                 If[points[[i]] == {0, 0, 2/3} || points[[i]] == {1, 0, 0},                     valid = False;                     Break[];                 ];             ];      points would usually hold more color data for points, I shortened code.


title: Interactive steam tables and phase diagrams in Mathematica

text: I teach an undergraduate course in Thermodynamics and I would love to use Mathematica to demonstrate the various engineering processes that involve the expansions and compressions of steam and common refrigerants such as R134a. I know that wolfram alpha does provide steam data but I'd rather have this from Mathematica. I also do know that in the Mathematica guide (`guide/ScientificAndTechnicalData`), some data is available but it is generally viscosities, molecular formulae etc. Is there any way I could get steam table data into/from Mathematica? Students generally use steam tables available in their textbooks and that is a fantastic starting point as I would never want to do away with that. However, using Mathematica would be a fantastic way of introducing my students to this wonderful tool that has helped me in my research. This would be very transformative to the way steam tables are particularly viewed as (with general disdain among sophomores and junior level students)!


title: How can I display a multigraph with different colored edges?

text: I'm new to Mathematica(version 9) and I'm trying to display a multigraph with different colored edges. Here's my code so far:               G = {{1 -> 2, 1},  {2 -> 3, 1},  {3 -> 4, 1}, {4 -> 5, 1},          {5 -> 6, 1},  {6 -> 7, 1},  {7 -> 8, 1}, {8 -> 9, 1},          {9 -> 1, 1},  {1 -> 2, 2},  {2 -> 3, 2}, {3 -> 4, 2},          {4 -> 5, 2},  {5 -> 6, 2},  {6 -> 7, 2}, {7 -> 8, 2},          {8 -> 1, 2},  {1 -> 2, 3},  {2 -> 3, 3}, {3 -> 4, 3},          {4 -> 5, 3},  {5 -> 6, 3},  {6 -> 7, 3}, {7 -> 1, 3},          {1 -> 2, 4},  {2 -> 3, 4},  {3 -> 4, 4}, {4 -> 5, 4},          {5 -> 6, 4},  {6 -> 1, 4},  {1 -> 2, 5}, {2 -> 3, 5},          {3 -> 4, 5}, {4 -> 5, 5},   {5 -> 1, 5}}          GraphPlot[G,                         EdgeRenderingFunction -> (Switch[#3, 1, {Black,  Line[#1]},                                              2, {Red,    Line[#1]},                                              3, {Blue,   Line[#1]},                                              4, {Green,  Line[#1]},                                              5, {Purple, Line[#1]}] &),         VertexLabeling -> True,         Method -> "CircularEmbedding",         MultiedgeStyle -> All]      ![example bug](http://i.stack.imgur.com/wOxkM.png) This draws a graph with only a few of its edges and gives many "Switch is not a graphics primitive or directive." errors. How can I get this code to draw all of the edges properly? Thanks, Corey


title: Using Memoization with a Mutable Object

text: In looking for a solution to this question, I ran across some old binary tree code by Daniel Lichtblau, reproduced below:               Clear[leftsubtree, rightsubtree, nodevalue, emptyTree, treeInsert]     leftsubtree[{left_, _, _}] := left     rightsubtree[{_, _, right_}] := right     nodevalue[{_, val_, _}] := val     emptyTree = {};          treeInsert[emptyTree, elem_] := {emptyTree, elem, emptyTree}     treeInsert[tree_, elem_] /; SameQ[nodevalue[tree], elem] := tree     treeInsert[tree_, elem_] /; OrderedQ[{nodevalue[tree], elem}] :=      {leftsubtree[tree],        nodevalue[tree], treeInsert[rightsubtree[tree], elem]}     treeInsert[tree_, elem_] := {treeInsert[leftsubtree[tree], elem],        nodevalue[tree], rightsubtree[tree]}      When mapped onto a list, `treeInsert` gives you a sorted duplicate free list. For example,               tr = {};     Scan[(tr = treeInsert[tr, #]) &, RandomInteger[100, 5]];     Flatten@tr      (* {13, 28, 53, 59, 88} *)      On my machine, this takes ~2 s to process `RandomInteger[10, 10^5]`, but this increases to nearly 20 s with `RandomInteger[10, 10^6]`. There are likely other techniques to speed this up, but I am curious as to how memoization could be adapted to this problem. At issue, though, is that the `tree` changes with each insertion, and so it cannot be used directly for memoization because the definition depends directly on that form. How would one do this? **Edit** : as I discovered in my own testing, `Fold` works much better than `Scan` for creating a tree, as follows               tr = Fold[treeInsert, {}, RandomInteger[100, 5]];     Flatten@tr      (* {13, 28, 53, 59, 88} *)      **Update** : while my question, per se, was not answered directly, the answers themselves indicated that there were better ways to accomplish what I wanted. In the end, I chose the one I did for two reasons: speed and simplicity.


title: StringCases: return list of outputs for each of several patterns

text: According to the documentation,               StringCases[{s1, s2, ...}, p]      returns               {StringCases[s1, p], StringCases[s2, p], ...}      but, oddly enough,               StringCases["string", {p1, p2, ...}]      returns the results which match _any_ of the patterns $p_i$, which is essentially equivalent to               Union[{StringCases["string", p1], StringCases["string", p2], ...}]      Is there a way to modify `StringCases["string", {p1, p2, ...}]` to return just               {StringCases["string", p1], StringCases["string", p2], ...}      in an analogous manner to how `StringCases[{s1, s2, ...}, p]` does it? One alternate way to get the same output would be               Through[Table[StringCases[#, p[i]] &, {i, n}]["string"]]      but I was curious if there was another way.


title: With comma as decimal separator, how do you insert a period in the header/footer?

text: I have enabled comma as my decimal separator, which means that comma still acts normally and when pressing period it will be converted to a comma. In the header I would like to make a period, so I insert a period and it looks like a period, however when I view the print preview, the period is converted to a comma. How do I keep this from happening or is there a special period character that doesn't get converted to a comma? Alternatively how can I make the header plain text, as this behaviour doesn't occur in plain text mode? **Edit:** Answering @SjoerdC.deVries questions:   1. With header I mean the option you set with `File > Printing Settings > Headers and Footers...`   2. The setting to change the decimal separator was found in Mathematica under `Preferences > Appearance > Numbers > Formatting > Decimal point character`   3. The period is the normal period key, not one on the keypad, although I would think they act similar.


title: TreePlot EdgeLabeling Style

text: I am trying to control the style for edge labels in treeplot and have run into a problem. Consider these two graphs:               edges1 = {{1 -> 2,"Test"}, 2 -> 3}     edges2 = {{1 -> 2,"Test"}, 2 -> 3, 1 -> 4}      If I plot the first then the labeled edge displays correctly:               TreePlot[edges1, BaseStyle-> 20]      ![enter image description here](http://i.stack.imgur.com/pm4rf.png) But if I plot the second it slants the text:               TreePlot[edges2, BaseStyle-> 20]      ![enter image description here](http://i.stack.imgur.com/R6FF9.png) Anyone have any insight how to stop the second behavior? **Edit** Here is a more complicated example showing how it slants the text in both directions and in different amounts (Note that in actuality my edges have different labels)               edges = {{1 -> 2, "Test"}, {1 -> 3, "Test"}, {2 -> 14,      "Test"}, {3 -> 4, "Test"}, {4 -> 99, "Test"}, {3 -> 6,      "Test"}, {6 -> 7, "Test"}, {6 -> 8, "Test"}, {7 -> 9,      "Test"}, {8 -> 10, "Test"}, {8 -> 11, "Test"}, {10 -> 12,      "Test"}, {11 -> 13, "Test"}};     edges[[All, 2]] = Map[Panel@Style[#, 12] &, edges[[All, 2]]];     TreePlot[edges, Top, 1, AspectRatio -> 1/3]      ![enter image description here](http://i.stack.imgur.com/q9NMG.png) * _Edit 2 *_ Combining M.R.'s solution and LayerSizeFunction I can somewhat still control the aspect ratio, but Mr. Wizard's solution is much better M.R. + LayerSizeFunction:               DeleteCases[TreePlot[edges, Top, 1, LayerSizeFunction -> (1/4 # &)], AspectRatio -> _]      ![enter image description here](http://i.stack.imgur.com/1mzx7.png) Mr. Wizard:               edges3 = {{1 -> 2, "Test"}, {1 -> 3, "Test"}, {2 -> 14,      "Test"}, {3 -> 4, "Test"}, {4 -> 99, "Test"}, {3 -> 6,      "Test"}, {6 -> 7, "Test"}, {6 -> 8, "Test"}, {7 -> 9,      "Test"}, {8 -> 10, "Test"}, {8 -> 11, "Test"}, {10 -> 12,      "Test"}, {11 -> 13, "Test"}};     TreePlot[edges3, Top, 1, AspectRatio -> 1/3, EdgeRenderingFunction -> ({Line[#1],       If[#3 === None, {}, Text[Panel@Style[#3, 16], Mean@#1]]} &)]      ![enter image description here](http://i.stack.imgur.com/ImiTn.png)


title: Symbolic Constrained Optimization

text: I have a question regarding evaluating constrained optimization problems in symbolic terms. I would like to perform How can I implement the method of Lagrange multipliers to find constrained extrema? without specifying the objective function. As a simple example, suppose I have a constrained utility maximization problem: $\max\limits_{x,y} U(x,y)$ $s.t.\ p_xx+p_yy=I$ where $U_x,U_y>0$, the Hessian matrix of the second-order derivatives is negative definite, and $p_x$ and $p_y$ are unspecified coefficients. Using Lagrangian multipliers, the first-order conditions are: $U_x-\lambda$$p_x=0$   $U_y-\lambda$$p_y=0$   $I-p_xx-p_yy=0$ Of course, the model that I want to use is a little bit more complicated than this (otherwise it would be no problem doing it by hand). Thus, given an unspecified objective function $U(x,y)$ and budget constraint(s) with unspecified coefficients, I was wondering if it was possible in Mathematica to:   1) produce the first-order conditions, and   2) given the system of equations in (1), produce symbolic rather than numerical solutions, which are functions of $U_x$, $U_y$, $p_x$, $p_y$, etc. Again, this differs from How can I implement the method of Lagrange multipliers to find constrained extrema? because: that question specified that the objective function $f(x,y,z)=xy+yz$, the coefficients of the constraints are implicitly equal to 1, and thus, it produces numerical solutions for the constrained extrema.


title: How to make use of Associations?

text: I have been curious about it for long. Now that Mathematica 10 arrives, I think it's time to ask the question: How the new `Association` data structure would be used to improve Mathematica programming? There are a few related aspects of this question: (1) How fast is the key-search in `Association` (on the website it is said to be extremely fast)? Would it be O(N) or O(N log N) (note added: those estimate are stupid. See benchmarks below and more in answers)? Is it recommended to be used with a lot of keys? Also, how fast is the operation of inserting a key to an assoication? Would it be O(N) or O(N^2)? (2) Previously I use pattern matching to implement similar functionalities. For example, I do `f[a]=x; f[b]=y` to effectively realize `f = <| a->x, b->y |>`. What's the advantage of the latter over the former? (Seems keys can be more easily managed. But I don't have systematic understanding of the advantages.) (3) The new structure `Dataset` is built upon `Association`. Is it efficient enough in terms of both memory space and computational speed, that I can use `DataSet` to store and calculate big data (say, table with more than 10 thousand rows, like MCMC chains)? Previously I used pure array. (4) Examples where old code can be improved making use of `Association`? I have read through the guide about `Association`, which is basically a collection of related functions. It would be great if the usefulness of those functions could get explained. **Note added:** The replies are really great! Many thanks :) I also did some benchmarks as below. The testing association is the same one as Leonid Shifrin's: `Association[Thread[Range[n] -> Range[n] + 1]]`, where `n` is the x-axis of the plots. We observe (in one case. I am not sure about worst case):   * Creation, insertion (middle) and deletion (middle) are O(N)    * Insertion and removal at head or tail are O(logN)   * Lookup is O(1)   * Association takes O(N) memory space, with a larger constant factor than array Note that, in the first figure, deletion is fast only when using `Most` or `Rest`. `Delete[store, -1]` and `Delete[store, 1]` are as slow as Delete[store, otherNumber]. Also, in the second figure, Association and Dataset takes almost the same memory thus not very visible. ![enter image description here](http://i.stack.imgur.com/Klshh.png) ![enter image description here](http://i.stack.imgur.com/uE2w5.png)


title: Replacing and combining elements in a list

text: I am trying to increase the level of nesting in the following list while adding a 'tag' to each leaf:               testd = {{59.15, 13.2, 13.52, 0.7}, {77.21, 12.27, 0.12, 0.01},               {77.25, 12.35, 1.01, 0.02}, {78.22, 11.74, 1.26, 0.01},               {79.26, 11.37, 1.03, 0.02}};             tag = {a, b, c, d}      So, the end product would look like                (*    {{{a, 59.15},{b, 13.2},{c, 13.52},{d, 0.7}},             {{a, 77.21},{b, 12.27},{c, 0.12},{d, 0.01}},               << ... >>             {{a, 79.26},{b, 11.37},{c, 1.03},{d, 0.02}}}  *)      I can use               Replace[testd, x_ -> {x}, {2}]      to get               (* {{{59.15},{13.2},{13.52},{0.7}},{{77.21},{12.27},{0.12},{<0.01}},        {{77.25},{12.35},{1.01},{0.02}},{{78.22},{11.74},{1.26},{0.01}},        {{79.26},{11.37},{1.03},{0.02}}}  *)      I have tried               Replace[testd, x_ -> {#, x}, {2}] & /@ tag      > {{{{a, b, c, d}, 59.15}, {{a, b, c, d}, 13.2}, {{a, b, c, d}, 13.52}, {{a, > b, c, d}, 0.7}}, {{{a, b, c, d}, 77.21}, {{a, b, c, d}, 12.27}, {{a, b, c, > d}, 0.12}, {{a, b, c, d}, "<0.01"}}, {{{a, b, c, d}, 77.25}, {{a, b, c, d}, > 12.35}, {{a, b, c, d}, 1.01}, {{a, b, c, d}, 0.02}}, {{{a, b, c, d}, 78.22}, > {{a, b, c, d}, 11.74}, {{a, b, c, d}, 1.26}, {{a, b, c, d}, 0.01}}, {{{a, b, > c, d}, 79.26}, {{a, b, c, d}, 11.37}, {{a, b, c, d}, 1.03}, {{a, b, c, d}, > 0.02}}} which is not what i want... Can someone help me with the right syntax? or suggest a better way?


title: Developing domain specific languages and computational knowledge engines using Mathematica

text: In one of Leonid Shifrin's excellent summaries, he mentioned that MMA capabilities include developing Domain Specific Languages (DSL). I'd like to develop a Health care IT application that can   * interpret users' natural-language   * perform automatic markup to tag, link and journal clinical documentation and    * communicate orders and queries to web services such as terminology servers and computational knowledge engines (CKE). In Mathematica 8, the `=` operator enables communication with Wolfram|Alpha, indicating that the front end can be programmed to host this type of user interaction. I understand this is very vague and underspecified, but am curious where to start in investigating the capabilities of MMA in developing DSLs.


title: Implementing Remainder Tree

text: I want to implement Remainder Tree based on this. With the answers on SE I've come up with:               listProduct2[list_] := Times @@@ Partition[list, 2, 2]          T = NestList[listProduct2, Prime[Range[2^7]], 7]          n = 31415926535;          r = {n};     Do[r = Outer[Mod, r, T[[i]]], {i, 7, 1, -1}];      The final desired output is to calculate `n mod p` for all first 2^n primes using remainder tree but it's very slow rather than being fast. I don't know where I was wrong! **Updated** I have read somewhere that this method can be used for faster sieve implementation, around 10 times faster than any available sieve method!!.               Primo[n_] := Product[i, {i, Prime[Range[n]]}]          primeslist = Prime[Range[10^6]];          prod = Primo[10^6];          n = Primo[205000] + 1;          Timing[MemberQ[listMod[n, primeslist],0]]          {36.719, False}          Timing[GCD[n, prod] != 1]          {2.14, False}


title: How can I transform a matrix to a vector (vectorization)?

text: How can I transform a matrix to a vector in mathematica? $A=\bigg{(}\begin{matrix} a_1 &a_2\\\a_3&a_4 \end{matrix}\bigg{)} \longrightarrow |a>>=(\begin{matrix} a_1 &a_2&a_3&a_4 \end{matrix}) $                   Vec2 := Function[{x}, For[i = 1, i <= Length[x], i++;                                   For[j = 1, j <= Length[x], j++;                                        Vec2[[i + j*4]] = x[[i, j]]]]]


title: Restrict Mathematica command to what is inside parentheses

text: I have a bunch of expressions like this one: $\frac{e^{-\frac{7 J}{2 k T}} \left(2 e^{-\frac{2 g H \mu _B}{k T}}+e^{-\frac{g H \mu _B}{k T}}-e^{\frac{g H \mu _B}{k T}}-2 e^{\frac{2 g H \mu _B}{k T}}\right)+e^{\frac{5 J}{2 k T}} \left(3 e^{-\frac{3 g H \mu _B}{k T}}+2 e^{-\frac{2 g H \mu _B}{k T}}+e^{-\frac{g H \mu _B}{k T}}-e^{\frac{g H \mu _B}{k T}}-2 e^{\frac{2 g H \mu _B}{k T}}-3 e^{\frac{3 g H \mu _B}{k T}}\right)}{e^{-\frac{7 J}{2 k T}} \left(e^{-\frac{2 g H \mu _B}{k T}}+e^{-\frac{g H \mu _B}{k T}}+e^{\frac{g H \mu _B}{k T}}+e^{\frac{2 g H \mu _B}{k T}}+1\right)+e^{\frac{5 J}{2 k T}} \left(e^{-\frac{3 g H \mu _B}{k T}}+e^{-\frac{2 g H \mu _B}{k T}}+e^{-\frac{g H \mu _B}{k T}}+e^{\frac{g H \mu _B}{k T}}+e^{\frac{2 g H \mu _B}{k T}}+e^{\frac{3 g H \mu _B}{k T}}+1\right)}$ and I want to convert all the terms inside the parentheses, and not the terms outside, into hyperbolic trig functions, using **ExpToTrig** command, but I'm not sure how to do this. Any help would be really appreciated.


title: How to get the digits of the base 2 representation of an integer

text: I would like to convert a number into base 2 and then use `IntegerDigits[]` on it. When using `BaseForm[i,2]`, the notebook only displays the output in a wrapper, but does not actually convert the number into a base 2 sequence. This causes problems when I want to use `IntegerDigits[]` on the base 2 number to get a list of the binary digits, e.g. `{1,0,0,1,1}`. It simply displays `IntegerDigits[10011 2]`. How could I solve this? Thank you


title: "Indexing" a vector

text: I need to "index" a vector according to the first occurence of its distinct elements. I have written               index[list_] :=      Module[{x = list, p},       p = Flatten /@ Map[Position[x, #] &, DeleteDuplicates@x];       Table[x[[p[[i]]]] = i, {i, 1, Length@p}];       x]      which gives the expected result:               vec= {1, 4, 4, 8, 7, 7, 4};     index @ vec      > {1, 2, 2, 3, 4, 4, 2} **(1)** How could a more functional / efficient solution look like? **(2)** How could such a solution be extended to work with matrices? ad (2)               mat = {{1, 4}, {2, 7}, {7, 2}, {9, 4}};      should give > {{1, 2}, {3, 4}, {4, 3}, {5, 2}}


title: How to solve that kind of partial fraction decomposition equations?

text: I need to find all variables $A, B, C, D$ for given equation with independent variable $s$.   How can I solve that with _Mathematica_ ?   Example, not working: ![enter image description here](http://i.stack.imgur.com/X6VoW.png) * * * UPDATE: **One** ![enter image description here](http://i.stack.imgur.com/uWOy8.png) **Two** ![enter image description here](http://i.stack.imgur.com/mUV8y.png) **Three** ![enter image description here](http://i.stack.imgur.com/NZZFH.png) **Four** ![enter image description here](http://i.stack.imgur.com/dAxKV.png) Nothing of listed above gives the result I need. * * * UPDATE2: I need denominators below $A,B,C,D$ to be predefined (not what `Apart` offers). $A,B,C,D$ must be numbers (don't include variable).


title: Replace a value in a nested array

text: When I run the following,               red = {{{-4, 50}, {100, 136}}, {{-19, 1}, {35, 73}}, {{-24, 0}, {26, 63}}};      y = {{0.01497, 1}, {0.04304, 3}, {0.07111, 2}, {0.09918, 1}};      red=Interval@@@red;     If[#[[1]] <= 0.05, xii = #[[2]]; If[IntervalMemberQ[red[[xii]], 47], #[[1]] = 999.];] & /@ y;     y      Instead of the following result               y = {{999., 1}, {999., 3}, {0.07111, 2}, {0.09918, 1}}      I am getting an error:                Set::setps:{0.01497`,1} in the part assignment is not a symbol. >>      I know based on this that it is to do with passing name of the variable vs. value of the variable, but not sure how to fix it. I tried `Insert[#, 999., 1]` and `ReplaceList[#, 1 -> 999.]` without much success :(