Orthonormalization of non-hermitian matrix eigenvectors

When using `Orthogonalize[]` one can specify which definition of "inner product" is to be used. For example, `Orthogonalize[vectors,Dot]` presupposes that all values are real. When dealing with non-hermitian matrices, the "inner product" definition (apparently) needs to be $|z|^2 = zz$, just like with real numbers. Consider this matrix:               mat = {{0. + 1.002 I, -1}, {-1, -I}}      The following code does not orthonormalize the eigenvectors of my matrix, as can be seen:               Orthogonalize[N[Eigenvectors[mat]]];     N[%[[1]].%[[2]]]          -2.90378*10^-15 + 0.999 I      The `Dot` option does not work, it presents me with an error > Orthogonalize::ornfa: The second argument Dot is not an inner product > function, which always should return a number or symbol. If its two numeric > arguments are the same, it should return a non-negative real number. which is not surprising, since I have complex entries. How can I force `Orthogonalize[]` to use the real number inner product definition, without `Dot`? _I'm using the words "inner product", but feel free to correct me as it seems they're not appropriate. Maybe I should say "involution"?_ **EDIT** As there's a bounty on this question, I'm leaving it open until the last day it's effective. Thanks for the answers. After talking with my supervisor, turns out we'll have to "manually" orthonormalize eigenvectors _that share the same eigenvalue_ , since the eigenvectors are otherwise already orthonormal, as in this case: ![Mathematica graphics](http://i.stack.imgur.com/zcPGN.png)


Pattern matching and HoldForm

Create rules based on data. I have a system that picks out on date,based on some rules. I then want to generate a new rule based on this date and apply the rule to a new dataset.               datePicked={{2008, 3, 21, 0, 0, 0.}}     rule=datePicked/. {t_, n_, o_, b___} :> HoldForm[{t, n, v_, b} /; v <= o];               d=DateRange[{2008, 2, 21, 0, 0, 0.`}, {2008, 3, 21, 0, 0, 0.`}]     Cases[d,#]&@@rule      Problem is that the rule I have made is not general, it has assigned the $ to v. How can I make it general?


How can I put an image on a surface

I want to paste an image on the surface of a 3D plot. For example consider this image ![](http://i.stack.imgur.com/5JpK4.jpg)which I want to paste on the surface of this sphere               ContourPlot3D[x^2 + y^2 + z^2 == 1, {x, -1, 1}, {y, -1, 1}, {z, -1, 1}, Mesh -> 1]      What will be the best way to do that? ## EDIT and Clarification My main objective is not to make a globe but to find a general way to use any arbitrary image on a surface. I choose the map and sphere just as an example (a popular one). `Texture` is a good option, but I find some difficulty to use it with `ContourPlot3D` or `Plot3D`. To make my point clear, I would request to show me an example with this image ![](http://i.stack.imgur.com/XVgk0.jpg) and the following surface,               Plot3D[Abs[x y], {x, -1, 1}, {y, -1, 1}]


How to import Mathematica folders into Workbench

I have been working with _Mathematica_ for a while and have accumulated a number of folders (not in _Workbench_ project form), each with a few files such as a .nb file, maybe a .m file, and their products (images etc.). I then acquired _Wolfram Workbench_ , and am up and running, and wish to transfer my existing folders to _Workbench_. If I try               File -> Import -> General -> Existing Projects into Workspace -> Next      and select the directory that contains my folders, the information up the top of the dialogue box says, "No projects are found to import". If I simply transfer my folders to the base _Workbench_ directory, they are not visible in the Package Explorer or Navigator even after pressing F5 (Refresh). Any ideas? * * * PS $\hspace{5mm}$ After experimenting a little more, I've discovered that I can go               File -> New -> Project -> Mathematica -> Basic Project      and create a project with the same name as the folder I wish to import; then paste the contents of my folder into the project folder. This is a work- around, but what I'd really like to do is import all of my existing folders into the base workspace and have _Workbench_ recognise them as projects (and create the necessary infrastructure around them if need be), without my having to faff around creating projects manually.


Transpose uneven lists

Is there a quick method to transpose uneven lists without conditionals? With:               Drop[Table[q, {10}], #] & /@ Range[10]      Thus the first list would have the first element of all the lists, the 2nd list would have all the 2nd elements of all the lists, etc. If there are no elements, skips. I have a feeling that this should incorporate Mathematica's Reap / Sow function, but unfamiliar.


Using Texture to color countries according to their timezones

So I'm trying to make a world map, where each country is colored according to its timezone. Except, for countries with multiple timezones, the country is filled with vertical stripes of colors corresponding to the various timezones.               colorstripes[zones_] :=        Graphics[MapIndexed[{#1, Rectangle[{#2[[1]], 0}]} &,          ColorData["Rainbow"][(# + 12)/24] & /@ zones]];     Graphics[{EdgeForm[Black],          Texture@colorstripes[CountryData[#, "TimeZones"]],          CountryData[#, "Polygon"]} & /@ CountryData["Countries"]]      ![does not work, everything is black](http://i.stack.imgur.com/o7mdD.png) Yet, my colorstripes function works: ![enter image description here](http://i.stack.imgur.com/4Z4DO.png) So, I am probably misusing `Texture` in a way, but as it does not give any warning or error, I'm kind of stuck. Do you see what's missing?


Notation for specifying transformation rules

I would like to have a compact notation for specifying conditions and results in transformation rules. Consider `ReplaceAll`:               r=ReplaceAll;          r[1, x_/;x>0:>-x]      (* -1 *)      I'd like to avoid writing `x_/;` and `:>`. Here is what I came up with:               Clear[f];     Attributes[f] = {HoldRest};     f[val_,cond_,res_] := val /. x_ /; cond :> res      I could only get it to work thus,               f[1, x$>0, -x$]      (* -1 *)      That expression may not even be robust, because I'm not sure that the pattern always gets renamed `x$`. But what I'm really after is a notation like this:               f[1, x>0, -x]      without the `$` on the `x`. It should work even if `x` is defined (hence the `HoldRest` `Attribute`): for this purpose `x` should be interpreted simply as a notational convenience. How can we do this? My motivation is now one of curiosity, to get a better understanding of how scoping works inside patterns. Initially I was setting up conditions on a problem, for which many different replacement rules were to be used on the same expression, and I was looking for ways to simplify the notation so as not to keep writing `/.`, `x_/;`, and `:>`.


How to plot Venn diagrams with Mathematica?

How does one plot Venn diagrams with Mathematica? I've searched quite a bit and I've found one source at MathWorld which provides the source code for doing them. But I don't understand this code, can someone help me?


Tab between elements in a GUI layout

If I have a bunch of input fields, I can tab between them quite conveniently, but if I want to navigate between the input fields and another element (in my case, a button), I have to click on the button manually. Is there any option or other code construct that would allow the user to tab out of an input field and takes the focus to the button? Ideally I could just press enter and the button would activate. A simple example:               Column[{       TableForm[{          Row[{           InputField[Dynamic@var, Number, ImageSize -> 150],            InputField[Dynamic@unit, String, ImageSize -> 150]         }]// Deploy       }],       Button["print", Print[#1] & [Quantity[var, unit]]]     }]


How do I sort complex numbers?

Okay, so I posted something about sorting, and it was linked as a duplicate to This post However, I am having problems trying to sort a list that contains both real and complex numbers. I put them into one big list and used `SortBy[]` but that does not sort the complex numbers as I want them to. Any ideas? I can post what code I am using if that helps. EDIT:: Data               A=      {{0.651301, 0.671298, -0.000107956 + 0.735512 I,        9.93642*10^-6 + 0.764605 I, 0.965926, 0.97048, 0.0344992 + 1.4214 I,        0.0028631 + 1.4505 I, -0.0626803 + 1.78014 I, -0.12443 + 1.98252 I,        0.167724 +         2.24691 I}, {{-6.79317*10^-6 - 2.8086*10^-6 I, -0.0000157028 +          0.0000511297 I, 0.000393492 + 0.0000998273 I,         0.000323404 - 0.00221263 I, -0.0140581 - 0.00161283 I,         0.00034936 + 0.0455525 I, 0.227164 - 6.59195*10^-17 I,         0.000350353 + 0.0494098 I, 0.0042655 - 0.0016156 I,         0.000351651 + 0.00161694 I, -2.50028*10^-6 -          0.0000297226 I, -0.0000277994 - 0.0000114935 I, -0.0000642597 +          0.000209235 I, 0.00161027 + 0.000408518 I,         0.00132345 - 0.00905464 I, -0.0575294 - 0.00660009 I,         0.00142967 + 0.186412 I, 0.929613 + 0. I, 0.00143373 + 0.202197 I,         0.0174555 - 0.00661145 I,         0.00143904 + 0.00661691 I, -0.0000102317 -          0.000121632 I}, {0.000325231 - 0.00225856 I, -0.0141806 -          0.00160866 I, 0.000361568 + 0.0454971 I,         0.220155 - 6.245*10^-17 I, 0.000362024 + 0.0494813 I,         0.00410192 - 0.00161389 I,         0.000363184 + 0.00165808 I, -6.77596*10^-6 - 0.000030037 I,         0.0000121624 + 0.0000262499 I, -1.0809*10^-6 + 2.11658*10^-8 I,         1.98638*10^-7 + 2.53517*10^-7 I,         0.00137179 - 0.00952634 I, -0.0598123 - 0.00678514 I,         0.00152505 + 0.191902 I, 0.92859 + 0. I, 0.00152698 + 0.208706 I,         0.0173014 - 0.0068072 I,         0.00153187 + 0.00699361 I, -0.0000285803 - 0.000126693 I,         0.0000512998 + 0.000110719 I, -4.55912*10^-6 + 8.92749*10^-8 I,         8.37833*10^-7 + 1.06931*10^-6 I}, {-0.00936005 - 0.00689504 I,         0.00194175 + 0.0457214 I, -0.0000294616 -          0.200724 I, -0.00204752 + 0.0455102 I,         0.00912273 - 0.00677289 I, -0.00206909 + 0.000712454 I,         0.000308104 + 0.000136869 I, -0.0000338275 - 0.0000413905 I,         6.69395*10^-8 + 6.60345*10^-6 I,         4.55605*10^-7 - 7.51471*10^-7 I, -8.81591*10^-8 + 3.57016*10^-8 I,         0.0318708 - 0.0432515 I, -0.211296 + 0.00894252 I,         0.927617 + 0. I, -0.210317 - 0.0094932 I,         0.0312938 + 0.042164 I, -0.0032911 - 0.0095625 I, -0.000632731 +          0.00142376 I,         0.000191303 - 0.000156301 I, -0.0000305169 + 3.04872*10^-7 I,         3.47251*10^-6 + 2.10602*10^-6 I, -1.6493*10^-7 -          4.07439*10^-7 I}, {-5.0264*10^-7 -          8.58797*10^-7 I, -2.37939*10^-7 + 7.30947*10^-6 I,         0.0000371583 - 0.0000443393 I, -0.000328693 + 0.00013847 I,         0.0021433 + 0.000752547 I, -0.00910293 - 0.00695052 I,         0.0021046 + 0.0453582 I,         2.50419*10^-6 - 0.192697 I, -0.00210251 + 0.0453522 I,         0.00910842 - 0.00696524 I, -0.00217144 + 0.000743651 I,         4.12576*10^-6 - 2.41481*10^-6 I, -0.0000351158 - 1.14264*10^-6 I,         0.000213015 + 0.000178511 I, -0.00066525 -          0.00157909 I, -0.00361522 + 0.0102968 I,         0.0333908 - 0.0437323 I, -0.217908 + 0.0101137 I,         0.925747 + 0. I, -0.217879 - 0.010098 I,         0.0334627 + 0.0437578 I, -0.00357275 -          0.0104319 I}, {-0.0000358944 + 0.000126095 I,         0.000744548 + 0.000168628 I,         0.000462218 - 0.00346567 I, -0.0160687 - 0.00154484 I,         0.000533786 + 0.0440688 I, 0.147403 + 6.93889*10^-17 I,         0.000538762 + 0.0497767 I, 0.00157728 - 0.00155399 I,         0.000527326 + 0.00215325 I, -0.000121227 - 0.0000164675 I,         0.0000226836 + 0.0000418986 I, -0.000217846 + 0.000765279 I,         0.00451873 + 0.00102342 I,         0.00280524 - 0.0210335 I, -0.0975223 - 0.00937576 I,         0.0032396 + 0.267458 I, 0.894604 + 0. I, 0.0032698 + 0.302099 I,         0.00957266 - 0.00943131 I,         0.00320039 + 0.0130683 I, -0.000735739 - 0.0000999426 I,         0.000137669 + 0.000254286 I}, {0.000740075 + 0.000166838 I,         0.000463177 - 0.00347749 I, -0.0160926 - 0.0015432 I,         0.000536526 + 0.0440383 I, 0.146592 - 1.38778*10^-17 I,         0.000541552 + 0.049773 I, 0.00153733 - 0.00155267 I,         0.000529806 + 0.00215943 I, -0.000123573 - 0.0000161104 I,         0.0000229325 + 0.0000423765 I, -4.68374*10^-6 + 1.27897*10^-6 I,         0.00451276 + 0.00101733 I,         0.00282432 - 0.0212047 I, -0.0981278 - 0.00940995 I,         0.00327157 + 0.268533 I, 0.893872 + 0. I, 0.00330223 + 0.303501 I,         0.0093742 - 0.00946775 I,         0.0032306 + 0.0131676 I, -0.000753512 - 0.0000982366 I,         0.000139836 + 0.0002584 I, -0.00002856 +          7.79878*10^-6 I}, {0.00919186 + 0.0428642 I,         0.00225897 - 0.0930717 I, -0.00582016 + 0.0395705 I,         0.00877203 - 0.00965772 I, -0.00354763 + 0.00153788 I,         0.000872782 + 0.000117415 I, -0.000154478 - 0.000120785 I,         0.0000131793 + 0.0000345226 I,         1.35683*10^-6 - 6.59455*10^-6 I, -7.61336*10^-7 + 8.03641*10^-7 I,         1.70839*10^-7 - 3.9198*10^-8 I, -0.380824 + 0.0913832 I,         0.831706 + 0. I, -0.354663 - 0.0434019 I,         0.0881538 + 0.0762489 I, -0.0145037 - 0.0313503 I, -0.00085944 +          0.0078202 I,         0.00104523 - 0.00140582 I, -0.000305462 + 0.000125187 I,         0.0000591896 + 0.0000106883 I, -7.34228*10^-6 - 6.62524*10^-6 I,         3.87106*10^-7 + 1.51725*10^-6 I}, {7.99461*10^-7 +          8.43966*10^-7 I, -1.30319*10^-6 - 6.8308*10^-6 I, -0.0000142133 +          0.0000348017 I,         0.000159864 - 0.000116815 I, -0.000870595 + 0.0000850061 I,         0.00342612 + 0.00169007 I, -0.00817676 - 0.00973414 I,         0.0032317 + 0.0383895 I,         0.000181951 - 0.0921798 I, -0.00259292 + 0.0392848 I,         0.00884829 - 0.0104629 I, -7.67732*10^-6 + 7.30127*10^-6 I,         0.0000622308 - 0.0000119998 I, -0.00031743 - 0.00012891 I,         0.0010675 + 0.00145486 I, -0.000790386 -          0.00793286 I, -0.0153412 + 0.0312552 I,         0.0885675 - 0.0746961 I, -0.349814 + 0.0301436 I,         0.840108 + 0. I, -0.358079 - 0.0229246 I,         0.0955152 + 0.0804529 I}, {-0.00253399 - 0.0719661 I,         0.0113022 + 0.0475596 I,         0.00389645 - 0.0167886 I, -0.00429156 + 0.00510902 I,         0.00166148 - 0.000734737 I, -0.000470727 - 0.0000705509 I,         0.0000855359 + 0.000066461 I, -7.33604*10^-6 -          0.0000215169 I, -9.97209*10^-7 + 4.33961*10^-6 I,         5.86732*10^-7 - 5.52976*10^-7 I, -1.38467*10^-7 + 2.36119*10^-8 I,         0.805934 + 0. I, -0.536402 + 0.107684 I,         0.186245 + 0.0501935 I, -0.0554538 - 0.0500129 I,         0.00756365 + 0.0188729 I,         0.000974495 - 0.00523727 I, -0.000777049 + 0.000930539 I,         0.000243554 - 0.0000735791 I, -0.0000481455 - 0.0000128628 I,         5.95393*10^-6 + 6.78033*10^-6 I, -2.09565*10^-7 -          1.55805*10^-6 I}, {-7.14387*10^-7 - 3.11508*10^-7 I,         2.34287*10^-6 + 3.33967*10^-6 I, -1.70002*10^-6 -          0.0000200966 I, -0.0000399888 + 0.0000837606 I,         0.000320663 - 0.000228999 I, -0.00148637 + 0.000164631 I,         0.00482644 + 0.00184217 I, -0.00988419 - 0.0106442 I,         0.0104973 + 0.0343516 I, -0.00368235 - 0.0586699 I, -0.0147028 +          0.0342975 I,         4.43882*10^-6 - 8.65524*10^-6 I, -0.0000434324 + 0.000026573 I,         0.000251662 - 5.46439*10^-6 I, -0.0010121 - 0.000563607 I,         0.00260183 + 0.00417338 I, -0.000888655 -          0.0186437 I, -0.0267204 + 0.0586804 I,         0.140318 - 0.114801 I, -0.436109 + 0.103903 I,         0.733702 + 0. I, -0.415733 - 0.20996 I}, {3.70775*10^-7 +          3.44736*10^-7 I, -5.72806*10^-7 -          2.43401*10^-6 I, -3.97703*10^-6 + 0.0000112541 I,         0.0000405196 - 0.0000326462 I, -0.000214321 + 0.0000263692 I,         0.000738563 + 0.000288755 I, -0.00162487 - 0.00211852 I,         0.00215028 + 0.00773783 I,         0.00384473 - 0.0174451 I, -0.0209518 + 0.0395755 I,         0.00377232 - 0.0505358 I, -4.47615*10^-6 + 5.59781*10^-6 I,         0.0000337592 - 0.0000106518 I, -0.000163074 - 0.0000442868 I,         0.000503592 + 0.000537642 I, -0.000598135 -          0.00299795 I, -0.00329824 + 0.0107312 I,         0.0281964 - 0.0251721 I, -0.106975 + 0.0385116 I,         0.250337 + 0.0358946 I, -0.580797 - 0.254086 I, 0.717427 + 0. I}}}      I want `A[[1]]` to be `{.9704,.9659,.67129,.6513,-.000107+.73i,.000000994+.76i,.0344+1.42i,....}` Sorry For the mess of data. I am trying to sort eigenvalues and keep the corresponding eigenvector with them


Another 3D plot question- good and ugly but no bad-

I have the following code with the intention to have a 3D plot:               f0[y_] :=1/(E^((1 + y)^2/2)*Sqrt[2*Pi])     f1[y_] :=1/(E^((-1 + y)^2/2)*Sqrt[2*Pi])          l[y_] :=f1[y]/f0[y]          t[x_] :=NIntegrate[f1[y]^x*f0[y]^(1 - x), {y, -Infinity, Infinity}]          epsilon0[x_] :=-Log[t[x]] + (x*NIntegrate[l[y]^x*f0[y]*Log[l[y]], {y, -Infinity, Infinity}])/t[x]          epsilon1[x_] :=-Log[t[x]] + ((-1 + x)*NIntegrate[l[y]^x*f0[y]*Log[l[y]], {y, -Infinity, Infinity}])/t[x]          Plot[epsilon0[x], {x, 0, 1}]     Plot[epsilon1[x], {x, 0, 1}]      I have the following figures ![enter image description here](http://i.stack.imgur.com/GWL05.jpg)! ![enter image description here](http://i.stack.imgur.com/q3CnX.jpg)! **Good:** > However I want to have a single graph probably a 3D plot for epsilon0, > epsilon1 and $x$ For example when $x=0.2$ we have $\epsilon_0=0.08$ and $\epsilon_1=1.28$ if I change $x\in[0,1]$ I will get a pair $(\epsilon_0,\epsilon_1)$ for each $x$ and this should be representable in 3D at least as points. But I couldt do it. **Ugly:** > What is the 3D figure if we allow **any** pair of continuous densities $f_0$ > and $f_1$ on $\mathbb{R}$ which have $D(f_0,f_1)=2$ and $D(f_1,f_0)=2$ where > $D$ is the relative entropy or KL divergence?


Why does the order of arguments in Show influence the result?

I am wondering why there is a difference in the results from evaluating the two expressions, which differ only in the order of the arguments given to `Show`. When I run               Animate[Show[spring[t], bob[t], traj], {t, 0, 20}]      the animation is different from               Animate[Show[traj, spring[t], bob[t]], {t, 0, 20}]      Parts of the plot get cut off, depending on the order of the arguments.


How to convert a spaceless data into tab delimited

I have a data set in form of:(this is just an example)               1324501020     3241030205     4332020134      the data are stored in a text file (e.g. data.txt) but I need to convert them into a matrix format such that each number be place in a cell like this:               1 3 2 4 5 0 1 0 2 0     3 2 4 1 0 3 0 2 0 5     4 3 3 2 0 2 0 1 3 4      or in terms of `List` in Mathematica, I need to have `{{1,3,2,4,5,0,1,0,2,0},{3,2,4,1,0,3,0,2,0,5},{4,3,3,2,0,2,0,1,3,4}}` in other words, the final data set supposed to be a matrix of numbers. Any idea??


Getting EPS imports to respect the original fill rule

One major problem in my attempt to answer to the CountryData flags question is that the way Mathematica handles filled curves differs from the way SVG and EPS style editors do. The latter two have the option to apply either of two rules, the non-zero rule or the even-odd rule, with the non-zero rule being default. The Windows .NET Framework 4.5 knows both rules too. Mathematica's`FilledCurve` doc page says: > Filled curves can be non-convex and intersect themselves. Self-intersecting > curves are filled according to an even-odd rule that alternates between > filling and not at each crossing. Unfortunately, since `Import` translates filled curve as a `FilledCurve` with this even-odd rule one gets a star that was efficiently coded in SVG with five points as follows:               Graphics[{Thickness[0.001388888888888889],            {FaceForm[{Blue, Opacity[1.]}],             FilledCurve[{{{0, 2, 0}, {0, 1, 0}, {0, 1, 0}, {0, 1, 0}}},                {{{366.902, 230.137}, {258.902,265.33599999999996},                  {326.105, 173.336}, {326.105,286.93799999999993},                  {258.902, 194.93800000000002}}}            ]}},             AspectRatio -> Automatic]      ![Mathematica graphics](http://i.stack.imgur.com/of7eu.png) (BTW: I would consider this behavior of `Import` a bug, as it doesn't respect the original's default setting.) Getting a star, filled as desired, takes twice as much points:               Graphics[{FaceForm[Blue],        Polygon@{{427.3, 183.3}, {401.5, 218.4}, {360.2, 204.8}, {385.7,           240}, {360, 275.2}, {401.5, 261.8}, {427.3, 296.6}, {427.2,           253.5}, {468.1, 240}, {427.2, 226.6}}}]      ![Mathematica graphics](http://i.stack.imgur.com/gyZZi.png) (and, of course, `Import` doesn't do this automatically.) > My question is: Is there a way to let `FilledCurve` behave according to a > non-zero rule, for instance using some undocumented properties like > discussed here and here? If not, would it be doable to automatically break > up a `FilledCurve` (that not necessarily contains only straight lines) into > separate entities that fill up the original shape as intended?


Metaquestion: how to find out why (e.g.) MatchQ[42, _?Function[x, True]] is False?

Suppose you run into a bewildering Mathematica result (which happens to me several times per Mathematica session, even after a 20-year acquaintance), such as, for example:               MatchQ[42, _?Function[x, True]]     False      So you go pore over the docs, but you still can't figure out an explanation. Then what? > What tool can one use to figure out why Mathematica's evaluation is > different from what one expects? PS. By sheer luck, I had read something a few days earlier that helped me figure out the answer to the one above, but I would have never guessed it without that prior hint. Yes, after knowing the answer I can zero in the place in the docs where the mystery is solved, but _only then_. This is why the documentation does not go as far in such situations as one would think: if one knew where in the documentation to look, one wouldn't have been puzzled by the original result in the first place. Here's a different hint: when completely nonplussed, what could be more fitting than to interrogate the documentation for ?


Web scraping and multi-threading in Mathematica

I'm working in some web scraping using Mathematica, and today, to speed-up the process, I used bash commands (xargs with parallel options with curl and wget) using `ReadList` or `Run`. I would like to do all this inside Mathematica, but I miss multi-thread capability with asynchronous evaluation. I could use more cores, but it's not the answer because the lag is due to time lag, not lack of processor capacity. In bash I can do things like:               cat url.txt | xargs - n1 - P20 wget      Even with 4 cores it distribute the download process in 20 processes. In Mathematica I can do this:               data = ParallelMap[Import,urlList]      But you get limited to cores number. I thought that it would be natural to be multi-threaded if Mathematica is able to use multiple cores. Any clues?


RevolutionPlot3D of 4 piecewise functions around X-axis crashing mathematica

I'm trying to rotate 4 piecewise functions around the X-axis using `RevolutionPlot3D`. The 4 functions I have are:               bottom[x_] := Piecewise[{{{2 + x - x^2/6}, 0 <= x < 3}}, Indeterminate]     side[x_] := Piecewise[{{7/2, 3 <= x < 15}}, Indeterminate]     top[x_] := Piecewise[{{{37/2 - x}, 15 <= x < 17}}, Indeterminate]     neck[x_] := Piecewise[{{3/2, 17 <= x <= 20}}, Indeterminate]      If I try to rotate all of these around the X-axis using `RevolutionPlot3D`, I get errors:               RevolutionPlot3D[{{bottom[x]}, {side[x]}, {top[x]}, {neck[x]}}, {x, 0, 20},                      AxesLabel -> {"x", "y", "z"}, RevolutionAxis -> {1, 0, 0}]      This gives me > Dot::rect: Nonrectangular tensor encountered. errors. This has worked previously with other functions. I tried only the straight lines one for debugging, that is `side` and `neck`:               RevolutionPlot3D[{{side[x]}, {neck[x]}}, {x, 0, 20},       AxesLabel -> {"x", "y", "z"}, RevolutionAxis -> {1, 0, 0}]      But this actually crashes the _Mathematica_ kernel. Any ideas how I get _Mathematica_ to show a revolution plot around the X-axis of these 4 functions?


Optimization in Mathematica

There is a R package called TIMP. By this package someone can fit data to a model. There is a GUI for TIMP called Glotaran. When I fit my data by this package it does not take so much time to get the answer which is consisted of lifetimes and amplitudes of the fluorescence spectra of a sample. However, when I try to do the same thing by Mathematica, doing a global analysis-> fitting different data sets to different models which have some parameters in common such as lifetime here, it takes so longer and Mathematica eats a huge chunk of RAM, at the bottom line Mathematica is not as fast as TIMP. I want to know that why this happens? Is it due to being written in Mathematica language? or Is it that TIMP package use a different algorithm? My objection is that I would expect Mathematica to do a much better job because 1- It is supposed to do heavy mathematical operations 2- It is expensive so I expect much higher quality Personally, I considered Mathematica a tool to do various heavy computations. What is the point of putting so much energy and time to mastering Mathematica if I have to learn other more specialized software to achieve my goal?


Second Order Non Linear Differential Equation

I'm trying to solve the following differential equation numerically:               s = NDSolve[{           (z + 2 r[z] r'[z]) (1 + r'[z]^2) -z r[z] r''[z] == 0,            r[0.01] == 0.0001,            r'[0.01] == 10          },           r, {z, 0.01, 10}         ]      But, when I set the initial condition to $z=0$, there are singularities, so I tried to set it as 0.01. Also, for $r(z=0.01)=0$ there is a singularity, so I set $r(z=0.01)=0.0001$. However, when I try to solve the equation for any value that I put in the boundary conditions, I'm getting "step size is effectively zero; singularity or stiff system suspected." Is there any method to sort this out?


Why does Equal["string", False] not evaluate to False?

Why does `Equal["string", False]` not evaluate to `False`? I would have thought _Mathematica_ could prove that these two things are not equal.


Getting error FullSimplify::infd: ... simplified to ComplexInfinity

I tried to run the following code:               FullSimplify[(4*          Pi*(-(r*(1 + r)^2*               Sqrt[-(((1 + r)^4 + (-1 + r^2)^2 -                      2*(1 + r)^2*(1 + r^2))/(r^2*(1 + r)^2))]) +             3*(1 + r)^3*ArcCos[(-1 + r^2 + (1 + r)^2)/(2*r*(1 + r))]))/        9 - (4*Pi*(-((1 - r)^2*r*               Sqrt[-(((1 - r)^4 + (-1 + r^2)^2 -                      2*(1 - r)^2*(1 + r^2))/((1 - r)^2*r^2))]) +             3*(1 - r)^3*             ArcCos[(-1 + (1 - r)^2 + r^2)/(2*(1 - r)*r)] + (r*                Sqrt[(1 - r)^2/(1 + r)^2]*                Sqrt[-(((-(1 - r)^2 + (-1 + r)^2)*(-(1 - r)^2 + (1 +                          r)^2))/r^2)]*                EllipticF[                 ArcSin[Sqrt[2 + (1 - (1 - r)^2)/r + r]/                   2], (4*r)/(1 + r)^2] -                2*r^3*Sqrt[(1 - r)^2/(1 + r)^2]*                Sqrt[-(((-(1 - r)^2 + (-1 + r)^2)*(-(1 - r)^2 + (1 +                          r)^2))/r^2)]*                EllipticF[                 ArcSin[Sqrt[2 + (1 - (1 - r)^2)/r + r]/                   2], (4*r)/(1 + r)^2] +                r^5*Sqrt[(1 - r)^2/(1 + r)^2]*                Sqrt[-(((-(1 - r)^2 + (-1 + r)^2)*(-(1 - r)^2 + (1 +                          r)^2))/r^2)]*                EllipticF[                 ArcSin[Sqrt[2 + (1 - (1 - r)^2)/r + r]/                   2], (4*r)/(1 + r)^2] + ((7*I)*                  Sqrt[1 - (1 - r)^2/(-1 + r)^2]*(1 - r)*(1 + r)^2*                  Sqrt[1 - (1 - r)^2/(1 + r)^2]*(EllipticE[                          I*ArcSinh[(1 - r)*                        Sqrt[-(-1 + r)^(-2)]], (-1 + r)^2/(1 + r)^2] -                     EllipticF[                     I*ArcSinh[(1 - r)*                        Sqrt[-(-1 + r)^(-2)]], (-1 + r)^2/(1 + r)^2]))/                Sqrt[-(-1 + r)^(-2)] + (I*                  Sqrt[1 - (1 - r)^2/(-1 + r)^2]*(1 - r)*r^2*(1 + r)^2*                  Sqrt[1 - (1 - r)^2/(1 + r)^2]*(EllipticE[                     I*ArcSinh[(1 - r)*                        Sqrt[-(-1 + r)^(-2)]], (-1 + r)^2/(1 + r)^2] -                     EllipticF[                     I*ArcSinh[(1 - r)*                        Sqrt[-(-1 + r)^(-2)]], (-1 + r)^2/(1 + r)^2]))/                Sqrt[-(-1 + r)^(-2)])/((1 - r)^2*r*               Sqrt[-(((1 - r)^4 + (-1 + r^2)^2 -                      2*(1 - r)^2*(1 + r^2))/((1 - r)^2*r^2))])))/9,       0 < r < 1 && r \[Element] Reals]      I cannot figure out what is wrong here. All the denominator pose no problems. Square root and Elliptic functions and Arc trig functions should not be able to produce complex infinity. Yet every time I run it will produce a warning and result in ComplexInfinity. The warning look like this:               FullSimplify::infd:Expression 4/9 π (-r (1+r)^2      Sqrt[-((Power[<<2>>]+Power[<<2>>]+Times[<<3>>])/(r^2 Plus[<<2>>]^2))]+3 (1+r)^3      ArcCos[(-1+Power[<<2>>]+Power[<<2>>])/(2 r Plus[<<2>>])])-4/9 π (-(1-r)^2 r      Sqrt[-((Power[<<2>>]+Power[<<2>>]+Times[<<3>>])/(Plus[<<2>>]^2 r^2))]+3 (1-r)^3      ArcCos[(-1+Power[<<2>>]+Power[<<2>>])/(2 Plus[<<2>>] r)]+<<1>>/((1-r)^2 r      Sqrt[-((Power[<<2>>]+<<1>>+<<1>>)/(<<1>>^2 r^2))])) simplified to ComplexInfinity. >>      (I got an error if I try to convert to input form, so I have to paste that as plain text; but in any case, all the <<1>> and <<2>> seriously obscure where the error are occurring) I am unable to simplify this on my own. I hope you can help. Thank you very much.


Possible bug: SparseArray Part assignment loses default value?

This sure looks like a bug to me (Mathematica 10.0.0, MacOS):               (Local) In[345]:= s = SparseArray[{}, {20}, 1]          (Local) Out[345]= SparseArray[< 0 >, {20}, 1]          (Local) In[346]:= s // Normal          (Local) Out[346]= {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}          (Local) In[347]:= s[[All]] = 1; s          (Local) Out[347]= SparseArray[< 0 >, {20}]          (Local) In[348]:= s // Normal          (Local) Out[348]= {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}      Apparently when I assigned 1 to all elements of s, it correctly realized that everything was still equal to the default, so left everything unspecified. But it incorrectly lost the 1 default value and changed the array to have the default default value of 0. This is a toy example, but it comes out of a more complicated example in which it is causing me a serious problem. I don't know the full scope of the problem, but it is not necessary to assign to the entire array for the default value to be lost. I guess the lesson is that non-zero defaults are fragile. Is this really a bug, or am I missing something obvious?


Truncate High order terms

Suppose I want to compute this : `Series[Sin[1/f], {f, Infinity, 10}]` but finally I prefer `Sin[1/f]` up to the fourth order in `1/f`. How can I do this ? My first idea was to use the `O[]` function but it didn't work because `1/f is not a valid variable`. My second idea was to use firstly `/. f -> 1/eps` and then `O[eps]^4` but it didn't work as well... Note also that, for many reasons, `Series[Sin[1/f], {f, Infinity, 4}]` is not a solution to me !


Why do images in a PopupMenu sometimes make a program load sluggishly?

In a demonstration, I would like to display a `PopupMenu` with a list of small PDF images, each weighing in at approximately 50k. The code of interest is below: ![PopupMenu](http://i.stack.imgur.com/uBuWR.png) After hitting `Shift`+`Enter`, the demo requires 25 seconds before being ready to operate. However, once it is ready, it works responsively, without hesitation. A simple list of numbers in the `PopupMenu` works much better:               {{s, 2, ""}, Range[12], PopupMenu, ControlPlacement -> Bottom}      One second or so after hitting `Shift`+`Enter`, the demo is ready to go. I realize that I could save some memory by using images with smaller footprints (e.g. moving to 8-bit or even 1-bit images), but there may be other things I should be considering to increase the efficiency of `PopupMenu`. Any suggestions would be appreciated. * * * **Update** Image file size was not the culprit in this case. It turns out that some of my PDF images were not in a format fully acceptable to Mathematica. When halirutan was able to quickly import and display large PDF files using my code (but adding the additional burden of importing), I decided to use his code to import my large files. Mathematica refused to import several of my files as `Images`, using the routine Halirutan included in his response. However, Mathematica does allow those same files to be imported via the menu via "Insert/Picture/From file". Because MMA had accepted all my images when I manually inserted them into the `Popupmenu` control (as shown above), and because it displayed them correctly (albeit after an initial delay), I did not suspect that some of the files (but not others) were in a format uncongenial to MMA. It accepted the corrupt files and "reluctantly" figured out how to display them properly in the PopupMenu control. So halirutan provided the essential resources that turned out to be instrumental for solving the issue. * * * **Update 2** Neither .pdf nor .png graphics files produced from OmniGraffle Pro (v. 5.3.6) can be successfully imported by Mathematica via the `Import[..., "Images"]` command. However GraphicConverter (v. 7.2) can import either of these. While in GraphicConverter, simply "saving as" a .png file from OmniGraffle to .pdf will produce a file that can then be imported by Import into Mathematica. That file will have a white background even if the original .png file had a transparent background. But the important thing is that MMA will accept it readily. By the way, by making my PDF's this way, they turn out to be 7k in size.


Manipulate BarChart with Mathematica

In the following minimal working example:               Manipulate[BarChart[{a,b}],{a,1,2},{b,1,2}]      I'd like to be able to control the size of the bars by using some sort of `Locator` property for manipulate i.e. change the vertical size of each bar by placing my mouse on the edge of the bar (ideally anywhere along its width). Obviously, `Locator` won't work. Any ideas how to easily do this? I want the value of the bar chart to dynamically update. In the above example, I would have `a, b` obey some constraint (like `a + b = 2` so whenever one changes the other does so accordingly). \-------- Answered -------- This was so that there's some playing with the Greek general election. I wanted to play with the latest poll results and vary them before the election on Sunday. @Mike Honeychurch: You are right, barspacing doesn't change the locator positioning but the locators are off center like so (this is my output when I run your code): ![Mikes](http://i.stack.imgur.com/p3XcT.png) I assume you run a different version of Mathematica than me - I run 7, sorry, should have said so. So, I had to fiddle with the x-coordinates of your locators in some way like this when defining `pt`: `numberofpoints = 5; barspacing = 0.1; xcoords = Table[i + barspacing i - 1/2, {i, 1, numberofpoints}]; pt = xcoords~Riffle~RandomInteger[{0, 3}, 3]~Partition~2` I got the chart to look OK at the end (locators here for only the first three bars): ![Mikes to mine](http://i.stack.imgur.com/q7Miz.png) but wasn't entirely happy with the way it was done because of the fiddling I mentioned above. So I am going with @Heike 's approach that works a treat out of the box exactly the way I wanted:               lastpoll = {{LightBlue, 24.3, "ΝΔ"}, {Green, 15.4, "ΠΑΣΟΚ"}, {Red, 10.9, "ΚΚΕ"},      {Yellow, 8, "ΔΗΜΑΡ"}, { Pink, 9.5, "ΣΥΡΙΖΑ"}, {Blue, 9.6, "Αν. Ελληνες"},     {Gray, 6.3, "Χρυση Αυγη"}, {LightBlue, 4.2, "ΛΑΟΣ"}, {Green, 4.4, "Οικολογοι"},      {LightCyan, 2.1, "Δημ. Συμμαχια"}, {Yellow, .8, "ΕΠΑΜ"}, { LightRed, .8, "ΔΡΑΣΗ"},     {Blue, .8, "ΑΝΤΑΡΣΥΑ"}, {LightGray, .8, "Κοιν. Συμφωνια"}, {White, 2, "Λοιπα"}};     values = #[[2]] & /@ lastpoll;     dragBar[values,      ChartLabels -> Placed[(Last /@ lastpoll), Axis, Rotate[#, 55 Degree] &],     ChartStyle -> (First /@ lastpoll), BarSpacing -> .6, ImageSize -> Large]      with the following result (all fiddlable): ![enter image description here](http://i.stack.imgur.com/Pnoct.png) In any case, thank you all for taking the time. This was harder than I expected it would be..


Plot a real part of complex equation depending on a parameter

I would ask you to kindly provide me a way to solve this problem in mathematica way. Let the equation $z^2 + 9 -1.5 e^{- t z}=0$ where $z\in \mathbb C$ and $t\in \mathbb R^+$. In order to plot graph of $t \mapsto \mathrm{Re}(z)$, I have triyed this:               f[z_] = z + 9  - 1.5 E^(- t z)          z = x + I y           ExpToTrig[       E^(-t (x + I y)) (-1.5 + 9. E^(t (x + I y)) + E^(t (x + I y)) x +          (0. + 1. I) E^(t (x + I y)) y)]      > >     (0. + 0. I) - 1.5 Cosh[t x + I t y] + 9. Cosh[t x + I t y]^2 + >       x Cosh[t x + I t y]^2 + (0. + 1. I) y Cosh[t x + I t y]^2 + >       1.5 Sinh[t x + I t y] - 9. Sinh[t x + I t y]^2 - >       x Sinh[t x + I t y]^2 - (0. + 1. I) y Sinh[t x + I t y]^2 >                 TrigExpand[(0. + 0. I) - 1.5 Cosh[t x + I t y] +         9. Cosh[t x + I t y]^2 +         x Cosh[t x + I t y]^2 + (0. + 1. I) y Cosh[t x + I t y]^2 +         1.5 Sinh[t x + I t y] - 9. Sinh[t x + I t y]^2 -         x Sinh[t x + I t y]^2 - (0. + 1. I) y Sinh[t x + I t y]^2]      > >     (9.` + 0.` I) + x + (0.` + 1.` I) y - >       1.5` Cos[t y] Cosh[t x] + (0.` + 1.5` I) Cosh[t x] Sin[t y] + >       1.5` Cos[t y] Sinh[t x] - (0.` + 1.5` I) Sin[t y] Sinh[t x] >   In the last I can't do Real part. Any help is welcome.


Does the VerticalCallout algorithm in PieChart3D work correctly?

In real world usage you often want to use real world labels with long strings (say 15-20 characters) in 3D pie charts. Here is a toy example :               Clear[labeler];     labeler[datax_][v_, {1, c_}, ___] :=        Placed[Column[{datax[[c]], v}, Alignment -> Center,          BaseStyle -> Directive[FontFamily -> "Arial", 11]],         "VerticalCallout"];     data = Transpose[{"This is label " <> ToString[#] & /@ Range[14],          Range[14]}];          PieChart3D[{data[[All, 2]]},      ChartElementFunction ->        ChartElementDataFunction["ProfileSector3D", "Profile" -> 4],      ChartStyle -> 54,      ImageSize -> 400,      LabelingFunction -> labeler[data[[All, 1]]],      PerformanceGoal -> "Speed",      PlotRange -> All,      SectorOrigin -> {Pi, 0},      SectorSpacing -> 0.2]      ![enter image description here](http://i.stack.imgur.com/WLUDT.png) We see that the plot area seems to have been determined without reference to the labels that will be placed around the chart. Consequently the labels are cut off. Q. Is this an `Image Padding` issue? A. no (note that `All` gives the same output as `Full`) ![enter image description here](http://i.stack.imgur.com/nixbd.png) Q. So why not expand the margins around the image to give the labels enough space to be rendered? ![enter image description here](http://i.stack.imgur.com/5ooGc.jpg) So increasing the image margins merely creates another graphics area around the original image. This looks like a bug or design flaw to me. Does anyone have any ideas about how to get `VerticalCallout` labels working in `PieChart3D`?


Area between Contours in ContourPlot

I feel slightly foolish for asking this because I am so close, but I'm having trouble, so I will anyway. I asked this question two days ago regarding finding the lengths of contours. Now, I'd like to find the areas between them. I have read and played around with the information here, here and here, but am having difficulties. ![The contour plot looks something like this...what are the areas?!](http://i.stack.imgur.com/TdjKk.jpg) Having extracted the individual contours of `f[x,y]` via the method given by chris, I would like to find the areas bounded by the contours and the plot region. Is there a simple way to do this? For reference, I am using the contour plot of the following function:               q[r_] := Piecewise[{{25/(0.1*1), r < 0.1}, {25/r, r >= 0.1}}]     phi[r_, t_] := (Pi/2) + q[r]*t     v[r_, t_] := q[r]*r*Cos[phi[r, t]]     s[x_] := Piecewise[{{x = -1, x < 0}, {x = 1, x >= 0}}]          f[x_,y_] := s[x]*v[Sqrt[x^2 + y^2],ArcTan[y/x]/q[Sqrt[x^2 + y^2]]]          ContourPlot[f[x, y], {x, -1, 1}, {y, -1, 1}, RegionFunction -> Function[{x, y}, x^2 + y^2 <= 1],      PlotPoints -> 100, Contours -> Range[-25, 25, 1]]


Mathematica 10 crashes when kernel is quit from MenuItem

I'm actively developing a large codebase that I load every time I use _Mathematica_. I frequently quit my kernel and reload the codebase to incorporate new changes. I've created a custom menu by editing `MenuSetup.tr` to include menu items and keyboard shortcuts that allow me to quit the kernel and reload my codebase quickly and easily. Unfortunately, the 'Quit' functionality no longer works in _Mathematica_ 10\. Both the `"EvaluatorQuit"` `FrontEndToken` and manually running `KernelExecute[ToExpression["Quit[]"]]` from a `MenuItem` cause the FrontEnd to crash (the code used in my `MenuItem` is derived from this thread). The same bits of code work fine when run directly from the FrontEnd. There clearly still exists a viable method of quitting a kernel from a menu, because the 'Quit Kernel' submenu in the 'Evaluation' menu still functions fine without crashing the FrontEnd. Unfortunately, the way this is done seems to be hidden behind the `"MenuListQuitEvaluators"` token used to generate that submenu. Any advice on how to get around this bothersome crashing behavior would be most welcome.


Exhaustive examples of variable replacement due to nested scoping constructs

Consider the following examples, where I have replaced dollar signs in the output by a D.               3/.x_:> Rule[var_,x]     3/.x_:> RuleDelayed[var_,x]     3/.x_:> Function[var, x]     3/.x_:> Hold[Compile[{var, _Integer}, x]]     3/.x_:> Hold[SetDelayed[var_, x]]     3/.x_:> Hold[Set[var_,x]]     3/.x_:> Hold[TagSet[2,var_,x]]     3/.x_:> Hold[UpSet[var_,x]]     3/.x_:> Hold[UpSetDelayed[var_, x]]     3/.x_:> Hold[TagSetDelayed[2, var_, x]]     3/.x_:> Hold[With[{var=b},x]]     3/.x_:> Hold[Module[{var=b},x]]          (*not Block*)     (*3/.x_:> Hold[Block[{var=b},x]]*)     (*not DynamicModule*)     (*3/.x_:> ToString@Hold[DynamicModule[{var=b},x]]*)     (*not the Table family*)     (*3 /. x_ :> Hold[Table[x, {var, 5}]] *)          Function[x,Condition[var_,x]][3] (*ReplaceAll interacts with Condition, so I use Function*)          (*not RuleCondition*)     (*Function[x, Hold[RuleCondition[var_, x]]][3]*)      > >     varD_->3 >     varD_:>3 >     Function[varD,3] >     Hold[Compile[{varD,_Integer},3]] >     Hold[varD_:=3] >     Hold[varD_=3] >     Hold[2/:varD_=3] >     Hold[varD_^=3] >     Hold[varD_^:=3] >     Hold[2/:varD_:=3] >     Hold[With[{varD=b},3]] >     Hold[Module[{varD=b},3]]   >     varD_/;3 >   and these ones               {"Replace",Replace[3,x_:> Rule[var_, x]]}     {"ReplaceAll",ReplaceAll[3, x_ :> Rule[var_, x]]}     {"ReplaceRepeated",ReplaceRepeated[{3},{x_Integer}:> Rule[var_, x]]}     {"With",With[{x=3},Rule[var_,x]]}     {"Module",Module[{x=3},Rule[var_,x]]}     (*not Block*)     (*{"Block",Block[{x=3},Rule[var_,x]]}*)     {"DynamicModule",ToString[DynamicModule[{x=3}, Rule[var_,x]],InputForm]}     (*The example below works for any "assignment function" (Set)*)     Clear[f]     {"Replacement by evaluation",Set[f[x_],RuleDelayed[var_,x]],f[3]}     (*not Function with Slots*)     (*Function[Rule[var_,#]][3]*)     {"FunctionNamedArg",Function[x,Rule[var_,x]][3]}      > >     {Replace,varD_->3} >     {ReplaceAll,varD_->3} >     {ReplaceRepeated,varD_->3} >     {With,varD_->3} >     {Module,varD_->3} >     {DynamicModule,DynamicModule[{x = 3}, varD_ -> 3, DynamicModuleValues :> > {}]} >     {Replacement by Evaluation, var_:>x, varD_:>3} >     {FunctionNamedArg,varD_->3} >   A general explanation of such examples can be found in the Q&A called "Enforcing correct variable bindings and avoiding renamings for conflicting variables in nested scoping constructs", in this answer. However I felt a bit more could be said about this. The first list of examples basically lists all functions that could be considered "inner scoping constructs". The "inner scoping constructs" are searched for by "outer scoping constructs" in their bodies. The outer scoping constructs are listed in the second set of examples. Note that in the second list of examples there is an example with `Set`, labeled "Replacement by Evaluation". This example is different from the others, in that it is not `Set` here that is the function that looks for scoping constructs in its body. Rather, it appears that whenever the kernel evaluates an expression `x`, it emulates searching for scoping constructs in `x`. The kernel already does a lot of this kind of bookkeeping, so maybe this is why it is not a big performance hit. In the example we use `Set`, but it appears that any definition made using "assignment functions" (`SetDelayed`, `Set`, `TagSet`, `UpSet`, `TagSetDelayed`, `UpSetDelayed`) will cause replacement of such variables. This replacement will happen for definitions corresponding to `DownValues`, `UpValues` as well as `SubValues`. It cannot happen for definitions that correspond to `OwnValues` as it is not possible to create an `OwnValues` with a pattern on the LHS of the (generated) rule. I think interaction between inner and outer scoping constructs depends on the combination of the scoping constructs in a kind of independent manner. I.e. all the outer scoping constructs have the same strategy for to resolve a conflict between a local variable and the second argument of `Rule`. If this is true, all the interaction between inner and outer scoping constructs can be illustrated with only a few examples. I would consider the list to be exhaustive if all the cases where variable replacement happens can be predicted from the list, because all inner and outer scoping constructs are present. **Question** Are my examples exhaustive? **Related** StringReplace, ReplaceAll and Rule interact in a bizarre way (answer by Leonid)


What is the correct way to use specific rule for specific pattern match when parsing an expression?

**update:** Thanks for the answers below. But I noticed they do not handle the following special cases: `lis=1` and `lis=z` , `lis=1/z` and `lis=-z` as these are also considered legal input as given in the question below. It is easy to add special case processing for these, by making them `lis={1}` and `lis={z}` etc... before calling the parser (this is what I actually had to do myself). but it will be nice if this was incorporated as special pattern/rule as well. I could not do it myself inside `Alternative` and had to check for this before as special case. To make sure what is the input, I'll clarify it again: Each term is of the form `c*z^n` where there can be _one or more terms_. i.e. `lis= term1+term2+term3...` In each term, `c` can be any numerical value, and `n` can be any numerical value (positive or negative). The result will be list of `{{c,n},.....}`, one entry for each term. Even if there is one term only, it should work. Examples to verify against:               lis=1   --->  {{1,0}}     lis=z ----> {{1,1}}     lis=-z --->{{-1,1}}     lis=1/z  ---->{{1,-1}}     lis=1+z^-1 --->{{1,0},{1,-1}}     lis=1/z^3 + 3/z + 3 z + z^3 -->{{1,-3},{3,-1},{3,1},{1,3}}     lis=6 + 1/z^4 + 4/z^2 + 4 z^2 + z^4 -->{{6, 0}, {1, -4}, {4, -2}, {4, 2}, {1, 4}}      **Original question** The hammer I use now for everything I see that needs parsing with patterns is `Cases`. So, I was trying to write a simple pattern based parser that accepts any output from `Expand(f[z])` where `f[z]` is rational function of `z` only. For example, it take such input as               Expand[(z + 1/z)^4]     (*6 + 1/z^4 + 4/z^2 + 4 z^2 + z^4*)      or               Expand[(z + 1/z)^3]     (*1/z^3 + 3/z + 3 z + z^3*)      or `1` or `z` or `z^-1` or `1+z` and so on. So the input can be thought of as power series in `z`. All terms are in this form. So it is well defined what it is. The output of the parser will be a list that shows the coefficient of each term, and the exponent of `z`. So given the input `6+(1/z^4) + 4/z^2 + 4 z^2 + z^4` the output will be                {{6,0},{1,-4},{4,-2},{4,2},{1,4}}      The best I can come up with is this:               lis = 6 + 1/z^4 + 4/z^2 + 4 z^2 + z^4     Cases[lis, Alternatives[x_. Power[z, e_.],                             Times[x_, Power[z, e_.]],                             x_.] :> {x, e}]      The problem is that the above generates                 {{6},{1,-4},{4,-2},{4,2},{1,4}}      and not                 {{6,0},{1,-4},{4,-2},{4,2},{1,4}}      This is because the pattern that matched x_. (the last one in the `Alternatives` does not have an `e` in it, and Mathematica replaced the `e` with the Null sequence as documented in help. Another problem with the above, is that `x_.` has to the last one in the alternatives. If I had wrote this instead:               Cases[lis, Alternatives[x_., x_. Power[z, e_.], Times[x_, Power[z, e_.]]] :>             {x, e}]      Then it would not have worked (another thing to worry about). Ok, this is all fine, except now the output is not symmetric and needs special case processing. What I was hoping to do is something like this                Cases[lis, Alternatives[x_. Power[z, e_.] :> {x,e} ,                               Times[x_, Power[z, e_.]] :> {x,e},                               x_. :> {x,0}]             ]      ie. have a specific rule for each specific pattern. The above is much easier to work with, since now I can specific the output for each pattern instead of having all pattern target one output. But the above of course is not valid Mathematica code and `Cases` does not like it. Are there such general ways of doing the pattern matching that allows one to write specific rules for specific pattern? It does not have to use `Cases` as long as it follows this general approach. I know that one can probably use the Polynomial specific functions (such as `CoefficientRules`, `CoefficientList`, and related functions to do this for this case, but I am more interested in this general approach so I can learn how to use it for things other that this example)


Prevent Grid from resizing images

Aligning my images in `Grid` causes one of them to become smaller, despite specifying each of their sizes with `ImageSize`:               dat = Table[{x, y, RandomReal[]*x*y}, {x, 1, 50}, {y, 1, 50}];     img = ListContourPlot[Flatten[dat, 1], ImageSize -> {300, 300}];     oldspotlight =        Graphics[{}, Background -> Black, PlotRange -> {{1, 50}, {1, 50}},         ImageSize -> 300];     a=Show[img,       Graphics[{Circle[{90, 60}, 10]}, PlotRange -> {{1, 50}, {1, 50}},        ImageSize -> {300, 300}]]     b=ImageMultiply[img,       ImageAdd[oldspotlight,        Graphics[{ColorData["GrayTones"][10/20], Disk[{90, 60}, 10]},         Background -> Black, PlotRange -> {{1, 50}, {1, 50}},         ImageSize -> {300, 300}]]]     Grid[{{a,b}}]      Output: ![enter image description here](http://i.stack.imgur.com/fxDPB.jpg) ![enter image description here](http://i.stack.imgur.com/z8vAq.jpg) ![enter image description here](http://i.stack.imgur.com/BgS8X.jpg) Please note that I don't want to use `GraphicsGrid`. (The reason is because it doesn't cooperate with `Dynamic`, which is an unrelated question.)


How to fix this error : SetDelayed::write: Tag Plus in (<<1>>)[x_] is Protected.?

I don't get the meaning of the sign <<>> and also from which line the error is coming as I have a program of more than 30 lines with many defined functions without using "Module" . Is not there any way to display line numbers in Mathematica so that we can know from which line error is coming?


Plotting with ColorFunction -> GrayLevel - no black

This is probably a fairly trivial question, yet I have been unable to find an answer - help would be much appreciated! :) I am trying to plot a 28 x 28 matrix (tabulated data given here), containing continuous pixels values on the interval [0;1]. I am using MatrixPlot and ColorFunction -> GrayLevel, so that 0 comes out as black and 1 as white, and all values inbetween will cover the gray spectrum. MatrixPlot produces a lovely 28 x 28 matrix plot - however, for some reason it uses a medium gray for 0, and scales the remaining values accordingly on the gray spectrum, with 1 still being white. This is the code used:               input1 = Get["http://pastebin.com/raw.php?i=PP2t8tp6"];     MatrixPlot[input1, ColorFunction -> GrayLevel, Mesh -> None, AspectRatio -> 1/1, ImageSize -> 300]      The resulting image: ![enter image description here](http://i.stack.imgur.com/3GGxr.png) Adding a file extension (.dat, .csv, .txt) and adding separators made no difference - I also tried forcing the color spectrum with ColorRule, but no luck.


Problem with SphericalPlot3D plotting

I want to plot the real part of the `SphericalHarmonicY[1,1,θ,φ]`. That is, I want to plot $$ - \frac{1}{2}\sqrt {\frac{3}{{2\pi }}} \cos[\phi ]\sin[\theta ]$$ To do so, I evaluated the following expression:               SphericalPlot3D[-(1/2) Sqrt[3/(2 π)] Cos[φ] Sin[θ], {θ, 0, π}, {φ, 0, 2 π}]      But the result I got doesn't show the negtive part. What is wrong? ![spherical](http://i.stack.imgur.com/XF1eS.gif)


Is there an easy way to specify an arbitrary two-dimensional Polyomino tiling in Mathematica 8.0?

Is there an easy way to generate an arbitrary two-dimensional Polyomino tiling: http://en.wikipedia.org/wiki/Polyomino? Specifically, I would like to generate an array of integer coordinates, for example: {{0,1},{10,11},{15,6},...}, and then output a graphic showing a tiling pattern where a tile is centered at each integer coordinate in my array, and where each tile is labeled with its integer coordinate. Is there a way for me to do this in three-dimensions? I have access to Wolfram Mathematica 8.0.


Symbolic multiplicative partitions

Let $p_n\\#\equiv\prod_{k=1}^{n}p_k$ (primorial):               p[n_] := Times @@ Prime[Range[n]]      then the multiplicative partitions of $p_{1,2,3,4}\\#$ are $$ \\{\\{2\\}\\},$$$$ \\{\\{6\\},\\{2,3\\}\\},$$$$ \\{\\{30\\},\\{2,15\\},\\{3,10\\},\\{5,6\\},\\{2,3,5\\}\\},$$$$ \\{\\{210\\},\\{2,105\\},\\{3,70\\},\\{5,42\\},\\{6,35\\},\\{7,30\\},\\{10,21\\},\\{14,15\\},\\{2,3,35\\},\\{2,5,21\\},\\{2,7,15\\},\\{3,5,14\\},\\{3,7,10\\},\\{5,6,7\\},\\{2,3,5,7\\}\\}$$ computed with               g[lst_, p_] :=      Module[{t, i, j}, Union[Flatten[Table[t = lst[[i]]; t[[j]] = p*t[[j]];     Sort[t], {i, Length[lst]}, {j, Length[lst[[i]]]}], 1],      Table[Sort[Append[lst[[i]], p]], {i, Length[lst]}]]];          z[n_] := Module[{i, j, p, e, lst = {{}}}, {p, e} =      Transpose[FactorInteger[n]];     Do[lst = g[lst, p[[i]]], {i, Length[p]}, {j, e[[i]]}]; lst];          Table[z[p[n]], {n, 1, 4}]      What is the best way to turn this into a symbolic function, so the output of the above becomes $$\\{\\{a\\}\\}$$$$ \\{\\{ab\\}\\},\\{\\{a,b\\}\\}$$$$ \\{\\{abc\\}\\},\\{\\{a,bc\\},\\{b,ac\\},\\{c,ab\\}\\},\\{\\{a,b,c\\}\\}$$$$ \\{\\{abcd\\},\\{a,bcd\\},\\{b,acd\\},\\{c,abd\\},\\{d,abc\\},\\{ab,cd\\},\\{ac,bd\\},\\{ad,bc\\}, \\{a,b,cd\\},\\{a,c,bd\\},\\{a,d,bc\\},\\{b,c,ad\\},\\{b,d,ac\\},\\{c,d,ab\\},\\{a,b,c,d\\}\\}$$ ? The primorial example above is given for combinatorial simplicity. I would ideally like the function to be applicable to any number, e.g.: $72$ ($2^3\cdot 3^2$) would be tackled as $a^3\cdot b^2$. Of course, it is possible to take this approach:               n = 4; ColumnForm[Map[FactorInteger[z[p[n]]][[#]] &, Range[Length[z[p[n]]]]]     /. 2 -> a /. 3 -> b /. 5 -> c /. 7 -> d]      ... etc., but I wondered whether there was a more direct route? _NB - This question is an extension ofthis one._ # Update Have got this far:               n = p[4];     m = ColumnForm[Map[FactorInteger[z[n]][[#]] &, Range[w[n]]]      /. 2 -> a /. 3 -> b /. 5 -> c /. 7 -> d];     ColumnForm[Table[Table[Map[m[[1, k]][[v]][[#]][[1]]^m[[1, k]][[v]][[#]][[2]] &,      Range[Length[m[[1, k]][[v]]]]], {v, 1, Length[m[[1, k]]]}], {k, 1, w[n]}]]      BTW, is there an easier way of doing               /. 2 -> a /. 3 -> b /. 5 -> c /. 7 -> d /. 11 -> e /. 13 -> f /.                          17 -> g /. 19 -> h /.      ...etc.?


What is available for editing Mathematica source code with Emacs?

I can find several Emacs libraries for _Mathematica_ , but I'm not aware of a clear favourite, a definitive list, or of a library which is actively maintained and developed. None of these appear to be in the Emacs Lisp Package Archive or Milkypostman’s Emacs Lisp Package Archive.   * http://www.watson.org/~mccann/mathematica.el   * https://github.com/Leockard/elisp   * http://library.wolfram.com/infocenter/MathSource/4567/   * http://www.itwm.fhg.de/as/asemployees/wichmann/mma.html   * http://chasen.org/~daiti-m/dist/math++.el I have been using the first one on the list for a while, but the indentation engine is not ideal. What do people use for editing _Mathematica_ source code in Emacs? I'm just talking about editing source code; I don't need to evaluate _Mathematica_ expressions in a subsidiary kernel process, etc. The important features for me are   * indentation,   * syntax-highlighting,   * forward/backward/up/down in _Mathematica_ bracketed expressions. Additional "IDE" features would be very welcome, especially imenu support.


How to make plots scaling consistent when running a series of simulations?

In my function it returns a plot of my data, say example, using ListLinePlot, and this is the size I obtain: ![enter image description here](http://i.stack.imgur.com/nAgS4.png) ![enter image description here](http://i.stack.imgur.com/ImAlW.png) but when running a series of simulations inside a Table: Table[tCorrStudentsT[i]=sensStudentsT[sensMat[[i]], mcRun,chrT,hrT,ppT,r] ,{i,10}] the resultant graphs look like these, without manually adjusting each graph after simulation is complete? ![enter image description here](http://i.stack.imgur.com/Tz129.png) so how can I set it such that the series of graphs will be consistent with my single simulation result plot size?


How to correctly use DSolve when the force is an impulse (dirac delta) and initial conditions are not zero

`DSolve` (and `NDSolve`) return different and unexpected solution to differential equation when the input is an impulse. This is because `DiracDelta[t]` at $t=0$ remains `DiracDelta[0]`. **This question is two parts question** : If it is a user error to use `DiracDelta[t]` in this example, should then software still return a solution? And the second part asks how to use `DSolve` or `NDSolve` in order to obtain the correct solution to a differential equation when the input is an impulse $\delta\left(t\right) $ as is commonly understood and used in engineering and mathematics problems (the dirac delta function). Initial conditions used are not all zero in this example. ## Problem description An example which is standard ODE is used that models a single degree of freedom second order differential equation for an underdamped system. When using $f(t)=\delta\left( t\right) $ as the RHS of the differential equation, the answer returned is the same as the answer when $f\left( t\right) =0$. The user might go on and use the solution without knowing that $\delta\left( t\right) $ effect was not used since no warning is issued. Here is an example solving $my^{\prime\prime}\left( t\right) +cy^{\prime }\left( t\right) +k=f\left( t\right) $. The solution was obtained for $f\left( t\right) =\delta\left( t\right) $ and $f\left( t\right) =0$ and for the same initial conditions $y\left( 0\right) =1,y^{\prime}\left( 0\right) =0$ The answers returned _are the same_ as can be seen by the plots, and also the analytical answers are the same as well.               plot[title_, sol_] :=        Plot[sol, {t, 0, 10}, PlotRange -> All, Frame -> True,         FrameLabel -> {{y[t], None}, {Row[{t, " (sec)"}], title}},         GridLines -> Automatic, ImageSize -> 300];     eq1 = m y''[t] + c y'[t] + k y[t] == DiracDelta[t];     eq2 = m y''[t] + c y'[t] + k y[t] == 0;     parms = {m -> 1, c -> .7, k -> 5};     sol1 = First@DSolve[{eq1 /. parms, y[0] == 1, y'[0] == 0}, y[t], t];     sol2 = First@DSolve[{eq2 /. parms, y[0] == 1, y'[0] == 0}, y[t], t];     Grid[{       {plot["DiracDelta[t]", y[t] /. sol1],         plot["zero RHS", y[t] /. sol2]},       {Simplify[y[t] /. sol1], Simplify[y[t] /. sol2]}       }, Frame -> All]      ![Mathematica graphics](http://i.stack.imgur.com/Ytx5i.png) The analytical answer are the same. When impulse is input, the solution given is               E^(-0.35 t) (1. Cos[2.20851 t] - 0.294317 Sin[2.20851 t] +         0.452795 HeavisideTheta[t] Sin[2.20851 t])      and when the input is zero, the solution given is               E^(-0.35 t) (1. Cos[2.20851 t] + 0.158478 Sin[2.20851 t])      And they are the same since `HeavisideTheta[t]=1` for $t>0$ The correct analytical solution for this differential equation derived by hand is different. And a plot of this solution is compared with the above solutions by Mathematica. Taking the case of underdamped system, the analytical solution is $$ u\left( t\right) =e^{-\xi\omega t}\left( u(0)\cos\omega_{d}t+\frac {u^{\prime}(0)+u(0)\xi\omega}{\omega_{d}}\sin\omega_{d}t\right) +e^{-\xi\omega t}\left( \frac{1}{m\omega_{d}}\sin\omega_{d}t\right) $$ where $\zeta=\frac{c}{2\omega m},\omega_{d}=\omega\sqrt{1-\zeta^{2}}% ,\omega=\sqrt{\frac{k}{m}}$, $u(0)$ and $u^{\prime}(0)$ are the initial conditions. For the parameters in this example, the solution is               parms = {m -> 1, c -> .7, k -> 5};     w = Sqrt[k/m];     z = c/(2 m w);     wd = w Sqrt[1 - z^2];     analytical =        Exp[-z w t] (u0 Cos[wd t] + (v0 + (u0  z w))/wd Sin[wd t] +1/(m wd ) Sin[wd t]);     analytical /. parms /. {u0 -> 1, v0 -> 0}           (* E^(-0.35 t) (Cos[2.20851 t] + 0.611273 Sin[2.20851 t]) *)      Compare the above to the solution by `DSolve` which is given above, here it is again:                (* E^(-0.35 t) (1. Cos[2.20851 t] + 0.158478 Sin[2.20851 t]) *)      Now plotting the above hand derived solution to compare:               Grid[{       {plot["DiracDelta[t]", y[t] /. sol1],         plot["drived", analytical /. parms /. {u0 -> 1, v0 -> 0}]}       }, Frame -> All]      ![Mathematica graphics](http://i.stack.imgur.com/5zR2H.png) The difference can be seen clearly around $t=0$. ![Mathematica graphics](http://i.stack.imgur.com/y9Rpi.png) A unit impulse has the effect of giving the system an initial velocity of $1/m$. In otherwords, a system with an impulse as input, can be replaced by an equivalent free input system by adding to its initial velocity an amount of $1/m$. This is why the initial velocity can not be zero in the solution. The slope of the displacement curve generated by the derived solution shows this, while the solution by DSolve used the zero initial velocity. This is all because `DiracDelta[t]` was basically not used. ps. If I have to post the derivation of the solution done by hand, I can do this as well.


Domain Coloring

My next project I'd like to start working on is Domain Coloring. I am aware of the beautiful discussion at: How can I generate this "domain coloring" plot? And I am studying it. However, a lot of the articles on domain coloring refer back to Hans Lundmark's page at: http://www.mai.liu.se/~halun/complex/domain_coloring-unicode.html So, I would like to begin my work by using Mathematica to draw these three images based on Hans' notes. I'd appreciate if anyone can provide some code that will produce these images, as I could use it to start my study of the rest of Hans' page. ![arg](http://i.stack.imgur.com/FuqMb.jpg) ![abs](http://i.stack.imgur.com/9S0I6.jpg) ![blend](http://i.stack.imgur.com/8cqhp.png) A very small adjustment. Still learning.               g[{f_, cf_}] :=        DensityPlot[f, {x, -1, 1}, {y, -1, 1}, PlotPoints -> 51,         ColorFunction -> cf, Frame -> False];          g /@ {{Arg[-(x + I y)], "SolarColors"},       {Mod[Log[2, Abs[x + I y]], 1], GrayLevel}}          ImageMultiply @@ %      ![scheme-blend-1](http://i.stack.imgur.com/115CH.png) Not sure where to put my current question, so I'll update here. Just came back to visit and discovered some wonderful answers at the bottom of this list. I do understand the opening code:               f[z_] := (z + 2)^2*(z - 1 - 2 I)*(z + I)          paint[z_] :=       Module[{x = Re[z], y = Im[z]},        color = Blend[{Black, Red, Orange, Yellow},          Rescale[ArcTan[-x, -y], {-Pi, Pi}]];       shade = Mod[Log[2, Abs[x + I y]], 1];       Darker[color, shade/4]]      But then I encounter difficulty with the following code:               ParametricPlot[{x, y}, {x, -3, 3}, {y, -3, 3},       ColorFunctionScaling -> False,       ColorFunction -> Function[{x, y}, paint[f[x + y I]]], Frame -> False,       Axes -> False, MaxRecursion -> 1, PlotPoints -> 50, Mesh -> 400,       PlotRangePadding -> 0, MeshStyle -> None, ImageSize -> 300]      I'm good with the first few lines. Looks like ParametricPlot is plotting points, where x and y both range from -3 to 3 (correct me if I am wrong). I also understand the ColorFunctionScaling and the ColorFunction lines. I understand Axes, PlotRangePadding, MeshStyle, and ImageSize. Where I am having trouble is with what PlotPoints->50 and Mesh->400 are doing. First of all, my image size is 300. What does PlotPoints->50 mean? Does that mean it will sample and array of 50x50 points out of 300x300 and scale the results to fit in the domain [-3,3]x[-3,3]? My next question is, then those points get colored? And if so, how are the remainder of the points in the image colored? For example, I tried:               Table[ParametricPlot[{x, y}, {x, -3, 3}, {y, -3, 3},        ColorFunctionScaling -> False,        ColorFunction -> Function[{x, y}, paint[f[x + y I]]],        PlotPoints -> n, MeshStyle -> None], {n, 10, 50, 10}]      And the images got a little sharper as the PointPlots->n increased. Here's another question. What does Mesh->400 do in this situation. For example, I tried lowering the mesh number:               ParametricPlot[{x, y}, {x, -3, 3}, {y, -3, 3},       ColorFunctionScaling -> False,       ColorFunction -> Function[{x, y}, paint[f[x + y I]]], Frame -> False,       Axes -> False, MaxRecursion -> 1, PlotPoints -> 50, Mesh -> 100,       PlotRangePadding -> 0, MeshStyle -> None, ImageSize -> 300]      And was completely surprised that it had an effect on the image, particularly when MeshStyle->None. Here's the image I get: ![today](http://i.stack.imgur.com/4jqEj.png) Why does setting Mesh->100 decrease the sharpness of the image? One final question I have regards adding the mesh lines. Simon suggested   For the mesh you could do something like Mesh->{Range[-5,5],Range[-5,5]}, MeshStyle->Opacity[0.5], MeshFunctions->{(Re@f[#1+I #2]&),(Im@f[#1+I #2]&)} and cormullion added them to produce a beautiful result, but I tried this:               ParametricPlot[{x, y}, {x, -3, 3}, {y, -3, 3},       ColorFunctionScaling -> False,       ColorFunction -> Function[{x, y}, paint[f[x + y I]]], Frame -> False,       Axes -> False, MaxRecursion -> 1, PlotPoints -> 50,       Mesh -> {Range[-5, 5], Range[-5, 5]}, PlotRangePadding -> 0,       MeshStyle -> Opacity[0.5],       MeshFunctions -> {(Re@f[#1 + I #2] &), (Im@f[#1 + I #2] &)},       ImageSize -> 300]      And got this resulting image. ![today2](http://i.stack.imgur.com/zamAO.png) So I am clearly missing something. Maybe someone could post the code that gives cormullion's last image? OK, just purchased and installed Presentations package. Tried this:               With[{f = Function[z, (z + 2)^2 (z - 1 - 2 I) (z + I)],        zmin = -2 - 2 I, zmax = 2 + 2 I,        colorFunction = Function[arg, HotColor[Rescale[arg, {-Pi, Pi}]]],        imgSize = 400},       Draw2D[{ComplexDensityDraw[Arg[f[z]], {z, zmin, zmax},          ColorFunction -> colorFunction, ColorFunctionScaling -> False,          Mesh -> 50, MeshFunctions -> {Function[{x, y}, Abs[f[x + I y]]]},          PlotPoints -> {50, 50}]}, Frame -> True, FrameLabel -> {Re, Im},        PlotLabel -> Row[{"Arg coloring and Abs mesh of ", f[z]}],        RotateLabel -> False, BaseStyle -> 12, ImageSize -> imgSize]]      But got this colorless image. ![today3](http://i.stack.imgur.com/xSlX8.png) Any thoughts on how to fix this?


How to replace Do loops by Inner

I need to replace `Do` loops by something else because it takes forever with big programs. I have been hinted towards `Inner`, but even though I tried, I did not manage to get what I need. Here's a toy example of my actual problem: Input:               u = {{u1a, u1b}, {u2a, u2b}, {u3a, u3b}, {u4a, u4b}};     v = {{v1a, v1b}, {v2a, v2b}, {v3a, v3b}, {v4a, v4b}};     f = {f1, f2, f3, f4};      The output I am looking for:               d = {{u1a*v1a*f1 + u2a*v2a*f2 + u3a*v3a*f3 +u4a*v4a*f4},         {u1b*v1b*f1 + u2b*v2b*f2 + u3b*v3b*f3 + u4b*v4b*f4}}      It is important not to have any loop constructs; only `Inner`, `Table`, etc. which are generally faster than loops


Substitution to write out powers of expressions

I am looking for a substitution command which will write out powers of expressions like this: $$\frac{a ~b^3~ c}{d~ e^{3/2}~ f^2}\to \frac{a ~b~b~b~ c}{d~ e^{1/2}~ e^{1/2}~ e^{1/2}~ f~f}$$ mathematica code to experiment with:               (a b^3 c)/(d e^(3/2) f^2)      Please note, this is needed to carry out substitutions on very large expressions, so that a `ComplexityFunction` is not an option since a `Simplify` will take forever to evaluate. **EDIT** I want to do this since I plan to apply substitutions for expressions like $$\frac{a b}{e^{1/2}}\to q ~~~\text{ and } ~~~\frac{b}{e^{1/2}f}\to p$$ which do not get recognized while all the terms are cluttered into one heap. **EDIT2** Maybe, as some point to start with, I should ask how to make mathematica take some literate input without performing any kind of simplification to it. Such that an input $b+b$ would still display as $b+b$ instead of the automatic $2b$? Is this possible?


How to deal with zero in NDSolve in mathematica?

I would like to solve the following ODEs $$\begin{cases} x'(t)&=y\\\ y'(t)&=-y(t)/t-e^{x(t)},\\\ x(0)&=1,\\\y(0)&=0, \end{cases}$$ ### (EDIT : The second equation _used_ to be $y'(t) = -x(t)/t - e^{x(t)}$). with the following code:               NDSolve[{       {x'[t] == y[t], y'[t] == -y[t]/t - Exp[x[t]]},        {x[0] == 1, y[0] == 0}}       ,       {x, y}, {t, 0, 1}]       I get the warning:               Power::infy: "Infinite expression 1/0. encountered."      How do I fix it? Note that, in some cases, a "small" change of the initial values will make a "large" change in in the solution, so substituting $0$ with a very small number, say $10^{-100}$ is not "good" enough. Are there other ways to fix this?


Specifying coordinates for Inset on a LogPlot

If I use `Epilog->Inset` within a `Plot`, the coordinates specified within that `Inset` match those of the plot's axis and scale:               Plot[y = 2 x, {x, 0, 5}, Epilog -> Inset["Text", {3, 3}]]      ![Plot Epilog Inset](http://i.imgur.com/0pKPcAO.png) Note that "Text" is placed at x=3, y=3. Different thing happens for when `Inset` is used within `LogPlot`:               LogPlot[y = x^x, {x, 0, 5}, Epilog -> Inset["Text", {3, 3}]]      ![LogPlot Epilog Inset](http://i.imgur.com/nt4vqNv.png) The coordinates are still (3,3) but "Text" is positioned at what appears to be (3,20) with respect to the on-axis coordinates. What is it about and how do I counter it? Thanks in advance, r.


Using PutAppend to write large data files

I have a loop which computes a table, `tab`, of results at each iteration. This table is usually very large and I would like to use `PutAppend`or anything of the sort to save the data in a file and therefore saving memory. An example would look like the following:               Put["test.csv"];          Do[tab=RandomReal[{0,1},10];PutAppend[tab, "test.csv"],{5}]      When I import the data in `test.csv` for later use I do this via `data=Flatten[Import[".../test.csv","Data"],1]`. However, the list `data` is not ready to use because typical elements look e.g. like               In[45]:= data[[1]]          Out[45]= "{0.3105121460958056"          In[43]:= data[[2]]          Out[43]= 0.0657094          In[44]:= data[[4]]          Out[44]= " "      Which is a mixture of strings and reals. So my question is: how can I append the table `tab` at each iteration of the loop to a file which later is ready to use as a list of rank two of reals? Thanks for your help.


How to set a function as a parameter?

In case I want to know whether a given function $f(t)$ have some property, I tried to write something like this:               IsSuppFun[f_[t_]] := Resolve[     ForAll[t, 0 <=t <= 2&&t\[Element] Reals,      f[t] + D[f[t], {t, 2}] >= 0]]      Which means, if the given function satisfies the condition: $f(t)+f''(t)\geq 0$ for all $0\leq t\leq 2$, then return TRUE, else return False. The problem is that it is not work as I supposed, for example, if I define               F[t_]:=t^2-3      then the output is:               IsSuppFun[-3 + t^2]      If I separate the code as               Resolve[ForAll[t, 0 <= t <= 2 Pi && t \[Element] Reals, F[t] + F''[t] >= 0]]      Which will get the Right Answer! Where did I go wrong? Solution is use the HoldAll attribute for the function IsSuppFun, Please see below for the answer! * * * there is my another problem in the same line: If I have tried to add another condition as:               SetAttributes[IsSuppFun, HoldAll]     IsSuppFun[f_[t_]] :=      Resolve[ForAll[t, 0 <= t <= 2 && t \[Element] Reals, (f[t] + D[f[t], {t, 2}] >= 0)&&(f[0]==f[2])]]      then with the same test function:               F[t_] := t^2 - 3      the output is not as desired True or False, but as:               \!\(\*SubscriptBox[\(\[ForAll]\), \(t\)]\(! \((0 <= t <= 2 &&  t \[Element] Reals)\)\)\)      * * * May be I should change the last question as (to make things clear and simple):               SetAttributes[{IsSuppFun}, HoldAll]     IsSuppFun[f_[t_]] := Resolve[     ForAll[t,     0<= t <= 2 && t \[Element] Reals,     f[1] >= 0]     ]      with the test function as:               F[t_] := Sin[t]      then the output of               IsSuppFun[F[t]]      is True; But if I have change it as               SetAttributes[{IsSuppFun}, HoldAll]     IsSuppFun[f_[t_]] := Resolve[     ForAll[t,     0<= t <= 2 && t \[Element] Reals,     f[1] <= 0]     ]      Then the same test function gives neither True nor False. (I Suppose it False!) Why?


Calculate inverse laplace transform by integration with four singular points?

I have a function U[s,x] to do inverse Laplace transform for analytical solution, as following               -((km (kp + la + (     E^(-((Sqrt[(-kp + KE la + KE la s)/KE] x)/Sqrt[       la])) (km - kp) (km (kp + la) + la (kp - KE la (1 + s))))/(     KE Sqrt[(-km + KE la + KE la s)/      KE] (km Sqrt[(-km + KE la + KE la s)/KE] -         kp Sqrt[(-kp + KE la + KE la s)/KE]))))/((-km + kp) (-(kp/KE) +      la + la s)))      Where               kp = 1/2 (-1 + KE la - KE s + KE la s + Sqrt[     4 la KE + (1 + KE s - KE la (1 + s))^2])          km = 1/2 (-1 + KE la - KE s + KE la s - Sqrt[         4 la KE + (1 + KE s - KE la (1 + s))^2])      KE and la are positive constants, say KE=100,la= 0.05 Since it contains nested square roots, the direct use of InverseLaplaceTransform was failed. Then I tried Apart followed by direct integration. I have difficulties when calculating residue of the following term:               KE/(2 (-1 + la + la s) Sqrt[4 KE la + (1 + KE s - KE la (1 + s))^2])      It seems have three singular points:               (1 - la)/la,          (-KE + KE la + KE^2 la - KE^2 la^2 -       2 Sqrt[-KE^3 la + 2 KE^3 la^2 - KE^3 la^3])/(KE^2 - 2 KE^2 la +       KE^2 la^2),          (-KE + KE la + KE^2 la - KE^2 la^2 +       2 Sqrt[-KE^3 la + 2 KE^3 la^2 - KE^3 la^3])/(KE^2 - 2 KE^2 la +       KE^2 la^2),       Is there any hints how to calculate the residue with nested square root? Thank you.


How can I avoid label collisions?

> **Possible Duplicate:**   >  How can I influence the spaces between labels on a BarChart How can I avoid label collisions in plot ticks and labels? For example, here is a histogram with colliding frame tick labels:               BarChart[{Labeled[{196}, Row[{"Jan", "Feb 23"}, "-"], Below],        Labeled[{349}, Row[{"Feb 23", "Apr 15"}, "-"], Below],        Labeled[{333}, Row[{"Apr 15", "Jun 6"}, "-"], Below],        Labeled[{308}, Row[{"Jun 6", "Jul 28"}, "-"], Below],        Labeled[{308}, Row[{"Jul 28", "Sep 19"}, "-"], Below],        Labeled[{344}, Row[{"Sep 19", "Nov 10"}, "-"], Below],        Labeled[{162}, Row[{"Nov 10", "Jan"}, "-"], Below]},       GridLines -> {Automatic, None},       BaseStyle -> Directive[FontFamily -> "Bitstream Charter", 10],       BarSpacing -> 0, Ticks -> None, GridLines -> None,       Frame -> {{True, False}, {False, False}}, PlotRange -> All,       BarOrigin -> Bottom, BarSpacing -> None, ChartLayout -> "Stacked",       PerformanceGoal -> "Speed",       ChartStyle -> {Directive[         EdgeForm[{Opacity[1.`], Thickness[Medium], Blue}], Opacity[1.`],          FaceForm[LightBlue]]}]      ![Mathematica graphics](http://i.stack.imgur.com/GXhd9.png) So the question has two parts:   1. How to detect collisions in frame tick labels in general.   2. How to rearrange labels to minimize collisions and optimize for aesthetics. I'm not sure how to do part 1, but part 2 should involve either rotations or columns I guess. I would rather not assume a specific font or size of text, but perhaps this is unavoidable.


Add two Histograms to calculate summed Mean and StandardDeviation

As a follow up to this question: Calculate mean and standard deviation from ImageHistogram I would like to add two histograms before calculating the mean and StDev. I would like to sum the numbers, not superimpose the graphics. Explanation: I have photographed flat samples, they have a front and back side, and so I would like to get 1 outcome/Histogram for both sides summed. Thank you for responding! Edit: We are now using:               hist = ImageHistogram[finalCrop, Appearance -> "Separated"];     Print[hist]; resImage = ImageResize[finalCrop, 200];          (*imagedata=ImageData[finalimage];*)          (*If[Mod[i,2]==0,histF=ImageHistogram[finalcrop,Appearance->\     "Separated"],histB=ImageHistogram[finalcrop,Appearance->\" Separated \     "]];          If[Mod[i,2] == 0, Print[histF],Print[histB]];*)          rgbImage = Transpose@Flatten[ImageData[finalCrop], 1];          (*hist2=GraphicsRow[Histogram/@rgbImage,ImageSize->500];     Print[hist2];*)          table = TableForm[Through[{Mean, StandardDeviation}[#]] & /@ rgbImage,         TableHeadings -> {{"Red", "Blue", "Green"}, {"Mean", "StDev"}}];     Print[table];      And I will the first to admit that I do not completely understand this, but as you can (hopefully) see, we are using histF (front of sample) en histB (back of sample) so then I would use               histTotal = Join @@@ Transpose[{histF,histB}]       followed by               GraphicsRow[Histogram /@ histTotal]      Correct? Am trying it now!


Why is Return not forcing an exit from my function?

Here is simplified version of my code that exhibits the behavior troubling me:               testFn[] := (       Do[        Print[i];        If[i > 3, Print["triggering result for true"]; Return [100]]        , {i, 1, 5}];       Return[200];       )          testFn[]     1     2     3     4     triggering result for true     200      Intuitively, once `i` is bigger than 3, it should evaluate the 2nd argument of the `If` and exit `testFn`, returning 100. However, although the 2nd argument of the If statement is getting evaluated, the function does not exit until it hits the `Return[200]`. I kind of guessed what might be the problem. The Return[100] is just exiting the `Do`, which seems to be confirmed by doing:               testFn[] := (       a = Do[         Print[i];         If[i > 3, Print["triggering result for true"]; Return [100]]         , {i, 1, 5}];       Print["a=" <> ToString[a]];       Return[200];       )          1     2     3     4     a=100     triggering result for true     200      If this is indeed what's happening, how can I make my code actually return from and exit `testFn`?


What can I use as the second argument to Return in my own functions?

Having found out about the second argument to `Return` I played a bit with it, and the following tests all resulted in `Return::nofunc`:               f[x_]:=x     f[Return[3,f]]          SetAttributes[g,HoldAll];g[x_]:=x     g[Return[3,g]]          h[x_]:=f[x]     h[Return[3,f]]          SetAttributes[i,HoldAll];i[x_]:=f[x]     i[Return[3,f]]      On the other hand, the following works fine:               Module[{i},Return[3,Module]]      Does that mean the second argument of `Return` can only be used with a predefined list of symbols? If so, is there an easy way to find out that list? Otherwise, what am I doing wrong (and how would I do it right)?


Reading many single files and creating numbered (? or indexed) variable

I tried many different approaches, but I could not solve the following problems, I appreciate your help: What is the best way to read many data files? I mean we have `file1.dat, file2.dat, file3.dat …`. and I would like to put them in a loop and by using the readlist, import the data, something like what we do in C and `sprintf` or in bash scripting. I have seen that there is a package which can handle `sprintf` functionality in Mathematica, but I am looking for simpler solution something like this: (I just used `$` sign to show what I mean, like bash)               Do[d$i = ReadList["/path/file$i.dat", Number, RecordLists -> True], {i, 1, 5}]      Can I create a variable like `d$i` inside the above loop over i? which creates `d1, d2, …`, and so on, after running the loop? How can I remove the curly braces from `Mean` output? I have a single list and the Flatten does not remove the curly braces.               tt = {1, 2, 3, 4, ...}      Flatten[Mean[tt]] = {1234.1234}


Using one complicated equation to reduce another

(Relative noob here so don't assume much!) I need to use a vector equation (with $N-1$ entries) in the general form $y_j(x_{i,j},x_{i,j+1},x_{i,j-1})=0, i=1...3, j=1...N-1; x_{i,0}=x_{i,N}=0$, which depends fairly complicatedly on the $x_{i,j}$s (etc), to solve another vector equation $w_j(x_{i,j}, x_{i,j+1}, x_{i,j-1}, z_{i,j}, z_{i,j+1}, z_{i,j-1}, r_1,r_2,p_0,p_1)=0, i=1...3, j=1...N-1;$ $z_{i,0}=z_{i,N}=0$, which is fairly fiendish but (when properly factorised) contains several occurrences of $y_j$, that I can therefore eliminate. How do I use $y_j$ to reduce $w_j$? I have tried using `Reduce[expr,var,varlist]`, but I don't want to rearrange the equation 'equal to' anything; I'd rather it equal 0 at the end, but just with the $y$ bits removed; and I also can't really tell what I'm supposed to put into 'varlist' - is it all the argument, including subscripted ones? EDIT - other things I have tried that didn't work:   * `Eliminate[{y==0, w==0}, {Subscript[x,i,j] (etc over j)}]` \- didn't produce anything, had to abort   * `Collect[w==0,y]` \- just spat out $w=0$ fully expanded EDIT2 - Yves - ok, here it comes! Definitions: `m[r_] := Sum[Subscript[m, i]*r^i, {i, 0, 5}] s[r_] := Sum[Subscript[s, i]*r^i, {i, 0, 5}] \[Omega][r_] := Sum[Subscript[\[Omega], i, j]*r^i, {i, 0, 5}] \[Omega]0[r_] := \[Omega][r] /. j -> j - 1 \[Omega]1[r_] := \[Omega][r] /. j -> j + 1 w[r_] := 1 - \[Omega][r]^2 + 1/2*(\[Omega]1[r]^2 + \[Omega]0[r]^2) \[Alpha][r_] := Sum[Subscript[\[Alpha], i, j]*r^i, {i, 0, 5}] \[Alpha]1[r_] := \[Alpha][r] /. j -> j + 1 \[Mu][r_] := Expand[1 - 2 m[r]/r - r^2/(l^2)]` Conditions: `Subscript[\[Omega],0,j] := Sqrt[j*(n-j)] Subscript[\[Omega],1,j] := 0 Subscript[\[Omega],i,0] := 0 Subscript[\[Omega],i,n] := 0 Subscript[\[Alpha],i,0] := 0 Subscript[\[Alpha],i,n] := 0 Subscript[m,0]:=0 Subscript[m,1]:=0 Subscript[m,2]:=0 Subscript[s,1]:=0` Equation: `Expand[Coefficient[-\[Mu][r]*D[\[Mu][r], r]*s[r]^2*D[\[Omega][r], r] -\[Mu[r]^2*s[r]*D[s[r], r]*D[\[Omega][r] - 1/4*\[Omega][r]*(\[Alpha][r] - \[Alpha]1[r])^2 -\[Mu][r]*s[r]^2/r^2*\[Omega][r]*w[r] - \[Mu][r]^2*s[r]^2*D[D[\[Omega][r], r], r], r, 2]]==0` Constraint: `Expand[Coefficient[-\[Mu][r]*D[\[Mu][r], r]*s[r]^2*D[\[Omega][r], r] -\[Mu[r]^2*s[r]*D[s[r], r]*D[\[Omega][r] - 1/4*\[Omega][r]*(\[Alpha][r] - \[Alpha]1[r])^2 -\[Mu][r]*s[r]^2/r^2*\[Omega][r]*w[r] - \[Mu][r]^2*s[r]^2*D[D[\[Omega][r], r], r], r, 0]]==0` which outputs as `2*Subscript[\[Omega][r],2,j]+Subscript[\[Omega][r],2,j-1]*Subscript[\[Omega][r],0,j-1]*Subscript[\[Omega][r],0,j]+Subscript[\[Omega][r],2,j+1]*Subscript[\[Omega][r],0,j+1]*Subscript[\[Omega][r],0,j]-2*Subscript[\[Omega][r],2,j]*Subscript[\[Omega][r],0,j]^2==0` As you'll see, with these above conditions, the constraint reduces down quite a lot, and if you examine the equation, it contains a few mentions of the constraint, or has some of the terms which you could use to replace the constraint with the others. This was one attempt: `Eliminate[{Expand[Coefficient[-\[Mu][r]*D[\[Mu][r], r]*s[r]^2*D[\[Omega][r], r] -\[Mu][r]^2*s[r]*D[s[r], r]*D[\[Omega][r], r] -1/4*\[Omega][r]*(\[Alpha][r] - \[Alpha]1[r])^2-\[Mu][r]*s[r]^2/r^2*\[Omega][r]*w[r] -\[Mu][r]^2*s[r]^2*D[D[\[Omega][r], r], r], r, 2] = 0, r, 2], Expand[Coefficient[-\[Mu][r]*D[\[Mu][r], r]*s[r]^2*D[\[Omega][r], r] -\[Mu][r]^2*s[r]*D[s[r], r]*D[\[Omega][r], r] -1/4*\[Omega][r]*(\[Alpha][r] - \[Alpha]1[r])^2 -\[Mu][r]*s[r]^2/r^2*\[Omega][r]*w[r] -\[Mu][r]^2*s[r]^2*D[D[\[Omega][r], r], r], r, 0] = 0], l != 0, Subscript[s, 0]! == 0, j != 0, j != n}, {Subscript[\[Omega], 2, j], Subscript[\[Omega], 2, j - 1], Subscript[\[Omega], 2, j + 1]}]` Output: `Set::write: Tag Plus in 1/4 (-Sqrt[j (Times[<<2>>]+n)]... Subscript[\[Omega], 4,1+j]) is Protected. >> Set::write: Tag Plus in 0+0+0-2 Subsuperscript[s, 0, 2]... Subscript[\[Omega], 2,1+j]) is Protected. >> Eliminate::eqf: 0 is not a well-formed equation. >>` And another: `Collect[Expand[Coefficient[-\[Mu][r]*D[\[Mu][r], r]*s[r]^2*D[\[Omega][r], r] -\[Mu][r]^2*s[r]*D[s[r], r]*D[\[Omega][r], r] -1/4*\[Omega][r]*(\[Alpha][r] - \[Alpha]1[r])^2 -\[Mu][r]*s[r]^2/r^2*\[Omega][r]*w[r] -\[Mu][r]^2*s[r]^2*D[D[\[Omega][r], r], r], r, 2]], Expand[Coefficient[-\[Mu][r]*D[\[Mu][r], r]*s[r]^2*D[\[Omega][r], r] -\[Mu[r]^2*s[r]*D[s[r], r]*D[\[Omega][r], r] -1/4*\[Omega][r]*(\[Alpha][r] - \[Alpha]1[r])^2 -\[Mu][r]*s[r]^2/r^2*\[Omega][r]*w[r] -\[Mu][r]^2*s[r]^2*D[D[\[Omega][r], r], r], r, 0]]]` (did nothing i.e. returned output fully expanded.)


How to group the powers of one variable?

Consider the following expression: $\sqrt{a x} \sqrt{b x}$ What do I use to make it simplify to: $\sqrt{ab} x$ I tried actually everything (Simplify, FullSimplify, Collect and so on...) and such expressions remain unchanged. Thanks in Advance and Regards, Misery


Dynamic content Aborts in Mathematica 10

I have written a notebook in v9 that contains dynamic content (a `Manipulate`). I just downloaded V10. If I double click on the notebook, of course it is opened by v10, but the dynamic output does not look correct and then it aborts this output of `Manipulate`. I then open it with v9 and everything is ok. What is happening?


integro differential equation

> **Possible Duplicate:**   >  Integro-differential equation I have to solve an Integro-differential equation with Mathematica or Matlab, in the following form:               Dy/Dt = Integral[K(x,u)(D2y/Du2) du] + Sin(y)      The function `K(x,u)` is known, as well as the initial conditions. I have no clue how to solve this; can anyone give me some pointers?


Is there a Mathematica API for the functions.wolfram site?   If there's not, has anyone implemented a web scraper for it? For example it would be nice to be able to access http://functions.wolfram.com/07.23.17.0081.01 from within Mathematica by using something like               In[1]:= FunctionsWolfram["07.23.17.0081.01", InputForm]     Out[1]= Hypergeometric2F1[a,b,a+b-1/2,z]             == Hypergeometric2F1[2 a-1,2 b-1,a+b-1/2,1/2 (1-Sqrt[1-z])]/Sqrt[1-z]          In[2]:= FunctionsWolfram["07.23.17.0081.01", RuleForm]     Out[2]= HoldPattern[Hypergeometric2F1[a_,b_,a_+b_-1/2,z_]]              :> Hypergeometric2F1[2 a-1,2 b-1,a+b-1/2,1/2 (1-Sqrt[1-z])]/Sqrt[1-z]          In[3]:= FunctionsWolfram["07.23.17.0081.01", TraditionalForm]     Out[3]=      ![Image_from_http://functions.wolfram.com/07.23.17.0081.01](http://i.stack.imgur.com/vDu9w.gif)


Is FinancialData for India available?

FinancialData["IndiaNSE", "Members"] // Shallow      gives               {"^CNXIT", "^CRSLDX", "^CRSMID", "NS:20MICRONS", "NS:3IINFOTEC", \     "NS:3MINDIA", "NS:526015", "NS:AARTIDRUG", "NS:AARTIIND", \     "NS:AARVEEDEN", <<1432>>}      But when I query               FinancialData["NS:20MICRONS"]      I get the following error                FinancialData::notent: NS:20MICRONS is not a known entity, class, or tag for       FinancialData. Use FinancialData[] for a list of entities. >>      Interestingly I tried the same query on Wolfram Alpha http://www.wolframalpha.com/input/?i=FinancialData[%22NS%3A20MICRONS%22] I got this **Assuming 20MICRONS | Use 533022 instead** I tried               FinancialData["MB:533022"]      and I got the same error! Is this expected ?


Double helices inside an ellipsoidal cavity

This question may be related to a previous query at Plotting a contour on a torus My question is how do you enclose double helix structures (see demonstrations.wolfram.com/DoubleHelix ) inside an ellipsoidal cavity and also within a torus. Following the examples in the previous query, I show a typical case below for the torus, but the coils are not in phase:               With[{rr = 3, r = 1},        torus[{u_, v_}] := {(rr + r*Cos[2*Pi*u])*          Cos[2*Pi*v], (rr + r*Cos[2*Pi*u])*Sin[2*Pi*v], r*Sin[2*Pi*u]}]*        (gr = ContourPlot[          Re[2*Exp[4*Pi*I*(x + 2*y)] + 3*Exp[4*Pi*I*(x - 2*y)]] == 0, {x,            0, 1}, {y, 0, 1}]; )*        (gr1 =          ContourPlot[          Re[2*Exp[4*Pi*I*(x - 2*y)] + 3*Exp[4*Pi*I*(x + 2*y)]] == 0, {x,            0, 1}, {y, 0, 1}]; )*        Show[ParametricPlot3D[torus[{u, v}], {u, 0, 1}, {v, 0, 1},         PlotStyle -> Directive[Opacity[0.3], Red], Mesh -> None],           Graphics3D[{Blue,          Cases[Normal[gr], Line[__], Infinity] /.           Line[pts_] :> Tube[torus /@ pts]}],           Graphics3D[{Red,          Cases[Normal[gr1], Line[__], Infinity] /.           Line[pts_] :> Tube[torus /@ pts]}]]!      ![enter image description here](http://i.stack.imgur.com/cgfaN.png)


Wrapping a rectangle to form a cylinder

I'd like to make an animation showing how we wrap a rectangle to form a cylinder (by joining a pair of parallel sides). Here's my first pass:                Manipulate[         ParametricPlot3D[         t {Cos[theta], Sin[theta], rho} + (1 - t) {rho, -1, theta},          {theta, -Pi, Pi}, {rho, 0, 2},          PlotRange -> {{-1.5, 1.5}, {-1.5, 1.5}, {-1.5, 1.5}},          PerformanceGoal -> "Quality", ViewPoint -> {-2.3, 0.77, -2},          ViewVertical -> {-0.08, 1, -0.06}],       {t, 0, 1}]      I'd much prefer the simpler looking transformation (without the twists this animation shows) which we'd do by simply rotating the pair of parallel sides until they touch to form the cylinder.


plotting evolution of points in the same plot

I am trying to plot the points (i,j,k) as they are generated in the loop but in the same plot. The next draws the points in different windows.               list = {};     Do[list = Append[list, {i, j, k}];       Print[ListPointPlot3D[list]], {i, 3}, {j, 3}, {k, 3}]      Is there any function in Mathematica that allows us to draw plots dynamically, i.e., keeping the plots that were already generated as new ones are being generated from a loop (all in the same window)?


How to extract the numerical value of a dynamical variable

I want to inspect interactively an image by selecting points by the mouse pointer. This is easily done by `LocatorPane` \- here is a simplified example:               plot = ListPlot[{{1, 1}}];     Manipulate[       x = Dynamic[First[pt]];       LocatorPane[Dynamic[pt],           Show[plot, Epilog -> {Red, PointSize[Large], Point[Dynamic[pt]],          Text[Style[StringForm["x = `1`", x], Blue, 20], {1, 1.5}]}]],       {{pt, {0, 0}}, None}      ]      ![Mathematica graphics](http://i.stack.imgur.com/LiXAg.png) Now imagine that for a selected point I would like to get the numerical value of the x-coordinate. I would like to calculate a function of it (like divide by 3) and/or save its numerical value to an external data file. This does not work because the x is a dynamical object. How to extract the current numerical value of x? In addition to solving this particular problem I would like to understand better how does Dynamic really work.


Return Values from DynamicModule

I found the answer to my question here. How to extract the numerical value of a dynamical variable Is it possible to have the return value from a `DynamicModule` be just the value and not the whole `DynamicModule` definition? Here is a (much) simplified version of the problem that I am having. The actual code has several interacting `Dynamic` variables that provide the end result.                   func[var_List] := DynamicModule[            {insideFunc, choice},            insideFunc = RadioButtonBar[Dynamic[choice], var];            DialogInput[             {},             Row[{insideFunc, Button["Return", DialogReturn[choice]]}]             ]            ];      Now, if I call `func` with a simple list, the output that I get is indeed the answer that I chose (2),                   In[63]:= func[{1, 2, 3}]              Out[63]= 2      But in the end I want to write this piece of data to a file for later use, and upon doing that, I find that really that simple little number 2 is the actual `DynamicModule`, here illustrated by `FullForm`.                   In[64]:= % // FullForm              Out[64]//FullForm=          DynamicModule[          List[Set[insideFunc, RadioButtonBar[Dynamic[choice], List[1, 2, 3]]],            Set[choice, 2]], 2, RuleDelayed[DynamicModuleValues, List[]]]      So, is there a way to back out the end value rather than the `DynamicModule`? A naive attempt to just use `Evaluate` failed. Also, I have played around with putting the `DialogInput` on the outside of the `DynamicModule` and in my particular case, a variety of things break in the various dynamic actions when I do that. While I have played around trying to debug those errors, it was to no avail. Hmmm, I should have done a little bit better research in this wonderful database, because about 1 minute after my original posting, I stumbled on the right answer. To fix the problem I simply needed to use `Setting` as you can see below.                   In[75]:= % // Setting // FullForm              Out[75]//FullForm= 2      Hopefully, my title will help somebody find this answer in the future.


How to extract value from dynamic list?

> **Possible Duplicate:**   >  How to extract the numerical value of a dynamical variable   >  Dynamic wraps a list that I cannot extract values from I want to extract value from list dynamically,this is my code               xData = {"Environment", "Building"};     DynamicModule[{},       Row[{tabP1 =          Dynamic[Position[xData, ToString[buttonValue]],           t = tabP1[[1, 1]]]}]]     Button[button1, buttonValue = Environment] Button[button2,        buttonValue = Building]      It gives `{{1}}` or `{{2}}` based on button i have clicked. Now i want to extract value(1) from this list(`{{1}}`) . I have tried to extract it as follows `t=tabP1[[1,1]]` but t has list(`{{1}}`) not value(1). I need value instead of list.


Getting value of clock

I have the following code:               a = Dynamic[Floor[Clock[2]]] (*So this basically alternates between 0 and 1*)     If[a==1, Print["true"]]      But this doesn't work, it instead prints the following `If[a==0, Print["true"]]` and then changes to `If[a==1, Print["true"]]` and then back. How can I get the value from the clock?


Undocumented overload for Graph?

I stumbled (here, in the expression for the block diagram) upon a version of Graph that I don't see in the documentation over here. That documentation admits three overloads (the following are in my own words):   1. `Graph[{` _edges_`}]`   2. `Graph[{` _vertices_`}, {` _edges_`}]`   3. `Graph[{` _decoratedVertices_`}, {` _decoratedEdges_`}]` For instance, the following example invokes overload 2:               Graph[{1,2,3}, {{1, 2}, {1, 3}, {2, 3}}]      ![enter image description here](http://i.stack.imgur.com/8tfwu.png) If I add a `Null` in an undocumented place, I get arrows:               Graph[{1,2,3}, { {{1, 2}, {1, 3}, {2, 3}}, Null } ]      Notice there is an extra level of `List` in the list of vertices. It's as though the list of vertices contains a nested list of vertices and a Null vertex. This seems to produce similar results to               Graph[{1, 2, 3}, {1 \[DirectedEdge] 2, 1 \[DirectedEdge] 3, 2 \[DirectedEdge] 3}]      Anyone happen to know what's going on? I'm ok with blindly using the cool feature, but I wonder what the other options for this API might be. ![enter image description here](http://i.stack.imgur.com/fxs14.png)