Cluster a signal into areas of equal intensity

**Introduction** I have a greyscale photograph that I want to partition into areas of equal intensity. This means, that the integral over each partition should be (roughly) equal. There is no unique solution to this problem, but although I have some ideas on how to implement it, I am looking for any effective solutions for _bitmap_ input. **1D-example** Let f be my signal, and g it's strictly positive, "padded" version:               f[x_] = 0.2 Cos[5 x] + Sin[x];     const = First[Minimize[f[x], {x}]];     g[x_] := 0.1 + f[x] - const;     G[x_] = Integrate[g[s], {s, 0, x}];      My signal is now of total intensity               max = F[4 \[Pi]];      and I can divide my y-axis into equal segments               k = 20;     sols = Table[FindRoot[G[x] - y == 0, {x, y}], {y, Range[0, max, max/(k - 1)]}];      and by intersecting these segments with my integral curve, I can project to the x-axis and get my desired intervals:               Show[      {       Plot[{g[x], G[x]}, {x, 0, 4 \[Pi]}, PlotStyle -> {{Thick, Green}, Red}],       Graphics[Point[{#, G[#]}] & /@ (x /. sols)],       Graphics[Line[{{0, G[#]}, {#, F[#]}, {#, 0}} & /@ (x /. sols)]]       }      ]      Which gives me ![Mathematica graphics](http://i.stack.imgur.com/P8Ohe.png) **2D-case** I can imagine that this method generalises to 2D, but it is unclear how to implement it. Also, a big penalty comes from attempts at interpolating the image. Another idea is to use Sasha's solution for sampling a probability distribution (in my case, the image itself): RandomVariate from 2-dimensional probability distribution Thereafter one can generate the Voronoi-diagram for the sample. However, I have been unable to create a feasible solution using this method as well. It seems to me, that this is a problem better approached by a combination of image processing algorithms. After all, all my input is, is a bitmap. However, after researching this, I could not find a previous description of the problem (or a solution for that matter) in any of the image-processing communities. **Questions**   1. Does this problem have an actual name in the community already?   2. Can I find an efficient way of clustering a signal, preferably working on the discrete data, into regions of similar intensity?   3. (Bonus points) Can I generate grids with nice combinatorics? There is a nice Z-combinatorics for the 1D-example of course. Although a Z^2 grid for the 2D-case is too much to ask, perhaps there is a way to get a Quadtree-looking grid?


Symbolically solve and Plot equation involving Tan

I currently have the equation below for a beam with a hinge at various locations, the variable a can vary between 0 and 0.5. $$ Tan\left( {a\sqrt \alpha } \right) + Tan\left\{ {\left( {1 - a} \right)\sqrt \alpha } \right\} - \sqrt \alpha = 0 $$ I wanted to use this equation to replicate the figure below: ![Taken from Exact Solutions for Buckling of Structural Members](http://i.stack.imgur.com/LG9YZ.png) My first thought was to solve the equation so that a= whatever the equation became and then I could plot this to replicate this graph. I've tried a few different ways to solve this equation but I'm being repeatedly told: > Solve::nsmet: This system cannot be solved with the methods available to > Solve. A few of the methods I've tried are below...               Solve[Tan[a*Sqrt[α]] + Tan[(1 - a)*Sqrt[α]] == Sqrt[α], a]          Reduce[Tan[a*Sqrt[α]] + Tan[(1 - a)*Sqrt[α]] == Sqrt[α], a]          Solve[TrigExpand[     Tan[a*Sqrt[α]] + Tan[(1 - a)*Sqrt[α]]] == Sqrt[α], a]          Reduce[     Tan[a*Sqrt[α]] + Tan[(1 - a)*Sqrt[α]] == Sqrt[α] && Element[     {a, α}, Reals], a]      Frustratingly a colleague has managed to get the equation to be rearranged with a as the subject but not with alpha as the subject using _MathCAD_ and then I can see that for certain circumstances the solutions are complex. For completeness the solutions using _MathCAD_ are below: $$ a=a\tan \left( {\frac{{\frac{{\sqrt \alpha }}{2} - \frac{{\sqrt {\frac{{\alpha \tan \left( {\sqrt \alpha } \right) - 4\tan \left( {\sqrt \alpha } \right) + 4\sqrt \alpha }}{{\tan \left( {\sqrt \alpha } \right)}}} }}{2}}}{{\sqrt \alpha }}} \right) $$ and $$ a=a\tan \left( {\frac{{\frac{{\sqrt \alpha }}{2} + \frac{{\sqrt {\frac{{\alpha \tan \left( {\sqrt \alpha } \right) - 4\tan \left( {\sqrt \alpha } \right) + 4\sqrt \alpha }}{{\tan \left( {\sqrt \alpha } \right)}}} }}{2}}}{{\sqrt \alpha }}} \right) $$ My questions for this I guess are:   1. How can I can rearrange and solve equations of this type? _Helping me understand why a simple Solve[] struggles with this would also be genuinely appreciated to help improve my understanding in Mathematica_   2. How to recreate the plot once solved? _(I'm not concerned with the smaller diagrams that have been added, I will do that myself in illustrator)_   3. Eventually I'm going to want to find the precise maxima of this and similar equations and I'm hoping that will be fairly straightforward once I've got the equation to rearrange into a more convenient format.


GraphPlot only working when I evaluate twice

I have some code that builds a graph and some vertex coordinates, but when I evaluate it I get a message that the list of coordinates is not valid and the graph is not valid and it shows the output as an unevaluated GraphPlot. Then if I evaluate the unevaluated GraphPlot manually it works fine. I have tried using Evaluate manually, but no luck. I evaluate this:               GraphPlot[edges, VertexCoordinateRules -> coords]      I get these: > GraphPlot::vpr: Value of option VertexCoordinateRules -> > {{1,2,3,4,5,6,7,8,9,10,11}->{1.,1.79586*10^-10},{1,10,3,11,7,6,5,9,8,2,4}->{0.,2.6938*10^-10},{8,9,4,1,2,5,7,3,6,10,11}->{2.,0.}} > is not a valid list of coordinate rules. >> > > GraphPlot::grph: > {{1,2,3,4,5,6,7,8,9,10,11}->{1,10,3,11,7,6,5,9,8,2,4},{1,2,3,4,5,6,7,8,9,10,11}->{8,9,4,1,2,5,7,3,6,10,11},{1,10,3,11,7,6,5,9,8,2,4}->{1,2,3,4,5,6,7,8,9,10,11},{1,10,3,11,7,6,5,9,8,2,4}->{9,8,11,1,10,7,5,3,6,2,4},{8,9,4,1,2,5,7,3,6,10,11}->{3,6,1,8,9,2,7,4,5,10,11},{8,9,4,1,2,5,7,3,6,10,11}->{8,10,4,11,7,5,2,6,3,9,1}} > is not a valid graph. >>               GraphPlot[{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11} -> {1, 10, 3, 11, 7, 6,          5, 9, 8, 2, 4}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11} -> {8, 9, 4,          1, 2, 5, 7, 3, 6, 10, 11}, {1, 10, 3, 11, 7, 6, 5, 9, 8, 2,          4} -> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, {1, 10, 3, 11, 7, 6, 5,          9, 8, 2, 4} -> {9, 8, 11, 1, 10, 7, 5, 3, 6, 2, 4}, {8, 9, 4, 1,          2, 5, 7, 3, 6, 10, 11} -> {3, 6, 1, 8, 9, 2, 7, 4, 5, 10, 11}, {8,          9, 4, 1, 2, 5, 7, 3, 6, 10, 11} -> {8, 10, 4, 11, 7, 5, 2, 6, 3,          9, 1}}, VertexCoordinateRules -> {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10,           11} -> {1., 1.79586*10^-10}, {1, 10, 3, 11, 7, 6, 5, 9, 8, 2,           4} -> {0., 2.6938*10^-10}, {8, 9, 4, 1, 2, 5, 7, 3, 6, 10,           11} -> {2., 0.}}]      Then if I manually evaluate the output it works fine. Here is the full code. I haven't figured out a smallest repro yet.               {op1, op2} = GroupGenerators@MathieuGroupM11[];     elems = {Range[11]};     edges = {};     coords = {};     frames = {};     frames = Reap@       While[Length@elems < 10,         AppendTo[elems, Permute[#, op1]]; AppendTo[elems, Permute[#, op2]];           AppendTo[edges, # -> Permute[#, op1]];           AppendTo[edges, # -> Permute[#, op2]]; & /@ elems;         elems = Union[elems]; edges = Union[edges];         Sow[g = GraphPlot[edges,            VertexCoordinateRules ->             If[Length@coords > 0, coords, Automatic]]];        coords =          Union[coords,           Rule @@@            Transpose@{Cases[g, Tooltip[_, a_] -> a, Infinity],              Cases[g, (VertexCoordinateRules -> a_) -> a,                Infinity][[1]]}];]


How to find this limit correctly?

How to find the limit               Limit[n*Sin[2*Pi*Exp[1]*n!], n -> Infinity]    ?      Mathematica 10 outputs                Interval[{-\[Infinity], \[Infinity]}]      which is not correct since the one equals $2\pi$, being a known limit.


How often does Mathematica contact its license server?

I know that Mathematica checks the validity of its license every time the program is launched. Say, however, that I have a valid license (which I do) and that I am running some code which takes a long time to evaluate and includes multiple separate instructions being sent to the kernel (i.e. not all in a single cell evaluation). If the license server in my institute goes down will Mathematica continue to run without error as long as I keep the program open or will it immediately give an error and cease operation? In brief: Does Mathematica check its license only at launch or continually while it is open? Theres no license tag apparently....


Simple differential equation to solve

Suppose we have this differential equation: $$ x^2 + y^2 + z^2 = \frac{\frac{\partial y}{\partial x}}{x+y+z}$$ I want to find $\frac{\partial y}{\partial x}$ at x=1,y=1,z=1. I tried this code but doesn't work..               eqn[x_, y_, z_] := x^2 + y^2 + z^2 == D[y[x, z], x]/(x + y + z)          Solve[ eqn[1, 1, 1], D[y[x, z], x] ]      I get an error saying "General::ivar: 1 is not a valid variable." I restarted mathematica and the error persists. * * * Too long for a comment - Your answer works, but I improvised this to my current problem and it doesn't seem to work..               Clear["Global`*"]     C1 = 10^(-10);     C2 = 0.1*C1;     R = 50;     Tb = 0.1;     Geb = 5*10^-15;     Z0 = 50;     L[Te_] := 10^-9 + 10^-9*(Te - 0.1);     Zlcr[Te_, w_] := (1/R + 1/(I*L[Te]*w) + I*C1*w)^-1;     Zload[Te_, w_] := -I*w*C2 + Zlcr[Te, w];     \[CapitalGamma][Te_, w_] := (Zload[Te, w] - Z0)/(Zload[Te, w] + Z0);     x[Te_, w_] := Abs[\[CapitalGamma][Te, w]];     y[Te_, w_] := (Abs[\[CapitalGamma][Te, w]])^2;               eqn1 [Te_, Pprobe_, w_] := 1 - 2 Pprobe*D[x[Te, w], Plocal] ==  Geb*D[Te, Plocal]     a = Solve[eqn1 [Te, Pprobe, w], D[Te, Plocal] ]     b = D[Te, Plocal]  /. a     b /. {Te -> 1, Plocal -> 1, w -> 1}


Adding Lists Together

This is something that should be simple, but the documentation and other questions don't seem to deal with it. I can think of mechanically doing it through a loop, but I know there must be a better way. In this example, I have three lists (although the actual operation will involve several sets of 20-30 each, and they're much longer):               list1={1,5,5,5,5,6};     list2={2,1,2,2,2,2};     list3={3,3,3,3,3,3};      What I need to do is add them together - as in all the first positions of the three lists being added together, all the second positions, and all the third positions, so that I just have say:               list4={6,9,10,10,10,11};      The actual order of the list is important (I'm using it to store data). Thanks in advance.


FindClusters giving wrong groupings

I am having trouble getting `FindClusters` to find the right clustering for this set of data (and many other sets of data similar to it):               mydata=  {{0.0393548, 518600.}, {0.0878788, 338.}, {0.113012, 4479.63},               {0.120947, 7030.38}, {0.121241, 2112.75}, {0.12131, 3114.},               {0.128903, 3528.63}, {0.151097, 2857.25}, {0.154496, 5622.75},               {0.167173, 1662.88}, {0.167782, 4528.25}, {0.52439, 85.875},               {0.771838, 776.875}, {0.989017, 1857.63}, {1., 629.875},               {1., 147.125}, {1., 523.5}, {1., 51.75},  {1., 33.},               {1., 571.125}, {1., 899.75}, {1., 1196.38},{1., 3080.}}      By eye, when this data is plotted with `ListLogLogPlot`, there are three reasonably clear clusters, with one cluster being the single point in the upper-left part of the plot on the y-axis (sorry it's hard to see): ![enter image description here](http://i.stack.imgur.com/RkD3c.jpg) However, I can't seem to get `FindClusters` to find the right groupings even when I tell it there are three clusters (it also fails when I try to get the clustering without any specified number of clusters) :               Length /@ FindClusters[myData, 3]          {3, 14, 6}  (* correct output would be {1, 10, 12} *)      I've tried some renormalizations and log transformations of the data but I still can't get the correct groupings using `FindClusters`. Any suggestions for how to get this right?


Can StringTemplate be extended to offer printf-like formatting capabilities?

Apparently, Mathematica has no real sprintf-equivalent (unlike any other high- level language known to man). This has been asked before, but I'm wondering if the new `StringTemplate` function in Mathematica 10 can be extended to include such formatting capabilities. What I have in mind is a function that takes a `TemplateObject`, and looks for "formatting specification strings" immediately after `TemplateSlot`'s and `TemplateExpression`'s and replaces them with `TemplateExpression`'s containing appropriate formatting code. So, for example, you could write:               st = applyFormat@StringTemplate["Number: `1`%.2 some other text"]      and you would get something equivalent to:               TemplateObject[{"Number: ",        TemplateExpression[ToString[NumberForm[TemplateSlot[1], {\[Infinity], 2}]]],        " some other text"}, InsertionFunction -> TextString,       CombinerFunction -> StringJoin]      I'm not particularly picky about the syntax (it doesn't have to mimic sprintf), as long as:   * it's easy to write and easy to read   * it supports Mathematica's number formatting functions (`AccountingForm`, `ScientificForm`...)   * it's extensible (e.g by delegating the formatting to a pattern that can be overwritten/extended)   * it's compatible with existing `StringTemplate` templates I've started a function that does this, but I'm curious if you have better ideas (both implementation- and syntax-wise), so I'm posting it as an answer, not as part of the question.


Selecting multiple columns from a matrix?

Sample data:               data = {        {{2013, 1, 1}, 24.13, 167.67, 231.82},        {{2013, 1, 2}, 32.15, 170.92, 225.99},        {{2013, 1, 3}, 35.43, 172.68, 221.67},        {{2013, 1, 4}, 36.73, 173.05, 218.32},        {{2013, 1, 5}, 58.19, 165.96, 197.05},        {{2013, 1, 6}, 69.99, 163.50, 187.52},        {{2013, 1, 7}, 71.37, 154.21, 175.58},        {{2013, 1, 8}, 72.51, 149.66, 163.25}};      I want a `DateListPlot` with three graphs, so for a matrix formed by columns 1 and 2, one for columns 1 and 3, and 1 for columns 1 and 4. At the moment I'm using this code:               data2 = Transpose[{data[[All, 1]], data[[All, 2]]}];     data3 = Transpose[{data[[All, 1]], data[[All, 3]]}];     data4 = Transpose[{data[[All, 1]], data[[All, 4]]}];     DateListPlot[{data2, data3, data4}, Joined -> True, Filling -> {3 -> {1}}]      but I have a hunch that this can be done more efficiently. I don't like the `Transpose`s in particular. Any ideas?    **edit** (for extra credit)   What if I need to multiply the second column by 2, which in my solution is simply               data2 = Transpose[{data[[All, 1]], 2 * data[[All, 2]]}];


Plotting Surface Graph from Excel Data Import to Mathematica

I am trying to make a surface graph on Mathematica using Excel Data. My x-axis should be the "A" Column and my y-axis should be the "1" Row. The box of data in between the x-axis and the y-axis should be my z-values. I'm not familiar with data importing Excel data to make these types of 3-D graphs. I was wondering if someone could help me out? Thanks! ![What I am Trying to Graph](http://i.stack.imgur.com/JA3dy.png)


Adding an image background to a graph that uses vertexposition

Hello Mathematica stackexchange community! I need your help on a research project. I'm looking to create a graph **g** with vertices in specifies places and then use an image I have as the background of the graph. However I want the vertices to be positioned relative to the image background. Let me use the code from another question here: **"How to impose custom style to the edges of a graph"** asked on Feb.29.1012 by PlatoManiac. Link to the question here: How to impose custom style to the edges of a graph Let's use the graph that he generates:               node = {11, 12, 13, 14, 15, 16};     edges = {11 -> 14, 11 -> 16, 12 -> 16, 12 -> 15, 13 -> 15, 13 -> 16,           14 -> 16, 14 -> 15, 15 -> 16, 15 -> 13, 16 -> 15, 16 -> 14};     vertexposition = {{6.51493919050084`, 44.04756585632944`},      {75.59445680043342`, 50.47455242214042`},      {87.32825501506514`, 13.395648943951699`},      {28.795707353492418`, 3.420138063734413`},      {60.729164933330765`, 16.915777496473908`},      {51.85158892659126`, 25.803692768150313`}};          Show[     Graph[node, edges, VertexCoordinates -> vertexposition,            VertexSize -> {"Scaled", .02},VertexLabels -> "Name"],     Frame -> True, FrameTicks -> True, ImageSize -> 600]      My question is then... How can I make the background of this graph be the image that I want, the federal district of Brazil (linked to an image of it here:http://www.wolframalpha.com/share/clip?f=d41d8cd98f00b204e9800998ecf8427e53vfptvv3q) However I want to import my own image and not necessarily call it from the wolfram server, just using it now for the example. But be able to reduce the size of the image such that the vertices change relative to the background image. My first thought for this is that I need to make the vertices be a percentage instead of an exact coordinate. The second part of the question is how can I designate the precise location for **certain nodes** and not others. For example If I make two nodes (two cities) and they are connected by a water pump in-between the cities as shown here: http://www.wolframalpha.com/share/clip?f=d41d8cd98f00b204e9800998ecf8427eetdfek9rli I only want a fixed coordinate for the two cities (acting as A & C) but don't care where the "B" node (or nodes) ends up lining up (if it changes anything, it will be a directed & weighted graph). I can't post images yet so I created them in wolfram alpha and put their links.


Handling holidays in financial time series

I have two lists: `list1`and `list2`, which are financial time series with only 2 variables—date and price. The problem is: these financial time series occur in 2 different countries, which have holidays on different days. For instance, if the first list is related to an asset in the US, there will be no data for this asset on July 4th (due to the American national holiday).   So the **first** need here is to FILL this missing (price-)values with the price of the previous date.   The **second** need is to COMPARE these lists, which have different dimensions due to different national holidays occurring on different dates for each country. In this case, some dates (with corresponding price values) must be _included_ in the lists. Let me give an example. Consider:               list1 = {{{2007, 1, 2}, 12.04}, {{2007, 1, 4}, 11.51}, {{2007, 1, 5}, 12.14}}     list2 = {{{2007, 1, 2}, 20.91}, {{2007, 1, 3}, 24.34}, {{2007, 1, 4}, 24.67},              {{2007, 1, 5}, 20.97}}      In this case it will be necessary to include in `list1` the observation `{{2007, 1, 3}, 12.04}`. Any idea of how can I do this in _Mathematica_? * * * ## Edited Please consider the following real time series:               list1 = FinancialData["PETR4.SA", {"2007"}];     list2 = FinancialData["XOM", {"2007"}];      Now consider the Dimensions of both lists:               Dimensions[list1]     {245, 2}          Dimensions[list2]     {251, 2}      I need to create `Modlist1` and `Modlist2`, so that both have `Dimensions[]` of order {257, 2}. This means: I need to include 12 observations in `list1` and 6 observations in `list2` to obtain the modified lists, both of same `Dimensions[]`.


Generate effective C/Java code (minimizing operations)

Is it possible to generate C/Java code with Mathematica so that it minimizes number of operations performed? For example, for matrix inverse or determinant? With good caching variables?


How to increase Maximum number of steps in any other functions except NDSolve?

I want to plot an output response from a state space model. I use `StateResponse[]` to calculate it and then plot it. When I run my code, I face this message: > NDSolve::mxst: Maximum number of 10000 steps reached at the point t == > 0.007796405242565201`. I do not even use `NDSolve[]` command to solve my equations! This is my code and its answer: `u = -kk.StateResponse[ssmModelC, UnitStep[t] , {t, 0, 10}]` How is it possible to increase number of steps in `StateResponse[]`?


What information is sent to Wolfram Research when loading or working with Mathematica?

Recently I am told that information unknown to the user is sent to Wolfram Servers. Is there any truth behind it ? I was told that more than just an IP address of the user is sent to them and that they catalogue all info and built a database from it. Even if you do not click on "internet connectivity option" info is sent to them. **Update** Question applies to three parts to make it easier to answer.               a) Mathematica on Raspberry Pi     b) Cloud Mathematica     c) Mathematica that can be installed on your personal computer      The answer to (a) and (b) are blatantly clear because the Wolfram Corporation takes control over the computation through their own servers. So they can hear, see and infer every bit of what's happening. For (c) is **fishy** what is going on and how the data is being used by Wolfram Corp. Just think of what can be deduced from I.P. data, USER ID and MACHINE ID AND HELP FUNCTION BROWSING EVERY TIME YOU USE Mathematica. This is metadata that Wolfram Corp has no real hesitation admitting to gathering. Wolfram Corp can profile user and possibly predict what she will do ? a not so hypothetical example. what if we know it was sold to research division who control and make policy. Based on user patterns here and there simple info will help us predict whether they will do this or that ... Banks, federal banks, Bank of England ? whether they will raise interest rates or cut them, other policy institutions. A simple footnote privacy http://www.wolfram.com/legal/privacy/wolfram- mathematica.html pointer is not really an answer to what is going on here.


The OpenCL documentation examples are not working, what does CUDAFunctionLoad::cmperr mean?

I just updated to the latest CUDA drivers and the documentation examples stopped working. I'm using the latest Mathematica, OpenCLQ is True and the error is:               CUDAFunctionLoad::cmperr: -- Message text not found --              (clang: error: unsupported option '-dumpspecs') >>          CUDAFunctionLoad::cmperr: -- Message text not found --              (clang: error: no input files) >>      I'd appreciate any ideas or help on this.


Built in way to de-list singletons?

Is there a built in method to de-list singleton expressions, like this rule- based solution:               expr_ :>  If[Length[expr] == 1, First@expr, expr]      In data analysis, this comes in handy to normalize the output of `Cases`, since a single exact match will be wrapped in a list, but wrapping that in `First` would break no-match cases and non-singleton lists.


Approximate solution to system of polynomial equations

I'd like to solve approximately the following system of equations for $a_1$, $a_2$, $\alpha_1$ and $\alpha_2$ all real and nonzero: $a_1(1+4\alpha_2)^3+8a_2(1+4\alpha_1)^2+\frac{\sqrt{\pi}}{64}(1+4\alpha_1)^2(1+4\alpha_2)^3=0$ $a_1(1+4\alpha_2)^5+16a_2(1+4\alpha_1)^4-\frac{11\sqrt{\pi}}{512}(1+4\alpha_1)^4(1+4\alpha_2)^5=0$ $a_1(1+4\alpha_2)^7+24a_2(1+4\alpha_1)^6-\frac{65\sqrt{\pi}}{8192}(1+4\alpha_1)^6(1+4\alpha_2)^7=0$ $a_1(1+4\alpha_2)^9+32a_2(1+4\alpha_1)^8-\frac{291\sqrt{\pi}}{65536}(1+4\alpha_1)^8(1+4\alpha_2)^9=0$ where I know that some approximate solutions are $a_1 = 117.429,\ \ a_2 = -755.468,\ \ \alpha_1 = 1.3177,\ \ \alpha_2 = 2.9026$ I'd like to improve on these or at least confirm them. Plotting the equations in one parameter while keeping the other three as above I see that there are indeed roots there, e.g:               a2 = -755.468; alpha1 = 1.3177; alpha2 = 2.9026;      and:               Plot[a1/(1 + 4 alpha1)^2 + (8 a2)/(1 + 4 alpha2)^3 +  Sqrt[Pi]/64, {a1, 110, 120},        PlotRange -> {{110, 120}, {-0.1, 0.1}}]      I've tried using `FindRoot` with different parameters (accuracies, iterations, methods), but I end up with `Failed to converge to the requested accuracy or precision within # iterations`, and results which are completely different. One example:               FindRoot[{a1 (1 + 4alpha2)^3 + 8 a2 (1 + 4alpha1)^2 +        Sqrt[Pi] (1 +4 alpha1)^2 (1 +4 alpha2)^3/64 ,        a1 (1 +4 alpha2)^5 + 16 a2 (1 +4 alpha1)^4 -        11 Sqrt[Pi] (1 + 4alpha1)^4 (1 + 4alpha2)^5/512 ,        a1 (1 +4 alpha2)^7 + 24 a2 (1 + 4alpha1)^6 -        65 Sqrt[Pi] (1 +4 alpha1)^6 (1 + 4alpha2)^7/8192 ,        a1 (1 +4 alpha2)^9 + 32 a2 (1 + 4alpha1)^8 -        291 Sqrt[Pi] (1 + 4alpha1)^8 (1 + 4alpha2)^9/65536}, {{a1, 110,        120}, {a2, -760, -750}, {alpha1, 1.3, 1.4}, {alpha2, 2.9, 3}},        MaxIterations -> 100000, WorkingPrecision -> 50]      Gives the error above and $a_1 \rightarrow 0.631165832,$ $a_2 \rightarrow -70.5406787,$ $\alpha_1 \rightarrow 0.30522891, $ $\alpha_2 \rightarrow 3.7582495135$. Any ideas how I can improve on this?


Why do syntax errors make a 8.` run through $PreRead in a TagBox?

Modified code from the help file on $Pre:               $PreRead =.          SetAttributes[saveinputs, HoldAll];     inputs = {};     saveinputs[new_] := (inputs = {inputs, HoldForm[new]}; new);     $PreRead = saveinputs;      Evaluating:               <>      then               Flatten[inputs]          {<>,8.,RowBox[{Flatten,[,inputs,]}]}      If you look at the Cell Expression for the 8. it is actually a TagBox               TagBox["8.`", HoldForm]      Why does a syntax error cause this? Example where this causes a problem in code:               $PreRead =.          SetAttributes[saveinputs, HoldAll];     inputs = {};     saveinputs[new_] := (inputs = {inputs, HoldForm[new]};       If[Unevaluated[new],        new,        new);     $PreRead = saveinputs;      When evaluating pretty much anything you get:               ToExpression::esntx: Could not parse 8.` as Mathematica input.      If the test clause of the if statement in the above code does not depend on new then it runs fine.               $PreRead =.          SetAttributes[saveinputs, HoldAll];     inputs = {};     saveinputs[new_] := (inputs = {inputs, HoldForm[new]};       If[True,        new,        new);     $PreRead = saveinputs;      The above works fine. How am I changing new in the test clause to cause this to fail?


Faster "stuttering" accumulate?

Given some list of arbitrary precision numbers, e.g. (actual lists are 1M+ elements long):               test={0, 2, 2, 47839283, 2, 0, 0, 2, 0, 1, 2, 0}      I need to accumulate the list, but where a specified element value is treated as "clear", that is, the accumulation is reset to zero at that point in the list and continues. With the above example, using zero as the "clear", the result would be e.g.:               {0, 2, 4, 47839287, 47839289, 0, 0, 2, 0, 1, 3, 0}      I'm using               Function[{lst, clr}, FoldList[If[#2 == clr, 0, +##] &, lst[[1]], Rest@lst]][test, 0]      Seems pretty snappy, wondering if there's a more efficient way of doing this.


Controlling quality of discretized region meshes

I want to discretize 3D constructive solids, supported by Mathematica 10 regions functionality. Quality of resulting meshes must be controllable, and meshes must be useful for further computation. This should be easy, but the trivial example below stuns me.               (* Simple derived region in 3D with a sharp edge: *)     r = RegionDifference[Ball[{0, 0, 0}], Ball[{0, 0, 1}]];          (* RegionPlot3D with PlotPoints handles this reasonably well: *)     RegionPlot3D[r, PlotPoints -> 50]      > ![enter image description here](http://i.stack.imgur.com/TE1uC.png)               (* This should create a discretized mesh, and it does, but with poor quality: *)     DiscretizeRegion[r]      > ![enter image description here](http://i.stack.imgur.com/DJxnm.png) Edges are noticeably jaggy. This is understandable, and usually option like `PlotPoints` fixes these kind of issues. `DiscretizeRegion` has numerous options which should affect quality of its' output. I think I've played with all of them. Biggest difference I've seen has been is through use of `MaxCellMeasure`, but interestingly enough, same ugly jaggies stay there even if complexity of the mesh itself increases. I would need an option like `PlotPoints` which apparently affects grid resolution of a marching cubes style algorithm in `RegionPlot3D`, but there isn't one for `DiscretizeRegion`. Any suggestions?


How to make Mathematica use the chain rule?

Lets say I have the following PDE: $$x^2 u_{xx} - u_{yy} + u_y = 0$$ And I have the following change of variables: $$ s(x,y) = x e^y \, \, \, , \, \, t(x,y) = x e^{-y}$$ How can I use Mathematica to compute $u_{xx}, u_{yy},u_y$ on terms of $u_{ss},u_{tt}, u_{ts},u_t,u_s$ using the definitions and the chain rule?


Exporting tables of interpolating functions

A few weeks ago I asked a question about manipulating parameters in NDSolve (Looping with NDSolve?) , and received some very helpful advice about the manipulate environment; now I want to take the result of these varying parameters and fit them to lab data. I have a series of equations to be solved, and two unknown variables $kme$ and $kmn$. I specify a range for these and a step size. The following code outlines shows what's happening; I solve am initial PDE ($Ox$ ) and use that result to solve two further PDEs, $Ef$ and $Eb$. Both of these depend on $kme$ and $kmn$, and I am interested in the output of $Eb$. The following code outlines what I'm doing so far - apologies in advance, the equation inside the manipulate command is extremely ugly!               (*Some constants used here*)          a = 7.5*10^-7;     omega = 3.0138*10^7;     Do2 = 2*10^-9;     po = 100;     ro = 300*10^-6;     micron = 1*10^-6;     k = 1;       De = 5.5*10^-11;     eo = 100;     qm  = 10^-4;          (*Then we solve an initial equation and take values from it... *)          s = Quiet[NDSolve[{D[Ox[r, t], t] - Do2*(D[Ox[r, t], r, r] + (2/r)*(D[Ox[r, t], r])) + (a*           omega)*((Ox[r, t])/(Ox[r, t] + k)) == 0, Ox[r, 0] == 0,       Ox[micron, t] == 0, Ox[ro, t] == po},      Ox, {r, micron, ro}, {t, 0, 14400}]];               p = Ox /. First[s];          (*Then we set up our other complicated expression in the MANIPULATE environment; *)               Quiet[Manipulate[Plot[Evaluate[Eb1[r, 14400] /. NDSolve[{D[Eb1[r, t], t] -           qm*((kme)/(kme + p[r, t])*((p[r, t])/(p[r, t] + kmn)))*           First[Evaluate[Ef1[r, t] /. NDSolve[{D[Ef1[r, t], t] -                   De*(D[Ef1[r, t], r, r] + (2/r)*(D[Ef1[r, t], r])) + qm*((kme)/(kme +                      p[r, t])*((p[r, t])/(p[r, t] + kmn)))*Ef1[r, t] ==                  0, Ef1[r, 0] == 0, Ef1[micron, t] == 0, Ef1[ro, t] == eo},                Ef1, {r, micron, ro}, {t, 0, 14400}]]] == 0, Eb1[r, 0] == 0}, Eb1, {r, micron, ro}, {t, 0, 14400}]], {r,      micron, ro}, PlotRange -> All], {kme, 0.1, 60, 0.1}, {kmn, 0.1, 60, 0.1}]]      Getting this far gives me a workable manipulate environment; now I have some lab data I want to compare to this output. I have 600 values of $Kmn$ and 600 values of $Kme$ - is it possible to "output" the result for each of these in some automated fashion to compare it against the lab data? Either in a format I can use inside Mathematica or an interpolating function for each that can be exported to MATLAB / excel etc? I would be very grateful for any guidance on how to do this and the syntax!


Clustering data sets with multiple variables

I am learning how to cluster large datasets and this maybe a newbie question, but I haven’t found a suitable answer in the Documentation or on this board. My question is best illustrated by an example. Let’s import some data:               irisData = Import["http://aima.cs.berkeley.edu/data/iris.csv", "CSV”];     (*Column labels *)     pLabels = {"Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Type”};      How do I construct clusters based on only two columns say “Sepal.Length” and “Sepal.Width” and still retain the rest of the data… as part of the clusters Ideally I would like a function:                 findClusters[data,n,columnlist]       that would cluster the _data_ into _n_ clusters using the data in the _columnlist_ such that output data format of the clusters is the same as the input data. I can find the clusters and plot them as:               clusters = {cluster1, cluster2, cluster3} = FindClusters[irisData[[All, 1 ;; 2]], 3];     ListPlot[{{#1, #2} & @@@ cluster1, {#1, #2} & @@@ cluster2, {#1, #2} & @@@ cluster3}, AspectRatio -> 1, ImageSize -> 200, FrameLabel -> pLabels[[1 ;; 2]]]      But I’d like to use the clusters that I found using FindClusters above to explore say “Sepal.Length” vs “Petal.Width” or some other data analysis.


Are there any tutorials on version 10 notebook templating and report generation? Are there missing docs?

I am trying to understand the new templating in version 10. While there is a general documentation page with links to docs for each new function, so far I am unable to find any report generation worked examples of what a user may do after they open File > New > Template Notebook. Additionally when I press the help button on the template notebook it seems there is documentation missing: ![enter image description here](http://i.stack.imgur.com/btXJP.png) When you type "ReportGeneration" in the docs this is what you get: ![enter image description here](http://i.stack.imgur.com/oDQYT.png) Templates were first introduced in the Finance Platform -- which is essentially a version of Mathematica with a few other functions. Rather than have report generation functions without any coherent description of how a user can start from scratch and make a template and an automated report, the Finance Platform has a wealth of material, including a tour: ![enter image description here](http://i.stack.imgur.com/lsD2Z.png) ...detailed extensive documentation: ![enter image description here](http://i.stack.imgur.com/opncs.png) ...a specific palette that contains links to the tour, the extensive documentation and a video: ![enter image description here](http://i.stack.imgur.com/ZMY2o.png) **All of this stuff is missing from my OS X version 10. Is it present in Windows?**


How to use Graphics@Rotate@Show@Graphics without "Graphics is not a Graphics primitive or directive."

If I have the following graphic:               Rotate[Show[{        Graphics@Line[{{0, 0}, {0, 1}}],         Graphics@Line[{{0, 0}, {1, 1}}],         Graphics@Plot[x^2, {x, -1, 1}, Axes -> False]}], Pi/3]      It looks like this: ![enter image description here](http://i.stack.imgur.com/Si8dx.png) I only want to rotate the content of the graphics, not the frame. Normally you would use `Graphics` after rotate, however this doesn't work:               Graphics@Rotate[Show[{       Graphics@Line[{{0, 0}, {0, 1}}],        Graphics@Line[{{0, 0}, {1, 1}}],        Graphics@Plot[x^2, {x, -1, 1}, Axes -> False]}], Pi/3]     (* Error: Graphics is not a Graphics primitive or directive. *)


Manipulating PlotRange

Currently, I am working with some dynamic simulations of mechanical/electrical systems (in this case a kitchen scale). The main simulation is running smoothly but while building a nice GUI around the simulation I encountered a problem with creating a plot using `Manipulate`. Problem: I would like to have the plot with either `Full` as `PlotRange` or (by toggling a radio button / togglerbar/ checkbox) or with a slider to control the vertical `PlotRange`. I tried putting `Evaluate` around my dynamic variable(s) as well as putting `Dynamic` around `Plot`, but the common outcome is that the radio buttons, togglebars or checkboxes "jump" out of their position and the `Plot` does not update. Moving the slider and afterwards toggling into "Slider-mode" results in correctly scaled axes. My code:               Manipulate[     Dynamic[Plot[Sin[t], {t, 0, 5},      PlotRange -> {{0, 5},      Evaluate@scalefunction}]], {scalefunction, {Full, {-scale,      scale}}, ControlType -> RadioButtonBar}, {scale, 1, 5}]      Since this method did not work out, I tried to do the same without `Manipulate`: The following line creates my variable scale2 that I'd like to use with `PlotRange`. It switches from `Full` to `{-scaleIntern, scaleIntern}` as was planned.               {Checkbox[Dynamic[scale2], {Full, {Evaluate@Dynamic[-scaleIntern],      Evaluate@Dynamic[scaleIntern]} }], Dynamic[scale2]}      This is the Slider to control `scaleIntern`               Slider[Dynamic[scaleIntern]]      The following line then creates my dynamic `Plot`               Dynamic[Plot[Sin[t] , {t, 0, 2 \[Pi]},      PlotRange -> {{0, 2 \[Pi]}, Evaluate@scale2}]]      Strange is the error from the messages window:               Plot::prng: Value of option PlotRange -> {{0,2 \[Pi]},{-0.559,0.559}} is not All, Full,      Automatic, a positive machine number, or an appropriate list of range specifications. >>      The number +-0.559 is interactively bound to my slider and due to the correct format of my range specification the error message does not help me to find the problem I've been having with my code. I would really appreciate any aid to solve the issue. (I don't really care which method is going to work out in the end, but I am interested in the solution of both for interests sake.)


Syntax highlighting in patterns with built-in functions

While working on my own `plotLegends` package I encoutered some weird behaviour of the front end's syntax highlighting. I reduced the problem to the following minimal example:               Unprotect[Plot];     AppendTo[Options[Plot], opt1 -> True];          Plot[a_, b_, c___, opt1 -> opt_, d___] :=      foo[Plot[a, b, c, d], opt]          Plot[a_, b_, c___, opt1 -> opt_, d___] /; True :=      foo[Plot[a, b, c, d], opt]     Protect[Plot];          Unprotect[ListPlot];     AppendTo[Options[ListPlot], opt1 -> True];          ListPlot[a_, c___, opt1 -> opt_, d___] :=      foo[ListPlot[a, c, d], opt]          ListPlot[a_, c___, opt1 -> opt_, d___] /; True :=      foo[ListPlot[a, c, d], opt]          Protect[ListPlot];      You can see what I mean by "weird behaviour" in the following screenshot: ![enter image description here](http://i.stack.imgur.com/bq3qU.png) For both `Plot` and `ListPlot`, adding `/;True` leads to the option being highlighted red (which it otherwise isn't) . But only for `Plot` the default green highlighting of the patterns gets lost too. Can anyone reproduce this? Is there any reason why `Plot` should differ from `ListPlot`? I'm using version 8.0 on Windows 7.


Setting $RecursionLimit crashes Mathematica 10

I have encountered what I shall presume is a bug: setting `$RecursionLimit` repeatably crashes the _Mathematica_ 10 kernel:               $RecursionLimit = 50    (* kernel crash *)      Further, setting `$RecursionLimit = 20` produces a malformed Suggestions Bar containing text code starting with: > >     Manipulate`Dump`eDynamicModule[ . . . >   I am running version 10.0.0.0 on Windows 7. Please report behavior on your system.


Frequency of elements in a list

I've got a list in the format of `list={{a,1},{a,1},{b,1},{c,1},{b,1}}` And I want it to "compress" into a list of pairs `{element, frequency}` such as this: `{{a,2},{b,2},{c,1}}` I've come up with this (faulty) solution:               upravit[l_List] := {l[[1]], l[[2]] + 1}     compression[list_List] :=          list //. {a___, b_List, c_List, d___} /; c[[1]] == b[[1]] -> {a, upravit[b], d}      The problem is that I'm only checking elements that are next to each other, and so in the example, I'd end up with`{{a,2},{b,1},{c,1},{b,1}}` Therefore, either I need to correct my code, or come up with an entirely different method (using similar methods thought, as this is a homework). Thanks for any help! **Edit** : as pointed out in the comments and answers, there is a function that easily does that. I should've specified that this should be done using the methods in my example only. Sorry!


How to draw timing diagram from a 0 and 1 string list

What is the most elegant way to draw a timing diagram from a "0 and 1" string list? Here I started to draw the clock pulse diagram, and like to continue to draw the timing diagram for a given 0 and 1 string list, say, `{11011011,11100110}`. The result is supposed as the figure shown below. Pls help.               clockWidth = 0.2;     pulseHgh = 0.1;     rowHgh = pulseHgh + 0.1;     pNum = 8;     diagWidth = 2;     yb = 0;     clock = Table[        Line[{ {xb,            yb} , {xb, yb} + {0, pulseHgh}, {xb, yb} + {clockWidth/2,             pulseHgh}, {xb, yb} + {clockWidth/2, 0}, {xb,             yb} + {clockWidth, 0}}], {xb, 0, clockWidth*pNum, clockWidth}];     txt = Table[        Text[Style[n, 12, Italic], {n*clockWidth + clockWidth/2,           yb + 0.13}], {n, 0, pNum}];     Graphics[{clock}, Epilog -> {Text["Clock", {2, yb}], txt},       PlotRange -> {-0.2, 0.2} ]      ![enter image description here](http://i.stack.imgur.com/CAEiE.gif)


How to embed graphic-element-specific metadata within a Graphics object?

One of the most crucial requirements for rich, interactive scientific graphics is being able to "annotate" individual graphic elements (e.g. the data points of a scatterplot, the individual curves in a plot of multiple curve fits to data, individual subregions of a density plot) with additional information. I'm using the term "annotate" very broadly here to stand for "associate additional information with". Minimally, one would like to be able to assign unique identifiers to each feature of interest, that can be used as keys in auxiliary data structures. (For example, one way to make a scatterplot interactive is to equip each data point in the scatterplot with a tooltip that will display additional information about that point when the user hovers the cursor over the point. Another way would be to give the user the ability to "light up" a subset of the data points based on some shared metadata value.) Can the Mathematica `Graphics` object accommodate such annotations within it? (NB: I don't doubt that it would be possible to implement this sort of capability "on top of" Mathematica. At the moment I am interested _only_ in whether such functionality is already built into Mathematica.) EDIT: added one more example of possible modes of interactivity.


Implementation of smoothing splines function

I have some problems by writing a module for spline smoothing. Actually i am trying for about two weeks. My listing is here:               SplSmooth[data_, knots_, lambda_, degree_] :=        Module[{M, Knots, NKnots, NBasis, X, Dsq, a},        M = Length@data;        Knots = Flatten@{Table[1, {i, 1, degree}], knots,Table[M, {i,1,degree}]};        NKnots = Length@Knots;        NBasis = NKnots - degree - 1;        X = Table[          Evaluate@BSplineBasis[{degree, Knots}, n, t] // N, {t, 1, M},             {n, 0, NBasis - 1}];        Dsq = Differences[X, 2];        a=Inverse[Transpose[X].X + lambda*Transpose[Dsq].Dsq // N].Transpose[X].data // N;        Return[X.a]        ];      When I am trying to place a knot in every point in my data, numerical errors are arising such as: > Inverse::luc: Result for Inverse of badly conditioned matrix > {{1.251,-0.1255,-0.251,0.0836667,0.0418333,0.,0.,0.,0.,0.,<<72>>},<<9>>,<<72>>} > may contain significant numerical errors. >> obviously the corresponding result is wrong (I can see it from the plot). It seems that the matrix to be inverted, is ill conditioned:               a = Inverse[Transpose[X].X + lambda*Transpose[Dsq].Dsq // N].Transpose[X].data // N;      but now comes the other problem. I use equidistant knots (lets say with 7 points distance) to overcome this problem. But then sometimes the algorithm works with:               Knots = Flatten@{Table[1, {i, 1, degree}], knots,Table[M, {i,1,degree}]};      and some other times works with               Knots = Flatten@{Table[1, {i, 0, degree}], knots,Table[M, {i,0,degree}]};      Now, I think that there is some kind of problem in `BSplineBasis` function. Q: Can you spot the problem please? Or has anyone of you implemented a simillar function in the past with `BSplineBasis` function?


Why is the output of my limit expression an interval?

Why is the output of the limit below an interval? It should be precisely $1$.               Limit[(2/Pi) ((2 n + 2)!!/(2 n + 1)!!) Integrate[(1 - x^2)^(n + 1/2), {x, 0, 1}],        n -> Infinity]


Error messages from NDSOlve

I am trying to solve a boundary value problem with `NDSolve`. The code is:               sol = Block[{M = 0.0},        NDSolve[{         f'''[x] + f[x]*f''[x] - f'[x]*f'[x] - M*f'[x] == 0,          f[0] == 0, f'[0] == 1, f'[15] == 0},          f, x,          MaxSteps -> 10^5,          AccuracyGoal -> 50,          PrecisionGoal -> 50,          WorkingPrecision -> 50,          Method ->           {"Shooting", "StartingInitialConditions" -> {f[0] == 0, f'[0] == 1, f''[0] == -0.5}}]]      The `f''[0] == -0.5` that you see in the `Method` option is just trial and error on my part. When I execute the code, I get the following error messages. > NDSolve::precw: The precision of the differential equation ({0. > (f^[Prime])[x]-(f^[Prime])[x]^2+f[x] > (f^[Prime][Prime])[x]+(f^(3))[x]==0,f[0]==0,(f^[Prime])[0]==1,(f^[Prime])[10]==0}) > is less than WorkingPrecision (50.`). >> > > NDSolve`Reinitialize::precw: The precision of the argument function > ({f[0]==0,(f^\\[Prime])[0]==1,(f^\\[Prime]\\[Prime])[0]==-0.5}) is less than > WorkingPrecision (50.`). >> > > NDSolve::ndtol: Tolerances requested by the AccuracyGoal and PrecisionGoal > options could not be achieved at x == 0. >> > > NDSolve::ndtol: Tolerances requested by the AccuracyGoal and PrecisionGoal > options could not be achieved at x == 0. >> > > NDSolve::ndtol: Tolerances requested by the AccuracyGoal and PrecisionGoal > options could not be achieved at x == 0. >> > > General::stop: Further output of NDSolve::ndtol will be suppressed during > this calculation. >> > > NDSolve::berr: There are significant errors > {4.3180842775472223126931759314001997855580001822181*10^-78,-0.50000000000000000000000000000000000000000000000000,0.50000000000000000000000000000000000000000000000000} > in the boundary value residuals. Returning the best solution found.>> I am completely stuck on the prolem. Please help me with this.


Grouping Nested Lists Based on Differing Values of Single Element

I've a list of lists representing k-rows of truth table having n elements each in a nested list consider                lst={{True, True, True}, {True, True, False}, {True, False, True}, {True,          False, False}, {False, True, True}, {False, True, False}, {False,          False, True}, {False, False, False}}      i want to get all those sublists having n-1 elements same but differ by jth element e.g. if i want the 2nd element to of a given list to be different i should get the following result group:                lst={{{True, True, True},  {True, False, True}}, {{True, True, False}, {True,       False, False}}, {{False, True, True}, {False,       False, True}},{{False, True, False}, {False, False, False}}}      similarly, if i want the third element to be differnt i should get this:               lst={{{True, True, True}, {True, True, False}}, {{True, False, True}, {True,        False, False}}, {{False, True, True}, {False, True, False}}, {{False,        False, True}, {False, False, False}}}      I'll be thankful for anyone helping out.


Extending D for four-derivatives

I'm currently trying to consistently define rules for extending D[] to four- derivatives. As 'backend' I'm using the package TRACER (http://library.wolfram.com/infocenter/MathSource/2987/), which can perform contractions with metric tensors, Dirac algebra, etc. Derivatives, however, are not implemented in this package. The rules here are independent of TRACER, but I adapted it's syntax, so   * `S[k, {σ}]` is the four-vector $k_\sigma$   * `S[{μ}, {ν}]` is the metric tensor $g_{\mu\nu}$ The basic assumption is that $\frac{\partial}{\partial k^\sigma}k^\rho=g^{\sigma\rho}$. So far, I have               D[S[notk_Symbol, idx_List], S[k_Symbol, derividx_List]] :=          0 /; FreeQ[notk, k];     D[S[k_Symbol, index_List], S[k_Symbol, derividx_List]] :=         S[index, derividx];     D[S[param1__]^n_Integer, S[deriv_, derividx_]] :=         n S[param1]^(n - 1) D[S[param1], S[deriv, derividx]]      For multiplication and addition, I have               D[S[param1__] + S[param2__], S[deriv_, derividx_]] :=          D[S[param1], S[deriv, derividx]] + D[S[param2], S[deriv, derividx]];     D[S[param1__] * S[param2__], S[deriv_, derividx_]] :=          D[S[param1],            S[deriv, derividx]]*S[param2] + S[param1] * D[S[param2],           S[deriv, derividx]]];      And for scalar products:               D[S[k1_Symbol, k2_Symbol], S[k_, derividx_List]] :=          D[S[k1, {dummy}],           S[k, derividx]] S[k2, {dummy}] + S[k1, {dummy}] D[S[k2, {dummy}],           S[k, derividx]];      These, however, do not deliver the correct results (the result is in fact 0) when trying to derive a product or sum with more than two terms. `//Trace` confirms that Mathematica does not know what to do. Does anyone have a pointer?


how to load packages on local computer when using remote kernels

I usually works remotely using kernels on our hpc and front-end on my local laptop. This enable me do relatively large computation within my laptop(IP address of my laptop may change frequently). But there is a problem when come across packages. Since I manage all the packages on my local computer, I can't just use `Get["mypack.m"]` when I use remote kernel, instead, I have to copy all the packages to my remote machine before `Get`. However, I'm constantly developing the packages and copying them back and forth between local and remote computer is quiet tedious. Are there simpler ways to deal with it?


How to create a SparseArray satisfying multiple conditions on Parts and Elements of a Matrix?

I have a matrix `m1` of size $3 \times 19$. Rows $1$, $2$ and $3$ represent $3$ different groups, and columns represent $4$ different blocks:   1. block1 - columns $1$, $2$, and $3$,   2. block2 - columns $4$, $5$, $6$, $7$, and $8$,   3. block3 - columns $9$, $10$, $11$, and $12$,   4. block4 - columns $13$--$19$. I want to construct a `SparseArray`, of the size $3 \times 19$, such that if any of the matrix `m1` elements is less than for example $5000$, then all of the elements of the corresponding group and block should be equal to $1$. If all of the elements of the corresponding group and block are greater than $5000$, then the values of the `SparseArray` should be equal to $0$. This is my input matrix `m1`:                   m1 = {{17000, 14542, 17000, 7000, 7000, 7000, 7000, 5666, 5127, 3810,             6027, 7000, 12000, 12000, 12000, 12000, 12000, 17000,             12000}, {17000, 12070, 17000, 7000, 7000, 7000, 7000, 5100, 4435,             3010, 5575, 7000, 12000, 12000, 12000, 12000, 12000, 17000,             12000}, {17000, 9743, 17000, 7000, 7000, 7000, 5530, 4250, 4358,             2876, 5002, 7000, 12000, 12000, 12000, 12000, 12000, 17000, 12000}}      I use `Map` and `Boole` to generate matrix `m2`:                   m2 = Boole[Map[# < 5000 &, m1, {2}]]      This is the output for `m2`:               (* {{0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},          {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},          {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0}} *)      Then I need to specify the conditions for my final solution.                   solution=Normal[SparseArray[{              {i_, j_} /; i == 1 && 1 <= j <= 3 && Total[m2[[1, 1 ;; 3]]] >= 1 -> 1,               {i_, j_} /; i == 1 && 4 <= j <= 8 && Total[m2[[1, 4 ;; 8]]] >= 1 -> 1,               {i_, j_} /; i == 1 && 9 <= j <= 12 && Total[m2[[1, 9 ;; 12]]] >= 1 -> 1,              {i_, j_} /; i == 1 && 13 <= j <= 19 && Total[m2[[1, 13 ;; 19]]] >= 1 -> 1,               {i_, j_} /; i == 2 && 1 <= j <= 3 && Total[m2[[2, 1 ;; 3]]] >= 1 -> 1,               {i_, j_} /; i == 2 && 4 <= j <= 8 && Total[m2[[2, 4 ;; 8]]] >= 1 -> 1,              {i_, j_} /; i == 2 && 9 <= j <= 12 && Total[m2[[2, 9 ;; 12]]] >= 1 -> 1,              {i_, j_} /; i == 2 && 13 <= j <= 19 && Total[m2[[2, 13 ;; 19]]] >= 1 -> 1,               {i_, j_} /; i == 3 && 1 <= j <= 3 && Total[m2[[3, 1 ;; 3]]] >= 1 -> 1,              {i_, j_} /; i == 3 && 4 <= j <= 8 && Total[m2[[3, 4 ;; 8]]] >= 1 -> 1,              {i_, j_} /; i == 3 && 9 <= j <= 12 && Total[m2[[3, 9 ;; 12]]] >= 1 -> 1,              {i_, j_} /; i == 3 && 13 <= j <= 19 && Total[m2[[3, 13 ;; 19]]] >= 1 -> 1,              Dimensions[m2]]]      This is the result I wanted:               (* {{0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0},          {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0},          {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0}} *)      I believe that there is a better way to get the results I need.


Generating list of alphabet letters

I want to create a list of length `n` with the letters of the alphabet. For example, if `n = 3`, by list would be `{a,b,c}`. If `n=6`, the list would be `{a,b,c,d,e,f}`. Is there any easy way to do this?


How to robustly apply ToBoxes to a Dynamic expression?

Inserting a `Dynamic` object in a boxform expression messes up syntax colouring. See the following example. where the variable `local` is dynamically replaced at the box level, and the syntax highlighter cannot keep up with it.               on = True;     Row@{          Checkbox@Dynamic@on, Spacer@10,          ExpressionCell[RawBoxes@RowBox@{"Block", "[", RowBox@{           RowBox@{"{", "local", "}"}, ",",           RowBox@{"{",                  (* autostyling applies fine *)             "local", ",",             ToBoxes@ToExpression["local", StandardForm, HoldForm], ",",             ToBoxes@Dynamic@ToExpression["local", StandardForm, HoldForm], ",",             ToBoxes@Dynamic@If[on, ToExpression["local", StandardForm, HoldForm],                 ToExpression["local", StandardForm, HoldForm]], ",",                  (* autostyling applies only for initial display *)             ToBoxes@Dynamic@If[on, ToExpression["local", StandardForm, HoldForm],                 ToExpression["global", StandardForm, HoldForm]], ",",                  (* autostyling does not apply *)             ToBoxes@"local", ",",             ToBoxes@Dynamic@"local", ",",             ToBoxes@Dynamic@If[on, "local", "global"],             "}"}           }, "]"}, "Input", ShowAutoStyles -> True, LanguageCategory -> "Mathematica"]}      When the checkbox is clicked, it switches between: ![Mathematica graphics](http://i.stack.imgur.com/KqF6S.png) ![Mathematica graphics](http://i.stack.imgur.com/W4yfF.png) ![Mathematica graphics](http://i.stack.imgur.com/NSVzy.png) and so on... Note, that the 5th `local` in the body of `Block` stays blue. How to overcome this?


Multidimensional Numerical Integral with Singular Behavior

I'm trying to numerically integrate a multidimensional integral where there is singular behavior when x = y. This is the integral               NIntegrate[-(1/((x-y)^2 (x+y)))π x Csch[π (x+y)] *       (-(x-y)^2+(x+y)^2 Log[-I (x-y)]-(x+y)^2 PolyGamma[0,1-I (x+y)]) *       (-(x-y)^2+(x+y)^2 Log[I (x-y)]-(x+y)^2 PolyGamma[0,1+I (x+y)]),{x,0,∞},{y,0,∞}]//Timing      I have reason to believe the answer is `0.0529592`. Any ideas?


Solving coupled transcendental equations with Nsolve

I'm trying to solve a system of coupled nonlinear equations using NSolve:               nbosons = 2;          x = Table[Symbol["x" <> ToString[i]], {i, 1, nbosons}];     k = Table[Symbol["k" <> ToString[i]], {i, 1, nbosons}];          u[j_] := Part[k, j];          BAE[c_, L_] :=        Table[Exp[I u[j] L] +           Product[(u[j] - u[l] + I c)/(u[j] - u[l] - I c), {l, nbosons},            Assumptions -> l != j] == 0, {j, 1, nbosons}];          BAEroots[c_, L_] := NSolve[BAE[c, L], {k1, k2}, Complexes]      But something goes wrong:               In[71]:= BAEroots[1, 1]      > During evaluation of In[71]:= NSolve::nsmet: This system cannot be solved > with the methods available to NSolve. >>               Out[71]= NSolve[{E^(I k1) - (I + k1 - k2)/(-I + k1 - k2) == 0,        E^(I k2) - (I - k1 + k2)/(-I - k1 + k2) == 0}, {k1, k2}, Complexes]      In general, I know that the values of k's are such that               i) -2 Pi/L < Re[k] < 2 Pi/L and -2 Abs[c] < Im[k] < 2 Abs[c]          ii) k1 + ... + knbosons = 0      how could I use this extra information in Nsolve? Thanks in advance!


Import an SPSS, SAS, or STATA file into Mathematica

I would like to import the World Value Survey data file into Mathematica, but it's only given in spss, sas or stata formats, which are statistical analysis softwares format I think. I can't get to import these files in Mathematica, they are not recognized. I've found a Wolfram executable that should allow me to import SAS files but it can't make it work on Linux. Have you already been able to import such files in Mathematica?


Plot in a 2-dimensional simplex

I have a row vector as $P=(p_1,p_2,p_3)$ which should be obtained from the following constraints:   1. $a_1p_1 + a_2p_2 + a_3p_3 = b_1p_1 + b_2p_2 + b_3p_3$ ($a_i$'s and $b_i$'s are known)   2. $p_1 + p_2 + p_3 = 1$   3. $p_i\geq 0,\ i=1,2,3.$ Furthermore, there may be more than one P vector satisfying the above constraints. Then, I want to use each P vector in the following equations to plot (x,y) in a 2-dimensional space.   1. $x = p_1x_1 + p_2x_2 + p_3x_3$   2. $y = p_1y_1 + p_2y_2 + p_3y_3$ (Both $x_i$'s and $y_i$'s are known) I would be very thankful if anyone has any idea! Best, * * * Thank you very much for your help! Your codes gave so many ideas to me since I'm a beginner in Mathematica. But the point is that putting $p_i=0$ at every step and finding the corresponding 2-dimensional line is not always correct because there may be some solutions whose $p_i$'s are not equal to 0. Maybe, I did not explain properly about my problem. Here is what I'm looking for: I have the following set of constraints:   1. $P.C>=0$, where $P=(p_1,p_2,p_3)$ and $C=(c_1,c_2,c_3)$ and $C$ is known.   2. $P.D>=0$, where $P=(p_1,p_2,p_3)$ and $D=(d_1,d_2,d_3)$ and $D$ is known.   3. $P.E>=0$, where $P=(p_1,p_2,p_3)$ and $E=(e_1,e_2,e_3)$ and $E$ is known.   4. $p_1+p_2+p_3=1$ (* edited *)   5. $p_i>=0$ for all $i$ As I said before, there may be several $P$ vectors satisfying the above constraints. Furthermore, there may be non-negative $P$ vectors, e.g. $P=(1/3,1/3,1/3)$ that satisfies the above constraints. After obtaining all such $P$ vectors, based on them, I want to plot the following x-y variables in 2 dimensions:   1. $x=p_1x_1+p_2x_2+p_3x_3$   2. $y=p_1y_1+p_2y_2+p_3y_3$ Furthermore, the way my problem is modeled, I am sure that I have a line in 2D. I tried so many different methods found in internet, but unfortunately, none of them worked. Again, I would be very grateful if anyone help me in this case!


How to apply GraphLayout to parts of a graph?

I'm trying to sketch polymers. Here is how I do it for the monomer:               Graph[{1 <-> 2, 2 <-> 3, 3 <-> 4, 4 <-> 5, 5 <-> 6, 6 <-> 1, 4 <-> 7, 7 <-> 8}]       ![Mathematica graphics](http://i.stack.imgur.com/7FWhO.png) How can the left part arranged to form a **regular hexagon**? This is only a subunit so for polymers there are more. Is there a general way to do so? For the polymer, I wrote an ugly one:               Mol[k_] := Join[        Table[Join[          Table[(8 n + i) <-> (8 n + i + 1), {i, 5}],          {(8 n + 6) <-> (8 n + 1), (8 n + 4) <-> (8 n + 7), (8 n + 7) <-> (8 n + 8),           (8 n + 8) <-> (8 n + 9)}], {n, 0, k - 2}],        Join[Table[(8 (k - 1) + i) <-> (8 (k - 1) + i + 1), {i, 5}],          {(8 (k - 1) + 6) <-> (8 (k - 1) + 1), (8 (k - 1) + 4) <-> (8 (k - 1) + 7),           (8 (k - 1) + 7) <-> (8 (k - 1) + 8)}]] // Flatten;          Graph[Mol[5], VertexLabels -> "Name", ImagePadding -> 10, ImageSize -> 1000]      ![Mathematica graphics](http://i.stack.imgur.com/acqAt.png)


Problem using WhenEvent to constrain solution

**Note: This question has also been posted at the** Wolfram Community Problem: Simulate pressure in volume 1 and 2 for 1 second. The circuit is as follows: ![enter image description here](http://i.stack.imgur.com/TWeRN.jpg) From this I set up the governing DE for both volumes and plot the solution:               Ad1 = 10/1000^2;          Ad2 = 1.5*1000^(-2);          Ad3 = 1.5*1000^(-2);          Cd1 = 0.67;          Cd2 = 0.67;          Cd3 = 0.67;          V1 = 10/1000;          V2 = 10/1000;          Rho = 875;          beta = 1000*10^6;          ps = 100*10^5;          Q1 = Ad1*Cd1*Sqrt[(2/Rho)*(ps - p1[t])];          Q2 = Ad2*Cd2*Sqrt[(2/Rho)*(ps - p2[t])];          Q5 = Ad3*Cd3*Sqrt[(2/Rho)*(p1[t] - p2[t])];          Q3 = Q1 - Q5;          Q4 = Q2 + Q5;          s = NDSolve[{p1'[t] == (beta*Q3)/V1, p2'[t] == (beta*Q4)/V2,           p1[0] == p2[0] == 0, WhenEvent[p1[t] >= ps, p1[t] -> ps],           WhenEvent[p2[t] >= ps, p2[t] -> ps]}, {p1, p2}, {t, 0, 1}];          Plot[Evaluate[{p1[t]/10^5, p2[t]/10^5} /. s], {t, 0, 1}]      ![enter image description here](http://i.stack.imgur.com/wvPll.jpg) Mathematica aborts integration after `t = 0.69` since it encounters complex solutions. This is due to `p1` and `p2` at some point getting larger than ps, which makes no sense, particularly since I have added 2 `WhenEvent`s which shouldn't 'allow' `p1` and `p2` to be greater than `ps` (see code). Complex solutions can be avoided by adding `Abs`, however, then the solution seem to completely diverge: ![enter image description here](http://i.stack.imgur.com/XADzB.jpg) **Question: Why doesn't`WhenEvent` seem to 'work'?** PS.; I have obtained a more credible solution using Matlab and the same constrictions: ![enter image description here](http://i.stack.imgur.com/6LCST.jpg) Matlab code:               close all;       [b][/b]       clear;            %Basic data            EndTime=1;            StepTime=1e-5;           ps=100*1e5;           Cd1=0.67;           Cd2=0.67;           Cd3=0.67;           Ad1=10*1000^(-2);           Ad2=1.5*1000^(-2);           Ad3=1.5*1000^(-2);           V1=10/1000;           V2=10/1000;           rho=875;           beta=1000*1e6;                     %Initialize           p1_initial=0;           p2_initial=0;           %Initially old values are simply set to current values           Time=0.0;           p1=p1_initial;           p2=p2_initial;                               %Initialize counters so that plot data is only saved once pr. a number of           %time steps corresponding to ReportInterval           ReportCounter=0;           ReportInterval=10;           Counter=ReportInterval;           %Start time integration           while Time<EndTime           if p1>=ps           p1=ps;           end           if p2>=ps           p2=ps;           end               Q1=Cd1*Ad1*sqrt(2/rho*(ps-p1));               Q2=Cd2*Ad2*sqrt(2/rho*(ps-p2));               Q5=Cd3*Ad3*sqrt(2/rho*(p1-p2));%Flow through orifice 3               Q3=Q1-Q5;%Q3 to volume 1               Q4=Q2+Q5;%Q4 to volume 2               p1Dot=beta*Q3/V1;               p2Dot=beta*Q4/V2;                                   %report               if Counter==ReportInterval                  Counter=0;                  ReportCounter=ReportCounter+1;                  Time_Plot(ReportCounter)=Time;                  p1_Plot(ReportCounter)=p1*1e-5;                  p2_Plot(ReportCounter)=p2*1e-5;                                  end;              %Time integrate              p1=p1+p1Dot*StepTime;              p2=p2+p2Dot*StepTime;              Time=Time+StepTime;              Counter=Counter+1;          end;          plot(Time_Plot,p1_Plot);          hold on;          plot(Time_Plot,p2_Plot,'r');          grid;      Matlab solution seems to be an OK fit with simulation results (from SimulationX): ![enter image description here](http://i.stack.imgur.com/ENnWD.jpg)


How to obtain SliceDistribution or StationaryDistribution for an ItoProcess when it is known to exist?

According to this reference page > StationaryDistribution[ _proc_ ] represents the stationary distribution of > the process _proc_ , when it exists. When I define the OrnsteinUhlenbeckProcess by the equivalent ItoProcess, SliceDistribution and StationaryDistribution are not found analytically any more. See for example the following:               In[25]:= SliceDistribution[OrnsteinUhlenbeckProcess[0, 1, 1], t]          Out[25]= NormalDistribution[0, 1/Sqrt[2]]          In[27]:= SliceDistribution[      ItoProcess[\[DifferentialD]x[          t] == -x[t] \[DifferentialD]t + \[DifferentialD]w[t],        x[t], {x, 1}, t, w \[Distributed] WienerProcess[]], t]          Out[27]= ItoProcess[{{-x[t]}, {{1}}, x[t]}, {{x}, {1}}, {t, 0}][t]


How to generate and label multiple histograms as Query operator(s)?

The Dataset documentation doesn't indicate how to label a Histogram with the key.               titanic =        ExampleData[{"Dataset", "Titanic"}][All, {"survived" ->(# /. {True -> 1, False -> 0} &)}]      ![enter image description here](http://i.stack.imgur.com/4L6Bm.png)               titanic[Histogram, #] & /@ {"age", "survived"}      gives: ![enter image description here](http://i.stack.imgur.com/Vp8il.png) (Note, unlike functions such as Counts, which can operate on tuples of keys (ie, counts the products), it doesn't seem possible to use the syntax: `titanic[Histogram, {"age", "survived"}]`). How can a Key be passed programmatically as argument to Histogram (or other operators) in order to label it, eg "age", "survived" ? Of course it's possible to project individual columns with KeyTake and then histogram but that's not the same as operating on the data.


How can I programmatically specify the positioning of a window at the time of its creation?

CreateDocument[{}, WindowSize -> {100, 100}]       always centers the new window.


Reconciling results from Fourier with those form FourierTransform

I need to use the discrete Fourier transform for function that represented as list of values. I started with an easy task to check my understanding. I tried to get the amplitude values for `2*Sin[x]`. I think they should be somwhere about 2. But using the discrete `Fourier` operation produces something quite different. Can someone tell me where my mistakes are? Here is what I tried.               data = Table[2*Sin[x], {x, 0, 100}];     ListPlot[data, Joined -> True]      ![enter image description here](http://i.stack.imgur.com/YtAVI.jpg)               ListPlot[Abs[Fourier[data]], Joined -> True, PlotRange -> All]      ![enter image description here](http://i.stack.imgur.com/ND47Q.jpg)               ListPlot[       Table[Abs[FourierTransform[2*Sin[x], x, w]] /.          DiracDelta -> DiscreteDelta, {w, 0.1, 10, 0.1}],        Joined -> True,        PlotRange -> All]      ![enter image description here](http://i.stack.imgur.com/0wyzX.jpg) How can I get the same results from 'Fourier' as I get from 'FourierTransform'?


How to find the inverse a symbolic matrix that Mathematica thinks might be singular

I have a square matrix depending on a parameter "a". When "a" has a numeric value (eg 2.1 * 10 ^ 8) through the inverse function Inverse[] I can invert the matrix. If I write the matrix as a function of "a" do not declare its value when the invert Mathematica tells me that it is singular (suspect singular) then not allow me to Invert it. The determinant of the matrix in symbolic form turns out to be a very small value in the order of 6*10 ^ -25000. Do you think I can get the inverse of this matrix in symbolic form? the matrix is generated by:               K0 = Ct.E0.Transpose[Ct];      where Ct is a matrix indipendent from "a" , while "E" is a diagonal matrix which depends on "a" in the following way : http://i.stack.imgur.com/VXX2A.png The matrix Ct and E are written manually. I attach the file containing the matrix mathematica https://drive.google.com/file/d/0B7In1ClJQ-FVZVRuNHMycGotUTg/edit?usp=sharing I was not able to include them here as a code. Thanks in advance


Why am I getting wildly incorrect results from FirstPassageTimeDistribution with inexact transition matrix?

Working on some large systems using `DiscreteMarkovProcess`, I changed the transition matrix to machine precision vs using exact values, which sped things up handily. The only problem was for edge cases, accuracy suffered. I expected that. However, when probing the limits using simple cases, I was surprised to find this happens when I'd not expected it. A simplified test example:               Table[      intleg = tleg/2;           sa = SparseArray[{{i_, i_} :>           1 - (intleg - i + 1)/tleg, {i_, j_} /;            j == i + 1 :> (1 - i + intleg)/tleg}, {intleg + 1, intleg + 1}];                saN = N[sa, 50];           mp = DiscreteMarkovProcess[1, sa];      mpN = DiscreteMarkovProcess[1, saN];           {tleg, N@Mean[FirstPassageTimeDistribution[mp, intleg + 1]],       N@Mean[FirstPassageTimeDistribution[mpN, intleg + 1]]},           {tleg, {10, 20, 30, 40}}]          (* {{10,22.8333,22.8333},{20,58.5794,58.5793},{30,99.5469,-1.24192},{40,143.91,0.}} *)      This simulates a simple "coupon-collector" situation with a population of `tleg` distinct items, where only half are "interesting" to me. So a transition matrix is built with appropriate probabilities with an absorbing state when all "interesting" are obtained. That same matrix is converted to inexact via `N`. Comparing the results, we see the last two are not even in the zip-code of the correct result. Upping the accuracy/precision of the conversion via `N` seems to have no effect. Any ideas what's going on here (I suspect some kind of catastrophic cancellation because of the characteristics of the probabilities)?


matrix with IF/THEN condition

How to generate all posible matrices with some conditions on the elements? I need to make for given $n$ all $n\times n$ matrices $A=(a_{ij})$ with three conditions: > I. $a_{ij}=+1$ or $0$ or $-1$. > > II. $a_{ij}=-a_{ji}$ > > III. if $a_{ij}\geq 0$ and $a_{jk}\geq 0$, then $a_{ik}\geq 0$; and > $a_{ik}=0$ only if $a_{ij}=a_{jk}=0$ The only way I see is to expand these three conditions to equivalent but more elementary eight IF/ELSE conditions: > 1) if $a_{ij}=+1$, then $a_{ji}=-1$ > > 2) if $a_{ij}=+1$ and $a_{jk}=+1$, then $a_{ik}=+1$ > > 3) $a_{ii}=0$ > > 4) if $a_{ij}=0$, then $a_{ji}=0$ > > 5) if $a_{ij}=0$ and $a_{jk}=0$, then $a_{ik}=0$ > > 6) if $a_{ij}=+1$ and $a_{jk}=0$, then $a_{ik}=+1$ > > 7) if $a_{ij}=0$ and $a_{jk}=+1$, then $a_{ik}=+1$ > > 8) $a_{ij}=+1$ or $0$ or $-1$ And to generate for given $n$ all possible matrices, make it antisymmetric, then make all permutates of $+1$, $0$, $-1$; and after that deleting unnecessary cases with help of cycles. But it quickly became too complicated. Is there any more natural way? PS this problem arised from this SE question and appeals to this book.


Mathematica 10 Graph issue

Please try to evaluate this code in Mathematica 10.               << ComputationalGeometry`     g = RandomGraph[{12, 18}];     pt = GraphEmbedding[g];     convexhull = ConvexHull[pt];     Show[PlanarGraphPlot[pt, convexhull, ColorOutput -> Red], g,     Graphics[{Red, PointSize@Large, Point[#]} & /@ pt]]      ![enter image description here](http://i.stack.imgur.com/YxsJm.png) Works perfectly fine on the version 9. What is this dynamic object showing up? Anybody got some explanation for this.


Mouse motion makes frame disappear in Overlay of long ListPlots

Using M9, OSX 10.8.4, most parts of the `Frame` in the following overlay disappear (also partially occluding some `FrameTicks`) when scrolling the mouse after the output is generated. Note the 10,000: the issue doesn't occur for much smaller `ListPlot` arguments. Can anyone replicate?                   With[{t = Table[Random[], {10000}]},      Overlay[{          ListPlot[t, Frame -> {True, True, True, False}, Axes -> False,          FrameStyle -> {Automatic, Blue, Automatic, Automatic},          PlotStyle -> Blue, Joined -> True, AspectRatio -> 1/10,          ImageSize -> 800, PlotRange -> All],          ListPlot[t+1,          Frame -> {False, False, False, True}, Axes -> False,          PlotStyle -> Darker@Red, FrameTicks -> {None, None, None, All},          FrameStyle -> {Automatic, Automatic, Automatic, Darker@Red},          Joined -> True, AspectRatio -> 1/10, ImageSize -> 800,          PlotRange -> All]}]      ]      Resulting in the following: ![enter image description here](http://i.stack.imgur.com/2aYNP.png)


Parameter sensitivities of ParametricNDSolveValue involving numerical function

This is a followup of my former question from here. Consider the code               pfun = ParametricNDSolveValue[{x'[t] == a*x[t], x[0] == 1}, {x}, {t,0, 10}, {a}];     part[l_List, n_Integer] := Part[l, n];     qfun = ParametricNDSolveValue[{y'[s] == a^2*y[s], y[0] == part[pfun[a], 1][2]}, {y}, {s, 0, 10}, {a}];      The goal is to calculate the sensitivity of the parameter $a$, $\partial_a y(t;a)$. However,               Derivative[1][qfun][2]      gives `ParametricFunction[<>][2]` instead of an `InterpolatingFunction` -object. It seems that this is a general issue for functions of the parameter $a$, which only allow numeric arguments:               f[a_] := a^2;     rfun = ParametricNDSolveValue[{y'[s] == a^2*y[s], y[0] == f[a]}, {y}, {s, 0, 10}, {a}];     Derivative[1][rfun][2]      gives `{InterpolatingFunction[{{0.,10.}},<>]}`, while               g[a_?NumericQ] := a^2;     sfun = ParametricNDSolveValue[{y'[s] == a^2*y[s], y[0] == g[a]}, {y}, {s, 0, 10}, {a}];     Derivative[1][sfun][2]      also not works and results in `ParametricFunction[<>][2]`. How can this issue be resolved?


Convert variable into function

Sorry if this is a duplicate, but I have a variable called `H`. `H` is some complicated function of `s`. Now I want to make this variable `H` into a formal function `f[s]`. I've tried just doing               f[s_] := H      But that doesn't seem to work. `H` was initially a value in a `InputField` and the type on that `InputField` was an `Expression`. Any ideas on how I can turn this into a proper _Mathematica_ function?


How to keep track of notebook dimensions

I want to create a cell that will resize automatically if the notebook is resized. I was hoping to find some function called NotebookDimensions[], and use it dynamically.


Fastest way to check for List membership

I have a set of say `100` numbers `{1,3,7,11,19,...3971}`. All elements are previously determined. I want to check whether `376` belongs to this set or not. what is the fastest way? Thanks


Use remote kernel on debian from win8

I spend almost two week to figure out how mma could use a remote kernel. The following is my results:   1. The basic environment is: mma9.0.1 on win8 as my host (local machine); mma9.0.1 on Deiban 7 as a remote one (`d1`), its host name is assumed to be `aaa.bbb.com`.   2. It seems all the methods provided on the net are not working for me.    3. I can connect to the remote one from another debian system, assume it's name `d2`:      * First, I generate a ssh-key on `d2`: `ssh-keygen -t rsa -b 2048` and press `Enter` for default location.     * Second, I copy the key to `d1` : `ssh-copy-id username@aaa.bbb.com`, where `username` is the username of `d1`. It asks me to input my password for my account on `d1`.     * Now I can login `d1` from `d1` with: `ssh username@aaa.bbb.com` without password     * It should be noted that, all the above steps can be skipped, in which case I am required to input my password for `username` on `d1` every time.     * Now I am ready to launch mma on `d1`: `ssh username@aaa.bbb.com math`, which will feedback a _Mathematica_ shell as `In[1]:=`, and run a test: `1 + 1` and `Enter`. I see `Out[1]= 2`, so it is clear that the connection from `d2` to `d1` works. (I can quit _Mathematica_ from `d1` by `Quit` or `Exit`)   4. Then the problem is that I want to connect `d1` from my win8. As I mentioned all the solutions seem not to work, such as:     * Official doc, after I input the right password, it alerts me with something like `the remote machine refused, error code 113`     * Official debug doc, all the steps seems right, but the results can be return back, It still runing after ten min.     * How do you use ssh-keys instead of a password to run a remote-kernel over ssh?, it seems that I need to install putty in order to use `ssh` instead of `java`. The problem seems that the shell command is not correct, since it is even can't connect to `d1`. I try to find `mathssh.jar` in win8, it seems it is not exists?     * Use putty's `plink` I successfully install putty, and try the link's suggestion:                           plink -ssh -batch -l `username` `1` "math -mathlink -linkmode Connect `4` -linkname '`2`' -subkernel -noinit  >& /dev/null &" to lauch a parallel kernel, the results says that: > SubKernels `Protected` kernelFlush::time: Operation LinkWrite timed out > after 15. seconds. KernelObject::rdead: Subkernel connected through > remote[aaa.bbb.com] appears dead.   5. I try to fix the missing `mathssh` problem by How to configure parallel remote kernels in Mathematica?, it works 100%.   6. Finally, my problem is to find out how to use the remote kernel as default, rather than as the `Local` kernel. Any ideas?


How to preserve graph properties under subgraph in MMA9

> **Possible Duplicate:**   >  Preserving labels when using graph functions I'm using               g = SocialMediaData["Twitter", "FriendNetwork"]       to get a nice graph with tooltips for the vertices, etc. Next, I get the weakly connected components via               wcc = WeaklyConnectedComponents[g]      and then I do               sg = Subgraph[g, wcc[[1]]]      to get the largest component. But, all the properties are gone in `sg`, i.e. I no longer have the tooltips, etc. Any suggestions?


General F statistic and p value in LinearModelFit

Many statistical packages provide a "F statistic" and the corresponding p value in their output of a multiple linear regression. I don't find that in the parameters of the Mathematica function `LinearModelFit`. All I can find are the t-statistics for the individual coefficients but no general statistic related to the regression as a whole. I also don't find how to test interactions between predictor variables. Where can I find the general F statistic and see the interactions between my predictor variables?


$L_\infty$ norm minimization

I write supplemental explanation to render my aim of optimization. First Consider **discrete time** linear system below: \begin{equation} G(z)=\frac{1-e^{-0.3T}}{z^{100}(z-e^{-0.3T})} \end{equation} where $z = e^{j\omega}$ and $\omega$ is **frequency** , $\omega \in [-\pi,\pi)$, and $T$ is sampling period, assume that $T = 1$. It's obvious that the absolute value of $z$ is equal to $1$ for all $\omega$ between $-\pi$ and $\pi$. When one is talking about maximum absolute value of $G(z)$, in fact he/she consider below function : \begin{equation} \max_{\omega} |G(e^{j\omega})|=|\frac{1-e^{-0.3T}}{e^{j\omega}-e^{-0.3T}}| . \end{equation} note that $|z^{100}| = |z|^{100} = 1.$ On the other hand consider another discrete time linear system : \begin{equation} C(z) = \frac{(x+\frac{T}{2}y)z+(\frac{T}{2}y-x)}{z-1} \end{equation} Consider these two linear system connected serially.Then the closed loop system transfer function (with unity feedback) is: \begin{equation} f(x,y,z) = \frac{G(z)C(z)}{1+G(z)C(z)}\end{equation} or \begin{equation} f(x,y,e^{j\omega}) = \frac{G(e^{j\omega})C(e^{j\omega})}{1+G(e^{j\omega})C(e^{j\omega})}\end{equation} **My aim** is to minimize the maximum absolute value of $f$ (respect to $\omega$) over $x $ and $ y$ as mathematically described bellow: \begin{equation} \min_{x, y} \max_{z \; or \; \omega} |f(x,y,z)|\end{equation} This is equal to minimizing the $L_\infty$ norm of $f$ (respect to $\omega$) over $x$ and $y$ (right?) In fact: \begin{equation}\min_{x, y} \max_{\omega} |f(x,y,\omega)| \equiv \min_{x, y} ||f(x,y,\omega)||_{\infty , \;\omega}\end{equation} How can I do the optimization with Mathematica? * * * I try the code below for defining the function and maximizing $f$ respect to $z$:               T = 0.01     z = Exp[I w]     f = (((x + (T/2) y) z + ((T/2) y - x)) (1 - Exp[-0.3 T]))/(           (z^100) (z - Exp[-0.3 T]) (z - 1) + ((x + (T/2) y) z + ((T/2) y - x)) (1 - Exp[-0.3 T]))     maxp = First[ NMaximize[{f[x, y, w], 0 <= w <= 10}, w, Method -> DifferentialEvolution]]      But when I run code, the following error appears: > >     NMaximize::nnum: The function value >     -((0.0029955 (-x + (0.89724 + 0.441543 I) (x + 0.005 y) + 0.005 > y))/((0.120832 -0.165872 I) >      + 0.0029955 ( -x + (0.89724 + <<20>> I) (<<1>>)+0.005 > y)))[x,y,0.457318] >     is not a number at {w} = {0.457318}. >> >   I try different intervals for $w$ but nothing changed. What's wrong with it?


How to compute the residue of $e^{z-\frac{1}{z}}$ at z=0?

I've tried the following but it didn't work:               Residue[Exp[z - 1/z], {z, 0}]      not even this:               Residue[Exp[1/z], {z, 0}]      Manually, I've computed the residue in the following way: $$ f(z)=e^{z-\frac{1}{z}}=e^ze^{-\frac{1}{z}}=\left(\sum_{n=0}^{\infty}\frac{z^n}{n!}\right)\left(\sum_{n=0}^{\infty}\frac{(-1)^n}{n!}z^{-n}\right)= $$ $$ = \sum_{n=-\infty}^{\infty}\left(\sum_{k=\max(0,n)}^{\infty}\frac{(-1)^{k-n}}{k!(k-n)!}\right)z^n $$ Since the residue is the coefficient of $z^{-1}$, it's equal to: $$ \sum_{k=0}^{\infty}\frac{(-1)^{k + 1}}{k! (k + 1)!} $$ Going back to _Mathematica_ , I get:               Sum[(-1)^(k + 1)/(k! (k + 1)!), {k, 0, Infinity}]     (* -BesselJ[1, 2] *)          N[-BesselJ[1, 2], 30]     (* -0.576724807756873387202448242269 *)      How can I get that result without manual computations? Of course, the symbolic result is much preferred.


Mathematica can't simplify ellipse-related trig equation over reals?

f[t_] = -4 + Sqrt[(-Sqrt[3] + 2*Cos[t])^2 + Sin[t]^2] + Sqrt[(Sqrt[3]      + 2*Cos[t])^2 + Sin[t]^2]       The function above is identically 0 for all real values of t. However:               FullSimplify[f[t],Reals]       just spits back the original function. I also tried TrigReduce, TrigExpand, etc, to no avail. How do I make Mathematica simplify things like this? For those interested: I'm playing w/ ellipses, and f[t] represents the sum of the distance from the focii minus the actual value of the sum of the distance from the focii. The more general case:               x[t_] = a*Cos[t]       y[t_] = b*Sin[t]       focus[a_,b_] = Sqrt[a^2-b^2]       f[t_]=Sqrt[(x[t]-focus[a,b])^2 + y[t]^2] + Sqrt[(x[t]+focus[a,b])^2 + y[t]^2]       where f[t] is constant for real t when a >= b (probably when a < b too, but things get a bit complex in that case)


How to write output to an external text file in addition to the standard output stream?

How to write output to an external text file in addition to the standard output stream, i.e. a notebook for a session with FE and stdout for command- line session?


Fourier transformation of solution of differential equation

I'm trying to plot a Fourier transform of solution of differential equation. I have tried with:               Plot[Evaluate@       Abs[FourierTransform[         Re@Evaluate[           p[t] /. NDSolve[{p'[s] == 1 + (-1.3 + I*10 + p[s])*p[s],               p[0] == 0}, p, {s, 0, 10}, MaxSteps -> 100000]],          t, \[Omega]]], {\[Omega], 0, 100}, PlotRange -> All]      without success. What am I doing wrong?


Altering layout and sizing of Manipulate controls?

I'm currently working on a display project using `Manipulate` and was wondering if there is a straightforward way to alter the placement of the control options that I use. For example, the following shows my issue: ![control area](http://i.imgur.com/ewDGbDE.png) The `Manipulate` argument of concern is as follows:               Style["View Control", 16, Bold],     {{setter, True, ""}, {True -> "Zoom", False -> "Pan"}},     ControlPlacement -> Left,      I would just like the Zoom and Pan buttons of the SetterBar to be a bit larger and closer to centered if possible. I've messed with things like `Appearance` and `Alignment`, but haven't really had any luck with previous questions or my own efforts.


How to Simplify equations over a Ring with Mathematica?

For example, when we work over a ring, the equation `x^3=0` does not imply `x^2=0` or `x=0`, but the vice versa is true. Can we use Mathematica to Simplify equations over a ring?


change font size and circle the pointers

**MWE**               {i1, i2} =       Import@# & /@ {"http://i.stack.imgur.com/laZeT.png",      "http://i.stack.imgur.com/LAHyF.png"};     (*Binarize the image and delete speckles to get clear edge detections*)     images = {DeleteSmallComponents@Binarize[i1, .2],      DeleteSmallComponents@Binarize[i2, .2]};     (*match corresponding points in both images*)     Print[Style[       "Find corresponding points in the two images that are similar ",        FontWeight -> "Bold", FontColor -> Blue]]     matches = ImageCorrespondingPoints[images[[1]], images[[2]]]     Print[Style["Find the resulting shift ", FontWeight -> "Bold",      FontColor -> Blue]]     ImgShiftCoord = {Flatten[matches[[1]]][[1]] -      Flatten[matches[[2]]][[1]],      Flatten[matches[[1]]][[2]] - Flatten[matches[[2]]][[2]]}      (*map the matching points in both images and calculate the pixel \     shifts*)     Print[Style["Show the outstanding matching region of interest ",      FontWeight -> "Bold", FontColor -> Blue]]     MapThread[      Show[#1, Graphics[{Red,         MapIndexed[Inset[#2[[1]], #1] &, #2]}]] &, {images, matches}]      **Plot:** ![1](http://i.stack.imgur.com/58mzK.png) * * * How can I change the font size of those markers {1,2,3} and also circle them so that I can show it in my presentation clearly as to what I am talking about ? The font sizes are so small and hard to see of there are many.


Expressing a decimal as a fraction in lowest terms

How can I express a decimal such as 0.1845095405274387 as a fraction in its lowest terms?


How do I constrain the result of fitting my non-linear model to be greater then 0

fitresulty21 =        NonlinearModelFit[ydata21,          {funfit[y, σ, A, B, x1, d, d/2], A > 0},          {{x1, 20}, {σ, 3}, {A, 200}, {B, 2000}, {d, 110}},         y];      Above is the code that I am using to develop a fit to data that is not included here. The result of the fit with the data looks like: ![enter image description here](http://i.stack.imgur.com/i1xYC.jpg) While the data does go slightly below 0 at points, I would like the fit to be constrained to be greater then 0 at all times, but I am unsure how to do that. Any other advice about how I might generally improve this fit is also welcome. The model `funfit` comes from the code:               f[x_, w_] := UnitStep[ x + w/2] * UnitStep[ w/2 - x];     PSF[x_, σ_] := PDF[ NormalDistribution[0, σ], x];     u[x_, A_, B_, x1_, d_, w_] := B - A*(f[x - x1, w] + f[x - x1 - d, w] + f[x - x1 - 2*d, w])     funfit[y_, σ_, A_, B_, x1_, d_, w_] := Convolve[u[x, A, B, x1, d, w], PSF[x, σ], x, y];


Is this integration error from a misuse of Mathematica or is it my poor math skills?

I have input this:               Integrate[1, f[t]*Exp[(v/V)*t]]      That is $\large\int 1*d(f(t)*e^{\frac{v}{V}*t})$ I expected this output: $\large f(t)*e^{\frac{v}{V}*t} + C$ but instead I get:               Integrate::ilim: "Invalid integration variable or limit(s) in E^((t\v)/V)\ f[t]. "      What am I doing wrong ? PS: in the model at the origin of my troubles t is the only variable v and V are constants


how to write my own interpolation method

I was comparing results of spline interpolation in Mathematica and C++/gsl- library Results of interpolation are different if I use:               Method -> "Spline", InterpolationOrder -> 3 in Mathematica      and cubic spline in C++ I believe this is due to difference in methods used by Mathematica and C++. While the method spline interpolation is generated in C++ is known I have no idea what Mathematica calls a cubic spline (probably BSpline , but I am not sure as C++ doesn't seem to have implementation of BSpline, so I can't compare) I thought of implementing C++ spline method in Mathematica to make one to one comparison to C++. Other option would be to learn what algorithm does Mathematica use for spline interpolation, but I believe it is not open source, or is it?


Using a web-crawler to search website for occurrences of keywords

Given this list of cities:               cities = {"Al-Safira", "Al-Nabk", "Qatana", "Al-Qutayfah", "Al-Tall",         "Yabrud", "Zabadani", "Izra", "Al-Sanamayn", "Hama", "Masyaf",         "Mudardeh", "Salamiyah", "Al-Suqalaybiyah", "Homs", "Al-Mukharram",         "Palmyra", "Al-Qusayr", "Talkalakh", "Idlib", "Arihah",         "Jisr al-Shugur", "Latakia", "Al-Haffah", "Jableh", "Qardaha",         "Quneitra", "As-Suwayda", "Salkhad", "Shahba", "Tartus", "Baniyas",         "Duraykish", "Safita", "Al-Shaykh Badr", "Atarib",         "South Mount Simeon", "Abu Kamal", "Mayadin", "Al-Rastan", "Harem",         "Ma'arrat al-Numan", "Fiq", "Al-Bab", "Dayr Hafir", "Jarabulus",         "Manbij", "Al-Raqqah", "Tell Abyad", "Al-Tharwah", "Afrin",         "Ayn Al-Arab", "Al-Malikiyah", "Ra's al-'Ayn",         "South Mount Simeon", "North Mount Simeon", "Aleppo", "Azaz",         "Darayya", "Duma", "Qudsaya", "Markaz Rif Dimashq", "Daraa",         "Deir ez-Zor", "Al-Hasakah", "Al Qamishli"};      Can I create a _web-crawler_ to search on bbc.co.uk/news in order to produce a table which shows how many times each city is mentioned on their website?


How to make dynamic input fields work with drag & drop

I have an application using `InputField` to allow a user to dynamically update a data structure. In some cases the user will want to remove a string from one field and paste it into another. If this is done using cut and paste everything works okay, and the underlying data updates to reflect what is seen in the GUI. However, if the string is moved using drag and drop, the `Dynamic` in the source field does not appear to register the change of contents, although the destination field works as expected. Here's an example:               test = {"string", ""};     Column[{       InputField[Dynamic[test[[1]]], String],       InputField[Dynamic[test[[2]]], String],       Dynamic[test]       }]      ![enter image description here](http://i.stack.imgur.com/xhL3k.png) If I now drag and drop the string from the upper field into the lower field I get this: ![enter image description here](http://i.stack.imgur.com/GYxGP.png) The upper input field is now empty but `test[[1]]` still contains `"string"`. This is a problem, because normally the `Dynamic[test]` line won't be there so the user relies on the input fields to correctly show the actual contents of `test`. How can I fix this?


Raspberry Pi GPIO operations with Mathematica

I started exploring GPIO operations on the RPi with _Mathematica_ by following this brief tutorial which describes how to use `DeviceWrite` to cycle an LED on and off. A natural extension is to use `DeviceRead` to find the current value of the pin, and this seems to work as well. I then thought I would attempt to translate some of the introductory python scripts that Adafruit uses to demonstrate basic features of the RPi GPIO programming. In particular, I am trying to operate a basic photocell for light monitoring. The meat of the python code is this:               def RCtime (RCpin):             reading = 0             GPIO.setup(RCpin, GPIO.OUT)             GPIO.output(RCpin, GPIO.LOW)             time.sleep(0.1)                  GPIO.setup(RCpin, GPIO.IN)             # This takes about 1 millisecond per loop cycle             while (GPIO.input(RCpin) == GPIO.LOW):                     reading += 1             return reading      which I first attempted to replicate with:               lightMeasure[] := Module[{r = 0, pin = 23},         DeviceWrite["GPIO", pin -> 0];         While[(pin /. DeviceRead["GPIO", pin]) == 0, r++];         r     ]      This function always returns 0. Executing something like:               DeviceWrite["GPIO", 23->0];DeviceRead["GPIO",23]      Gives a value of 1, which I interpret to mean that the `DeviceWrite` operation is not discharging the capacitor. To test this, I removed the circuit from +3.3V and executed the code above, and the result is still 23 -> 1. I can then physically remove the capacitor, discharge it and return it to the circuit. Finally, I get 23->0. Looking at the python code, I _think_ that the `GPIO.setup`/`GPIO.output`/`time.sleep` commands force the pin low for 100 ms, allowing the capacitor to discharge. It does not look like the analogous _Mathematica_ command, `DeviceWrite` is able to do the same thing. Is there some way I might be able to force a Device object to maintain a set value for a given amount of time?


Mapping functions over multiple lists

I am not sure if this is a duplicate. Spent some time looking over list-manip questions. I’d like to know the Quickest Way to achieve the following Mapping of a function over multiple lists. Suppose we have multiple lists of unequal length:               l1 = {a, b, c, d};     l2 = {x, y, z};     l3 = {u, v};      **Q1 What is the quickest way to generate another list as follows (where f is a function):**               {{f[a, x, u], f[b, x, u], f[c, x, u], f[d, x, u]},     {f[a, y, u], f[b, y, u], f[c, y, u], f[d, y, u]},     ...     {f[a, z, v], f[b, z, v], f[c, z, v], f[d, z, v]}}      Now suppose you have a list of functions:               {f,g,h,i}      **Q2 What is the quickest way to generate a list as follows:**               {{f[a, x, u], g[b, x, u], h[c, x, u], i[d, x, u]},     {f[a, y, u], g[b, y, u], h[c, y, u], i[d, y, u]},     ...     {f[a, z, v], g[b, z, v], h[c, z, v], i[d, z, v]}}


Dsolve not working

I am new to using `DSolve`. In trying to solve a differential equation I was getting nonsense from _Mathematica_ , so I tried to solve an even easier equation $\frac{du}{dt}=u$, but still I get nonsense. My _Mathematica_ input is               Clear[u, t];     DSolve[u'[t] == u[t], u, t]      And the output it gives is               {{u -> Function[{t}, 0]}}      How am I supposed to interpret this? We all know the solution should be $u=e^t + C$. What is _Mathematica_ doing here?


How to monitor the progress of a plot

Im a _Mathematica_ newbie. Can someone tell me how to watch the progress of a plot. For example say I want to watch the curve `Exp[-x]` when `x` progresses from 0 to 5. How could I do that?


add a scale bar to a microscopy image?

Is there any way to add scale bar to a image for example. I just need to add a bar and a text on top of it to all my images without having to rewrite               Graphics[{Thick, Thick, Yellow, Line[{{100, 100}, {166, 100}}],              Text[Style["10 μ", Yellow, Bold, 25], {120, 110}]}]      for every image. I just want to put this bar and text at left corner of the images I have. ![1](http://i.stack.imgur.com/HtLcX.jpg)


Is it possible to disable assumptions used by FullSimplify for zero testing

Sometimes when I invoke `FullSimplify` on a large expression, I get a series of messages like this:               FullSimplify::ztest1 "Unable to decide whether numeric quantity «1» is equal to zero. Assuming it is."      I suppose _Mathematica_ makes this assumption when numeric calculations with reasonably high precision do not produce a number that can be distinguished from the exact `0`. While in certain cases this is useful, I want to be able to disable this assumption in cases that I believe involve tiny non-zero quantities. **Is it possible to disable this kind of assumption in`FullSimplify`?**


Can Mathematica (or its extensions) do integration following Risch algorithm?

I wonder whether there are option for indefinite integration in Mathematica that alow to choose the algorithm? Is there an option to use this algorithm in Mathematica?


How can I link the c library GAUL into Mathematica?

Is there a way to load the library GAUL (Genetic Algorithm Utility Library) for use within Mathematica?


Making a plotted curve interactive

Is it possible to make a plotted curve interactive in the sense that when hovering over it a line is drawn from the "hovered" point to one (or both) of the axes. I did do my homework, I just can't figure it out. Edit: Let's say I plot this curve:               Manipulate[Plot[Sin[a x],{x,0,Pi}],{a,1,5}]      Whenever the mouse hovers over a point on the curve a line is drawn from that point to the x-axis.


how implement OOP

I have a task implement OOP in wolfram mathematica. I think write class Point and inherit from it class Rectangle. In C# or C++ it's very easy, but I don't know how do it in wolfram mathematica. All books which I found I must pay for them. Can you advise some free books, or give examples how write and work wit classes. Tnanks,Maria.


Threading Distribute[]

I wish to use `Distribute[p.(q+r)+m]` to get `p.q+p.r+m`. However, Distribute apparently does not thread through all parts of the expression. What should I do instead?