title: MatrixPlot with Tooltips

text: `MatrixPlot` is very nice to have a first look of data, I would like to have a `MatrixPlot` with tooltips for each value. I tried adding `Tooltip` to all the values but it didn't work. My matrix is not very big (~20x25), so each square is visible. **EDIT:** This is the version I did using the answer of Heike:               matPlot[matWithTooltips_, opts : OptionsPattern[]] :=       With[{dim = Dimensions[matWithTooltips],         mat = matWithTooltips /. Tooltip[a_, ___] :> a},       DynamicModule[{pt = {0, 0}, ij, xy, label, direction},        direction[mxy_] := 1 - 2 Boole[Thread[mxy > dim/2]];        LocatorPane[Dynamic[pt],         Dynamic[          xy = Floor[pt];          ij = {dim[[1]], 1} + Cross[xy];          label = If[And @@ Thread[1 <= ij <= dim],            {{FaceForm[], EdgeForm[{Thick, LightGray}], Rectangle[xy]},             Text[              Framed[Replace[                Extract[matWithTooltips, ij], {Tooltip[a_, b_] :> b,                  Tooltip[a_] :> a}], Background -> White],              direction[xy] + xy,              -1.2 direction[xy]]},            {}];          MatrixPlot[mat, Epilog -> label, opts]],         AutoAction -> True,         Appearance -> None]]]      The main improvement is that it can receive a matrix with its own tooltips in the data. Thanks to all for the help.


title: how to solve a linear system (Ax=b) using domain decomposition?

text: The Domain decomposition is a natural technique for reducing the computational cost for solving large-scale linear systems, somebody know how to do it using mathematica?


title: CreateDialog behaves differently in Player Pro

text: nm = "start";          d1 :=        Dynamic[Grid[{{         TextCell["Enter a name: "],         InputField[Dynamic[nm], String],         DefaultButton[DialogReturn[ret = nm]]}}]];          CreateDialog[TabView[{"dlg1" -> d1, "dlg2" -> d1}], WindowTitle -> "tt"];      In _Mathematica_ initially the edit box will show `Start`. After exiting the dialog both variables, `ret` and `nm`, will have value that was entered in the box. In Player Pro the initial value of `nm` is not shown in the edit box and the entered value is not assigned to the variables. What is the reason for that and how to pass values in and out of the dialog in _Player Pro_ or better how to make the code exhibit the same behaviour? Both _Mathematica_ and _Player Pro_ are _v9_. I believe the player in previous versions behaved like _Mathematica_.


title: How to plot the product of the NDSolve result and any known function

text: How can I plot the product of the `NDSolve` result, e.g. `x[t]/.solution` and any known function, for instance, `Sin[x]`?


title: Finding "Maxima" and "Minima" on a B-Spline

text: I need to find the "Maxima" and "Minima" on a B-Spline or more correct the points where the 2nd components of the derivate equal zero. For example:               g = BSplineFunction[{{1, 2}, {2, 4}, {3, -1}, {4, 2}}] ;      dg=g';     Solve[{dg[t][[2]] == 0, 0 <= t <= 1}, t]      The problem is that "Solve" wont work for this kind of application, and "Minimize" or similar functions stop at the first finding. Any ideas?   CX


title: Real and/or improved CForm of expressions

text: I'd quite like to be able to automatically generate C++ versions of certain mathematical expressions that I've manipulated in Mathematica. The resultant C++ code fragment is then going to be used independently of Mathematica. Mathematica provides a `CForm` function, which almost seems like what I want, but I can't get it to do basic conversions nor tell it how to convert Mathematica symbols into my C++ identifiers. **For example, I would like the output from`CForm[x[0]^2]` or `ToString[x[0]^2, CForm]` to be `"std::pow(obj.x_[0], 2)"`.** This can be a string; it doesn't need to be usable in Mathematica any more. Of course, my actual expressions of interest are a lot more complicated than this. But:   * I don't have a way of telling Mathematica that symbol `x` is to be renamed to `obj.x_` (not a valid symbol name in Mathematica so can't use it directly). String manipulation after conversion is too unreliable for this so a more direct method is preferred.   * I can't tell Mathematica that `x` is an array, not a function, so it gives me `x(0)` instead of `obj.x_[0]`.   * Mathematica thinks I want to use its own `Power` function, but I'd really like to use `std::pow`. Perhaps `CForm` isn't suited to this task, but I would still appreciate a solution using any other available method if possible. I really think that Mathematica should be able to help me here, because it knows where I need brackets and so on. I've tried:               Format[x[a_], CForm] :=         "obj.x_[" <> ToString[a, CForm] <> "]"          Format[Power[a_, b_], CForm] :=          "std::pow(" <> ToString[a, CForm] <> ", " <> ToString[b, CForm] <> ")"          ToString[x[0]^2, CForm]      but of course `Power` is protected so the second `SetDelayed` gives me an error, and my `ToString[x[0]^2, CForm]` output is really weird (`Power("obj.x_[0]",2)`) because I've tried to use strings in the `Format`.


Is it possible to show Tooltips in a ListPicker menu? This effect is possible using TabView, but I would much prefer using ListPicker. Below is a simplified version of my code.               ItemList =       {"Apples",        "Oranges",        "Bananas",        "Watermelon"};     ReviewsList =       {"10 Reviews",        "7 Reviews",        "16 Reviews",        "12 Reviews"};     TooltipList =       {"5 Positive, 3 Neutral, 2 Negative",        "4 Positive, 1 Neutral, 2 Negative",        "10 Positive, 2 Neutral, 4 Negative",        "6 Positive, 3 Neutral, 3 Negative"};     CombinedList = Table[Column[         {Style[ItemList[[i]], FontColor -> Purple,            FontFamily -> "Verdana", FontSize -> 12, FontWeight -> Bold],          Tooltip[           Style[ReviewsList[[i]], FontFamily -> "Verdana",             FontSize -> 12], TooltipList[[i]]]}         ], {i, 1, 4}];          (* Column *)     Column[CombinedList]          (* TabView *)     TabView[Table[CombinedList[[i]] -> 1, {i, 1, 4}], Dynamic[x],       ControlPlacement -> Left]          (* ListPicker *)     ListPicker[Dynamic[x], CombinedList]


title: Incrementally revealing Grid (or TableForm) entries

text: I have a `Grid` (or `TableForm`) object like this `Grid[{{Ins, Outs}, {a, b}, {c, d}, {e, f}}, Frame -> All]` ![enter image description here](http://i.stack.imgur.com/nFp9q.png) that I would like to "incrementally reveal" (within a `Manipulate`) in the sense, for example, that one row at a time is revealed with each click of the `Manipulate`. The part giving me trouble is that I want to "fill in" the table from _bottom to top_ , while maintaining the (final) header cells and grid lines throughout each incremental reveal. I started out by filling the yet-to-revealed entries with white space (until they are revealed). This is fine for small tables like this, but I also need it to work for tables with dozens of rows so I am seeking something more systematic. Any hints/tips/nudges would be appreciated. **Edit:** To clarify, the desired behavior is like this:               one = Grid[{{Ins, Outs}, {, }, {, }, {e, f}}, Frame -> All];     two = Grid[{{Ins, Outs}, {, }, {c, d}, {e, f}}, Frame -> All];     three = Grid[{{Ins, Outs}, {a, b}, {c, d}, {e, f}},        Frame -> All];      Manipulate[{one, two, three}[[i]], {i, {1, 2, 3}}]      ![enter image description here](http://i.stack.imgur.com/wJoTH.png) ![enter image description here](http://i.stack.imgur.com/MMmel.png) ![enter image description here](http://i.stack.imgur.com/owg6U.png)


title: How to dynamically update a variable by using mouse over?

text: I want to extract the `Graphics` type when I hover my mouse over an object, but I failed to do so. Below is the code I am working on. Any suggestions are welcome               m = "E";     Graphics[{        Mouseover[ {Black, Disk[{-10, 0}]}, {m = "D"; Red, Disk[{-10, 0}]}],       Mouseover[ {Black, Rectangle[{10, 0}]}, {m = "R"; Red,          Rectangle[{10, 0}]}]       ,  Text[Dynamic[m], {0, 0}]       }]


title: How can I create a list containing the normalized element-by-element product of two given lists?

text: I have to calculate: ![enter image description here](http://i.stack.imgur.com/nfbVq.jpg) How can I create such a sum? Do I have to set the factors of each term manually (one by one), like `G1 = 1, H1 = 1, G2 2, H2 = ...`.? ### Update ![enter image description here](http://i.stack.imgur.com/UxKzV.jpg) Addtional Questions:   1. How can I store te results into another List? (In this example, the list `F`)   2. Sometimes, a variable turns blue and does not get calculated in expression. How do I fix this?


title: Fast way to extract data from a list

text: I used `data=Table[{i,f[i]},{i,1,n}]` to produce a list, here `n` is greater than 2^20 = 1048576. The function f(N) runs in time `O(N*Log(N))`, it is defined as:               Mod[PowerMod[i,n,n]-i,n] (n is an argument in a function which use this)      Now I want to give a table which shows the values of i that f(i) is 0, and another table for f(i) non-zero. I used `zero = Select[data,#[[2]]==0&]`, but it is slow in the following sense:               n=2^22, timing for data =  10.171, timing for zero =  4.508     n=2^23, timing for data =  21.606, timing for zero =  9.250     n=2^24, timing for data =  43.399, timing for zero = 17.971     n=2^25, timing for data =  84.209, timing for zero = 34.523     n=2^26, timing for data = 167.420, timing for zero = 71.885      The hardest computation is the `data`, But after that I want to have a much faster way to know the zeros of the function `f`. Of course I can use `For` or `Do` to append the zeros `i` each time f(i) is zero. But we know that `AppendTo` is slow, and `For` or `Do` is slower than `Table`. Is there any way to construct a list + exact data fast? * * * Update: Thanks for all the suggestion. Here is a table of comparison. The green columns is to find i such that `f[i]=0` and the white columns (excluding the 1st and 2nd column) is to find i such that `f[i]!=0`. The last 2 columns are in fact using "NonzeroPositions" (the last column) as mentioned by ubpdqn, then do the complement (the second last column). This method is faster. ![enter image description here](http://i.stack.imgur.com/jucJm.png)


title: How to loop in reverse order?(e.g. for i from 10 to 1)

text: I have a list `F = {382.856, 638.53, 915.482, 1192.44, 1469.39, 1746.34, 2023.29, 2181.91}` And I want to use it to calculate V: ![enter image description here](http://i.stack.imgur.com/ZaVI3.jpg) I think it should be something like: `V = Table[ V[i] = V[i+1] + F[i], {...loop in reverse order}]`, I'm not sure about the expression, and didn't find options to excute loop in reverse order. In Mathematica's reference, I only find that `Do[expr,{i,imax}]` , does this mean that the loop can only go in increasing order?


title: Problem with PlanarGraphPlot And ConvexHull

text: I'm getting a lot of strange errors when using `PlanarGraphPlot` with a simple list of 11 points. This is using Mma 9.0.1 64-bit Mac OS X.               << ComputationalGeometry`;     x = {{184978.59580704456`, 77909.66948289984`},           {184978.27815712072`,77909.76595227784`},          {184978.27082673783`, 77909.74177736834`},          {184977.5543690799`, 77909.95958192856`},          {184977.65873976916`, 77910.2913545858`},          {184977.87393886593`, 77910.32174601014`},          {184978.3127146399`, 77911.75682671613`},          {184979.13720817852`, 77911.37094455786`},          {184979.40459261995`, 77911.34308556134`},          {184979.6157774594`, 77912.04232488069`},          {184980.40222282038`, 77911.69604330455`}};     PlanarGraphPlot[x]      Errors I get are               Mod::indet: Indeterminate expression Mod[-1,0] encountered. >>          Part::partw: Part 1 of {} does not exist. >>          Part::pspec: Part specification Indeterminate is neither a machine-sized integer nor a list of machine-sized integers. >>          Part::pspec: Part specification {{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,5,6,3,5},{11,10,9,4},{},{7,10},{9,7,11},{10,7}}[[8,1]] is neither a machine-sized integer nor a list of machine-sized integers. >>          Part::pspec: Part specification {{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,5,6,3,5},{11,10,9,4},{},{7,10},{9,7,11},{10,7}}[[8,1]] is neither a machine-sized integer nor a list of machine-sized integers. >>          General::stop: Further output of Part::pspec will be suppressed during this calculation. >>          Part::partw: Part 1 of {} does not exist. >>          Set::shape: Lists {ComputationalGeometry`Private`merge$30945[[ComputationalGeometry`Private`l0$30945]],ComputationalGeometry`Private`merge$30945[[ComputationalGeometry`Private`r0$30945]]} and ComputationalGeometry`Private`insert[{{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,5,6,3,5},{11,10,9,4},{},{7,10},{9,7,11},{10,7}}[[{6,{{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,5,6,3,5},{11,10,9,4},{},{7,10},{9,7,11},{10,7}}[[8,1]]}]],6,{{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,<<3>>,5},<<1>>,{},{7,10},{9,7,11},{10,7}}[[<<1>>]],2,3] are not the same shape. >>          Mod::indet: Indeterminate expression Mod[-1,0] encountered. >>          Part::partw: Part 1 of {} does not exist. >>          General::stop: Further output of Part::partw will be suppressed during this calculation. >>          Set::shape: Lists {ComputationalGeometry`Private`merge$33935[[ComputationalGeometry`Private`l0$33935]],ComputationalGeometry`Private`merge$33935[[ComputationalGeometry`Private`r0$33935]]} and ComputationalGeometry`Private`insert[{{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,5,6,3,5},{11,10,9,4},{},{7,10},{9,7,11},{10,7}}[[{6,{{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,5,6,3,5},{11,10,9,4},{},{7,10},{9,7,11},{10,7}}[[8,1]]}]],6,{{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,<<3>>,5},<<1>>,{},{7,10},{9,7,11},{10,7}}[[<<1>>]],2,3] are not the same shape. >>          Mod::indet: Indeterminate expression Mod[-1,0] encountered. >>          General::stop: Further output of Mod::indet will be suppressed during this calculation. >>          Set::shape: Lists {ComputationalGeometry`Private`merge$35305[[ComputationalGeometry`Private`l0$35305]],ComputationalGeometry`Private`merge$35305[[ComputationalGeometry`Private`r0$35305]]} and ComputationalGeometry`Private`insert[{{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,5,6,3,5},{11,10,9,4},{},{7,10},{9,7,11},{10,7}}[[{6,{{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,5,6,3,5},{11,10,9,4},{},{7,10},{9,7,11},{10,7}}[[8,1]]}]],6,{{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,<<3>>,5},<<1>>,{},{7,10},{9,7,11},{10,7}}[[<<1>>]],2,3] are not the same shape. >>          General::stop: Further output of Set::shape will be suppressed during this calculation. >>      Removing certain points from the list (like the last one) causes the plot to succeed. Also this set of points fails to give proper `ConvexHull`               y = {{1.8497859580704457`, 0.7790966948289985`},         {1.8497827815712071`, 0.7790976595227784`},         {1.8497827082673783`, 0.7790974177736835`},         {1.849775543690799`, 0.7790995958192857`},         {1.8497765873976917`, 0.779102913545858`},         {1.8497787393886593`, 0.7791032174601015`},         {1.849783127146399`, 0.7791175682671613`},         {1.8497913720817853`, 0.7791137094455786`},         {1.8497940459261994`, 0.7791134308556135`},         {1.849796157774594`, 0.7791204232488069`},         {1.849804022228204`, 0.7791169604330455`},         {1.849803552734635`, 0.7791159289575218`},         {1.8498057134522492`, 0.7791151852825192`},         {1.8498006729413692`, 0.7790991813917657`},         {1.8498002121744468`, 0.7790984699581178`},         {1.8497995890919037`, 0.7790977401058187`},         {1.8497986151981813`, 0.7790973602143807`},         {1.8497975924352397`, 0.7790973993547065`},         {1.8497955957785752`, 0.77909842160827`},         {1.8497951821355425`, 0.7790997823117062`},         {1.8497944840038416`, 0.779101624213374`},         {1.8497934996381435`, 0.7791037516125543`},         {1.8497920021456453`, 0.779106194441444`},         {1.849792775326504`, 0.7791094914607818`},         {1.8497897908134828`, 0.7791098506337076`}}     Graphics@Point@y[[ ConvexHull[y] ]]      Thanks


title: Determining whether two $k$-chromatic graphs are isomorphic (respecting vertex coloration)

text: Consider the case where I have two $k$-chromatic graphs $G_1$ and $G_2$, i.e. two graphs where individual vertices can be colored with one of a set of $k$ total colors, and I would like to determine if the two graphs are equivalent while respecting vertex coloration. Is there a way to do this in Mathematica 8 or 9? If so, is there a known computational complexity for the algorithm being employed?


title: What's the internal command for entering a fraction?

text: I'm looking for the `FrontEnd`Foo[...]`-like command that's triggered when pressing `Ctrl + /`. Are there any discoverability features in Mathematica that would have helped in this case? E.g., in Emacs I could have just pressed `Ctrl + h k Ctrl + /` ("Find function for key `Ctrl + /`").


title: What is the order of execution of Animate?

text: I used to think the execution order of `Animate` is the same as `For` until I find:               Animate[var++,{n,0,10,1}];       the var increases while `n` not. But               Animate[var=n,{n,0,10,1}];       the `n` keeps increasing. Why would this happen? If I want a expression which don't contain n to be executed only once in every step, what should I do? (Actually, I want to embed a code in my website using `CDF`. It will be OK if there are other solutions without using `Animate`.)


title: Is there a convenient way to copy/paste text-interspersed SE code snippets into Mathematica?

text: Is there a way to copy and paste code snippets from SE to _Mathematica_ if these snippets are interspersed with text? Like e.g. in Morphing Graphics, color and location in both the question and answer, there are code blocks separated by text and graphics. Pasting this into _Mathematica_ in `n` steps is tiresome. Perhaps there is some nice way to make pasting as comfortable as the other way round with the code and graphics palettes?


title: Speed up plot of $\sum_{j\ge1} 2^{-j}(1-2^{-j})^{n-1}$

text: I'm a beginner at Mathematica. I would like to plot the following function: $${n\over2} \sum_{j\ge1} 2^{-j}(1-2^{-j})^{n-1}$$ However the following code is just too slow:               Plot[n/2 NSum[2^(-j) (1 - 2^(-j))^(n - 1), {j, 1, Infinity}], {n, 1, 100}]      I think it may be trying to expand the $(n-1)$th power symbolically instead of numerically. How can I fix that?


title: How to find the non-differentiable point(s) of a given continuous function?

text: For example, the non-differentiable point of the function $f(x)=|x|$ is at $x=0$.   How to find the non-differentiable points of a continuous function that is defined numerically?


title: Constructing a Summation with a Variable Number of Inner Sums

text: I have a question regarding multiple sums. And my second index depends on the first index. Here it is: $$ \sum_{d=1}^{P}e^{-d}\sum_{\substack{1\leq k_{1}\leq Q \\\ 1\leq k_{2}\leq Q \\\\... \\\\...\\\1\leq k_{d}\leq Q}}e^{-(k_{1}+...+k_{d})} $$ I could not write this sum in mathematica. The problem is that my second sum is a multiple sum and I do not know how to sum $d$ times. How can I do it?


title: Finding all dictionary words that can be made with a given set of characters (Wordfeud/Scrabble)

text: This is a slightly more involved variant of this recent question. By sheer coincidence I happened to have been building a Wordfeud (Scrabble clone) game in Mathematica. ![Mathematica graphics](http://i.stack.imgur.com/RHMKk.png)   _My interactive Wordfeud board in Mathematica_ I used `DictionaryLookup` with `StringExpression` to find matches corresponding to my hand (7 letters) and the fixed letters in the same row on the board that can be used. With 15 characters on a row that would be a maximum of 8 extra letters at fixed positions. I believe Mr.wizard's solution of generating all permutations would be unbearably slow in this case. I wonder whether the mma.se community has better ideas for this variant. Being far removed from my own MMA installation I can't currently post what I've got so far, but will do so this weekend. My solution typically took somewhere around 10-20 secs if memory serves, which is a tad slow. The next step-up in complexity would be having to deal with all potential words crossing your row. Extra points if you have ideas to tackle that efficiently.


title: Thousands separator (comma) option for NumberString/StringCases?

text: I've been looking for a way to read numbers that have thousands separators in them:               StringCases[" 1142.123 ",  Whitespace ~~ NumberString ~~ Whitespace, 1]      gives               {" 1142.123 "}      but               StringCases[" 1,142.123 ", Whitespace ~~ NumberString ~~ Whitespace, 1]      gives               {}      So ideally there's a Mathematica way of defining `NumberString` to recognize commas in numbers. Or should I be looking into regexen at this point?


title: Trying to solve simultaneous equations based on format found on official website

text: $\def\1{x_1}\def\2{x_2}\def\3{x_3}\def\f{f(\1,\2,\3)}\def\bs{\bigskip}\def\b{\begin{pmatrix}}\def\e{ \end{pmatrix}}\def\le{\left}\def\ri{\right}\def\g{g(\1,\2,\3)}\def\l{\lambda}\def\n{\nabla}\def\x{\lambda_1}\def\y{\lambda_2}$ I am putting in the following input:               Solve[{2 + 2 a*d + 2 a*e == 0, 1 - 2 b + 2 d*b + 2 e*b == 0,        1 + 2 d*c + 2 e*c == 0, -2 + a^2 - 2 b + b^2 + c^2 ==         0, -2 + a^2 + b^2 + c^2 == 0}, {a, b, c, d, e}]      And it is returning:               (* {} *)      What am I doing wrong? Is this not computable? \begin{align} 2+2\x\1+2\y\1 = 0 \\\ %8 1+2\x\2+2\y\2-2\y = 0 \\\ %9 1+2\x\3+2\y\3=0 \\\ %10 \1^2 + \2^2 - 2\2+\3^2-2=0 \\\ %11 \1^2 + \2^2 + \3^2 - 2 = 0 %12 \end{align}


title: How to make 3 parameters selection and then execute, and not with each selection?

text: Manipulate[{u*v}, Row[{Control[{u, 0, 1}], Control[{v, 0, 1}]}],       ControlType -> VerticalSlider, ControlPlacement -> Up]      Q1.- How to select the operation *, +, - or /? in the first parameter of Manipulate Q2.- AND how to force Manipulate/MAthematica to WAIT that I modify various paramenters ( u , v and operation) to execute the operation, AND NOT make the operation in every change I made in u, and in every change of v, and in every change of "+-*/" ? . Iwant to select u, v and operation, and THEN (only whe I push a buttom or similar) execute with the parameters.


title: LinkSnooper troubles on Windows

text: I'm trying to get LinkSnooper up and working on a Windows 7 machine to monitor the interaction between the Mathematica front end and MathLink. I'm facing great troubles following the instructions here. Namely, my arguments to MLOpen are as follows:               -LinkMode Launch -LinkName "'C:/Program Files/Wolfram Research/Mathematica/9.0/SystemFiles/Java/Windows-x86-64/javaw' -classpath \"C:/Program Files/Wolfram Research/Mathematica/9.0/SystemFiles/Links/JLink/JLink.jar\" com.wolfram.jlink.util.LinkSnooper -kernelname 'C:/Program Files/Wolfram Research/Mathematica/9.0/mathkernel.exe'"      and when loading the kernel, a file system browser pops up and asks me to select a MathLink program to run. Anyone got this working on a windows machine and perhaps have some suggestions?


title: Multivariable Delay Diff. Equ. with Ndsolve and Nintegrate

text: I'm trying to simulate the following equation in _Mathematica_ for $u(x,t)$: $$\frac{1}{\alpha} \frac{\partial u(x,t)}{\partial t} = -u + \int_{-\infty}^\infty {\rm d} y w(x-y) f(u(y,t - |y|/v))$$ where $$w(z)=-\frac{w_o}{2\pi}(1-|z|)e^{-\frac{|z|}{\sigma}}, f[u] = \frac{1}{1+e^{-a(u-\theta)}}$$. So far I've written the following code to do this without the absolute value in `y`, spatial distance and time delays in $u$, which works:               h[z_Real] := Integrate[-(1/(2 Pi))*(1 - y)*Exp[-y]*(1/(1 + Exp[z])), {y, 0, 10}];          solu = NDSolve[{D[z[x, t], t] == -z[x, t] + h[z[x, t]], z[x, 0] == 0.8 Abs[Sin[x]]},                     z[x, t], {t, 0, 5}, {x, -5, 5}];          Plot3D[Evaluate[z[x, t] /. solu], {t, 0, 5}, {x, -5, 5}, PlotRange -> All]      The question I'm asking is whether it's possible to add in the delay. Unfortunately, when I include it and change the initial condition to `z[x,t/;t<=0]=0.8`, I get an error message. Does anyone have a suggestion about how I should proceed? Thanks.


title: How to put the labels in the minimun and maximun option in the slide verticals? Manipulate

text: I like this, but.. .. how could I put the labels to know +- over where value I are moving? for examples, between 0 and 8.                Manipulate[{u*v}, Row[{Control[{u, 0, 1}], Control[{v, 0, 1}]}],        ControlType -> VerticalSlider, ControlPlacement -> Up]


title: A simple expression which Mathematica will not simplify

text: Sorry for the vague title, but I wasn't sure how to phrase this. I was using _Mathematica_ to solve a fairly simple algebraic equation, but when I tried to substitute the solution into the original equation as a check, I can't seem to recover my original answer. Minimal example:               eq = a == (1 - b)/Sqrt[1 - 2 b]          sol = Solve[eq, b]          FullSimplify[(1 - b)/Sqrt[1 - 2 b] /. sol, a > 0]      The final line outputs > >     {(a (a + Sqrt[-1 + a^2]))/Sqrt[-1 + 2 a (a + Sqrt[-1 + a^2])], >      (a (a - Sqrt[-1 + a^2]))/Sqrt[-1 + 2 a (a - Sqrt[-1 + a^2])]} >   even after I've specified that a is positive. So `FullSimplify` is not enough to make this last line output `a`. What am I missing?


title: Are there a function to choose the greatest value in a discrete function?

text: Supose a discrete function show 1st, 2nd,...6th value are               h = {5, 4, 2, 8, 9, 1}      And I want to find the maximun in the subset of indexes 1,3,5,6 (what are {5,2,9,1}) Are there any function to do this easily? or Must I prgram one for doing that?


title: Manually adjust graph vertex location by dragging?

text: Sometimes I have a graph and I want to make tweaks to the vertex locations. Is there any way to manually adjust graph vertex location by dragging? If I double click to edit, I can move around the vertex rendered shape (square) or the label inside the square, but not the vertex itself. Also, even if I could move the vertex, it is under the rendered square/circle which does not seem to move with it. I have been using `GraphPlot`. (Should I be using `Graph` instead? I don't really understand the difference.):               GraphPlot[Import["D:/dev/ProjectEuler/keylog.gv"],       VertexLabeling -> True, PlotStyle -> {Black},       VertexRenderingFunction -> ({EdgeForm[Black], White, Disk[#1, 0.08],           Black, Text[#2, #1]} &)]


title: Prove an identity in quantum harmonic oscillator

text: **Problem** : In the context of quantum harmonic oscillator the eigenfunctions are given by: $ u_n(x) = (N_n/\sqrt{b}) H_n(x/b) \exp\left[-x^2/(2b^2)\right] $, where $N_n$ is the normalization factor: $ N_n = \left(\frac{1}{\sqrt{\pi} 2^n n!}\right)^{1/2} $ and $b = \left(\frac{\hbar^2}{m k}\right)^{1/4}$, where $m$ is the mass and $k$ is the spring constant. My book asks me to prove that the following equation holds, where $\varphi_n(k)$ are the eigenfunctions in the momentum space: $ \varphi_n(k) = \sqrt{b} N_n H_n(b k) \exp(-b^2 k^2 / 2), k=p/\hbar $ **Attempted solution** :               ClearAll["Global`*"];     norm[n_] := (1/(Sqrt[π] 2^n n!))^(1/2)          u[n_, x_] := 1/Sqrt[b] norm[n] HermiteH[n, x/b] Exp[-(x^2/(2 b^2))]          φ1[n_, k_] :=      Assuming[       {n ∈ Integers, n > 0, x ∈ Reals, k ∈ Reals, b > 0},       1/Sqrt[2 π] Integrate[u[n,x]Exp[-I k x], {x, -∞, +∞}]]          φ2[n_, k_] :=      Assuming[       {n ∈ Integers, n > 0, b > 0},       Sqrt[b] norm[n] HermiteH[n, b k] Exp[-((b^2 k^2)/2)]]          ParallelTable[         {j, Simplify[φ1[j, k] == φ2[j, k]]},         {j, 1, 8}] // TableForm      And here is the output: ![enter image description here](http://i.stack.imgur.com/37i18.png) **My question is** : Why does the relation hold only for $4k, k \in Z$ ? If I print $φ1[n,k]$ and $φ2[n,k]$ I see that in $φ1$ there are $(-i)^j$ terms, which is why the equation holds only for multiples of 4. Does anyone have any idea at all on where the error is ? (In my book? In how I do the Fourier transform? Something else I'm missing?)


title: Simple problem about shadow symbols in multi-contexts

text: When I'm tiding up my simple packages, `shadow` awlays comes out. Here is an example. Packages1                      BeginPackage["MyTest1`"]                 f1[x0_]:=Module[{x=x0},StringReplace["sdfasdfwhat hahahahah",x_->"DummyInMyTest1"]]                 g1[x0_]:=Module[{x=x0},StringReplace["sdfasdfwhat hahahahah",x_->"DummyInMyTest1"]]                 EndPackage[]      Packages2                      BeginPackage["MyTest2`"]                 f2[x0_]:=Module[{x=x0},StringReplace["sdfasdfwhat hahahahah",x_->"DummyInMyTest2"]]            g2[x0_]:=Module[{x=x0},StringReplace["sdfasdfwhat hahahahah",x_->"DummyInMyTest2"]]                 EndPackage[]      At first time, they are in one packages, now split them into two packages. Shadows about x is confusing, for I've used Module... actually I wish it to prevent the shadow problem but failed. Here we go               `$ContextPath`     Out[2]= {PacletManager`,QuantityUnits`,WebServices`,System`,Global`}     In[3]:= <<MyTest1`     In[4]:= <<MyTest2`     In[4]:= x0::shdw: Symbol x0 appears in multiple contexts {MyTest2`,MyTest1`}; definitions in context MyTest2` may shadow or be shadowed by other definitions. >>     In[4]:= x::shdw: Symbol x appears in multiple contexts {MyTest2`,MyTest1`}; definitions in context MyTest2` may shadow or be shadowed by other definitions. >>     In[4]:= x$::shdw: Symbol x$ appears in multiple contexts {MyTest2`,MyTest1`}; definitions in context MyTest2` may shadow or be shadowed by other definitions. >>     In[5]:= $ContextPath     Out[5]= {MyTest2`,MyTest1`,PacletManager`,QuantityUnits`,WebServices`,System`,Global`}      How to avoid these shadows but Quiet? Maybe duplicates with some shadows Q/A. :)


title: J/Link: Callback from J/Link into Java when Mathematica process terminates?

text: Is it possible to get a callback from J/Link into java when the (remote) link closes or the Mathematica process is terminated (killed) altogether?


title: Numerical Differentiation using 1500 data points

text: I have a set of 1500 data points (which are some energy eigenvalues) corresponding to a parameter H0 (which represents magnetic field. H0 values are equispaced going from $-3.0$ to $3.0$ in steps of $0.005$. Please note that the energy eigenvalues are not exact and they have experimental error in them. What I am trying to do is first plot those data points in _Mathematica_. I have found the command `ListLinePlot[{{x1, y1}, {x2, y2}, ...}]`. However, feeding such a huge set of data points consumes a lot of time. So is there any other way out? For example, importing the data file from Fortran. I have used the command `Import["file", "table"]` where "file" is a Fortran data file. But it is giving the error message "File not found during import". Then I would like to find the second derivative of the plot. Accurate evaluation of second derivative is very crucial for my purpose. I have done the plot using "gnuplot" and then found the first derivative of the plot using the central difference formula: $\frac{f(x+h)-f(x-h)}{2h}$. Here $h = 0.005$. Then I evaluated the first derivative of the latter plot using the same formula to get the second derivative plot. I am getting the plot but not the desired result (a peak is to be obtained near a value of H0, pre-calculated). In other words, I am getting a disagreement between theoretical and numerical values of H0. The eigenvalue evaluation is OK I think because I have checked it both in _Mathematica_ and Fortran. Maybe something is going wrong in the second derivative evaluation. Kindly advise how to carry out numerical differentiation from a set of data points in _Mathematica_.


title: Entering numbers in Scientific Notation?

text: I need to play with a lot of powers such as `10^-3`. `1E-3` does not work for it. Is there any short form for it?


title: Find a notebook I had open recently

text: I worked on a notebook a few weeks ago and now I can't find after looking through the most likely directories. The recent list only has 6 items in it, none of them the notebook in question. Is there a way to find ALL notebooks I have created or opened?


title: NMaximize the Likelihood

text: I am still pretty new to Mathematica, but have to solve a quite complex problem. The function               kdis[x_, a_] := KernelMixtureDistribution[Inner[List, x, (1+x)^a, List]]      gives me a bivariate kernel density estimate of two gamma random variables given by               gamran[k_, t_, nr_] := RandomVariate[GammaDistribution[k, t], nr]      Given some observations               xy = {{x_1,y_1},{x_2,y_2},...,{x_n,y_n}}      , I seek to maximize the likelihood function               Likelihood[kdis[gamran[2, 0.5, 250000], gamran[k, t, 250000]], xy]      using either NMaximize or FindDistributionParameters.               NMaximize[{Likelihood[kdis[gamran[2, 0.5, 250000], gamran[k, t, 250000]], xy], 0 < k <= 10 && 0 < t <= 10}, {{k, 0.01, 10}, {t, 0.01,10}},StepMonitor :> Print[k]]          FindDistributionParameters[xy,kdis[gamran[2.7, 0.5, 250000], gamran[k,t,250000]],{{k,1},{t,1}}, ParameterEstimator -> "MaximumLikelihood"]      Both functions seem to run endlessly. In particular, NMaximize never even finishes the first step (StepMonitor never prints something). As the problem is constrained to positive values of $k$ and $t$, I define constraints and a positive initial region for NMaximize. However, I get the following error message:               GammaDistribution::posprm: "Parameter k at position 1 in GammaDistribution[k,t] is expected to be positive."      which makes no sense to me given the constraints and the intial region. I know the problem is computationally very demanding. However, plotting the Likelihood with ContourPlot takes some time, but works and gives me relatively well defined maxima within my initial region. So I dont quite understand what is wrong with my script.


title: Fast Spherical Harmonics radiative transfer

text: This is a rather specific question and I apologize for spamming you with some lengthy code. But it could be interesting for some reader and maybe you can help out, so please bear with me. I am using the Spherical Harmonics Method to solve a radiative transfer problem in spherical symmetry, namely the penetration of diffuse UV radiation into interstellar clouds. It uses an expansion in Legendre polynomials to approximate the depth and angular dependence of the problem. I have a working solution and I am interested in a some additional input:   1. Is there a more elegant/simpler way to set up solutions for the intensity for varying values of $\omega$ (scattering albedo) and g (mean scattering angle $\langle \cos(\theta)\rangle$)   2. My solution is monochromatic and still relatively slow. For real applications one needs to perform the same calculations on a wavelength grid numerous times. How to speed up the solution? Wouldn't it be neat if _Mathematica_ could do the radiative transfer efficiently?   3. For higher approximation order, solving the Eigenvalue problem and getting the list of $A_m$ from the boundary conditions becomes extremely slow. Any ideas on how to improve? Here is what I got so far. First some definitions:               (* definition of the modified spherical Bessel function of the first kind *)     SphericalBesselI[0, 0] := SphericalBesselI[0, 0] = 1;     SphericalBesselI[l_, z_] := Sqrt[π/(2 z)] BesselI[l + 1/2, z];     (* expansion coefficients for the Henyey-Greenstein phase function *)     σ[l_][g_] := g^l     (* diagonal matrix elements *)     h[l_][g_, ω_] := h[l][g, ω] = (2 l + 1) (1 - ω σ[l][g]);     (* low-order determinants *)     F[0][g_, ω_][k_] := F[0][g, ω][k] = -h[0][g, ω];     F[1][g_, ω_][k_] := F[1][g, ω][k] = h[0][g, ω] h[1][g, ω] - k^2;     F[l_][g_, ω_][k_] := F[l][g, ω][k] = -h[l][g, ω] F[l - 1][g, ω][k] -       l^2 k^2 F[l - 2][g, ω][k];     (* helper function to access the i-th Eigenvalue k *)     kEV::mmatch = "Inconsistent list of Eigenvalues.";     kEV[list_List][m_Integer] := Module[{pos, neg},        pos = Select[Sort@list, Positive];        neg = Select[Sort@list, Negative];        If[(Length[pos] == Length[neg]) && m <= Length[pos],          If[Positive[m], pos[[m]], neg[[m]]],          Message[kEV::mmatch]; $Failed]];     (* calculate the Eigenvalues *)     calculateEigenvalues[L_][g_, ω_] :=         NSolve[F[L][g, ω][k] == 0, k][[All, 1, 2]];     R[0, m_][g_, ω_][k_] := R[0, m][g, ω][k] = 1;     R[1, m_][g_, ω_][k_] := R[1, m][g, ω][k] = (1 - ω)/k[m];     R[l_Integer, m_Integer][g_, ω_][k_] /; m < 0 := R[l, m][g, ω][k] = (-1)^l R[l, -m][g, ω][k]     R[l_Integer, m_][g_, ω_][k_] :=  R[l, m][g, ω][k] =           1/(l k[m]) (h[l - 1][g, ω] R[l - 1, m][g, ω][           k] - (l - 1) k[m] R[l - 2, m][g, ω][k]);     (* Mark's boundary condition *)     getAngles[M_Integer] :=       Sort@Select[      List @@ (NRoots[LegendreP[2 M, x] == 0, x] /. Equal[_, x_] :> x),       Negative]      B[i_Integer, m_Integer][g_?NumberQ, ω_?NumberQ][Lmax_,         taumax_?NumberQ, k_, angles_] :=         Sum[(2 l + 1) R[l, m][g, ω][k] LegendreP[l,         angles[[i]]] SphericalBesselI[l, k[m] taumax], {l, 0, Lmax}];      Now the procedure to set up function to calculate the mean intensity (averaged over the full solid angle) as function of the optical depth $\tau$ and the specific intensity as function of optical depth $\tau$ and angle $\mu=\cos(\theta)$.               createSphericalHarmonics[g_, ω_, I0_, tauMax_, L_?OddQ] :=       Module[       {M = (L + 1)/2, angles, eigenvalues, kEigenValues, AList},       (* angles for the boundary conditions from Mark's condition *)       angles = -SetPrecision[getAngles[M], Infinity];       (* calculate Eigenvalues from the recurrence relations F*)       eigenvalues =          SetPrecision[calculateEigenvalues[L][g, ω], Infinity];       (* calculate the A_k from the boundary conditions, i.e.           that the incoming intensity at the edge of the sphere and at          angle_i equals I_ 0*)       (* assuming isotropic illumination gives ConstantArray[I0, Mmax].           Alternatively we could define an I_ 0[mu] as declination dependent I_ 0*)       AList = LinearSolve[          N[SetPrecision[             Table[B[i, m][g, ω][L, tauMax, kEV[eigenvalues], angles],                    {i, 1, M}, {m, 1, M}]           , Infinity], 30],           N[SetPrecision[ConstantArray[I0, M], Infinity], 30]];           (* the N[#, 30] should prevent the LinearSolve::luc error but it doesn't *)      (* output are two InterpolationFunctions: {mean intensity as function of tau, intensity as function of angle and optical depth tau} *)      {       Function[tau,         Sum[AList[[m]] R[0, m][g, ω][        kEV[eigenvalues]] SphericalBesselI[        0, (tauMax - tau) kEV[eigenvalues][m]], {m, 1, M}]],       Function[{tau, mu},        Sum[(2 l + 1) LegendreP[l, mu] Sum[        AList[[m]] R[l, m][g, ω][          kEV[eigenvalues]] SphericalBesselI[          l, (tauMax - tau) kEV[eigenvalues][m]], {m, 1, M}], {l, 0, L}]]       }      ]      To demonstrate the solution, let's assume $g=0.5$, albedo $\omega=0.6$, approximation order of the Legendre polynomials $L=19$ and incoming intensity $I_0=1$, and optical depth to cloud center $\tau_c=10$.               {meanIntensity, intensity} = createSphericalHarmonics[0.5, 0.6, 1., 10, 19];          PolarPlot[{1, intensity[0, Cos[mu]], intensity[1, Cos[mu]]}, {mu, 0, π/2},           Epilog -> {Dashed, (Line[{{0, 0}, {Cos[ArcCos @ #],           Sin[ArcCos @ #]}}] & /@ (-getAngles[10]))}]      ![polar plot of intensity](http://i.stack.imgur.com/nvBOW.jpg) The wavy curve is the approximated intensity as function of angle $\mu$ at the surface of the cloud, the dashed lines show the angles that were used to specify the boundary conditions. The olive curve shows the angular dependence of the intensity at $\tau=1$. The angular averaged, mean intensity:               Plot[Log10@(meanIntensity[tau]/meanIntensity[0]), {tau, 0, 10},           PlotRange -> {{0, 10}, All}]      ![plot of angular mean intensity](http://i.stack.imgur.com/Xfs3F.jpg) I am pretty sure there are plenty of bugs still in the code, but they are not the point of this post, but rather the performance and coding style.


title: How to make a plot on top of other plot?

text: I want to plot two functions. One should appear on top of the other. The x axis has the same values for both functions, but should appear twice (the second- upper I want to be dashed). y axis should change to dashed type (when it reaches a little more than the highest value for the first function), start from zero again and have a different frame label. Here is just a simple example how can I present the graphs:               Needs["PlotLegends`"]     Plot[{Sin[x], Cos[x]}, {x, 0, 2 \[Pi]},       PlotStyle -> {Red, {Black, Dashed, Thick}},       BaseStyle -> {FontFamily -> "Times", FontSize -> 16},       Frame -> {True, True, False, True},       FrameLabel -> {"x", "y", "", "y1"},       FrameStyle -> {Directive[18], Directive[18], Directive[18], Directive[18, Dashed, Thick]},       PlotLegend -> {Style["Sin(x)", 14], Style["Cos(x)", 14]},       LegendPosition -> {1.05, 0.1}, LegendSize -> {0.4, 0.3},       LegendShadow -> 0.005, LegendTextSpace -> 4, ImageSize -> 550]      But I don't want the functions to be together. Let's say cos(x) in example should be above sin(x) and y1 should start above the end of y (at value y= 1.2). I also want to have another (dashed) x axis, which is at value y=1.2 (y1=0). ![enter image description here](http://i.stack.imgur.com/undUI.png) **EDIT:** Thank you for all answers. I tried all of them and come to my final code:               AA = Plot[barvilo, {\[Lambda], 337, 717}, PlotRange -> {0, 1.8},         PlotStyle -> {Black, Dashed, Thick},         BaseStyle -> {FontFamily -> "Times", FontSize -> 16},         Frame -> {True, True, False, False}, ImageSize -> 1200,         FrameLabel -> {"", "Absorbanca [p.e.]"},         FrameStyle -> {Directive[18, Dashed], Directive[18, Dashed]},         PlotLegend -> Style["\[Alpha](N719)", 14],         LegendPosition -> {1.1, -0.15}, LegendSize -> {0.3, 0.2},         LegendShadow -> 0.005, LegendTextSpace -> 2,         ImagePadding -> {{60, 30}, {50, 30}}];     BB = Plot[{a, b, c, d}, {\[Lambda], 337, 717}, PlotRange -> {0, 1.9},         PlotStyle -> {Red, Orange, Black, Purple},         BaseStyle -> {FontFamily -> "Times", FontSize -> 16},         Frame -> {True, True, False, False},         FrameLabel -> {"Valovna dolžina [nm]",           "Spektralna gostota sevanja [W/\!\(\*SuperscriptBox[\(m\), \     \(2\)]\)nm]"}, FrameStyle -> {Directive[18], Directive[18]},         Filling -> {1 -> {{4}, {Lighter[Yellow], Opacity[0.02]}},           4 -> {Axis, {Lighter[Yellow], Opacity[0.06]}}},         ImagePadding -> {{60, 30}, {50, 30}},         PlotLegend -> {Style["AM1,5G", 14], Style["AM1,5G + TrPt", 14],           Style["AM1,5G + TrEl", 14], Style["AM1,5G + TrPtEl", 14]},         LegendPosition -> {1, 0.1}, LegendSize -> {0.4, 0.3},         LegendShadow -> 0.005, LegendTextSpace -> 4, ImageSize -> 1200];     izracun =        Graphics[Text[         StyleForm["269,37 W/\!\(\*SuperscriptBox[\(m\), \(2\)]\)",           FontSize -> 16], {550, -900}, {-1, -1}]];     izracun1 =        Graphics[Text[         StyleForm["490,22 W/\!\(\*SuperscriptBox[\(m\), \(2\)]\)",           FontSize -> 16], {160, -970}, {-1, -1}]];     Show[GraphicsColumn[{AA, BB},        Spacings -> {0, -380}], izracun, izracun1]      I am satisfied with it but I need to save it. Why is it not possible to save it, when I select it (Save selection as)? I can save like this just separate graphs (AA and/or BB). When I tried the code in the link bellow, the result is in the right form to save with _Save graphic as_. But this code is to complicated for me. http://mathematica.stackexchange.com/a/6882/6357 I can use print screen option .. Is there a better way to save it?


title: Calling a dll from Mathematica

text: I would like to call the following function from Mathematica               ps3000aOpenUnit     PICO_STATUS ps3000aOpenUnit     (        short * handle,        char * serial     )      I define the DLLFunciton in Mathematica:               ps3000OpenUnit =  DefineDLLFunction["ps3000aOpenUnit", "PS3000a.dll", "short", {"short[]", "char[]"}]      I get following error when executing               ps3000OpenUnit[handle, serial]     NET::methodargs: Improper arguments supplied for method named ps3000aOpenUnit.      What is wrong with my code? Thanx for helping me in advance.


title: How can I define a 3D version of the built-in VoronoiDiagram (VoronoiMesh in V10) function?

text: Can anybody point me in a direction that will guide me to extend the VoronoiDiagram function in Mathematica to handle 3D (three dimensional) situations (i.e. points in 3D)? Any help will be greatly appreciated. **Update** The current `VoronoiMesh` function in **V10** still does not compute 3D Voronoi diagrams, which is strange since both the `DelaunayMesh` and `ConvexHullMesh` functions work with 3D data sets. I guess the waiting continues.... For the Wolfram Research employees, any ideas on why this was omitted and timeframe for when this functionality will be included in _Mathematica_?


title: Doing an Interpolation through a list of lists into a single function

text: Suppose I have a list of lists, i.e.               list = Table[{x, x^ k}, {k, 1, 10}, {x, 0, 1, 0.05}];      and I want to interpolate each of the lists by a function using `Interpolation` (or another appropriate function). Is there a way to create a function of `k` and `x`, i.e               Table[interpFunct[k] = Interpolation@list[[k]],{k,1,10}]      so I have `interpFunct[1,x]`, `interpFunct[2,x]`, etc. available? I know I can interpolate the surface but the mesh is not structured, which leads to new difficulties that have nothing to do with my needs. Any advice will be very helpfull.


title: How do I cut down on file size of exported eps without losing quality?

text: I need to import the following to eps so that I can put it into my TeX file. The problem is two-fold: the exported file looks terrible (unlike the Mathematica output), and secondly, the file size is huge (over 1 MB), making it take forever to render in the pdf file.               potential1 =        Plot3D[-3600. h^2 + 0.02974 h^4 - 5391.90 s^2 + 0.275 h^2 s^2 + 0.125 s^4, {h, -400, 400},          {s, -300, 300}, PlotRange -> {-1.4*10^8, 2*10^7}, ClippingStyle -> None,          MeshFunctions -> {#3 &}, Mesh -> 10,  MeshStyle -> {AbsoluteThickness[1], Blue},          Lighting -> "Neutral", MeshShading -> {{Opacity[.4], Blue}, {Opacity[.2], Blue}},          Boxed -> False, Axes -> False]     Export["pot1.eps", potential1, ImageSize -> 500]      The Mathematica output (in png) is ![enter image description here](http://i.stack.imgur.com/bKldN.png). I can't use png in LaTeX. I tried to export in pdf, but I'm running into an error: "Cannot determine size of graphic in pot1.pdf (no BoundingBox)."


title: Solving determinant of a Kronecker product of matrices gives a numerical error - why?

text: I am doing the following steps (code at the end of the post):   1. I start with a 2x2 matrix (smatrix), which is a function of a single variable (u2). I want to set the determinant of this matrix (smatrix) to zero, therefore solving for u2.    2. There are two real solutions (sols), which Solve (or NSolve) delivers. These are exact, as the determinant is the order 2 polynomial in the variable (u2). It might be important that the coefficients of this polynomial are on the order of 10^-10.   3. I make a 4x4 matrix (matrix2) which is just the earlier 2x2 matrix two times on the diagonal (KroeneckerProduct). Its determinant is then the determinant of the first matrix squared.   4. I solve the new determinant to be zero, now getting different solutions. They are complex. Moreover, when plugging in the old and the new solutions into the new determinant, I see that the new solutions apparently are more accurate (by 10^4!). I have tried playing around with global `WorkingPrecision`, but it does not seem to change anything. Can somebody explain to me what goes wrong here? Moreover, what should I change in my code to retain the exact results? Thanks a lot!               smatrix = {{1. - 2.96392/u2,  0.0000196744/ u2},                {1. - 2.96392/u2, -2.11737*10^-10 + 0.0000196746/u2}};     sols = (smatrix // Det) // Solve[# == 0, u2] &      > {{u2 -> 0.987752}, {u2 -> 2.96981}}               (smatrix // Det) /. sols[[1]]      > 0.               matrix2 = KroneckerProduct[({          {1, 0},          {0, 1}         }), smatrix];     (matrix2 // Det) // Solve[# == 0, u2] &      > {{u2 -> 0.987752 - 4.12625*10^-6 I} , {u2 -> 0.987752 + 4.12625*10^-6 I} , > {u2 -> 2.96981 - 0.000012998 I} , {u2 -> 2.96981 + 0.000012998 I} }               (matrix2 // Det) /. %[[1]]      > 3.85186*10^-34 - 1.84553*10^-36 I               (matrix2 // Det) /. sols[[1]]      > 3.15024*10^-30


title: StringMatchQ error messages printed to console while main notebook is sitting idle

text: > **Possible Duplicate:**   >  Strange ::usage behavior in v9 I'm currently finishing up a _Mathematica_ vector calculus package (MMA9.0 on Mac Os X), but have had a persistent problem that I haven't been able to get rid of. Basically, the message > StringMatchQ::strse: "String or list of strings expected at position 1 in > StringMatchQ[$Failed,"ToCanonical*"]" persistently appears in the console (Messages notebook). `ToCanonical*` can be replaced with another function name, depending on what is called. As is standard, 3 messages are printed before a `General::stop` message is printed. This behavior only happens on some function executions (i.e. evaluating the same line will sometimes produce it and sometimes not) and often does not start until a dozen or so function calls have been made after loading the package. In addition, after the messages start appearing, they sometimes continue even when nothing in the notebook is being evaluated. The messages seem to have no adverse consequences other than causing Mathematica to pause for 5-10 seconds before doing anything useful, a behavior that persists even if the relevant message is turned off with `Off`. With the goal of figuring out what's going on, here are a couple of more specific questions I have that may provide some insight.   1. What is the difference between messages printed to the console and those printed to the user's notebook? From the Preferences/Messages window it seems that the messages are probably "User log interface messages," but I couldn't find any information on why these would be generated.   2. Is there a way to generate a list of all MMA functions that can generate `$Failed`? I do not use `$Failed` anywhere in the package so it must be being generated by an internal function.  I'm sorry for the rather general question, but am currently completely stuck. Any suggestions would be very much appreciated!


title: Consistently annoying error messages in Mathematica 9

text: > **Possible Duplicate:**   >  Strange ::usage behavior in v9 Has anyone had any issues with a function, let's call it Function, which worked in Mathematica 8 getting the error message StringMatchQ::strse: "String or list of strings expected at position 1 in StringMatchQ[!($Failed, \"Function*\")]" This message occurs not after the function is evaluated, but instead a dialogue box appears if one uses the backspace key while typing the arguments of the function.


title: Use Mathematica as a terminal

text: I love how notebooks work in Mathematica. You can edit code in real time and hit Ctrl+Shift to run it. Additionally you copy and paste different cells around to organize and test ideas. Search and replace, plot/visualization,etc.. are built into the system. My question: **How could you adequately adapt Mathematica to use as a terminal replacement?** If not (this might get transferred to stackoverflow.com) is there a terminal editor that exists that works like Mathematica's notebook interface?


title: Passing f[x][[1]] to FindRoot

text: `FindRoot` seems to fail for most examples of the form               f[x_?NumericQ] := {x - 3 , x^3};     FindRoot[f[x][[1]], {x, 3}]      > >     {x -> 0.} >   I expected `{x -> 3}`. The same occurs for `FindMinimum`, even for this case               FindMinimum[{f[x][[1]], x > 1}, {x, 3}]      > >     {1., {x -> 1.}} >   What is going here guys? I'm using _Mathematica_ 9.0.1.0 for Linux x86.


title: On the definition of the associated Legendre polynomials

text: _Mathematica_ computes for n = 1,2,...:               (-1)^n (LegendreP[n, -1, -3]/Sqrt[2])      > >     -I, -3 I, -11 I, -45 I, -197 I, ... >   _Maple_ computes for n = 1,2,...:               (-1)^n*LegendreP(n, -1, -3)/sqrt(2)      > >     1, 3, 11, 45, 197, ...   >   Question: Is there a bug or just different definitions? **Edit:** Which one conforms with the (standard) definition in the _Handbook of Mathematical Functions_ respectively with the definition in DLMF?


title: Solving cubic equation for real roots

text: I'm looking to solve the following cubic equation for x: $\beta\, x^3 - \gamma \,x = c$. I have plugged in some sample values ($\beta = 2$, $\gamma = 5$ and $c = 2$). When I try to solve this equation using mathematica's Solve[] function, I get one real root and 2 complex roots. However, I have tried plotting the equation for these values, and can clearly see there should be 3 real roots. How can I obtain them. I am sure the roots are real, but mathematica gives me back complex roots. Thanks.


title: How to Sort on row by row basis?

text: Say I have matrix ![original](http://i.stack.imgur.com/A0mVQ.png) how to sort on row by row basis to get: ![sorted](http://i.stack.imgur.com/HNE7P.png)


title: Summing along rows or columns of a matrix

text: I have a list of rows in database such as               {{a,b,c}, {d,e,f},{g,h,i}}      I want to be able to add each row across and each column down (like a spreadsheet). In other words be able to pick columns and rows and add down or across.   Could you point me in the right direction?


title: Exporting Graphics3D is not complete

text: When I export the result defined as the variable `pot1` to pdf, the lower contour plot isn't showing. How do I fix this?               potential1 =        Plot3D[-3600. h^2 + 0.02974 h^4 - 5391.90 s^2 + 0.275 h^2 s^2 + 0.125 s^4,         {h, -400, 400}, {s, -300, 300},  PlotRange -> {-1.4*10^8, 2*10^7},          ClippingStyle -> None, MeshFunctions -> {#3 &}, Mesh -> 10,          MeshStyle -> {AbsoluteThickness[1], RGBColor[0, 0, 1]},          Lighting -> "Neutral", MeshShading -> {{RGBColor[0, 0, 1]}, {RGBColor[1, 1, 1]}},          Boxed -> False, Axes -> False];     potContPlot1 =        ContourPlot[-3600. h^2 + 0.02974 h^4 - 5391.90 s^2 + 0.275 h^2 s^2 + 0.125 s^4,         {h, -400, 400}, {s, -300, 300}, PlotRange -> {-1.4*10^8, 2*10^7},          ClippingStyle -> None, MeshFunctions -> {#3 &}, Contours -> 10,          ContourStyle -> {{AbsoluteThickness[1], RGBColor[0, 0, 1]}},          ContourShading -> {{RGBColor[.5, .5, 1]}, {RGBColor[.7, .7, 1]}},          Axes -> False, Frame -> False];     potFace1 =          Graphics3D[{EdgeForm[], Texture[potContPlot1],             Polygon[{{-400, -200, -2.0*10^8}, {400, -200, -2.0*10^8}, {400, 200, -2.0*10^8},                {-400, 200, -2.0*10^8}},               VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0, 1}}]}];     pot1 = Graphics3D[{potential1[[1]], potFace1[[1]]},         Lighting -> "Neutral", BoxRatios -> {1, 1, .7}, Boxed -> False]     Export["pot.pdf", pot1]


title: Generating Suffixes

text: I am doing a large Matrix calculation in which I need to generate symbols first like $F^{\mu\nu}$ I would like to get $\mu\nu = 00, 11, 22, 33$ and so on. I need to have the symbols before I can assign anything. Is there way to achieve this?


title: How to create a neon light effect in Mathematica?

text: I tried to use `Glow` to create a neon light effect on a torus object. The result shown on the left of the picture below looks quite different from the real one on the right. Is there a way to obtain a better result?               (* Assuming the .obj file located in the root of c: *)     model =  Import["c:\\torus.obj"] ;      Graphics3D[{Glow[Cyan], First[model ] }, Boxed -> False ,      Background -> Black       ]      ![enter image description here](http://i.stack.imgur.com/vlTwC.jpg)


title: "ClosingActions" option for FrontEnd`AttachCell

text: I'm looking to find the possible values for the `ClosingActions` options `FrontEndAttachCell`. I have found `SelectionDeparture` and `ParentChanged` so far. Moreover, is there a general method to determine the options for "undocumented" functions such as this one?


title: Find the number of nonzero elements

text: How do you find the number of elements in a matrix that are non-zero. For instance, the following matrix has 5 nonzero elements.               {0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1}


title: Full width of graphics in GraphicsColumn

text: I have a list of graphics which are all the same width, and I would like to combine them into a single Graphics object that has them all stacked on top of each other, column-style, without changing their widths. The help page for GraphicsColumn lists `Alignment->Full` as the option that would do that, but I'm having some trouble implementing it. To take one of the examples in the help page, entering               GraphicsColumn[Table[Graphics[Disk[], ImageSize -> 10 i], {i, 1, 5}],        Alignment -> Center, Frame -> All]      will produce the following column. ![enter image description here](http://i.stack.imgur.com/PkQzE.png) I would expect changing `Alignment->Center` to `Alignment->Full` to provide a column with five circles of equal width. Instead, it returns the error message > GraphicsGrid::optv: "Value of option Alignment->Full in GraphicsGrid[{{ > [...] },{ [...] },{ [...] },{ [...] },{ [...] }},Alignment->Full,Frame->All] > is not valid. " This seems to me to be a bug, which came up here/here, and which I will report shortly. I am running Mathematica 9.0.1.0 on Linux x86 (64-bit), Ubuntu 12.04.3 LTS; I also observe the error on Mathematica 9.0.0.0 over Widows 7. ### In the meantime, is there a practicable workaround? * * * To provide a bit more detail: the circles above are a MWE; my actual problem is more complicated. I have a table of similar plots, some of which have "stuff" on top added in using `FrameTicks`. A MWE that's closer to my actual situation is               GraphicsColumn[{       ContourPlot[x^2 - y^2, {x, -2, 2}, {y, -2, 2}, ImageSize -> 200,         PlotLabel -> Graphics[Circle[], ImageSize -> 100]],       ContourPlot[x^2 - y^2, {x, -2, 2}, {y, -2, 2}, ImageSize -> 200]       }]      ![enter image description here](http://i.stack.imgur.com/XJ4lB.png) * * * The objects in the question are a MWE, my actual problem is more complicated. I have a table of objects which are _already_ the same widths (and therefore the same `ImageSize`s), but they have different aspect ratios. Setting their `ImageSize`s constant would not do anything. Perhaps a more representative example of my situation is:               GraphicsColumn[Table[Graphics[Rectangle[{0, 0}, {1, i}]], {i, 1, 5}],        Alignment -> Center, Frame -> All]


title: Assign variable's value programmatically

text: Not easy to explain what I'm looking for, so please sorry if I'm not so short. Having many variables to be managed in several different combinations, I need to automate the assignment of preset values for those variables. So, I have some saved preset data to be assigned to variables but because this is very frequent in my source code, I want to make it automatically, without to name variables in each piece of code. So I would use a variable to keep the whole list of variables. Export is very easy, the problem is for Import. Here is an example:               vars = {"a", "b", "c", "d", "e", "f", "g", "h"};     Export["data.csv", Transpose[{vars, ToExpression[vars]}]]      I have to use the strings to list the variables otherwise the names will be replaced by variables' values before to export. And I have to save also the name of variables because files have to be exported to other software and be human readable. So the problem is when I have to import back the saved data. Normally I should write               {a, b, c, d, e, f, g, h} = Import["data.csv"][[All, 2]]      but (here is the problem) I would write               ToEpxression[vars] = Import["data.csv"][[All, 2]]      so to have assignments in just one line and without naming all variables in each piece of code. Of course, `ToExpression[vars]` doesn't work because it automatically replaces variables names with their values. So, my question: Is there a combination of `Hold`, `Unevaluated`, `Defer`, or similar constructs so to automatically create the list $\\{a, b, c, d, e\\}$ (unevaluated) as left-hand site of the Set statement. Sorry for not being more clear and thanks in advance.


title: Functions defined via inverse Laplace transform - plotting issue

text: I need to define a function $k(t,c_1,\alpha_1,c_2,\alpha_2)$ in the following manner:               Clear[c1, c2, a1, a2, p1, p2, q, Q] (*clearing symbol assertions - just in case*)     p1[t_, c1_, a1_] := c1 (1 - E^(-a1*t))      p2[t_, c2_, a2_] := c2 (1 - E^(-a2*t))      q[t_, c1_, a1_, c2_, a2_] := p1[t, c1, a1] + p2[t, c2, a2]     Q[s_, c1_, a1_, c2_, a2_] :=        FullSimplify[ LaplaceTransform[ q[t, c1, a1, c2, a2], t, s]]     k[t_, c1_, a1_, c2_, a2_] :=        FullSimplify[          InverseLaplaceTransform[ 2s^2 Q[s, c1, a1, c2, a2]/(1 - 2s Q[s, c1, a1, c2, a2]),                                   s, t]]      Now, if I execute the following code:               cmax := 1     amax := 1     tmax := 10     Manipulate[ k[t, c1, a1, c2, a2],                  {t, 0, tmax}, {c1, 0, cmax}, {a1, 0, amax},                  {c2, 0, cmax}, {a2, 0, amax}]      _Mathematica_ produces proper output, in a way that a concrete numerical value is returned. However, if I execute                Manipulate[ Plot[k[t, c1, a1, c2, a2], {t, 0, tmax}],                   {c1, 0, cmax}, {a1, 0, amax}, {c2, 0, cmax}, {a2, 0, amax}]      then I get no result - only plot axes are printed, regardless of the parameters or plot range. Interestingly, if in the last expression explicit form of $k$ is inserted, everything works perfectly. What do I do wrong?


title: How to construct a graph from a list of edges

text: I have a list of pairs of numbers, representing connections between objects in the real world. Each number is the identifier of an object, there are gaps in the range from the smallest number to the largest number.               43,292     22,11     932,11     292,22     etc...      I need to visualise how all of the objects are related. I intended to create a graph representation of that network.


title: Why is NDSolve solving in term of two 1st order ODE slower than 2nd order?

text: As mentioned in the documentation for NDSolve it's often convenient to reduce a 2nd order ODE to a system of first order equations. When I do this however I seem to see a significant speed reduction in finding the solution. Is there any reason this would be the case? **An Example:** Some definitions:               rstar[r_] := r + 2 M Log[r/(2 M) - 1];     M=1;     rinf=10000;     rH = 200001/100000;     r0 = 10;     wp=30;     ac=wp-8;     \[Lambda][l_] = l (l + 1);      Take the equation                eq[\[Omega]_,l_] := \[CapitalPhi]''[r] + (2 (r - M))/(      r (r - 2 M)) \[CapitalPhi]'[       r] + ((\[Omega]^2 r^2)/(r - 2 M)^2 - \[Lambda][l]/(        r (r - 2 M))) \[CapitalPhi][r] == 0;      Solve it with certain ICs:               init=-0.0000894423075560122420468703835499 +      0.0000447222944185058822813688948339 I;     dinit=-4.464175354293244250869336196691640386266791`30.*^-6 -       8.950483248390306670770345406047835993931665`30.*^-6 I;           sol := \[CapitalPhi] /.       Block[{$MaxExtraPrecision = 100},       NDSolve[{eq[1/10, 1], \[CapitalPhi][rinf] ==          init, \[CapitalPhi]'[rinf] == dinit}, \[CapitalPhi], {r, r0,         rinf}, WorkingPrecision -> wp, AccuracyGoal -> ac,        MaxSteps -> \[Infinity]]][[1]];      **Now as set of first order equations** It turns out this system can be written as a first order set in terms of a related dependent variable $r^*$, and an effective potential $V$. Some more definitions:               init2=-0.8944230755601224204687038354990773373534 +      0.4472229441850588228136889483392836606307 I;     dinit2=-0.04472224961131835705979008430399621833410 -      0.08944221816744666391325700074861130268693 I;          r[rs_] := 2 (M + M ProductLog[E^(-1 + rs/(2 M))]);     V[rs_, \[Omega]_,l_] := \[Omega]^2 - (1 - (2 M)/r[rs]) (\[Lambda] [l]/(r[rs])^2 + (2 M)/(r[rs])^3);     rsH = N[rstar[rH], wp];     rsinf = N[rstar[rinf], wp];     rs0 = N[rstar[r0], wp];      Solve the first order system                 sol2 :=  {R, Rp} /.        NDSolve[{Rp[rs] == R'[rs], Rp'[rs] == -V[rs, 1/10, 1] R[rs],        R[rsinf] == init2, Rp[rsinf] == dinit2}, {R, Rp}, {rs, rsinf,        rs0}, WorkingPrecision -> wp, AccuracyGoal -> ac,        MaxSteps -> \[Infinity]][[1]];      Now run:                sol // AbsoluteTiming      sol2 // AbsoluteTiming      I find that sol2 takes roughly three times as long, and for even large $\omega,\ell$ this time difference gets more pronounced


title: How can I connect shortcut keys to Button

text: I want to connect a shortcut key (ctrl + c) to a `Button` in my application. To that purpose I wrote some code using `EventHandler`. When the mouse button is clicked it's working fine, but the ctrl + c key press isn't working.                EventHandler[ Button["Click"],        {          {"KeyDown", "c"} :>MessageDialog["This is button"],           "MouseClicked" :>MessageDialog["This is button"]        }      ](*EventHandler Function is closed*)


title: Mathematica: summing over n abstract indices

text: This probably has a one line answer, but I'm totally stuck. I have two tensors, i.e. two objects that depend on NN abstract indices which i've labelled `i[m] (m=1,...,NN)`. I want to keep NN general for now. Each index `i[m]` ranges over the values `{1,2}`. I want to sum over all the `i[m]`s, i.e.               Sum[a[i[1],...,i[NN]] * b[i[1],...,i[NN]], {i[1],1,2},{i[2],1,2},...,{i[NN],1,2}]      The only problem I have is finding a general expression that generates the "array" {i[1],1,2},{i[2],1,2},...,{i[NN],1,2} in the summation. I tried Table but that gives me an array of the form               {{i[1],1,2},{i[2],1,2},...,{i[NN],1,2}}      and I can't get rid of the outer brackets.


How can I make notebook cell's background become transparent? And can be saved as html with the translucent or transparent effect? One of the use is in HTML files, the background of cell hides the background of the web page's background. I wish there would be some setting in Mathematica and could be changed to HTML with transparent background, if no such direct manipulation, then should post process the HTML source file. Also, it it possible to make an Image as the background of the Notebook? something like the part effect of some slideshow stylesheet?


title: Which group of points connects more strongly?

text: I have two groups of points, and the lenth of them may be different.I want to know which group of points connects more strongly, are there any existing algorithms for this? Here are two groups of points, group1 has 13 points, group2 has 10 :               group1={{8, -2}, {10, -2}, {6, -2}, {9, -1}, {5, -2}, {5, -3}, {9, -2}, {7, \     -1}, {7, -3}, {7, -3}, {2, -1}, {9, -4}, {2, -2}};     group2={{9, -3}, {3, -4}, {10, -3}, {10, -4}, {12, -2}, {8, -4}, {7, -1}, \     {9, -1}, {8, -2}, {13, -3}};      ![enter image description here](http://i.stack.imgur.com/hhxX3.png) First I prefered to caculate the average point of each group, than get summation of all the distances between each point and the average one. But look at the picture, the most left one labeled "far away" of the yellow group is a particular case, it should contribute less to the result. Now I'm stuck here. This may be a mathematical problem, but I'm going to solve it in mma, so I post it here.Thanks guys. **Edit:** All the points are on integer coordinates.


title: RSquared Mathematica Excel incoherence

text: I've done a NonLinearRegression with this data               {{0.245, 0.0917011}, {0.25, 0.0894304}, {0.25, 0.108895},       {0.25, 0.111991}, {0.251, 0.0898849}, {0.251, 0.107753},      {0.254, 0.114524}, {0.254, 0.121882}, {0.255, 0.130478},      {0.255, 0.186865}, {0.256, 0.108817}, {0.256, 0.128742},      {0.256, 0.131999}, {0.257, 0.150797}}      The model is a simply parabola:               y=a x^2+b x +c      The coefficiets are:                a= 317.459      b=-154.723      c= 18.9415      Then I've done the same with Excel and the coefficients are the same, but `R^2` is not the same. In Mathematica I've got `R^2=0.97` and Excel tells me `R^2=0.45`. Why there is this incoherence?


title: RevolutionPlot3D: but NOT revolving about the z axis

text: I want to demonstrate generating a solid of revolution by revolving a planar region about, say, a horizontal axis. However, `RevolutionPlot3D` doesn't seem to have an option for revolving a curve about something other than the $z$ axis. I'm curious how you all would handle this. Here's a simple example:               theta0 = Pi;     Manipulate[       GraphicsRow[{         Plot[x^2, {x, 0, 1}, PlotStyle -> {Thick, Black}, Filling -> Axis],         Rotate[RevolutionPlot3D[Sqrt[x], {x, 0, 1}, {t, theta0 - .001, T},         PlotRange -> {{-1, 1}, {-1, 1}, {0, 1}}, BoxRatios -> 1,          Boxed -> False, Axes -> False, ViewPoint -> {0, -2, 1}], -Pi/2]       }],     {T, theta0, theta0 + 2 Pi}]      ![enter image description here](http://i.stack.imgur.com/nlGje.png) My questions:   1. Is there a "better" way to showcase revolving about a horizontal axis of revolution than what I've done with `Rotate`?   2. Is it possible to generate the higher quality, finished surface of revolution while the slider bar is moving instead of only when the slider is released?   3. How do I prevent the vertical tick labels on the far left edge as well as the graphic on the far right edge from being clipped? (I tried `Spacings` and `ImagePadding`.)   4. How do I vertically align the horizontal axis of revolution of the right graphic with the horizontal axis of the left graphic? **Edit:** I had a follow up question but I will spin that off as a separate question.


title: How to revolve a surface about a line other than the $x,y,z$ axes?

text: I just started working with _Mathematica_ 8 and I'm having trouble revolving a function the way I want. I have to revolve the function $x^2/4 +2$ and $y= 0$ around $y=6$ to form an ashtray, but I can't find how to do it. EDIT: So far I've got :               RevolutionPlot3D[{{f[x] - 6}, {-6}}, {x, 0, 6}, RevolutionAxis -> x]      And for clarification, this is the complete surface I'm revolving (Or trying to) https://www.dropbox.com/s/irpaw37nayox414/Capture.PNG Now I just need to revolve the explicit functions "x=0" from 0 to 2 and "x=5" 0 t0 6


title: Revolve A Function Around the Y axis?

text: I am seeking to revolve the are between the functions function $d(x) = Exp(x)$ and $e(x) = 4 - x^2$ around the line $x = 2$. I am using `RevolutionPlot3D`, so I thought it best to use the Y axis instead. Here is the modified code:               d[x_] := E^(x + 2)     e[x_] := 4 - (x + 2)^2          RevolutionPlot3D[{{d[x]}, {e[x]}}, {x, -1.96464 - 2, 1.05801 - 2},                      RevolutionAxis -> "Y"]      However, I find that the code does not produce the revolution that I am seeking. Is there a syntax error or an error in my methodology? Any push in the right direction would be quite helpful.


title: How to graph the revolution of solid limited by 2 points in x axis

text: I'm learning how use this program. And I have problem with how graph the solid of revolution.Here i write one exercise.   y=2-1/2x, y=0,x=1,x=2; about the x-axis. This is the graph also the volume ![enter image description here](http://i.stack.imgur.com/13ImD.jpg) x=1 and x=2 limited the size of the graph and I don't know how do that in Wolfram Mathematica. The steps i think are: RevolutionPlot3d [2-1/2x,{x,0,4},{y,0,4}] ....


title: Solving a System of four equations (with logs)

text: I am trying to solve a system of four equations in four variables. I have read a number of threads on similar issues and tried to follow the suggestions. But I think it is a bit messy because of the logs and cross products here. This is the exact system:               7*w = (7*w+5*x+2*y+z) * ( 0.76 + 0.12*Log[w] - 0.08*Log[x] - 0.03*Log[y] -                 0.07*Log[7*w+5*x + 2*y + z]),        5*x = (7*w+5*x+2*y+z) * ( 0.84 - 0.08*Log[w] + 0.11*Log[x] - 0.02*Log[y] -                 0.08*Log[7*w+5*x + 2*y + z]),             2*y = (7*w+5*x+2*y+z) * (-0.45 - 0.03*Log[w] - 0.02*Log[x] + 0.05*Log[y] +                 0.12*Log[7*w+5*x + 2*y + z]),                     1*z = (7*w+5*x+2*y+z)*(-0.16 + 0*Log[w]- 0*Log[x] - 0*Log[y] + 0.03*Log[7*w+5*x + 2*y + z])      This is an extension of a consumer demand system and we, theoretically, know that there exists a unique solution to this system that is positive. **Trys**   * Solve & NSolve : As there should be a solution I tried these, but neither works. I guess that the system has too many logs to handle.   * FindRoot : I started with an initial value of (14,15,10,100) which I get from my data. FindRoot returns the last value (which does not satisfy my system) and the following message. > FindRoot::lstol: The line search decreased the step size to within tolerance > specified by AccuracyGoal and PrecisionGoal but was unable..... ` I tried different initial values, including the value returned by FindRoot. I tried to analyze the pattern of the solution value at each step. I didn’t see any pattern, but noticed that the z values become negative early in the process. So, I put bounds on the values. This just stops the code at the minimum value of 0.1. I also tried an exponential system instead of log - same issues.               Reap[FindRoot[{            7*w == (7*w+5*x + 2*y + z)*(0.76 + 0.12*Log[w] - 0.08*Log[x] - 0.03*Log[y] -                  0.07*Log[7*w+5*x + 2*y + z]),            5*x == (7*w+5*x + 2*y + z)*(0.84 - 0.08*Log[w] + 0.11*Log[x] - 0.02*Log[y] -                  0.08*Log[7*w+5*x + 2*y + z]),            2*y == (7*w + 5*x + 2*y + z)*(-0.45 - 0.03*Log[w] - 0.02*Log[x] + 0.05*Log[y] +                 0.12*Log[7*w + 5*x + 2*y + z]),            z == (7*w + 5*x + 2*y + z)*(-0.16 + 0*Log[w] -0*Log[x] -0*Log[y] +                  0.03*Log[7*w + 5*x + 2*y + z])},           {{w, 14, 0.1, 500},{x, 15, 0.1, 500},{y, 10, 0.1, 500}, {z, 100, 0.1, 500}},            EvaluationMonitor :> Sow[{w, x, y, z}] ]]        * FindMinimum : As we can write this problem as a minimization problem, I tried this (following the suggestion here). The value returned did not converge the system or equations to zero. I tried with only the first two equations, and that sort of converged to zero.              {g1,g2,g3, g4} = {                7*w - (7*w+5*x+2*y+z)* (0.76+0.12*Log[w]-0.08*Log[x]-0.03*Log[y] -                       0.07*Log[7*w + 5*x + 2*y + z]),                5*x - (7*w +5*x+2*y+z)*(0.84-0.08*Log[w]+0.11*Log[x]-0.02*Log[y] -                       0.08*Log[7*w + 5*x + 2*y + z]),                2*y - (7*w+5*x+2*y+z)*(-0.45-0.03*Log[w]- 0.02*Log[x] + 0.05*Log[y] +                       0.12*Log[7*w+5*x+2*y+z]),                1*z - (7*w+5*x+2*y+z)*(-0.16+0*Log[w]-0*Log[x] - 0*Log[y] +                       0.03*Log[7*w+5*x+2*y+z])};          subdomain = 0 < w < 100 && 0 < x < 100 && 0 < y < 100 && 0 < z < 100;     res = FindMinimum[{Total[{g1,g2,g3,g4}^2],subdomain},{w,x,y,z}, AccuracyGoal->5]             {g1,g2,g3,g4}/.res[[2]]      Hope this is engaging enough for the experts here! Any ideas how I should find the solution or why can’t I? It’s the first time I am using Mathematica, and unfortunately the first time I am empirically solving a system/optimizing! Thanks a lot.


title: Mathematica-To-MATLAB Dictionary!

text: Is there a dictionary to translate _Mathematica_ functions and commands to _MATLAB_?


title: "do ... while" loop equivalent in Mathematica

text: Have I missed something or is there no built-in which mimics the behaviour of _do ... while_ loop? I am looking for a construct that evaluates `procedure` **once** and then repeatedly evaluates it while `test` is not fulfilled. I'm ended up using:               While[procedure; test, {}]      But clearly the second argument is redundant, so I have a feeling that I'm missing something. Maybe not, but I just want to be sure :)


title: Compile function which calls other functions to C

text: I have a function which calls other functions and I would like to compile it to C code. For example:               foo[p_] := 0.7 Exp[-p^2]     f[a_, n_] :=       Module[{s, p, i}, s = 0; p = a;        For[i = 0, i < n, i++, s += foo[p]; p *= a;]; s]      Now if I do               cf = Compile[{{a, _Real}, {n, _Integer}}, f[a, n]]      and print the C code with               Needs["CompiledFunctionTools`"]     CompilePrint[cf]      the output is               R1 = MainEvaluate[ Hold[f][ R0, I0]]      which is obviously not desired. When I try `Compile[{{a, _Real}, {n, _Integer}}, Evaluate@f[a, n]]`, it just gives a function which returns 0...


title: ReadList with header and foot lines

text: I want to do some large data analysis, and i want to be able to import files in a fast way. I tried Import, but it is quite slow; ReadList takes half the time. This is the code I was using:               files = FileNames["Path\\*.dat"];     a = Table[Delete[Import[file, "Table", "HeaderLines" -> 38], {{-1}, {-2}}], {file,files}];      They are files with 38 header lines and 2 foot lines which i dont want. My question is how to import the same files using ReadList and ignoring those unwanted lines, or another approach to improve import performance.


title: How can one write a robust ListableQ function?

text: I would like to have a test that determines if a particular function is Listable. In the case of Symbols this is merely a matter of checking `Attributes`. `Function` definitions with the `Listable` attribute are a bit more involved but quite easy. **However I specifically want to test for _inherent listability_ in as many cases as possible.** For example consider the function from **Case #4** in Alternatives to procedural loops and iterating over lists in Mathematica:               (3 - #)/(7 * #) &      This function is _inherently listable_ :               fn = (3 - #)/(7*#) &;     Map[fn, {1, 2, 3}]     fn @ {1, 2, 3}      > >     {2/7, 1/14, 0} >     {2/7, 1/14, 0} >     * One must consider Functions with multiple arguments, both the `Slot` and named parameter type.   * Ideally the test would handle pattern-based (DownValues) functions to the extent that is possible.


title: Show that three given vectors lie on a line, a plane, or span 3-space

text: Given three vectors, `{2, 0, 0}`, `{0, 2, 2}`, `{2, 2, 3}`, how could I see if they are all on the the same line, plane, or all of r3 in _Mathematica_? I can graph them all, like:               data = {{1, 2, 3}, {3, 4, 5}, {5, 6, 7}};     Graphics3D[Arrow[{{0, 0, 0}, #}] & /@ data]      but how can I say take two of them, draw a plane from them, and visually see the 3rd vector in relation to the plane?


title: Is it possible to insert an animated image into Mathematica notebook?

text: I find it very convenient to use Mathematica notebooks to **organise** the codes + results. I was wondering if it is possible to **insert** an **animated image** (say an animated gif) in the middle of a notebook. (I tried dragging and dropping an animated gif into a notebook, the gif itself was created using Mathematica. Mathematica **Import[]** s it and I see a bunch of images in the notebook). This suggests, one solution namely using a **Manipulate[]** or **Animate[]** , with those bunch of images. But is there an **less tedious and more elegant way**? Thanks!


title: Make the code shorter for solving Fizz buzz

text: Here is Fizz buzz > Write a program that prints the integers from 1 to 100. But for multiples of > 3 print "Fizz" instead of the number and for the multiples of 5 print > "Buzz". For numbers which are multiples of both 3 and 5 print "FizzBuzz". I found the python version is much shorter, so I decided to write a short one, I have wrote several version               Table[If[# != {}, Row@#, n] &@({Fizz}[[Sign[n~Mod~3] + 1 ;;]]~Join~{Buzz}[[Sign[n~Mod~5] + 1 ;;]]), {n, 100}]          StringJoin@{If[#~Mod~3 == 0, "Fizz", ""], If[#~Mod~5 == 0, "Buzz", ""]} /. "" -> # & /@ Range@100          d = Divisible; Range@100 /. {_?(#~d~15 &) -> FizzBuzz, _?(#~d~3 &) -> Fizz, _?(#~d~5 &) -> Buzz}      Can you show a more shorter one?


title: How to identify patterns in a tensor-polynomial and replace appropriate symbol?

text: I want to write a function `tensorReplace[input]` that takes a tensor polynomial in $r_i$ such as $r_i r_j r_k+r_i q_j q_k +q_i q_j q_k$ , and replaces each monomial with a function `f[{idx}]` using the rule $r_i\rightarrow f(\\{i\\})$, $r_i r_j\rightarrow f(\\{i,j\\})$, _etc._ leaving the $q$'s and another other symbols untouched. So for in the example above, if my input is $$r_i r_j r_k+r_i q_j q_k +q_i q_j q_k\,,$$ I am shooting for an output $$f(\\{i,j,k\\})+f(\\{i\\})q_i q_j+q_i q_j q_k\,.$$ I also need to allow the possibility where a vector with same index is squared (repeated in a monomial) given the obvious $r_i^2\rightarrow f(\\{i,i\\})$. I don't know how to even begin, because my input could be an arbitrarily high order polynomial in $r$, with many terms.


title: Addition of sparse array objects

text: I have been having some trouble with the addition of large (but very sparse) matrices using SparseArray. Here is the simplest example to illustrate the issue. First, I will define diagonal matrices with random boolean entries:               Do[A[i] = DiagonalMatrix@SparseArray@RandomChoice[{0, 1}, 10^4];, {i,1, 5}]      Now I add them:               AbsoluteTiming[Sum[A[i], {i, 1, 5}];]      In my system (Mathematica 9 in Mac OS) this operation takes 2.39 seconds. Next I implement this sequentially, adding one matrix to another at each step:               B = 0;     AbsoluteTiming[Do[B += A[i], {i, 5}];]      This operation takes in my machine 0.001226 seconds (!). This seems to be independent of the method used to sum; all the following choices take approximately the same time:               Sum[A[i], {i, 1, 5}]     Total@Table[A[i], {i, 1, 5}]     Plus @@ Table[A[i], {i, 1, 5}]     A[1] + A[2] + A[3] + A[4] + A[5]      Of course, what I am really interested are non-diagonal matrices with non- trivial entries. Even though I could continue to use the aforementioned "sequential" approach, this behaviour is puzzling for me and I would really like to understand it. Any help would be appreciated. Thank you in advance. Gabriel


title: How can I expand a inequality with Abs

text: I want               Abs[x] + Abs[y] <= 1      to be convert to               x + y <= 1 && x + y >= -1 && x - y <= 1 && x - y >= -1        How could I get it with Mathematica?


title: How to combine two usages of # into one and speed up the code?

text: I have a function _num_ with two variables, _matf_ and _matg_. How can I combine the _last two_ lines of code below into one? The code is aimed to find out the maxiaml count _bel_ when we give each $i3 = 1,\cdots,5$ a value $f[[i3]]$ and each $i4 = 1,\cdots,5$ a value $g[[i4]]$. How can I speed up this code? Any help or suggestions will be appreciated.                FG = Tuples[{0, 1, 2, 3}, 5];      num[matf_, matg_] :=         Module[{f = matf, g = matg},           bel = 0;          For[i3 = 1, i3 <= 5, i3++,             For[i4 = 1, i4 <= 5, i4++,               If[Mod[IntegerPart[(i3 + i4)/2 - 1], 5] == Mod[f[[i3]] + g[[i4]], 5], bel++];            ];          ];          bel        ];     num2[f_] := Max[num[f, #] & /@ FG]     Max[num2[#] & /@ FG]      Here is an example to explain what does _num_ do.               Bell = {};     f = {0, 0, 1, 3, 4};     g = {1, 3, 2, 4, 1};     For[i3 = 1, i3 <= 5, i3++,        For[i4 = 1, i4 <= 5, i4++,         If[Mod[IntegerPart[(i3 + i4)/2 - 1], 5] ==         Mod[f[[i3]] + g[[i4]], 5],        AppendTo[Bell, {f[[i3]], g[[i4]], i3, i4}]];];];     Bell     Bell // Length      The output is                 {{4, 3, 5, 2}, {4, 4, 5, 4}}       2      which means that if we assign each $i3 = 1,\cdots,5$ the i3th element in _f={0, 0, 1, 3, 4}_ and $i4 = 1,\cdots,5$ the i4th element in _g={1, 3, 2, 4, 1}_ , then there is only $i3=5$ (the correspondig value is 4) $i4=2$ (the correspondig value is 2) or $i3=5$ (the correspondig value is 4) $i4=4$ (the correspondig value is 4) satisfy the condition _Mod[IntegerPart[(i3 + i4)/2 - 1], 5] == Mod[f[[i3]] + g[[i4]], 5]_.


title: Running MathKernel from Emacs brings cursor to end of line

text: When I start `MathKernel` from the `Emacs` shell, there are always extra spaces inserted so the cursor goes to the far right side of the screen. For example               % emacs -q M-x shell /Applications/Mathematica.app/Contents/MacOS/MathKernel      produces               Mathematica 9.0 for Mac OS X x86 (64-bit)       Copyright 1988-2013 Wolfram Research, Inc.     In[1]:=                                                                       |<-      where I am using `|<-` to show where the cursor is after the 70 whitespace characters are inserted after `In[1]:=`. Does anyone knows why such a thing happens and how to prevent it?


title: How do I place a graphical marker (box, circle, ...) in a MatrixPlot?

text: I'm trying to locate minima / maxima in matrices on a heat map. So I have my 2D matrix and did a `MatrixPlot`, ![my matrix plot](http://i.stack.imgur.com/84jU7.png) and I can find the position of the smallest value. My question: how do I place a graphical marker at that position? Like a box to outline field (7,6)? Completely stumped.


title: How to make the GroupOpeners visible in the SlideShow regime?

text: I am preparing a presentation on Mathematica and realized that though I made the GroupOpeners visible in the working regime (through the OptionInspector), they are invisible in the regime of the slide show. My question: how to make the GroupOpeners visible both in the Working and SlideShow regimes? Mma 9.0.1 WinXP and Win7. Later edit: 1) There is a possibility to use the OpenerView. But this makes all constructs a bit too heavy.   2) I apologize for a wrong term I used. It is not presentation, but a slide show regime where I need to have the openers. Now I corrected it.


title: Financial number format

text: How can I change this function:               nFormat=NumberForm[#,{\[Infinity],2},NumberPoint->",",NumberSeparator->".",DigitBlock->3,ExponentStep->10]&;      So when I use it like:               nFormat/@{10.01,10.1,0.1}//Column      > 10,01 > > 10,10 > > 1.000.000.000,00*10^(-10) The last number `1.000.000.000,00*10^(-10)` get the format equals to `0.10`?


title: Evaluating an If condition to yield True/False

text: I would like to decide whether an option passed to my custom function has the value `Automatic` or something else. This is my attempt:               f[x_, OptionsPattern[{DataRange -> Automatic}]]:=          Module[{opt = OptionValue[DataRange]},{x, If[opt == Automatic, True, opt]}];      However,               f[x, DataRange -> 20]      produces               {x, If[20 == Automatic, True, opt$540]}      rather than the expected               {x, 20}      What do I need to change?


title: Else branch of If expression doesn't print

text: > **Possible Duplicate:**   >  Evaluating an If condition to yield True/False I am trying to print `1` when `a` is found and `0` when it is not, but my code doesn't print `0`. Why? Here it is:               list = {a, b, a, a, c};     Do[If[list[[i]] == a, Print[1], Print[0]], {i, 5}]


title: How to use Select to exclude a single element which I can control?

text: I have code which inserts an expression into lists that I need to remove. I can insert anything I want, a string, variable, or number, into the lists. Suppose I insert the number 13 as my blacklisted element and have a list like               l={12, 14 y, 13, 13 x, 13 x -y}        I then implement               Select[l, # != 13 &]      but the output is               12        My desired output in this case would have been               {12, 14 y, 13 x, 13 x -y}      I've created a working solution that doesn't feel as elegant as it could be, with now a string blacklist element "13"               Select[{12, 14 y, "13", 13 x, 13 x - y}, Not@StringMatchQ[ToString[#], "13"] &]      which gives the desired output. Is it possible to refine the original attempt at a solution to work a bit more simply?


title: Testing a List inside of an Table if it is != 0

text: I'm new to mathematica so I hope this is not a too stupid question, but I couldn't find a solution in the mathematica documentation. I've got a normal table, initialized with "0" as entries. In the first element, I want to put a List of few numbers. I tried to build a minimalistic example as follows:               visitedNodes = Table[0,{i,1,5}]     visitedNodes[[1]] = List[1,2,3]      so visitedNodes = {{1,2,3},0,0,0,0}. Now I test:               For[i=1, i <= Length[visitedNodes], i++,         If[visitedNodes[[i]] != 0,              a = 5;   (* like: "do something" *)             Print["I'm in!"];         ];     ];      Since it's a "List Object", for me it's != 0, but guess I have to test it on somewhat else... but on what? :) Thank you a lot, this site also helped me already a lot =). Edit: The question is, that the If statement for i=1 should be like "Yes, a List[1,2,3] is not equal 0, since it's the first element of visitedNodes", but it does not. So why is it like that?


title: How would I add together any list of arguments as a pure function?

text: Let's say I have a list of arguments, of any length. How would I add them all together?               f = Evaluate[Plus @@ Array[Slot, 3]] &     f[1, 2, 3]      This would add together 3 numbers, but how would I add together any amount of numbers?


title: Extract data from plots in papers including error bars

text: I would like to know how to extract data from plots in a paper and, also, how to do that in a way that include **error bars**. I know there are specific softwares to do that, e.g. Plot Digitizer, which also work for scanned graphs. But I want to "digitize" inside Mathematica, so I don't need external softwares. Furthermore, the plots in a paper can be a bit polluted. An example of a graph to digitize follows below. The desired points are the black points including **error bars**. ![enter image description here](http://i.stack.imgur.com/hoeHR.jpg)


title: How to improve this code for solving the "Mr.S and Mr.P" puzzle?

text: > **Mr.S and Mr. P puzzle** — "Formalization of two Puzzles Involving > Knowledge", McCarthy, John (1987) > > We pick two numbers $a$ and $b$, such that $a\geq b$ and both numbers are > within the range $(2,99)$. We give Mr.P the product $a b$ and give Mr.S the > sum $a+b$. Then following dialog takes place: > > **Mr.P:** I don't know the numbers   >  **Mr.S:** I knew you didn't know. I don'tknow either.   >  **Mr.P:** Now I know the numbers   >  **Mr.S:** Now I know them too > > Can we find the numbers $a$ and $b$? I tried to do this, but it is very slow. I am sure there must be a simpler way.               Clear[pool, f1, f2, f3];     pool = Join @@ Table[{i, j}, {i, 2, 99}, {j, 2, i}];          f1[x_] := Length@Select[pool, Times @@ # == x &] != 1     f2[x_] := Length@Select[pool, Plus @@ # == x &] != 1     f3[x_] := And @@ (f1 /@ (Times @@@ Select[pool, Plus @@ # == x &]))     f4[x_] := Length@Select[Select[pool, Times @@ # == x &], f3[#[[1]] + #[[2]]] &] == 1     f5[x_] := Length@Select[Select[pool, Plus @@ # == x &], f4[#[[1]]*#[[2]]] &] == 1          Select[pool,        f1[#[[1]]*#[[2]]] && f2[#[[1]] + #[[2]]] && f3[#[[1]] + #[[2]]] &&          f4[#[[1]]*#[[2]]] && f5[#[[1]] + #[[2]]] &] // Timing


title: Extracting text from cells, preserving non-ASCII characters

text: Consider the following setup, based on this answer by WReach:               eval = (ToString[#] &)          CellPrint[      Cell[TextData["őúű"], "Program",        Evaluatable -> True,              CellGroupingRules -> "InputGrouping",       CellEvaluationFunction -> eval]]      This will create a cell that, when evaluated, will simply output its own contents, converted to a string. My goal is to preserve non-ASCII characters during this conversion. Notice that with the example contents I included, I get this string as output               "\[ODoubleAcute]\[UAcute]\[UDoubleAcute]"      This is not the same as the input, `"őúű"`. The difference is not just in display, it's actually a different string as you can verify using `StringLength` or exporting the string to a file. What I need to get is:               "őúű"      i.e. a string of length 3. How can I get this? * * * EDIT: Inspecting the cell expression shows that it does indeed contain the 39-character string `"\[ODoubleAcute]\[UAcute]\[UDoubleAcute]"`. So the key to the solution may be figuring out how to convert this to a unicode string containing those characters. EDIT 2: I found the following way to convert named characters in a string `str` to actual unicode characters. But this is undocumented, I don't know where it may go wrong, and I'm sure there must be something better ...               First@FrontEndExecute[FrontEnd`ExportPacket[Cell[str], "InputText"]]


title: Generating a vector of dummy variables

text: So I'm the situation of needing analytical solutions to a family of equations of the form Ax=b, where A is an nxn matrix. I've written a function that does what I want, but I'm currently using a bit of a hack to generate arbitrary (dummy) variable names for the n-vector 'x' :               Map[Clear, Table["x" <> ToString[j], {j, n}]];     x = ToExpression[Table["x" <> ToString[j], {j, n}]];      Can anyone suggest a more elegant way of accomplishing this task?


title: Extracting variables from an expression

text: I'm looking for a way to extract a list of variables from an expression, for example with an input like:               Leff= (mc dm^2 + mc/12*(h^2 + 3 R^2) + ma da^2 + ma/12 La^2)/(mc dm + ma da)      I want this output:               {mc, dm, ma, da, La, h, R}.      The built-in _Mathematica_ function `Variables` can do this but doesn't work with more complex expressions containing trascendental functions. Any help would be very appreciated.


title: Generating a list of symbolic coefficients

text: I am trying to do something which I assume should be very simple: I want to generate a list with symbolic coefficients that looks like this:               A = {a0, a1, a2, a3, ... , a20};      And I mean to do this a lot up to an arbitrary number, so I wouldn't want to type them all. So of course when I set one of them, say `a1 = 5`, then it should be updated in the list, so now:               A = {a0, 5, a2, a3, ... , a20};      I might just be missing an obvious _Mathematica_ command here that does this... Is there a way to do such a thing?


title: Understanding the computation of the geometric median

text: In the Wolfram Demonstration Fermat Point for Many Points, it appears that the geometric median is being calculated for an arbitrary set of five manipulable points. How might one extend this demonstration to computing the median of an arbitrary list of points?