Organizing Code

Are there any recommended ways to organize code? THe simulation project I'm working on has gotten a little unwieldy. I've read up on packages but have never used them before. It seems fairly straightforward? Right now I have all my code for this simulation in 3 cells:               Cell 1: Function definitions     Cell 2: Parameter Initializations     Cell 3: Main time stepping loop      This way of working seemed reasonable when the code was small but it has gotten unwieldy. Modifying function definitions is problematic since the variable names used in function definitions tend to be used in Cells 2 and 3, so they have to be Cleared in order to re-run the cell with the function definitions. I'm thinking I should just move the function definitions into a package? Then if I modify a function I do it in the package and just rerun the Package? If some of the arguments in the functions in the package are also used in the notebook where I'm working this won't cause any problems as the package won't know about the notebook?


How to use ContourPlot3D for Piecewise 3D function

How would I plot in 3D: $\begin{cases} (4 - z^2) = x^2 + y^2, 2 \le z \le 4 \\\ x^2 + y^2 = 4, -2 \le z \le 2 \end{cases}$. I tried http://reference.wolfram.com/mathematica/ref/Piecewise.html `ContourPlot3D[ Piecewise[{(4 - z)^2 == x ^2 + y^2, 2 \le z \le 4}, {x^2 + y^2 = 4, -2 \le z \le 2}], {x, -3, 3}, {y, -3 , 3}, {z, -2, 4}]` I realise there's tex in my code but I don't know how otherwise to symbolise my attempt.


Numeric mixed derivatives

**In short** I need _NumericCalculus`ND_ extended to mixed partial derivatives. This can be done by nesting them, but care has to be taken to evaluate underling ND only when the parameters become numeric. There are examples in the answers on "Numerical partial derivative" and "Numeric calculation of Hessian" (make sure to notice the discussion on the efficiency). The challenge is to build such patterns with arbitrary number of parameters. **Long story** I am forced to take the derivative of my 200k leafcount expressions numerically. I am aware of _NumericCalculus`ND_ which works great, but does not allow mixed derivatives. There are some examples on how to do it efficiently in this and this answer. I would like to play around with a greater number of parameters and use a `Scale` option for each of them. So I would like to have a nice top level function. An example of what I would like it to be capable of:               nd[Sin[x Conjugate[y]] Cos[u v] /.{u->u0, v->v0}, {x, x0}, {y, y0}, Scale -> {xScale, yScale}]      To define such a function with variable number of parameters and understanding the syntax in some of the examples is beyond my capabilities. Could someone provide the function? It is a pity that _Mathematica_ does not ship with one. **Update to the long story:** Both of the related answers I linked discuss how the underling ND should be called only, when all parameters are finally numeric. This avoids big number of ND calls with partially numeric expressions. I would like the method to have the same feature and not just nesting the ND calls. **Update 2** As I did not consider it relevant, I did not mention that I have complex variables. In this case finite difference method is ill defined and some simple reimplementation of ND would not do.


Solving numerically system with Mathematica

I'm trying to solve the following system with Mathematica:               Poblacion = {       {1900, 1.65},       {1910, 1.75},       {1920, 1.86},       {1930, 2.07},       {1940, 2.30},       {1950, 2.53},       {1960, 3.02},       {1970, 3.70},       {1980, 4.45},       {1990, 5.30},       {2000, 7.29}       }          P[t_] := 1 / (-q (K t + C))^(1/q)          NSolve[{P[1900] == 1.65, P[1910] == 1.75, P[1920] == 1.86}, {K, q, C}]      But I can't get it working. Could you please tell me what I'm doing wrong?


How to get all permutation of k-partition

If I want to get the list of k-partition, and the rule are below:   1. here are `k` partitions   2. all elements of partition are in the range of 1 to 30.   3. the total of element from each partition equals to 30. For example, if `k=5`, the partition includes {1,1,1,1,26},{1,1,1,2,25},{1,1,1,3,24}...... Many thanks!!!


How to improve this code for exploring large matrices?

What I'm actually trying to do is to elaborate this question. I'd like to use `Pane` with scrollbars enabled to explore large (sparse) matrices like this one: ![enter image description here](http://i.stack.imgur.com/X6rNA.png) Here is what I have so far using some ideas from this answer:               A = ExampleData[{"Matrix", "HB/west0381"}, "Matrix"] // Normal;     {n, m} = Dimensions@A;     mp = MatrixPlot[A, ImageSize -> 9 m, Mesh -> All];     DynamicModule[{trans, ij, mpos},      trans[{x_, y_}] := {Clip[Floor[n - y] + 1, {1, n}],        Clip[Floor@x + 1, {1, m}]};      Pane[       Show[mp, ImagePadding -> {{40, 20}, {20, 20}},        Epilog -> Text[           Framed[            Dynamic[(ij = trans@MousePosition["Graphics", {0, 0}]) ->               A[[Sequence @@ ij]]], Background -> White],           Dynamic[MousePosition["Graphics", {0, 0}]],           {1, -1}           ]~Style~Larger        ],       {500, 500},       Scrollbars -> True]      ]      The result is ![enter image description here](http://i.stack.imgur.com/SLaS3.png) * * * **Now about the problems** **1.** The main trouble is that it does not correctly translate coordinates for horizontal scrolling. If we don't touch the horizontal scrollbar everything is fine: ![enter image description here](http://i.stack.imgur.com/RP8aZ.png) But if I slide horizontally the label shifts and falls outside the visible area. It looks like a Mma bug. **2.** The second funny thing is that if I remove `//Normal` from the first row then `MatrixPlot` produces the following: ![enter image description here](http://i.stack.imgur.com/JIChf.png) which seems to be the second bug. **3.** And finally the issue which is due to my confusion with `Dynamic` things. In the code I use `MousePosition["Graphics", {0, 0}]` twice (can this be the reason for the item 1 from above?). When I tried to save this coordinates in a variable I had no luck. But there must be a way to do this. * * * **SUMMARY** Thanks to Andy for resolving problems number 2 and 3, and to David for nice solution using `MouseAnnotation`. I accept kguler's answer since it resolves the main problem with runaway tooltip by effectively using `CoordinatesToolOptions` option. Here is complete working example with kguler's solution. Try it (to enable the tooltip right-click on the plot and select "Get Coordinates"):               mtrxPlot2[mat_, opts : OptionsPattern[]] :=       With[{dims = Dimensions[mat],        indx = {Clip[Floor[#1[[1]] - #2[[2]]] + 1, {1, #1[[1]]}],            Clip[Floor[#2[[1]]] + 1, {1, #1[[2]]}]} &},        With[{copiedvalues =           "CopiedValueFunction" ->            Function[pt, {indx[dims, pt], Extract[mat, indx[dims, pt]]}],          coordtooltips =           "DisplayFunction" ->            Function[pt,             Row[{"mat[[", Row[indx[dims, pt], ","], "]]  =  ",               Extract[mat, indx[dims, pt]]},             Background -> White,             ImageSize -> {Automatic, 30},             ImageMargins -> {{5, 5}, {10, 10}},             Alignment -> Center]]},        MatrixPlot[mat, opts,          CoordinatesToolOptions -> {coordtooltips, copiedvalues}]        ]       ]          A = ExampleData[{"Matrix", "HB/west0381"}, "Matrix"];     Pane[mtrxPlot2[A, ImageSize -> 3000, Mesh -> All,        MaxPlotPoints -> 500], {500, 500}, Scrollbars -> True]


How to force mathematica v.9 and 10 notebooks to open in their respective front end

I have version 9 and 10 installed on Windows 7. if I double click to open version 9 notebook, then it opens in version 10, how I can force a notebook to open in its respective front end. I have installed both versions: with different init: link


Delete `x,y,z` occurrence (or any permutation of it) from parent data set (dynamically)?

Simple question: I would like to dynamically specify a list of 3 elements, `{x,y,z}`. Then I'd like to find that list, _or_ any of its permutations, in a parent data set. The parent data set is composed of lists which are at least 3 elements long (like mine), but could also be 4 or 5 elements long. I will then be dynamically deleting the entire part which has an occurrence of `x,y,z` or `z,x,y` etc. from the parent data set (list of lists). The first way I tried doesn't work for obvious reasons (I've removed `Dynamic` functionality because it doesn't work anyway):               data={{0,0,0},{1,1,1},{1,2,3},{3,2,1,9}};     x=3;     y=1;     z=2;     DeleteCases[data,Permutations[{x,y,z}]]      As you can see, I want this to find and delete the 3rd and 4th elements, so that `{{0,0,0},{1,1,1}}` is returned. I'd also like to update `{x,y,z}` dynamically. Are there any tricks to make this work? Or am I doing it entirely wrong? Thanks!


How to draw a pane with rounded corners?

Pane[      Style["text is here", Bold, FontColor -> Darker[Gray, .6],       Background -> Red       ],      Alignment -> {Center, Center}      ]      ![Mathematica graphics](http://i.stack.imgur.com/T5Gcp.png) How to let the pane have rounded corners?


Conditional Data Selection, efficiency

Building up on the solution proposed here : Simplifying nested If statements You can find here the data set : allGazes.dat               allGazesX =       Uncompress@        Import[FileNameJoin[{NotebookDirectory[], "allGazes.dat.gz"}],          "String"];      I need to filter large data set and believe I lack an efficient method to do so. The purpose here is to filter given the `EuclideanDistance[]` between gazes. Below is what I am using currently : This is what i am using currently :               GZ[delta_] := ParallelTable[                   Table[                         Reap[z = allGazesX[[subNO, dispNo, 1, ;; 2]];Sow[z];                         Scan[                              If[                                 EuclideanDistance[#, z] > delta,                                 z = #;Sow[z]] &,                                 allGazesX[[subNO, dispNo, All, ;; 2]]]][[2, 1]],                        {dispNo, Range[Length[allGazesX[[subNO]]]]}],                   {subNO, Range[5]}];


Is there a way to "hold" prefix / infix / postfix notation?

Is it possible to preserve a specific style of notation in $Mathematica$ output?               foo // bar     (* bar[foo] *)          Hold[foo // bar]     (* bar[foo] *)      I'm writing some code that generates sample code ( _e.g._ a usage hint), and in one case I feel that postfix notation is easier on the eyes. I know it's subjective and not that important but now I'm just curious whether this is possible to control. * * * ## Edit `Postfix` preserves the notation as @rasher pointed out. However, my intent was to allow convenient evaluation of sample code by being able to immediately evaluate the output—that is, `Shift``Enter` the `foo//bar`. When `Postfix` is the head of an expression though, the evaluation simply returns the expression—which, makes complete sense, since that's what `Postfix`... does. (This question almost seems circular now.) Is there a way, perhaps, to create a custom `PostfixToEvaluate` head that would _display_ the expression in postfix but, maybe via an UpValue, remove itself and evaluate its contents, upon evaluation? (I don't know if that makes any sense. I'm going to try it now...) * * * Tags I considered but don't believe are relevant: stylesheet hold expression- manipulation. Note that I've left "hold" in the title as that's the intuitive keyword by which I would have searched, were I a future visitor.


Fourier-Analysis How to display every period correctly?

I want to express a function as a sum of fourier series.   I tried the code below. It works. But only get one period (from 0 to 1).   How to display every period correctly?               f = Piecewise[{{10 x, 0 <= x < 0.1}, {-(10/9) x + (10/9), 0.1 <= x < 1}}];     coeff[0] = 1/4 Integrate[f, {x, 0, 1}];     coeff[n_] = 1/4 Integrate[f*Exp[I Pi n x/2], {x, 0, 1}];     series[m_, x_] := Sum[Exp[-I Pi n x/2] coeff[n], {n, -m, m}];     Plot[Evaluate[Table[series[j, x], {j, 1, 5}]], {x, -2, 2}]      ![enter image description here](http://i.stack.imgur.com/gpde1.jpg)


Why is this minimization with Boole functions failing?

I am running this command in Mathematica 8.0.4.0:               Minimize[(x1*1 - 1)^2 + (x1*0.823202 + x2*1 - 0.7551)^2 +               lambda*(Boole[x1 != 0] + Boole[x2 != 0]), {x1, x2}]      Now, with `lambda=0` (negating the `Boole` functions), I get:               {7.70372*10^-34, {x1 -> 1., x2 -> -0.068102}}      With `lambda=1`, I get:               {2., {x1 -> 1., x2 -> -0.068102}}      It seems to be ignoring the Boole functions, because clearly `x2 -> 0` is a better solution:               (x1*1 - 1)^2 + (x1*0.823202 + x2*1 - 0.7551)^2 +       lambda*(Boole[x1 != 0] + Boole[x2 != 0]) /. {x1 -> 1, x2 -> 0}          1.00464      I assume Mathematica is minimizing this function numerically; is it simply incapable of doing this with `Boole` functions, given their stepwise nature?


Multivariate series expansions to different powers

I have a function that (I believe) correctly takes the multivariate Taylor series expansion about the origin for some expression (first argument), in some variables (second argument, list), to different orders (third argument, list). My method for taking the multivariate series expansion follows the answer provided here. I take the series expansion to the highest order requested in the list (unless the highest order is infinity, in which case the next-highest is used), then I truncate the series by adding a "big-O" for each variable at its requested order plus one. If the requested order of a variable is infinity, no expansion is performed on that variable.               mySeriesMWE[exp_, x_List, o_List] := Module[       {pos, ow, xw, xDummy},       pos = Position[o, Infinity];       If[(Length[o] < 1) || (Length[pos] == Length[o]),       Return[exp],       ow = o // Delete[#, pos] &;       xw = x // Delete[#, pos] &;       (exp /.              Thread[xw -> xDummy*xw] //             Series[#, {xDummy, 0, Max[ow]}] & //            Normal) /.          {xDummy -> 1} //         # +            Sum[O[xw[[i]]]^(ow[[i]] + 1), {i, 1, Length[xw]}] & //        Normal       ]     ];      Usually, the results are as-expected, but there is a test-case that provides a result that is unintuitive, but I think, technically correct: when the expression is $x y z$ and we compare the expansion at the origin for the powers $\\{1,1,3\\}$ and $\\{1,1,\infty\\}$.               mySeriesMWE[x y z, {x, y, z}, {1, 1, 3}]     mySeriesMWE[x y z, {x, y, z}, {1, 1, Infinity}]     --output--     x y z     0      It was surprising to me that taking the third power in $z$ gave a better approximation (in fact, the entire expression) than not taking the expansion in $z$ at all! I checked in the general case, however, and I think this result is correct:               mySeriesMWE[f[x, y, z], {x, y, z}, {1, 1, 3}] // Expand     mySeriesMWE[f[x, y, z], {x, y, z}, {1, 1, Infinity}]     --output--     f[0,0,0]+z (f^(0,0,1))[0,0,0]+1/2 z^2 (f^(0,0,2))[0,0,0]+1/6 z^3 (f^(0,0,3))[0,0,0]+y (f^(0,1,0))[0,0,0]+y z (f^(0,1,1))[0,0,0]+1/2 y z^2 (f^(0,1,2))[0,0,0]+x (f^(1,0,0))[0,0,0]+x z (f^(1,0,1))[0,0,0]+1/2 x z^2 (f^(1,0,2))[0,0,0]+x y (f^(1,1,0))[0,0,0]+x y z (f^(1,1,1))[0,0,0]     f[0,0,z]+y (f^(0,1,0))[0,0,z]+x (f^(1,0,0))[0,0,z]      The last term in the first output is $x y z$ when the expression is $x y z$, and I believe both expansions match the definition of a multivariate Taylor series about the origin, throwing away the proper higher-order terms. My first question is: is the function valid for orders less-than infinity? (I believe the answer is "yes," but I have never seen a multivariate Taylor series expansion truncated in certain orders.) My second question is: is the function's behavior correct when the requested order of a variable is infinity? My third question is: is there a better way to write the function such that the variable we do not wish to expand in is somehow better-preserved? ## Edit Here's a better way, based on a suggestion by John Sidles. The idea is to "penalize" higher-order terms by weighting the replacement of `xDummy` with an exponent that depends (unintuitively: inversely) on the requested orders of expansion in that variable. Here is the modified function.               mySeriesMWE[exp_, x_List, o_List] := Module[        {pos, ow, xw, n, xDummy, xDummyPower, xDummyList, testList},        pos = Position[o, Infinity];        If[(Length[o] < 1) || (Length[pos] == Length[o]),         Return[exp],         ow = o // Delete[#, pos] &;         xw = x // Delete[#, pos] &;         n = Length[xw];         xDummyList = Array[xDummy^(1 + Max[ow] - ow[[#]]) &, n];         testList = Array[If[#1 == #2, ow[[#1]], 0] &, {n, n}];         xDummyPower =           Max[           Table[            Sum[             testList[[j, k]]*(1 + Max[ow] - ow[[k]]),             {k, 1, n}             ],            {j, 1, n}            ]           ];         (exp /.                Table[xw[[i]] -> xDummyList[[i]]*xw[[i]], {i, 1, n}] //                      Series[#, {xDummy, 0, xDummyPower}] & //              Normal) /.            {xDummy -> 1} //           # + Sum[O[xw[[i]]]^(ow[[i]] + 1), {i, 1, n}] & //          Normal         ]        ];      There is some ambiguity in choosing the order of expansion in `xDummy`. I chose a conservative value (including extra terms) and truncated with `O` in the usual manner, in case an obvious term was missed in the expansion (which does happen).


Plot of a periodic triangular wave

I'm trying to graph the zig-zag function at the top of this page: http://www.math.ubc.ca/~feldman/m321/nondiffble.pdf I have a little bit of experience with Mathematica but not a ton. Any suggestions?


How to find the integer solution number of a linear system with inequalities?

I have the following system with mixed equality and inequalities defined as:               n = 100;     eqn = (n1 + n3 + n5 == n2 + n4 + n6) && (n1 >=          n2) && (n1 - n2 + n3 - n4 >= 0) && (n1 <= n) && (n1 - n2 + n3 <=          n) && (n1 - n2 + n3 - n4 + n5 <= n) && (2 n <=          n1 + n2 + n3 + n4 + n5 + n6 <= 6 n) && (n1 > 0) && (n2 > 0) && (n3 > 0) && (n4 > 0) && (n5 > 0) && (n6 > 0);      How can I find all the integer solutions and especially the number of all integer solutions? It seems `Reduce` or `Solve` does not work:               sol = Reduce[eqn, {n1, n2, n3, n4, n5, n6}, Integers]      produces:                 (n1 | n2 | n3 | n4 | n5 | n6) \[Element]        Integers && ((1 <= n1 <= 99 &&           0 < n2 <=            n1 && ((0 < n3 < 100 - n1 && 0 < n4 <= n1 - n2 + n3 &&               100 - n1 - n3 <= n5 <= 100 - n1 + n2 - n3 + n4 &&               n6 == n1 - n2 + n3 - n4 + n5) || (100 - n1 <= n3 <=                100 - n1 + n2 && 0 < n4 <= n1 - n2 + n3 &&               0 < n5 <= 100 - n1 + n2 - n3 + n4 &&               n6 == n1 - n2 + n3 - n4 + n5))) || (n1 == 100 &&           1 <= n2 <= 100 && 0 < n3 <= n2 && 0 < n4 <= 100 - n2 + n3 &&           0 < n5 <= n2 - n3 + n4 && n6 == 100 - n2 + n3 - n4 + n5))


Apply a function to a matrix of vectors

I have a matrix containing on each position a pair of numbers $(a,b)$. I would like to compute the norm of each vector $(a,b)$ and keep the result in form of a matrix. So basically, I need to apply the function `Norm` elementwise to a matrix of vectors. How could I do that?


Define function that goes from one point to another parametrically

I have two points p1 and p2, and I want to get the parametric equation of a linear function that passes through those, but ranging from one point to another. For example, if I have 2 points {0,0} and {1,1/2}, the equation would be {t,t/2}. > The goal of having a **parametric equation** is to have the function defined > even when the slope is $\infty$. I tried this (here the angle[] function is Atan2, is basically `ArcTan` but ranging from 0-2π):               Piecewise[      {       {{t, Last@p1 + Tan@angle[p1, p2] (t - First@p1)},         Min[First@p1, First@p2] <= t && t <= Max[First@p1, First@p2]},       {{First@p1, t}, First@p1 == First@p2}       },      Indeterminate      ]      But when a point is on top of the other the function is a vertical line, ranging from $-\infty$ to $\infty$; I would only want the function to be defined from Last@p1 to Last@p2. In other words, I want a Graphics' `Line`, but using parametric equations. Something like this: ![enter image description here](http://i.stack.imgur.com/buJF5.png)


Is there a relatively quick way to solve my integer-valued equation?

This is a very simple problem. It can be solved by nested `For`loops that exhaustively test every possible case, throwing out all non-solutions. > Find all the distinct positive integer solutions $0<a_i \leqslant 100$, such > that: > > $$\sum\limits_{i=1}^{10}\dfrac{1}{a_i}=1$$ There are 69014 solutions in total. But it will take a long time to find them all by nested `For`loops. Is there an efficient method for this problem, i.e, one that will find all the solutions in less than 20 minutes?


Parallel and perpendicular symbol from mathematica to latex

I want to get the following expression from mathematica to latex: \begin{bmatrix} E_{\parallel} \\\ E_{\perp} \end{bmatrix} I have tried to use inbuilt 'symbol' character from the special characters window but get an error: ![error](http://i.stack.imgur.com/aYfwh.png) So I thought maybe I can just type in \parallel and \perp so when I convert it to tex it will be there and work, but I get different errors: ![more erros](http://i.stack.imgur.com/Tuzxh.png) Any way to achive what I want? Thanks


Manipulating a sublist based on position

I have a huge list with huge sublists of the form               list={{a,b,c,d},{e,f,g,h},{i,j,k,l}}      I am looking for a way to manipulate these sublists based on the positions of the elements. Something like               list/.{j_,k_,l_,m_}->{j-1,k,l,m}      but without having to write the whole pattern. Is there any way to specify such manipulation based on the position of the element? Something like               list/.#[[1]] & -> #[[1]] - 1 &      that would work?


WordData [ ] returns ReplaceAll::reps error message

# Situation:               In:= w = WordData[];     During eval of In:= ReplaceAll::reps: {Expression/. Null} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing.[>>][1]     During eval of In:= LinkOpen::linke: Specified file is not a MathLink executable..[>>][2]            In:=  WordData["Day", "Definitions"]     Out:=  WordData["Day", "Definitions"]            (*last seems unevaluated...*)            In:=  Here     Out:=  Missing[NotAvailable]    ## Intention: I am simply calling this function to use it but its not working.   * I am connected to the internet and I am able to call WolframAlpha["query"] sucessfully...   * Any idea that do not include acrobatics with the Mathematica File System is more than welcome...   * I already check my firewall settings ... ## Here is another one:               In:=  CountryData[]     Out:=  DataPaclets`CountryDataDump`$GroupHash["Countries"]        * Any ideas...?       ## System Info:               ~$uname -a     Linux ***** 3.16.1-1-ARCH #1 SMP PREEMPT Thu Aug 14 07:40:19 CEST 2014 x86_64 GNU/Linux         Network information:               In[2]:= SystemInformation["Network"] //Column                                             Out[2]:= IPAddresses -> {fe80::****:274c:a7c7:***, 192.168.1.145}             AllowInternetUse -> True             LoadOnDemand -> True             LoadOnDemandServers -> {http://pacletserver.wolfram.com}             LatestTransaction -> Missing[NotActive]             LatestTransactionServer -> Missing[NotActive]             LastLocalIndexUpdate -> {2014, 8, 28, 19, 11, 30.766294}             LastLocalIndexUpdateServer -> {}             Paclets -> PacletManager Version 2.2.0             TotalDownloads -> Missing[NotActive]             DownloadsDirectory -> Missing[NotActive] Mathematica Kernel Information:               In[3]:= SystemInformation["Kernel"] //Column                                              Out[3]:= Version -> 10.0 for Linux x86 (64-bit) (June 29, 2014)             ReleaseID -> 10.0.0.0 (5098646, 5098517)             LicenseID -> *****-****             PatchLevel -> 0             ActivationKey -> ****-9190-****             ActivationGroupID -> *****-****             MachineID -> 6539-*****-01360             UserName -> *****             MachineName -> ****             MachineDomains -> {sd.cox.net}             LicenseServer -> gabriel             MaxLicenseProcesses -> Infinity             LicenseExpirationDate -> {Infinity, 0, 0, 0, 0, 0}             MachineType -> PC             OperatingSystem -> Unix             ProcessorType -> x86-64             Language -> English             CharacterEncoding -> UTF-8             SystemCharacterEncoding -> UTF-8             TimeZone -> -7.             CreationDate -> DateObject[{2014, 6, 29}, TimeObject[{19, 7, 59}]]             InstallationDirectory -> /usr/local/Wolfram/Mathematica/10.0             WSTPVersion -> 4.25 (2014062701)             ProcessorCount -> 2             LicenseSubprocesses -> 1             MaxLicenseSubprocesses -> Infinity      I also tried `Trace` and `TracePrint` on the `WordData[]` function call. _Nothing clear so far ..._    This is a **__link_ to the output_** of:               System`Dump`AutoLoad[Hold[CountryData], Hold[CountryData], "DataPaclets`CountryData`"] // TracePrint    Wolfram Documentation: ReplaceAll::reps error docs.      LinkOpen::linke error docs.


Kalman filter by hand

I am now learning the Kalman filter and wants to implement it by hand to understand it better. To be specific I want to first simulate a sequence of data by $$ \dot x=Ax+Bw\\\ y=Cx+Dv,\\\ E[x(0)]=0,E[x(0)x'(0)]=P_0, $$ where $w,v$ are white noise processes with unit variance. Then I need to construct the Kalman filter by $$ \dot{\hat x}=A\hat x+QC'(y-C\hat x), \hat x(0)=0 $$ where $Q$ solves the ricatti differential equation $$ \dot Q=AQ+QA'-QC'CQ+C'C,Q(0)=P_0. $$ I have two questions:   1. How do I generate the sequence of data governed by a differential equation?   2. How do I solve the ricatti differential equation? I know this post shows no effort, but I am new to mathematica and have no idea where to start (especially that I cannot generate the data needed, which stops me from any progress). Any hint is appreciated.


Left-aligned PlotLabel?

Is it possible to have the text generated by `PlotLabel` (or any other function) aligned to the left side of the plot instead of in the center?


StringMatchQ and Alternatives throws message in init.m

The report of this issue, which itself relates to code of my answer here, exposed a behavior I cannot explain. If I use `StringMatchQ` in combination with `Alternative` inside the `init.m` a message is thrown on start of the kernel. You can test this by putting this line in your `init.m`               StringMatchQ["name", "noMatch" | "name"];      and when you start the kernel you see two messages saying > Throw::nocatch: Uncaught Throw[False] returned to top level. Surrounding the statement by `Catch` does not help. The solution is to substitute this regex-alternative into a logical `Or`               StringMatchQ["name", "noMatch"] || StringMatchQ["name", "name"]      but that doesn't explain the issue. What am I missing here?


Solving recurrence relation using Mathematica defined in a piecewise way

I have a recurrence relation defined as following:               RSolve[      {       p[0] == p0,       p[1] == λ p[0]/μ,       p[i + 1] == λ p[i]/(2 μ)       },      p[i], i     ]      Note that the relation is differently for `i=1`, than for `i >= 1`. This yields the following error: > DSolve::bvnul: For some branches of the general solution, the given boundary > conditions lead to an empty solution. >> When I use `Piecewise`, Mathematica just echos the input:               RSolve[      {       p[i + 1] ==         Piecewise[{          {p0, i == -1},          {λ p[i]/μ, i == 0},           {λ p[i]/(2 μ), i >= 1}}]       },      p[i], i     ]      Also using `If` or `Condition` does not to work out. Appreciate your help! (Btw, this simple example can easily be solved by hand, but I would like to solve more complicated recursions involving piecewise definitions.)


Mathematica9 linux version crash, how to fix it?

Ubuntu 12.04 x86_64 kernel 3.2.0-35-generic _Mathematica_ 9 linux version (x86_64) crashes with errors: > X Error of failed request: BadGC (invalid GC parameter)   >  Major opcode of failed request: 59 (X_SetClipRectangles)   >  Resource id in failed request: 0x0   >  Serial number of failed request: 2266   >  Current serial number in output stream: 2268 > > X Error of failed request: BadGC (invalid GC parameter)   >  Major opcode of failed request: 59 (X_SetClipRectangles)   >  Resource id in failed request: 0x0   >  Serial number of failed request: 2267   >  Current serial number in output stream: 2268 > > ... The above errors occur when I run command `mathematica` as a general user. It crashes before GUI is started. However, if I run it as root `sudo mathematica`, all work well. Can someone fix this problem?


Vertex labels versus vertex names in VertexRenderingFunction

The VertexRenderingFunction seems to only use names, not labels. For example:               GraphPlot[Import["D:/dev/ProjectEuler/keylog.gv"],VertexLabeling->True,PlotStyle->{Black},VertexRenderingFunction->({EdgeForm[Black],White,Disk[#1,0.08],Black,Text[#2,#1]}&)]      The imported gv file here has both names and labels defined for each node. The names are always unique, but the labels are not necessarily unique. Unfortunately, the above GraphPlot only shows the NAMES of the vertices, not the labels. How can I get the labels and not the names? ![enter image description here](http://i.stack.imgur.com/kdM22.png) The vertex annotations above are names, not labels of each vertex. The DOT file is as follows:               digraph Passcode {         0 [label="3"];         1 [label="1"];         2 [label="9"];         3 [label="6"];         4 [label="8"];         5 [label="0"];         6 [label="2"];         7 [label="7"];         0 -> 1;         0 -> 2;         0 -> 3;         0 -> 4;         1 -> 4;         1 -> 6;         1 -> 5;         1 -> 3;         1 -> 2;         2 -> 5;         3 -> 4;         3 -> 2;         3 -> 6;         3 -> 5;         4 -> 5;         4 -> 2;         6 -> 2;         6 -> 5;         6 -> 4;         7 -> 3;         7 -> 1;         7 -> 6;         7 -> 0;         7 -> 2;     }


What does the slash-colon symbol do?

I came across a bit of code that uses the syntax `/:` and I don't know what it does. I can't find its documentation, or maybe I'm just not looking properly. The code snippet is something like:               F/:F[A___,b_?NumberQ B_, C___] := b*F[A,B,C]      (i.e. part of the definition of multi-linearity). How does this behave differently than the following?:               G[A___,b_?NumberQ B_, C___] := b*G[A,B,C]      Thanks!


Functions in a different context are replaced with infix forms of their namesake in System`

So, in an attempt to help out Fabian with his question, I did what I often do, and created a new symbol in the `Pillsy`` package that I could play with. Since it was in a package I control completely, I thought, "Hey, I can just call it `Times`!". I was really surprised when this happened:               In[3]:= Pillsy`Times[a, b, c]     Out[3]= a * b * c      It looks like Mathematica uses just the symbol name in determining whether to replace something with infix syntax, without paying attention to the context. However, I'm fairly sure I've never seen it happen before and I don't recall coming across it in the documentation. Evidently specifying `InputForm` shows you the whole thing:               In[4]:= Pillsy`Times[a, b, c] // InputForm     Out[4]= Pillsy`Times[a, b, c]      This is in contrast to the `InputForm` for `System`Times`. Is this an intentional feature (it's hard to imagine otherwise), and if so, how does it interact with things like `MakeBoxes`, `MakeExpression` and `Format`? Also, how do you avoid being burned by it? I'm a little alarmed that my assumption that `a * b * c` is the same thing as `System`Times[a, b, c]` is unfounded, even in the absence of changes to `$Post` and the like.


What is so special about Prime?

When we try to evaluate `Prime` on big numbers (e.g. `10^13`) we encounter the following issue :               Prime[10^13]      > >     Prime::largp: Argument 10000000000000 in Prime[10000000000000] is too > large >     for this implementation. >> >     Prime[10000000000000] >   Following this message we can read in M - documentation that the largest supported argument in `Prime` is typically about 2^42. With a kind of divide and conquer approach we can figure out that the maximal argument of `Prime` is :               OmegaPrime = 7783516045221;      **1\. What determines this number ? A hardware/software and/or conceptual/mathematical issue or maybe is it an arbitrary system cut-off ?** The problem seems to be a bit more obscure since one encounter something like this :               Prime@{# + 1, #, # + 1} & @ OmegaPrime      > >     Prime::largp: Argument 7783516045222 in Prime[7783516045222] is too > large for >     this implementation. >> >     {Prime[7783516045222], 249999997909357, 249999997909367} >   (It takes more than two minutes to evaluate) An analog of `OmegaPrime` is `OmegaPrimePi` for `PrimePi` :               OmegaPrimePi = 25 10^13 -1;      I can find even bigger primes with `Prime` if I evaluate for example :               Select[Range[249999997909357, 25 10^13], PrimeQ] // Length      > >     63142Q >                 Prime@( OmegaPrime + 63142 )      > >     250000000000043 >   However I cannot evaluate `PrimePi` for numbers greater than `OmegaPrimePi`. It appears that `Prime` has a dynamically extensible domain while `PrimePi` has not. **2\. How do I detect this property in advance from the system ?** I mean not to play around with e.g. `Select[Range[a,b], PrimeQ]`, but for example to read it from `Attributes` or anything else.


Limits of PrimeNu

Is there any way to find distinct prime factors for very large numbers using `Prime` and/or `PrimePi` that exceeds the capabilities/limits of `PrimeNu`?


Internals of Prime function

Does anyone knows how exactly `Prime` works ? For example how `Prime[1000000000]` is calculated ? The only information I found was some inequalities in Wolfram's Function site. Thank you.


differential equations with implicit functions

I have an ordinary differential equation that contains coefficient functions that depend implicitly on the independent variable via an algebraic equation. I am trying to go ahead and use NSolve to solve for that coefficient function, but it doesn't work, even approximately. The problem seems to be in the evaluation of NSolve, but I can't fix it. Anybody knows help?               PP=a^5+a^2 +3w+4          (* 4+a^2+a^5+3 w *)          sol=NDSolve[{f'[w]==(a/.NSolve[PP,a][[1]]),f[0]==0},f,{w,0,3}][[1]]          (*Out[2]= {f->InterpolatingFunction[{{0.,3.}},<>]}*)          f'[0]/. sol          (*Out[3]= -1.13496*)          NSolve[PP/. w->0,a][[1]]          (* Out[4]= {a->-1.43359} *)


How can I obtain a zero-filled Fourier transform, as produced by MATLAB's fft?

The MATLAB FFT function, `fft(X,n)`, can be used to return the _n_ -point DFT. This effectively extends the original signal, `X`, to `n` points if `n` is larger than the dimension of `X`. But, with the `Fourier` function in _Mathematica_ , the transform always has the same dimensions as `X`. So, how can I obtain the same behaviour in _Mathematica_ as implemented in MATLAB?


Reversibly abstracting a list of strings as a graph object where vertices represent strings and edge connect pairs of strings based on various tests

Imagine I provide you a list of arbitrary strings, say: `Map[StringJoin, Tuples[{"0", "1", "2"}, 4]]`. I'd like to abstract these strings as a graph object in Mathematica v9, where each string $s_i$ becomes a vertex $v_i$, and two vertices $(v_a,v_b)$ share an edge if one or more test cases return `TRUE` for the two strings. For example, if `EditDistance[sa,sb] > 3` is `TRUE` and if `StringReverse[sa] == sb` is `TRUE`, then I'd like the respective vertices $v_a$ and $v_b$ to share an edge. Once I've performed some graph operation to generate a subgraph of the original graph, I'd like to pull back down the list of strings corresponding to the vertices in this subgraph. Being new to Mathematica v9's treatment of graphs, what would be the best way to proceed here? Is it at all reasonable to do this for large sets of vertices, $10^5$ or so?


How to make Layer Directed Graphs (LDG) in mathematica?

I am wondering if I can make a graph like that somehow: ![LDG Graph for a Chemical Process Industry](http://i.stack.imgur.com/w6pwO.png) I am new to mathematica, I tried to play with Creating a graph with variable size of vertices and variable thickness of edges . I figured if I could get the data in that form I could make some changes and try to adapt it to mine. But that is not working. Can someone help me please?? This is what the data sample looks like in tabulated form: ![enter image description here](http://i.stack.imgur.com/pYJXr.png) I used this:               trans = Uncompress@     "1:eJxTTMoPShNkYGAoZgESPpnFJWlMIB4PkHDJLEpNLklNcU1JTy1mBEkXg+\     TcDAkrMcKjJASsJASXKWBJI4hKPErcIEp8BolzIdRAuxdqEUE/Uc0mfF5CdowhABdjfqo=\      ";     l = VertexList[Graph[trans]];     (*Weigths for vertices*)     r = RandomReal[{0.5, 1}, Length[l]];     vs = Transpose@{l, r} /. List[a_, b_] -> Rule[a, b];     (*Adjust font size*)     vls = Transpose@{l, r} /.      List[a_, b_] -> Rule[a, Directive[Black, Bold, 20*b]];     (*Weigths for line thicknes*)     rr = RandomReal[{0.1, 1}, Length[DeleteDuplicates@trans]]/100;     es = (First@# > Directive[Thickness[Last@#], Opacity[.5]]) & /@      Transpose@{DeleteDuplicates@trans, rr};     g = Graph[DeleteDuplicates@trans,      VertexLabels -> Placed["Name", Center],      VertexShapeFunction -> "Capsule", VertexSize -> vs,      VertexLabelStyle -> vls, EdgeStyle -> es,      EdgeShapeFunction ->      GraphElementData["ShortUnfilledArrow", "ArrowSize" -> 0.03]]      and got this, which is not what I need   ![Graph](http://i.stack.imgur.com/u7PVH.gif)


How do I find the equation of line based on two points in WolframAlpha?

What would be the proper syntax to enter in WolframAlpha to find the equation of line, if I know two points on it. I know how to do it by hand, but I want to get into the proper syntax of WA.


Unexpected behavior of GeometricTransformation

I have the following mapping on the complex plane: $$ z \mapsto \tau \mu z-1, $$ where $\mu$ is complex, $\tau$ is real number. I want to draw the image of left unit semidisk and play with $\tau$.               μ = 0.16255558520216132` + 0.1849493244071408` I;          pic[τ_] := Block[{d, ds},        d = Disk[{0, 0}, 1, {π/2, 3 π/2}];        ds =         Fold[GeometricTransformation, d,            {RotationTransform[Arg@#, {0, 0}],             ScalingTransform[τ Abs@# {1, 1}],             TranslationTransform[{-1, 0}]             }] & @ μ;        Graphics@{Gray, d, Red, Opacity[.5], ds}        ];          Manipulate[      Dynamic@Show[pic[τ], Frame -> True, Axes -> True,         AxesOrigin -> {0, 0}, PlotRange -> zz {{-100, 100}, {-100, 100}},        ImageSize -> 400        ],      {τ, 0.01, 1000, 0.01},      {zz, 0.01, 10, 0.01}      ]      Here `zz` is introduced to control zooming. The problem is that I get different (wrong) images for different zooms. It is clearly seen for big $\tau$'s. ![enter image description here](http://i.stack.imgur.com/A33DX.png)![enter image description here](http://i.stack.imgur.com/r4Lll.png)![enter image description here](http://i.stack.imgur.com/2rooj.png) It looks very like a bug, but I can not rule out that I'm making some silly mistake (Mathematica 8.0.4). So, what is the problem here and what is the best way of doing the job (I have several mappings for different $\mu$ actually)?


Generating a power series expansion of the function with parameter

I'm trying to generate a power series expansion of the following function:                S[x_, l_] :=         (C[1] + Integrate[E^(2 Sum[t^i/i, {i, 1, l - 1}]) (1 - t)^2               Sum[(l - i*2) t^i, {i, 1, l - 1}]/((t - 1) t^l), {t, 1, x},              GenerateConditions -> False])*x^(l - 1)*E^(-2 Sum[x^i/i, {i, 1, l - 1}])/(1 - x)^2;      For `l=2` and `l=3` it works perfectly, but not in case of `l=4`:               Table[CoefficientList[Series[S[x, i], {x, 0, 4}], x], {i, 2, 4}]      Is it possible to solve this problem?


Extending a ternary plot to a tetrahedron (using ListPlot)

I have been making ternary plots of data that is a list of sets of 3 numbers, where the numbers in each set sum to one (call this "DATA"). To do this, I first transform DATA onto the 2D surface with the following:               transf[{a_, b_, c_}] := {b + c/2, (Sqrt[3] c)/2}          Map[transf,DATA].      This gives a list of sets of 2 numbers that map onto a simplex (call this DATA2). This is how I've plotted DATA2:               Show[{       RegionPlot[Sqrt[3] a1 - a2 < 0, {a1, 0, .5}, {a2, 0, 1},         DisplayFunction -> Identity, PlotStyle -> White,         BoundaryStyle -> None],       RegionPlot[Sqrt[3] a1 + a2 > Sqrt[3], {a1, .5, 1}, {a2, 0, 1},         DisplayFunction -> Identity, PlotStyle -> White,         BoundaryStyle -> None],       RegionPlot[a2 < 0, {a1, 0, 1}, {a2, -.2, 1},         DisplayFunction -> Identity, PlotStyle -> White,         BoundaryStyle -> None],       ListPlot[{{0, 0}, {1, 0}, {.5, Sqrt[3]/2}, {0, 0}}, Joined -> True,         PlotStyle -> {Black, Thickness[.015]}],       ListPlot[{DATA2}, Joined -> True,          PlotMarkers -> Automatic]},      AspectRatio -> Automatic, Frame -> False,       PlotRange -> {{0, 1}, {0, 1}}]       Example: ![example of two data sets plotted on the simplex](http://i.stack.imgur.com/zr8Pw.jpg) Question: Now, I have an extended data set that is made up of sets of 4 numbers that sum to one. I'd like to plot the data in an analogous way, but now on the corresponding tetrahedron. However, I'm not sure how to transform the data or how to draw the appropriate tetrahedron. Can anyone help with this, please?


How to get shadow of a 3d object

Suppose that we have a box or a sphere or an other 3D object and a ponctual light source. How we can generate the cast shadow using mathematic? Is there any tools to render a shadow given the light source position?


Filling between two spheres in SphericalPlot3D

Manipulate[      SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi},        Mesh -> None, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], {n, 0,        1}]      I cant' seem to be able to make a filling between two spheres. I've already tried the obvious `Filling -> {1 -> {2}}` but _Mathematica_ doesn't seem to like that option. Is there any easy way around this or ...


Add coordinate axes to a 3D plot of concentric spheres

I want to add coordinate axis to a figure of nested spheres. I have the command.               Graphics3D[Table[{Opacity[.6], Specularity[White, 20], Sphere[{0, 0, 0}, r]},      {r, 1/2, 3, 1/2}], Boxed -> False]      Which reproduces the set of nested spheres ![enter image description here](http://i.stack.imgur.com/5tN0r.jpg) Now, I would need to add axes X, Y and Z It would also be good to be able to label the spheres 1, 2, 3... Thanks Edit: and to do something similar to this picture? ![enter image description here](http://i.stack.imgur.com/4Nywf.png)


Iterative way to find roots of confluent hypergeometric function

I am trying to find roots of confluent hypergeometric function and I wonder if I can choose the initial guess by the choice of $\beta$.               eq[n_, \[Beta]_, \[Lambda]_] :=                                     Hypergeometric1F1[1/4 (2 - \[Lambda]/\[Beta]), n + 1, \[Beta]]     ED[n_, \[Beta]_, k_Integer: 1] := \[Lambda] /. FindRoot[eq[n, \[Beta], \[Lambda]] == 0,                                             {\[Lambda], (4 k - 2) \[Beta]}]      My goal is to plot the function (x-axis:$\beta$ and y-axis:$\lambda$). To do that, I need good $\lambda$-values for each $\beta$. The problem is that for each $\beta$ we can have lots of roots, so I want to choose $\beta$ depends on the previous $\lambda$-value for initial guess to find the next root. For example, Start from $\beta=0$. For $\beta=0$, I want to find a root, $\lambda$, around $BesselJZero[n,k]^2$. Next, For $\beta=1$, I want to get a root around $\lambda$-value at $\beta=0$. Then, for $\beta=2$, I want to get a root around $\lambda$-value at $\beta=1$ and so on. For the iterative way I think I should use "for loop" or "if", but I am not sure how to use it. Could you help me out? Thank you.


How do I create and use Mathematica packages?

I have created a package following the tutorial in _Mathematica_ 8 virtual book. However this tutorial is quite, let's call it, "short". I have a `TestPackage.m` file:               BeginPackage["TestPackage`"];     TestPackage::usage = "Test package"          Begin["`Private`"]     TestPackage[1] := {1}       (*private functions and stuff*)     Mesg := Print["Private function of TestPackage"]     End[]          TestPackage` f[x_] := Module[{a = 3, b = 3}, Mesg; a x^b]          EndPackage[]      and a file `UseTestPackage.nb` that uses the package:               ClearAll["Global`*"]     dir = "C:/...and so on"     Get["TestPackage`", Path -> dir]          f[2] (*this should give an output defined in TestPackage.m, but it doesn't*)          $ContextPath          (* {"PacletManager`", "WebServices`", "System`", "Global`"}*)     (*seems it didn't read the m file*)      but nothing happens. No symbols of functions are exported, despite the fact that `Get[]` doesn't throw an error. How do I make it work?


How to import date (YYYY-MM-DD) data from a file?

I have a file with data in form `{date, value}`:   `2010-05-19 17`   `2010-05-20 20`   `2010-05-21 19`   `...`   How would I import such data in form `{DateList, value}`?


Outputting a film (in .avi, .mp4, etc. formats) where frames correspond to Graphics3D outputs

I'd like to make a exportable film (in some format like .avi or .mp4, something playable on most computers) where each frame is a Graphics3D output. For example, we might generate frames in the following way:               polytopeSize = 3;          numFrames = 10;       frameSet = Table[Graphics3D[Table[Translate[Scale[PolyhedronData["Dodecahedron", "Faces"], polytopeSize], RandomReal[{0, 5}, 3]], {i, 1, 5}]], {k, 1, numFrames}];      I'd like to be able to set a time delay individually for each frame:               frameSetTimeDelaysInSeconds = RandomReal[{0,1}, numFrames];      Is this possible?


Enlarge the axes text

Plot[Sin[x^2], {x, 0, 3}, AxesLabel -> {"x value", Sin[x^2]}]      In the above code give a graph. In the graph the axes fonts are too small. My problem is that, how can I enlarge the axes text `x` and `x^2` without changing the basic.


Several functions in one RegionPlot with different grayscale

I try to plot the following, but something seems to be wrong in my code and I can't figure out how to fix it:               RegionPlot3D[       {        CountRoots[σq33[ω, V1, V2, V3], {ω, 0, Infinity} == 0],        CountRoots[σq33[ω, V1, V2, V3], {ω, 0, Infinity} == 1],         CountRoots[σq33[ω, V1, V2, V3], {ω, 0, Infinity} == 2],         CountRoots[σq33[ω, V1, V2, V3], {ω, 0, Infinity} == 3],         CountRoots[σq33[ω, V1, V2, V3], {ω, 0, Infinity} == 4]       },       {V1, 0, 50}, {V2, 0, 50}, {V3, 0, 100},       {GrayLevel[i, 0.5], {i, 0, 0.8, 0.2}},       Mesh -> None,        LabelStyle -> (FontSize -> 14)     ]      The number of roots in omega of the function `σq33` depends on the other Variables V1, V2 and V3. I would like to visualize that. The regions where `CountRoots` gives different values should be in different gray levels, all with an opacity of 0.5. I think the problem I have is that I do not know how to use `GrayLevel` to define different shades of gray for the different areas. And do you have an idea how to define the `CountRoots`-functions all in one, maybe with `Map` or something like that? Here is the `σq33`, in case it is necessary to answer the question:               σq33[ω_, V1_, V2_,        V3_] = (1/48 (Exp[-V1] + Exp[-V2]) (1 + Exp[-V3]) +         1/48 (Exp[-(V2 - V1)/2] - Exp[(V2 - V1)/2])/(Exp[(V2 - V1)/2] +             Exp[-(V2 - V1)/2]) ((Exp[-V1] - Exp[-V2] Exp[-V3]) - (Exp[-V2] -              Exp[-V1] Exp[-V3])) +         1/8 ((Exp[-V1] - Exp[-V2] Exp[-V3]) + (Exp[-V2] - Exp[-V1] Exp[-V3])) (-2 (Exp[-V1] +              Exp[-V2] Exp[-V3] + Exp[-V2] +              Exp[-V1] Exp[-V3]) (-Exp[-(V1 + V2)/2 - V3] +                Exp[-(V2 + V1)/2])/(Exp[(V2 - V1)/2] +                Exp[-(V2 - V1)/2])/(ω^2 + (Exp[-V1] + Exp[-V2] Exp[-V3] + Exp[-V2] +                  Exp[-V1] Exp[-V3])^2)) +         1/2 ((Exp[-V1] - Exp[-V2] Exp[-V3]) - (Exp[-V2] -              Exp[-V1] Exp[-V3])) (-(Exp[-V1] + Exp[-V2] Exp[-V3] - Exp[-V2] -               Exp[-V1] Exp[-V3]) (-Exp[-(V1 + V2)/2 - V3] +               Exp[-(V2 + V1)/2])/(Exp[(V2 - V1)/2] +               Exp[-(V2 - V1)/                2]) (2 ω^2 - (Exp[-V1] + Exp[-V2] Exp[-V3] + Exp[-V2] +                  Exp[-V1] Exp[-V3])^2)/((ω^2 + (Exp[-V1] + Exp[-V2] Exp[-V3] +                    Exp[-V2] + Exp[-V1] Exp[-V3])^2) (4 ω^2 + (Exp[-V1] +                    Exp[-V2] Exp[-V3] + Exp[-V2] + Exp[-V1] Exp[-V3])^2))) + ((Exp[-V1] -              Exp[-V2] Exp[-V3]) + (Exp[-V2] -              Exp[-V1] Exp[-V3])) ((Exp[-V1] + Exp[-V2] Exp[-V3] + Exp[-V2] +               Exp[-V1] Exp[-V3]) (-Exp[-(V1 + V2)/2 - V3] +                Exp[-(V2 + V1)/2])/(Exp[(V2 - V1)/2] +                Exp[-(V2 - V1)/                 2]) ((Exp[-V1] + Exp[-V2] Exp[-V3] + Exp[-V2] + Exp[-V1] Exp[-V3])^2 -                5 ω^2)/(6 (9 ω^2 + (Exp[-V1] + Exp[-V2] Exp[-V3] + Exp[-V2] +                     Exp[-V1] Exp[-V3])^2) (ω^2 + (Exp[-V1] + Exp[-V2] Exp[-V3] +                     Exp[-V2] + Exp[-V1] Exp[-V3])^2)) + (Exp[-V1] + Exp[-V2] Exp[-V3] -                Exp[-V2] -                Exp[-V1] Exp[-V3])^2 ((Exp[-V1] + Exp[-V2] Exp[-V3] + Exp[-V2] +                 Exp[-V1] Exp[-V3]) (-Exp[-(V1 + V2)/2 - V3] +                  Exp[-(V2 + V1)/2])/(Exp[(V2 - V1)/2] +                  Exp[-(V2 - V1)/                   2]) (11 ω^2 - (Exp[-V1] + Exp[-V2] Exp[-V3] + Exp[-V2] +                     Exp[-V1] Exp[-V3])^2)/(2 (ω^2 + (Exp[-V1] + Exp[-V2] Exp[-V3] +                       Exp[-V2] + Exp[-V1] Exp[-V3])^2) (4 ω^2 + (Exp[-V1] +                       Exp[-V2] Exp[-V3] + Exp[-V2] +                       Exp[-V1] Exp[-V3])^2) (9 ω^2 + (Exp[-V1] + Exp[-V2] Exp[-V3] +                       Exp[-V2] + Exp[-V1] Exp[-V3])^2)))))


How to make TraditionalForm display the same in the Manipulate output as in a notebook?

I noticed that TraditionalForm does not display as nice in the Manipulate output as in normal notebook. Is there a way to make it look the same? Here is an example,               Manipulate[     TraditionalForm[-Derivative[2, 0][u][x, y]-Derivative[0, 2][u][x, y] == f[x, y]],      {z, None}     ]      and compare the output above to the same command, but without the Manipulate wrapper:               TraditionalForm[-Derivative[2, 0][u][x, y]-Derivative[0, 2][u][x, y] == f[x, y]]      Here is the output, side by side. (left side is the Manipulate output). ![enter image description here](http://i.stack.imgur.com/pdxGl.png) There might be an option to correct this inside Manipulate? Will keep looking. But meanwhile, any one knows why that is? btw, I found that by Rasterizing it, it looks close to the notebook, but need to work on the resolution little:               Manipulate[      Rasterize@       TraditionalForm[-Derivative[2, 0][u][x, y] -           Derivative[0, 2][u][x, y] == f[x, y]],      {z, None}      ]      ![enter image description here](http://i.stack.imgur.com/PzMG8.png) thanks


Computing a logarithmic function

Possibly this is a very lame question for this site. There is a function $f(n)=-\ln(a*n); \space \Bbb Z \to \Bbb R$, and I want to define $a$ for pairs of values. For example: $f_1(n_1)=15; f_1(n_5)=1.157$ $f_2(n_1)=454; f_2(n_8)=1.0042$ and so on. How can I write a function that could calculate $a$ values from the starting values?


Plotting - recursive

# Slightly clearer, hopefully: I would like to plot Solve[Normal[Series[E^(n x), {x, 0, n}]] == 0 for incrementally increasing n, and show all plots overlayed. Here is my effort with up to n=63 using this code: ![enter image description here](http://i.stack.imgur.com/oqfEc.gif) ...Very time consuming though, & I would really like to find a way of plotting it (& similar plots) up to any n without the labour-intensive copying & pasting.


Why won't SparseArray let me store values with the head List?

When you attempt to define a `SparseArray` with elements that have the head `List` it complains:               SparseArray[{1 -> {1, 2, 3}, 2 -> {"a", "b"}}]      > SparseArray::valnl: The value specified by the rule 1->{1,2,3} should not be > a List. >> >   >   >     SparseArray[{1 -> {1, 2, 3}, 2 -> {"a", "b"}}] >   Nevertheless (other) arbitrary expressions are accepted:               SparseArray[{1 -> foo[1, 2, 3], 2 -> bar["a", "b"]}]      ![enter image description here](http://i.stack.imgur.com/aW617.png) There does not appear to be any actual limitation of `SparseArray` that prevents it from storing `List` elements. In fact with a bit of fiddling we _can_ get `SparseArray` to hold `List` elements! First wrap the Lists an additional head so that `SparseArray` accepts them, then use `Part` to extract the first part of every element, essentially stripping the arbitrary extra heads (`foo`):               sa1 = SparseArray[{1 -> foo@{1, 2, 3}, 2 -> foo@{"a", "b"}}];          sa2 = sa1[[All, 1]];      We now have a `SparseArray` with `List` elements:               sa2 // Head     sa2[[1]] // Head     Head /@ Normal[sa2]     sa2["NonzeroValues"]      > >     SparseArray >   >     List >   >     {List, List} >   >     {{1, 2, 3}, {"a", "b"}} >   However if we try to use the `InputForm` of the expression (as input) it does not work:               ToString[sa2, InputForm] // ToExpression      > >     SparseArray[Automatic, {2}, 0, {1, {{0, 2}, {{1}, {2}}}, {{1, 2, 3}, > {"a", "b"}}}] >   Sadly this false equivalence breaks the use of `Save` and pattern-based manipulation of the object. Why would `SparseArray` be blocking the use of `List` when apparently any other head is accepted, and when there is internal support for `List` itself?


Computing the genus of an algebraic curve

How-to compute the genus of an algebraic curve in Mathematica ? In my case the algebraic curve is explicitly defined by a polynomial.


Asymptotic expansion, negative powers

The question was inspired by this discussion: How to expand a function into a power series with negative powers? I am interested in asymptotic behavior of a function at infinity:               f[r_]:=(0.04962 Exp[-2 r] (-1.000+r))/((0.06119+(Exp[-2 r])^(2/3))^2 r)      or (TeX) $$ f(r)=\frac{0.04962 e^{-2 r} (r-1.000)}{\left(\left(e^{-2 r}\right)^{2/3}+0.06119\right)^2 r} $$ Tried `Series[f[r],{r,0,10}]` for expansion in **_negative powers_** at infinity (as suggested) and got: $$ -\frac{0.04406}{r}+0.02146+0.02106 r+0.004405 r^2-0.001355 r^3-0.001205 r^4-0.0003607 r^5-\left(8.402\times 10^{-6}\right) r^6+0.00004149 r^7+0.00001982 r^8+\left(3.921\times 10^{-6}\right) r^9-\left(6.018\times 10^{-7}\right) r^{10}+O\left(r^{11}\right) $$ Seems like the function decays faster than $1/r^n$ and the expansion is meaningless. But what does the term $-\frac{0.04406}{r}$ mean then? The function is strictly positive at infinity and I am kinda confused by that. Does this mean that the asymptotic form of the function is _something_ plus the term $-\frac{0.04406}{r}$ which effectively gives the observed behavior? Can someone clarify it? How can one explain the term $-\frac{0.04406}{r}$?


Volumetric analysis from topological maps

I want to calculate the volume of fill required to level an area about the size of three foodball fields. The Department of Public Works in my city can provide me with topo data for the area. Their request form lists ArcView shapefile, AutoCAD.dwg, Geodatabase, and "other" data file formats, and JPEG, TIFF, and PDF map file formats. What kind(s) of files should I ask for? How do I calculate the volume of data required for an area I'm interested in? I don't know anything about this stuff. I would also like to estimate the number of trees, associated carbon dioxide sequestration, etc. for the area, and other things related to the wildlife in the area (based on some assumptions relevant to my area and the type of vegetation in the area). This additional question may not really be a _Mathematica_ question, but if there is something relevant in _Mathematica_ 's curated data, I would appreciate suggestions.


Calculations in sequence

I have a this calculation, as you can see it is doing a calculation on each list, from list 1 to list 4 of the datafile. My problem is that using Mapthread to do this calculation does not work because it does not do it stepwise. Is it possible to do these calculations in one go. example=datafile[[2 ;;, 1]] is a singe list of stock close price from a period of 500 days, looking like this: sample:               {4.40267, 4.85723, 8.80984, 4.62259, 6.74677, 3.41247, 2.3579, \     1.5767, 8.1023, 0.846309}          xt=Range[20]     In[81]:= d1 = CorrelationFunction[datafile[[2 ;;, 1]], #] & /@ xt          Out[81]= {0.999145, 0.998342, 0.997537, 0.996713, 0.995874, 0.995047, \     0.994209, 0.9934, 0.992535, 0.991635, 0.990724, 0.989826, 0.988893, \     0.98796, 0.987006, 0.986039, 0.985056, 0.984071, 0.983062, 0.982049, \     0.981015, 0.980023, 0.979034, 0.978088, 0.977124, 0.976173, 0.975284, \     0.974368, 0.973422, 0.972492}          In[86]:= d2 = CorrelationFunction[datafile[[2 ;;, 2]], #] & /@ xt          Out[86]= {0.998978, 0.997943, 0.996913, 0.995889, 0.994845, 0.993787, \     0.992737, 0.991701, 0.990673, 0.989631, 0.988578, 0.987528, 0.986518, \     0.985486, 0.984453, 0.983412, 0.982381, 0.981336, 0.98028, 0.97924, \     0.978187, 0.977157, 0.976174, 0.975197, 0.974231, 0.97327, 0.97235, \     0.971439, 0.970547, 0.969652}          In[92]:= d3 = CorrelationFunction[datafile[[2 ;;, 3]], #] & /@ xt          Out[92]= {0.999266, 0.998475, 0.997678, 0.996881, 0.996119, 0.995341, \     0.994551, 0.993777, 0.992971, 0.992156, 0.991314, 0.990456, 0.989605, \     0.988753, 0.98795, 0.98713, 0.986287, 0.985381, 0.984481, 0.983552, \     0.982617, 0.981703, 0.980813, 0.97997, 0.979149, 0.978341, 0.977537, \     0.976723, 0.975906, 0.975078}          In[90]:= d4 = CorrelationFunction[datafile[[2 ;;, 4]], #] & /@ xt          Out[90]= {0.998632, 0.997179, 0.995736, 0.994285, 0.99281, 0.991288, \     0.989771, 0.988194, 0.986626, 0.985064, 0.983506, 0.981978, 0.980482, \     0.978987, 0.977529, 0.976089, 0.974685, 0.973293, 0.971882, 0.970521, \     0.969074, 0.967699, 0.966367, 0.965024, 0.963719, 0.962478, 0.961284, \     0.960064, 0.958861, 0.957659}


Filtering pixels of a certain color

What is the best way to filter an image so that only the pixels close to a certain color are left? I've downloaded some satellite images from the web where a specific pixel color corresponds to a some type of crop. Thus I would like to filter out with Mathematica those pixels that are specifically for that color so I can next run ComponentMeasurements to obtain the area covered by those pixels, so I was trying to figure out what function to use or build that would just return an image with the pixels that match or are truly similar to the color provided.


How can I use Mathematica's graph functions to cheat at Boggle?

This question is inspired by a Stack Overflow question that I decided to solve using _Mathematica_. In addition to _Mathematica_ , I thought I'd use some of the new version's graph-related functionality, which I've never really explored in the past. It seemd like a natural fit, but the further I got into my program, the more awkward everything seemed. First, the board from the orginal question:               F X I E     A M L O     E W B X     A S T U      I use a mix of features to turn this into a `Graph`; with `ImportString` I was able to copy and past from my browser directly into a string literal in my notebook.               makeBoggleBoard[s_String] :=      makeBoggleBoard@ImportString[s]          makeBoggleBoard[mat : {{__String} ..}] /; MatrixQ[mat] :=      With[{dims = Dimensions@mat,        cPatt = {_Integer, _Integer},        dPatt = Alternatives[{1, 0}, {0, 1}, {1, -1}, {1, 1}]        },       With[{coords = Tuples[Range /@ dims]},        With[{          vertexRules =            Thread[coords -> Thread[{Range@Length@coords, Flatten@mat}]],          edgePattern = {c1 : cPatt, c2 : cPatt} /; MatchQ[c1 - c2, dPatt]          },         Graph@Cases[Tuples[coords, 2],           c : edgePattern :> ((UndirectedEdge @@ c) /. vertexRules)]]]]      This already seems a little bit clunky. Most of the difficulty comes about from trying to associate a letter with each vertex in my graph while keeping all the vertices distinct. However, this mostly seems to work well. Also, it will help to winnow the dictionary so it only contains valid words (they must have more than three letters and only use letters on the board). This part, at least, is pretty easy and quick:               makeBoggleDictionary[board_Graph] :=       With[{chars =           ToLowerCase@DeleteDuplicates@(VertexList@board)[[All, -1]]},        DictionaryLookup[chars ~~ chars ~~ chars ~~ (chars ...)]];      Now it's time to traverse the graph, finding all the words along the way. We need to traverse each possible path from each vertex, check to see if the path so far spells a word, and if it does, collect it. In order to keep performance reasonably in hand, we want to cull paths that can't possible spell a word as quickly as possible. Here's the function I came up with:               findWordsInBoggleBoard[graph_Graph, dict : {__String}] :=      With[{        makeWord = ToLowerCase@StringJoin[#[[All, 2]]] &,        lookup =          Function[pattern,           Flatten[StringCases[dict,             StartOfString ~~ pattern ~~ EndOfString]]]        },       Module[{extendPaths},        extendPaths[v_, {}] :=         With[{adj =             DeleteCases[VertexList@NeighborhoodGraph[graph, v], v]},          Join @@ (extendPaths[#, {{v}}] & /@ adj)];        extendPaths[v_, paths_] :=         Module[{           extended = Append[#, v] & /@ paths,           nexts,           strings,           feasible,           adj = DeleteCases[VertexList@NeighborhoodGraph[graph, v], v]},          strings = makeWord /@ extended;          Scan[           Sow,           lookup[Alternatives @@ strings]           ];               feasible =           Pick[            extended,            Function[string,              MatchQ[               Select[lookup[string ~~ __],                 StringLength@# >= 3 &], {__String}]] /@ strings];               nexts =           DeleteCases[            {#, Select[feasible, Function[path, FreeQ[path, #]]]} & /@ adj,            {{_, _}, {}}];                    extendPaths @@@ nexts          ];             Reap[Scan[extendPaths[#, {}] &, VertexList@graph]] /.         {{Null, {}} -> {}, {Null, {words : {__String}}} :> Union@words}]]      The performance is sort of acceptable (it takes about 3 seconds to find all the words in the sample board), but the entire approach I'm taking here seems very ugly. In particular, the repeated use of `NeighborhoodGraph` to find adjacent vertices in the recursion for `extendPaths` seems faintly ridiculous, and the whole approach feels quite low-level compared to some of the other graph functions. Can anyone suggest some possible ways to speed this up? **EDIT** : Part of what I'm interested in seeing is whether _Mathematica's_ graph functions are a good fit for this problem, though of course I'm happy to see the good, fast implementations that people have posted.


Strange behavior of CreateDialog's WindowSize option

Compare the two dialog windows, created by the same code except in the first `WindowSize` has a value while I omit it in the second one. Note, that `CreateDialog` (and especially its default option `WindowSize -> All`) can lead to unexpected behaviour.               DynamicModule[{switch = 1},       CreateDialog[        DocumentNotebook@TextCell@Dynamic@Switch[switch, 1, "A", 2, "B"],        WindowSize -> {200, 100}]];          DynamicModule[{switch = 1},       CreateDialog[        DocumentNotebook@TextCell@Dynamic@Switch[switch, 1, "A", 2, "B"]        ]];      ![Mathematica graphics](http://i.stack.imgur.com/MVYE8.png) While the value of the `WindowSize` option is recognized and used on the left, any explicit value prevents the evaluation of the dynamic content (be it a number, list of numbers, `Automatic`, `Full`, etc.). The same behavior is experience if `Module` is used instead of `DynamicModule`. Is it a bug? I need a workaround that works with a fullscreen window (i.e. `WindowSize -> Full`), any idea? **1\. Update** Even more strange is the workaround that I've found by eliminating part of my code, expression-by-expression. I ended up with the following stripped piece:               DynamicModule[{a = 1, b, c, d, e, f, g, h, i, j, k},       b = Plot3D[Join@{x, y}, {x, 0, 1}, {y, 0, 1}];       CreateDialog[Dynamic@Switch[a, 1, "A"], WindowSize -> {200, 100}]       ];      which correctly produces the dialog on the left, while (and this is the strangest bug I've ever experienced in _Mathematica_ so far) when I comment out **any part** of this code it results in an unevaluated `Switch` in the dialog window (on the right)! ![Mathematica graphics](http://i.stack.imgur.com/LOLnU.png) Below are some examples, that obviously should not change the output, but they do, and are producing the above right dialog. I think this behaviour has something to do with the parsing of `DynamicModule`, but I am quite clueless...               DynamicModule[{a = 1, b(*,c,d,e,f,g,h,i,j,k*)},       b = Plot3D[Join@{x, y}, {x, 0, 1}, {y, 0, 1}];       CreateDialog[Dynamic@Switch[a, 1, "A"], WindowSize -> {200, 100}]       ];          DynamicModule[{a = 1, b, c, d, e, f, g, h, i, j(*,k*)},       b = Plot3D[Join@{x, y}, {x, 0, 1}, {y, 0, 1}];       CreateDialog[Dynamic@Switch[a, 1, "A"], WindowSize -> {200, 100}]       ];          DynamicModule[{a = 1, b, c, d, e, f, g, h, i, j, k},       b = Plot3D[(*Join@*){x, y}, {x, 0, 1}, {y, 0, 1}];       CreateDialog[Dynamic@Switch[a, 1, "A"], WindowSize -> {200, 100}]       ];          DynamicModule[{a = 1, b, c, d, e, f, g, h, i, j, k},       (*b =*)Plot3D[Join@{x, y}, {x, 0, 1}, {y, 0, 1}];       CreateDialog[Dynamic@Switch[a, 1, "A"], WindowSize -> {200, 100}]       ];          DynamicModule[{a = 1, b, c, d, e, f, g, h, i, j, k},       (*b=Plot3D[Join@{x,y},{x,0,1},{y,0,1}];*)       b = Plot3D[x, {x, 0, 1}, {y, 0, 1}];       CreateDialog[Dynamic@Switch[a, 1, "A"], WindowSize -> {200, 100}]       ];      Each of these were tried with a fresh kernel, without any user package loaded. **2\. Update** The following example shows that the variable `a` displayed in the dialog has **no initial value** in spite of defining it two times (note however that the `Initialization` code is not evaluated at all, you can make sure about that by putting any `Print` in it):               DynamicModule[{a = None},       Print[a];       CreateDialog[{         Dynamic@a,         Dynamic@Switch[a, True, "A", False, "B", None, "C"],         (*Checkbox@Dynamic@a*)         }, WindowSize -> {200, 100}],       Initialization :> (a = None)       ];      > `None` ![Mathematica graphics](http://i.stack.imgur.com/Rjqvl.png) Thus `a` has a value (`None`) inside the `DynamicModule` but not inside the dialog. Uncommenting the commented line proves that the `a` displayed in the dialog is **not the same** as the `a` being locally defined in `DynamicModule`:               DynamicModule[{a = None},       Print[a];       CreateDialog[{         Dynamic@a,         Dynamic@Switch[a, True, "A", False, "B", None, "C"],         Checkbox@Dynamic@a         }, WindowSize -> {200, 100}],       Initialization :> (a = None)       ];      > `None` ![Mathematica graphics](http://i.stack.imgur.com/qXRM8.png) that is: still printing `None` as the value of the `DynamicModule`-`a`, but displaying `False` as the dialog-`a`, which is the default value that `Checkbox` assignes to a variable without any value. **To conclude: a dialog does not necessarily inherit the variables of its enclosing`(Dynamic)Module`.** Printing `Dynamic@a` instead of simply `a` helps, as it forces the front-end to claim the dynamically displayed `a` of the wrapping module. Please correct me if I'm wrong.               DynamicModule[{a = None},       Print[Dynamic@a];       CreateDialog[{         Dynamic@a,         Dynamic@Switch[a, True, "A", False, "B", None, "C"],         Checkbox@Dynamic@a         }, WindowSize -> {200, 130}],       Initialization :> (a = None)       ];      ![Mathematica graphics](http://i.stack.imgur.com/OQqZY.png) * _3\. Update: *_ The purpose of this construction is to design a gui where the displayed content switches according to user interaction. While there might be easier ways to do this, I am now inclined to solve the underlyings of this behavior. The following example uses three "screens" as different contents (`first`, `second`, `third`). Changes made to dynamic controls in one screen should affect other screens (hence the variable `x`).               DynamicModule[{a = 1, x = .5, first, second, third},       first := Column@{"First", Row@{"x: ", Slider@Dynamic@x}, Button["Next", a = 2]};       second := Column@{"Second", Row@{"x: ", Dynamic@x}, Button["Next", a = 3]};       third := Column@{"Third", Button["Reset x", x = .5], Button["Next", a = 1]};       CreateDialog[Dynamic@Switch[a,          1, first,          2, second,          3, third          ], WindowSize -> {300, 200}]];


Why does MatrixForm affect calculations?

This is a really newbie question, but it has me confused. Why does this code **work without** `// MatrixForm` and **doesn't work with** `// MatrixForm`?               cov = {{0.02, -0.01}, {-0.01, 0.04}} // MatrixForm     W = {w1, w2}; FindMinimum[ W.cov.W, W]      The error is:               The function value ... is not a real number      Is `MatrixForm` supposed to be typesetting feature or it has other impact? * * * A similar problem appears here:               a = {{1, 0, 1, 0}, {2, 1, 1, 1}, {1, 2, 1, 0}, {0, 1, 1, 1}};     inv = Inverse[a];     b = MatrixForm@{{0}, {0}, {0}, {1}};     soln = inv.b      ![enter image description here](http://i.stack.imgur.com/Aw8jS.png)


Difference between matrix rapresentation

I've noticed different behaviour in Mathematica between matrix representation: The matrix               a={{1,2},{3,4}}     is different from      b=a // MatrixForm      Why i obtain different results using the same matrix in command like Eigensystem? What kind of definition should i use in my programs?


Problem with List Dimension Outer Map

I am currently handling a big list which has the following dimension: `{6, 3, 4, 2, 2, 1, 8}` where the last number `8` represent a number of equation that are in each sublist. If I apply solve to the 7 level               Ssols = Map[Flatten[Solve[#, vars]] &,SSEquations, {7}]      I get a list in which               Dimensions[Ssols]     Dimensions[Ssols[[1]]]      > {1}   >  {6, 3, 4, 2, 2, 1} so until now it seems fine, even if I don't understand this wrapping that comes out with another List containing the previous one. But then things get compplicated               SCSystem =        Outer[# && #2 && #3 && #4 && #5 &, Eq1, Eq4, Eq5, Eq6, Eq8, {2}]        /.SCEq1 /. SCEq4 /. SCEq5 /. SCEq6 /. SCEq8 // MatrixForm;     Dimensions[SCSystem[[1]]]      > {6, 3, 4, 2, 2, 1} where: `EqX = {IX,IIX, etc}` and `SCEqX ={IX->a+b<c,etc.}` or similar inequalities Now if I apply a `FullSimplify` to get which one of this set of inequalities is `True` and which one is not, and also geting a simplified form of the set of inequalities                SCsols = ParallelMap[FullSimplify[#] &, SCSystem, {7}] //MatrixForm      I get something really strange               Dimensions[SCsols[[1]]]     Dimensions[SCsols[[1, 1]]]      > {1}   >  {6, 3, 4, 2, 2, 1} How this is possible? Do you have any suggestions? And moreover I would like to go and substitute for each level 6 of `Ssols` the corresponding value in `SCsols` and I thought to do in the following way:               SCsolsSub =        Parallelize[Outer[#1 /. #2 &, SCsols, Ssols],{6}] // MatrixForm      but doesn't work probalby because the two list have not the same dimensions.


Inverting a matrix

> **Possible Duplicate:**   >  Why does MatrixForm affect calculations? I am facing a strange behaviour from Mathematica when asking it to invert the following matrix:               m = {{a, b, b, 0, 0, 0}, {b, a, b, 0, 0, 0}, {b, b, a, 0, 0, 0},           {0, 0, 0, c, 0, 0}, {0, 0, 0, 0, c, 0}, {0, 0, 0, 0, 0, c}} // MatrixForm          Inverse[m] // MatrixForm      It doesn't output the inverse of the matrix but just the command I entered. But, knowing that my matrix is bloc diagonal, when I enter each one of the blocs separately it does compute their inverses. Where is the trick?


Using functions as input for a function - won't simplify

I've defined a function P[k_] := 1/[Sqrt]2 (R[k] + L[k]) where R and L generate matrices. However the output of this function never full simplifies (even when I use the Simplify[%] functions). It always leaves the output at 1 over root 2 followed by each of the matrices with the binary operator. Can anyone tell me what I need to do to simplify this output?


Matrix multiplication involving MatrixForm

> **Possible Duplicate:**   >  Why does MatrixForm affect calculations? I am doing a matrix multiplication, but not getting the desired output. I am doing the matrix multiplication of $A^{-1}B$ from the following $Ax=B$. Multiplying a square matrix times a column vector, I would expect to get a column vector as so: $4\times 4 \cdot 4\times 1=4\times 1$ vector. When I do this, the kernel just spits back what $A^{-1}$ is and what $B$ is. The following code is what I did.               a = {{1, 0, 1, 0}, {2, 1, 1, 1}, {1, 2, 1, 0}, {0, 1, 1, 1}};     inv = Inverse[a];     b = MatrixForm@{{0}, {0}, {0}, {1}};     soln = inv.b      ![enter image description here](http://i.stack.imgur.com/Aw8jS.png) What seems to be the problem or slight piece that I may be missing here for full simplification?


Why does Eigenvalues[matrix I defined] not work?

This is the code I have in my mathematica notebook. I want to find the eigenvalues of the matrix I created called Hmatrix as defined below. However when I type Eigenvalues[Hmatrix] I get the Hmatrix back with an extra set of brackets preceded by "Eigenvalues" again. Essentially, I am not getting the eigenvalues of this matrix and I wish to know what sort of syntax I have to use to find the eigenvalues of my Hmatrix.               ϵs = -13.6;     ϵso = -29.1;     ϵp = -14.1;     ssσ = -7.20;     spσ = 9.46;          θ = (π - β/2);          Hmatrix :=       MatrixForm[{{ϵs, 0, ssσ,          Cos[θ]*spσ, -Sin[θ]*spσ,      0}, {0, ϵs,      ssσ, -Cos[θ]*spσ, -Sin[θ]*spσ,      0}, {ssσ, ssσ, ϵso, 0, 0,      0}, {Cos[θ]*spσ, Cos[θ]*spσ,      0, ϵp, 0,      0}, {-Sin[θ]*spσ, -Sin[θ]*spσ, 0,      0, ϵp, 0}, {0, 0, 0, 0, 0, ϵp}}]


I can't get Compile to work

I've got some problems with my code, and I try to make it faster. Some of you suggested me to split my problem, and I'm here... I post the same function with and without Compile. This is a support function and does not involve my question               r=8.314472     fug1 = Compile[{v, p, t, a, b},     Module[{y, z, vbv, vb, f1, f2, f3, f4, f},     y = b/(4 v);     z = (p v)/(r t);     vbv = Log[(v + b)/v];     vb = v + b;     f1 = (4.*y - 3.*y^2.)/(1 - y)^2.;     f2 = (4.*y - 2.*y^2.)/(1 - y)^3.;     f3 = (2.*vbv)/(r t*b)*a;     f4 = (vbv/b - 1./vb)/(r t)*a;     f = f1 + f2 - f3 + f4 - Log[z];     Exp[f]]]      g2 doesen't work and I don't know why               g2 = Compile[{p, t, a0, a1, a2, b0, b1, b2},     Module[{a, b, csd, vol, sol, vliquid, vvapor, fl, fv},     a = a0*Exp[a1*t + a2*t^2];     b = b0 + b1*t + b2*t^2;     csd = a/(r*t*(b + v)) - (-(b^3/(64.*v^3)) + b^2/(16.*v^2.0) +          b/(4.*v) + 1.)/(1 - b/(4*v))^3 + (p*v)/(r*t);     vol = NSolve[csd == 0. && v > 0., v, Reals] // Quiet;     sol = v /. vol;     vliquid = Min[sol];     vvapor = Max[sol];     fl = fug1[vliquid, p, t, a, b];     fv = fug1[vvapor, p, t, a, b];     Print[{t, p, vol, Abs[fl - fv]}];     Abs[fl - fv]],     RuntimeAttributes -> {Listable}]      This works without Compile!               g[p_?NumericQ, t_?NumericQ, a0_?NumericQ, a1_?NumericQ, a2_?NumericQ,        b0_?NumericQ, b1_?NumericQ, b2_?NumericQ] :=      Module[{a, b, csd, vol, sol, vliquid, vvapor, fl, fv},     a = a0*Exp[a1*t + a2*t^2];     b = b0 + b1*t + b2*t^2;     csd = a/(r*t*(b + v)) - (-(b^3/(64.*v^3)) + b^2/(16.*v^2.0) +          b/(4.*v) + 1.)/(1 - b/(4*v))^3 + (p*v)/(r*t);     vol = NSolve[csd == 0. && v > 0., v, Reals];     sol = v /. vol;     vliquid = Min[sol];     vvapor = Max[sol];     fl = fug1[vliquid, p, t, a, b];     fv = fug1[vvapor, p, t, a, b];     Print[{t, p, vol, Abs[fl - fv]}];     Abs[fl - fv]];       g works very well and is the same of g2!               FindRoot[g[p, 100, 500., -4.4627562855*10^-3, -2.7625748*10^-6,      7.30402014*10^-2, -2.2222592*10^-4, 9.42486*10^-8], {p,      34.376}] // Timing      g2 doesen't work               FindRoot[g2[p, 100, 500., -4.4627562855*10^-3, -2.7625748*10^-6,      7.30402014*10^-2, -2.2222592*10^-4, 9.42486*10^-8], {p,      34.376}] // Timing


Locators in Manipulate not moving properly

I thought a simple Mathematica kerning machine (for adjusting the space between characters) would be interesting, but I'm having trouble with the locators. (There are a number of other questions related to this, and I've read the answers, but as yet without finding a solution, or understanding them that well.)                Manipulate[       LocatorPane[Dynamic[points],        text = "Wolfram";        fonts = FE`Evaluate[FEPrivate`GetPopupList["MenuListFonts"]];        Column[{          Button["Export", Export["/tmp/t.png", g]],          g = Graphics[{               MapIndexed[               Text[Style[#1, FontSize -> fontsize, FontFamily -> font],                  points[[First[#2]]]] &, Characters[text]]}, ImageSize -> 500]          }]],       {points, {Table[{ x, 0}, {x, 1, Length[Characters[text]]}]},          ControlType -> None},       {fontsize , Table[x, {x, 96, 256, 12}]} ,       {font, fonts}      ]      (The font menu gets populated once you use it.) ![kerning machine](http://i.stack.imgur.com/T1aNl.png) I want to be able to slide the letters right or left (but not up or down), but at the moment they don't move like they're supposed to. ## The solution Thanks to the fine answers, I've got something useful working. There are some kludges and hacks too, and some problems still to be ironed out (string length needs to be dynamic, 'canvas' needs resizing, and so on), but this is excellent for now.               With[{fonts = FE`Evaluate[FEPrivate`GetPopupList["MenuListFonts"]]},      DynamicModule[{kernedText, points},       points = Table[{x, 0}, {x, 1, Length[Characters[text]] + 10}];       Column[{         (* input *)         InputField[Dynamic[text], String],         (* main panel *)         Panel@LocatorPane[           Dynamic[            points, (points = ReplacePart[#, {{_, 2} -> 0}]) &],            Dynamic[kernedText =              Graphics[{MapIndexed[                Text[Style[#1, FontSize -> fontsize, FontFamily -> font],                   points[[First[#2]]]] &, Characters[text]]},               PlotRangePadding -> 0,               PlotRange -> {{0, 1 + Length[Characters[text]]}, Automatic},               Background -> None, ImageSize -> 800]], Appearance -> None],         (* controls *)         Row[          {           PopupMenu[Dynamic[fontsize], Table[x, {x, 72, 416, 12}]],           PopupMenu[Dynamic[font], fonts],           Button["Export",             Export[FileNameJoin[{$HomeDirectory, "Desktop",                "KernedText.png"}], kernedText],             ImageSize -> {Full, Automatic}]           }]         }, Left]]]      ![final](http://i.stack.imgur.com/5DKID.png) I realised that the locator dots didn't need to be showing - just click on the characters. The result can be compared to the unkerned version:               Text[Style[text, 192, FontFamily -> "Palatino"]]      ![unkerned](http://i.stack.imgur.com/lKUuh.png) For me, this area of Mathematica (Manipulate/Dynamic) is gradually becoming less confusing (but only gradually).


Error changing edge thickness in a GraphPlot

I'm having some problems with the _Mathematica_ graphics inspector. I want to make a graph with the following code:               GraphPlot[{{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}},         DirectedEdges -> True, MultiedgeStyle -> True, SelfLoopStyle -> True]      ![Mathematica graphics](http://i.stack.imgur.com/Vcgft.png) Which results in a good looking graph. But when I use Graphics Inspector to alter the weight of the edges, it gives me an error and _Mathematica_ closes. Does anyone else have ever experienced this? Or do you have another solution for me to achieve my graph with weighted edges? I'm using _Mathematica_ version 7.


MapThread and parallel computing

This time I have a very short question. Is there a deeper reason why ParallelMapThread does not exist? Regards, Frink


Numerically finding a derivative jump of a function

How would I numerically find where a function has derivative jumps? In particular, I'm working with this function:               f[k_?IntegerQ,y_?NumberQ] :=         x /. FindRoot[Nest[y/4 Sin[\[Pi] #] &, x, k] == x, {x, 1}]      ![k=1](http://i.stack.imgur.com/PgU5R.png) ![k=2](http://i.stack.imgur.com/CULAx.png)


Timing display of Graphics (Front End timing)

I want to know how much wall-time it takes to display a `Graphics` For example this one:               ballGrid[n_] := Module[{lines},       lines = Line[Flatten[Table[{            {{i, j, 0}, {i, j, 1}},            {{i, 0, j}, {i, 1, j}},            {{0, i, j}, {1, i, j}}},           {i, 0, 1, 1/n}, {j, 0, 1, 1/n}], 2]];       Graphics3D[{Sphere[Tuples[Range[0, 1, 1/n], 3], 1/(10 n)], lines},         Boxed -> False]]      First of all note that running `ballGrid[50]` and `ballGrid[50];` takes significantly different wall time to run Just using `AbsoluteTiming` does not give accurate representation (I assume it only measures kernel time):               In[]:= AbsoluteTiming[ballGrid[50];]     In[]:= AbsoluteTiming[ballGrid[50]]     Out[]:= {0.082963,Null}     Out[]:= {0.029378,<<Graphics>>}      I answered my own question, but I'd like to see other solutions too, and know why/if the `Print` workaround can be trusted


How to fit 3 data sets to a model of 4 differential equations?

I'm a biologist and a newbie in Mathematica. I want to fit three data sets to a model consisting of four differential equations and 10 parameters. I want to find the parameters best fitting to my model. I have searched the forum and found several related examples. However, I could not find anything that matched my question. Here are the details: **I have three time-series datasets: (xdata, ydata, zdata)**               time = Quantity[{0, 3, 7, 11, 18, 25, 38, 59}, "seconds"];     tend = QuantityMagnitude[Last[time]];      **xdata:**               xdata = Quantity[{0, 0.223522, 0.0393934, 0.200991, 0.786874, 1,          0.265464, 0.106174}, "milligram"];     xfitdata = QuantityMagnitude[Transpose[{time, xdata}]];      **ydata:**               ydata = Quantity[{0, 0.143397, 0.615163, 0.628621, 0.53515, 0.519805,          0.757092, 1}, "milligram"];     yfitdata = QuantityMagnitude[Transpose[{time, ydata}]];      **wdata:**               wdata = Quantity[{0.0064948, 0.221541, 1, 0.434413, 0.732392,          0.458638, 0.1484432, 0.0294298}, "milligram"];     wfitdata = QuantityMagnitude[Transpose[{time, wdata}]];      **I used`ParametricNDSolve` to solve the 4-DE model:**               pfun = {x, y, z, w} /.         ParametricNDSolve[{x'[t] ==           k1 - k10 x[t] w[t - 25] - k2 x[t] - k3 w[t] w[t],          y'[t] == -k8 y[t] + k10 x[t] w[t - 25] + k3 w[t] x[t],          z'[t] == k4 y[t] - k5 z[t],          w'[t] == (k6 x[t])/(y[t]^n + 1) - k7 w[t], x[t /; t <= 0] == 0.01,          y[t /; t <= 0] == 0.01, z[t /; t <= 0] == 0.01,          w[t /; t <= 0] == 0.01}, {x, y, z, w}, {t, 0, tend}, {k1, k2, k3,          k4, k5, k6, k7, k8, n, k10}]      Then I used `FindFit`. But I don't know how to specify that `xdata` is supposed to be fitted to `x[t]`, `zdata` to `z[t]` and `wdata` to `w[t]` via least-squares fit. For `y[t]`, there are no time-series data, but the parameter (`k8`) for `y[t]` is supposed to be determined as well. **I have tried the following, which is apparently wrong:**               fit = FindFit[xfitdata,        pfun[{k1, k2, k3, k4, k5, k6, k7, k8, n, k10}][        t], {{k1, 0.0859}, {k2, 0.0125}, {k3, 0.8541}, {k4, 0.0185}, {k5,          0.1004}, {k6, 0.5002}, {k7, 0.0511}, {k8, 0.0334}, {n, 9}, {k10,          0.8017}}, t]      **This is the error message:**               FindFit::nrlnum: The function value {0. +<<1>>[0.],-0.223522+<<1>>,-0.0393934+<<1>>,-0.200991+<<1>>,-0.786874+<<1>>[{0.0859,0.0125,0.8541,0.0185,0.1004,0.5002,0.0511,0.0334,9.,0.8017}][18.],-1.+<<1>>[25.],-0.265464+<<1>>,-0.106174+<<1>>[59.]} is not a list of real numbers with dimensions {8} at {k1,k2,k3,k4,k5,k6,k7,k8,n,k10} = {0.0859,0.0125,0.8541,0.0185,0.1004,0.5002,0.0511,0.0334,9.,0.8017}. >>      I'm lost and I would really appreciate your help!


How to fit data with numerical solution of system of parametric ODE?

I need to find the parameters (`k1,k2,k3,k4,k1r,k2r,k3r,k4r`) that fit my data (list of `[Intensity, time]`) using the function `b(t)`, solution of the following system of parametric ODE:               {a'[t] == -k1*a[t] - k2*a[t] + k1r*g[t] + k2r*p[t],      g'[t] == -k1r*g[t] - k3*g[t] + k1*a[t] + k3r*b[t],      p'[t] == -k4*p[t] - k2r*p[t] + k4r*c[t] + k2*a[t],      b'[t] == -k3r*b[t] + k3*g[t],      c'[t] == k4*p[t] - k4r*c[t]}      Initial conditions:               a[0] == 1,     c[0] == 0,     b[0] == 0,     p[0] == 0,     g[0] == 0,      The system of ODE has no analytical solution, so I tried to use `NDSolve`, but it is of course not working because the ODEs are parametric. I guess `ParametricNDSolve` would help me, but unfortunately it is not implemented in the version of Mathematica I am using (Mathematica 8). Do you have any idea about how to address this problem, avoiding the `ParametricNDSolve` function?


Using FindFit to fit nonlinear ODE parameters, subject to a constraint (an inverse problem)

Similar to this post I am finding that constraints tend to make `FindFit` poor at finding a good fit. However, unlike the previous post, the constraints are required and the success of `FindFit` seems to be very sensitive to initial values. Below I describe my particular problem in detail. Any suggestions to make the parameter fitting more robust would be appreciated. I am trying to fit the parameters `A`, `a0`, and `n` in the following nonlinear ODE               ExpODE = a'[t] == A * Exp[0.0583 * n * Sdot * t * Sqrt[a[t]]      to a set of experimental data. The primary varyiable `a[t]` is the crack length as a function of time `t`, and `a[0]=a0`. For those familiar with linear elastic fracture mechanics, this is a crack growth equation for a linearly increasing far-field stress `S = Sdot * t`. My experimental data consists of time to failure `tf` for various stress rates, `Sdot`. As an example, here is some fake experimental data               FakeData = {{100, 2.67886}, {200, 1.80317}, {300, 1.51754}, {400, 1.10085}, {500, 0.984215}, {600, 0.9044}, {700, 0.724567}, {800, 0.784177}, {900, 0.654773}, {1000, 0.627198}}      which looks like this when plotted ![FakeData](http://s11.postimg.org/khketh4r7/LEFM_calcs_page_1.jpg) The link between my ODE and my experimental data is an equation for the crack length at failure:               a[tf] == 294.295 / (Sdot^2 * tf^2)      Given values for `a0`, `A`, and `n`, I can solve `ExpODE` using `NDSolve` for `a[t]`, and solve for the time when the crack length equals the failure crack length. Here is my function for doing just that:               ExpModelFun[a0j_?NumberQ, Aj_?NumberQ, nj_?NumberQ][Sdotk_?NumberQ] :=     (Sol = NDSolve[{ExpODE /. {A -> Aj, n -> nj, Sdot -> Sdotk}, a[0] == a0j, WhenEvent[a[t] > 0.140, "StopIntegration"]}, a[t], {t, 0, 60}][[1]];     tf = t /. FindRoot[(a[t] == 294.295 / (Sdot^2 * t^2)) /. Join[Sol, {Sdot -> Sdotk}], {t, 0.01}];     ExpModelFun[a0j, Aj, nj][Sdotk] = tf)      (The `WhenEvent` clause is there to avoid having the crack run away on me. Once the crack length goes past 0.140 the ODE gets very stiff.) Of course, I do not know `a0`, `A`, and `n` a-priori, so I am using `FindFit` to iteratively solve for them. The following code               FindFit[FakeData, {ExpModelFun[a0, A, n][Sdot]}, {{A, 0.001}, {a0, 1*10^-9}, {n, 0.5}}, Sdot, StepMonitor :> Print[{A, a0, n}]]      results in               NDSolve::nrnum1: "The function value -0.140165-1.98689*10^-15 i is not a real number when the arguments are {1.010824975706311`*^-6,-0.000164548-1.9868921541309406`*^-15 i}"      a whole host of other errors, and a final fit of               {a0 -> -0.00013947, A -> -0.00290892, n -> 18.9563}      These parameters are not physical. I can fix this by adding the constraints `a0 > 0` (initial crack length is positive) and `A > 0` (cracks cannot shrink), but `FindFit` seems to get stuck, even if I set the `AccuracyGoal` to 1. The values it gets stuck at are               {a0 -> 4.58074*10^-9, A-> 0.000743962, n -> 1.37966}      The starting guesses `{a0, 1*10^-9}, {A, 0.001}, {n, 0.5}` are the parameters I used to create `FakeData`, before adding a little bit of noise, so they should be pretty good. I went ahead and changed `0.001` to `0.0005` anyways and found that               FitSol = FindFit[FakeData, {ExpModelFun[a0, A, n][Sdot], {a0 > 0, A > 0}}, {{a0, 1*10^-9}, {A, 0.0005}, {n, 0.5}}, Sdot, StepMonitor :> Print[{a0, A, n}], AccuracyGoal -> 3]      produces               {a0 -> 1.65801*10^-10, A -> 0.000756955, n -> 1.33919}      which looks like ![fit](http://s15.postimg.org/ozqhdosu3/LEFM_calcs2_page_1.jpg) This is a decent fit. What's frustrating is these values are quite close to the values `FindFit` got stuck at previously. I am guessing that `FindFit` is getting stuck in a local minimum. In my real application, I doubt I will have very good initial guesses. Am I just doomed to tweak initial values endlessly until I get right next to good fit?


How can I get the limit of a certain infinite product?

A first look at it suggests the fact the limit is precisely $1$. To check that I tried _Mathematica_ , but no output so far. Most probably it converges very slowly. Is there any way to get the limit?               Limit[1/n^n Product[(n Sqrt[n] + (n + 1) Sqrt[k])/(Sqrt[n] + Sqrt[k]), {k, 1, n}],        n -> Infinity]


Assigning values to a list of variable names

As part of a calculation I need to do something like this               Evaluate[{aaa, bbb, ccc}[[ index]]] = {1, 2, 3, 4, 5}      so if index is `1` then `{1, 2, 3, 4, 5}` will be stored into the variable `aaa`.   But if I re-evaluate this it does not work because `aaa` is now a list and not a variable. I tried various options with `Hold[]` etc but did not manage to solve this.


Better way to select all array indexes matching predicate?

I'd like to select (offset) indexes of a number of array points, that match a selection criteria. I can do this by creating a Table of all the coordinates, and then selecting all the values:               data = Array[ RandomInteger[1] &, {4, 4}]     {wx, wy} = data // Dimensions ;     t = Flatten[       Table[ {x - wx/2, y - wy/2, data[[x]][[y]]}, {x, 1, wx}, {y, 1,         wy}], 1]     Select[ t, #[[3]] == 1 &]      This resulted in the respective values:               {{1, 1, 1, 1}, {1, 0, 0, 1}, {1, 0, 1, 0}, {1, 0, 0, 1}}     {{-1, -1, 1}, {-1, 0, 1}, {-1, 1, 1}, {-1, 2, 1}, {0, -1, 1}, {0, 0,       0}, {0, 1, 0}, {0, 2, 1}, {1, -1, 1}, {1, 0, 0}, {1, 1, 1}, {1, 2,       0}, {2, -1, 1}, {2, 0, 0}, {2, 1, 0}, {2, 2, 1}}     {{-1, -1, 1}, {-1, 0, 1}, {-1, 1, 1}, {-1, 2, 1}, {0, -1, 1}, {0, 2,       1}, {1, -1, 1}, {1, 1, 1}, {2, -1, 1}, {2, 2, 1}}      However, my real data is big (800x800) and sparse. This method creates a big data set and then throws most of it away. What is a more efficient way to do this?


Factoring a two variable polynomial in a special way

Let $$f=x^9-x^6+4x^5y+2x^3y^2-y^4$$ I would like to factorize $f$ into form: $$(y-F_1(x))\cdots(y-F_k(x))$$ over complex numbers. How can I do it with _Mathematica_?


How can I solve my system of differential equations?

I have a question pertaining to my code below: I require to find the values of the roots `E2` that will set the function `f1[E2] - f2[E2]` to zero. I know how to obtain the roots one at a time: for instance a root of `E2` lying between, say 0 and 2. But I would like to know whether it is possible to get _Mathematica_ to generate all the roots that lie within a certain interval at once, say those lying between 0 and 10. I have tried using `NSolve` and `Reduce`, but I got nothing, so any help will be most appreciated!               xmin = -6.5;      xmax = 6.5;      xmatch = 1.5;      eq1[x_, x0_, E2_] := {Derivative[2][y][x] + (E2 - x^2) y[x] == 0,                            y[x0] == 0, Derivative[1][y][x0] == 1/10^6};           y1[x_, E2_] := y[x] /. NDSolve[eq1[x, xmin, E2], y, {x, xmin, xmatch}][[1]];      f1[E2_] := Abs[D[y1[x, E2], x]/y1[x, E2] /. x -> xmatch];      y2[x_, E2_] := y[x] /. NDSolve[eq1[x, xmax, E2], y, {x, xmax, xmatch}][[1]];      f2[E2_] := Abs[D[y2[x, E2], x]/y2[x, E2] /. x -> xmatch]     f[(E2_)?NumericQ] := f1[E2] - f2[E2];      (* The following trial doesn't success *)     NSolve[f[(E2_)?NumericQ] == 0 && 0 < E2 < 10, E2]     rts = Reduce[f == 0 && 2.5 < E2 < 10., E2]     c2 = N[E2 /. {ToRules[rts]}]     Print["The value of E2   was=", c2]      * * * this is the code that i have written to numerically try to solve the DEs to obtain the roots E2. i am able to obtain the roots by plotting "exp" versus E2. however, when i try to use the erzek root finder, an error message is generated               xmin = (-8.5);          xmax = 8.5;          xmatch = 0.50;          eq[x_, x0_, E2_] := {y''[x] + (2 E2 - x^2) y[x] == 0, y[x0] == 0,         y'[x0] == 1/10^6};          exp := (# - #2) & @@ ((y'[xmatch]/y[xmatch] /.              NDSolve[eq[x, #, E2], y, {x, #, xmatch}][[1]]) & /@ {xmin,            xmax});          Plot[exp, {E2, 0, 10}]          Needs["Ersek`RootSearch`"];          rst = RootSearch[exp == 0, {E2, 0, 5}](* gives an error message  *)


How can I prevent Superscript from being interpreted as Power?

I have very strong desire to use superscript as the index of the variable. However, it looks like that the Mathematica automatically recognize the superscript as the power and I got message that my variable with superscript is 'protected'. Could you help me to make the superscript used as the index of the variable instead of power?


Get brief help for a set of functions

When we are in console mode or working with a notebook we can get brief help about a function just by shift-entering `?function` I would like to have a list like the following               {Map, Function, List, Transpose, Outer, Sequence, Apply, Tuples, \     Distribute, Thread, Equal, Fold, Slot, Reverse, Plus, Times, Total, \     MapThread, Inner, ReplaceAll, Rule, Composition, Through, Nest, \     ToExpression, ToString, Row, Part, Range, ComposeList, Compose, \     SlotSequence, Flatten, FoldList, NestList, Hold, Release}      and get a list of strings containing the corresponding help(s). `?` cannot be mapped to a list of course so i am trying to find another way. `?` works with Wildcards like `?*Plot*` so i suppose it accepts some kind of pattern matching. Any ideas ?


How to plot a function with variable with an open interval?

I want to plot this revenue function: $r=30q-0.3q^2$ I have no range, its an open interval, but when I try to plot in _Mathematica_ it requires the min and max of the plotting limits. How do I do this? *Edit: Thank you for helping, my professor gave us the revenue function mentioned up, and asked us to plot " revenue versus quantity (q) ", he did not specify any range, or max and min. My question is can i plot this without a max and min?


Maximum but still limited magnitude region is not plotted with ContourPlot

![enter image description here](http://i.stack.imgur.com/5ZtSi.png) The function is well defined in the whole region. But it just skips plotting the center region. I've tried PlotPoints, Mesh, Contours - it didn't help. ![enter image description here](http://i.stack.imgur.com/kTbCN.png) After making more contours. White hole is still there. ![enter image description here](http://i.stack.imgur.com/8GBrC.png) After zooming in the region suddenly reveals data. How can I make it to plot central part in detail when zoomed out? Thank you in advance. UPD: Yes, thanks, that's PlotRange :)


How do I remove an entry from the Format > Stylesheet menu?

I was playing a bit with the stylesheets to make my own. In the process I have created and installed a few stylesheets but now I would like to remove some of them. First, how do I remove an entry from the Format > Stylesheet menu? Second, where are the stylesheet files kept? I have deleted the files from the `$UserBaseDirectory/SystemFiles/FrontEnd/StyleSheets`, reloaded _Mathematica_ , even rebooted the computer, but my styles are still working! Apparently _Mathematica_ keeps a copy of my files somewhere I don't know about.