Minimize solution to linear system with singular system matrix

I am trying to solve a time-dependent linear system with a singular system matrix, $A$, thus an infinite number of solutions, ${\bf x}$(t), exist that satisfy the linear system. The solution I am looking for is one that minimizes the maximum value of the functions x(t). The problem can therefore be phrased as minimizing the square of L2-norm of the maximum of x(t) subject to the Ax=b equality constraints: $$ \text{Minimize}~~\vert~\text{Max}[{\bf x}(t),t]~\vert_2^2 $$ $$ \text{such that}~~{\bf Ax}(t)={\bf b}(t) $$ I can solve this system at one point in time ($t=t_0$), but am looking for a solution ${\bf x}(t)$. My current code is:               (*provide base values*)     n1 = 1;     n2 = 1;     n3 = 1;     i1 = Cos[ω*t];     i2 = Cos[ω*t - (2 π/3)];     i3 = Cos[ω*t - (-2 π/3)];          (* Clear base values and use symbolic representations *)     nbase = {n1, n2, n3};     ibase = {i1, i2, i3};     Clear[i1, i2, i3, n1, n2, n3];          (*values used to form 'A' and 'b' *)     coilList =       {        {1, 19, i1, n1},        {2, 20, i1, n1},        {3, 21, i1, n1},        {4, 22, i1, n1},        {5, 23, i1, n1},        {6, 24, i1, n1},             {7, 25, -i3, n3},        {8, 26, -i3, n3},        {9, 27, -i3, n3},        {10, 28, -i3, n3},        {11, 29, -i3, n3},        {12, 30, -i3, n3},             {13, 31, i2, n2},        {14, 32, i2, n2},        {15, 33, i2, n2},        {16, 34, i2, n2},        {17, 35, i2, n2},        {18, 36, i2, n2}        };          qs = 36;          (*create b vector*)     bVec = ConstantArray[0, {qs, 1}];     For[j = 1, j <= Dimensions[coilList][[1]], j++,      bVec[[coilList[[j, 1]], 1]] += coilList[[j, 3]]*coilList[[j, 4]];      bVec[[coilList[[j, 2]], 1]] += -coilList[[j, 3]]*coilList[[j, 4]];      ]          (*form A matrix*)     aMat = DiagonalMatrix[Table[-1, {j, 1, qs - 1}], -1];     For[j = 1, j <= qs, j++,       aMat[[j, j]] = 1;       ];     aMat[[1, qs]] = -1;          (* create symbolic unknown vector*)     xVec = Table[Symbol["x" <> ToString[j]], {j, 1, qs, 1}];          (* introduce Ax=b as a list of equality constraints *)     constraints = Table[Sum[aMat[[j, k]]*xVec[[k]], {k, 1, Length[xVec]}]         == bVec[[j, 1]], {j, 1, Length[bVec], 1}];          (* find unconstrainted solution by minimizing the squared 2-norm of \     the slot MMFs *)     Block[{i1 = ibase[[1]], i2 = ibase[[2]],i3 = ibase[[3]],             n1 = nbase[[1]], n2 = nbase[[2]], n3 = nbase[[3]]},      solMin = FindMinimum[         {Norm[Table[MaxValue[xVec[[j]], t], {j, 1, Length[xVec]}], 2]^2,           And @@ Thread[constraints]}, xVec];      ]     xSol = xVec /. solMin[[2]];      Any help would be Greatly appreciated!


Mapping a function over the parts of a deeply nested Array

I have two tensors:                   tensorS = Array[Subscript[s, #1, #2, #3, #4] &, {2, 16, 16, 19}];         tensorR = Array[Subscript[r, #1, #2, #3] &, {2, 16, 19}];      Here is a `Part` of the solution that I want to obtain:                   Map[Plus[tensorR[[1, 1]], #] &, tensorS[[1, 1]], {1}];      which is the same as:                   Thread[Plus[Transpose[tensorS[[1, 1]]], tensorR[[1, 1]]], List];      or:                   Inner[Plus, tensorS[[1, 1]], tensorR[[1, 1]], List];      The resulting tensor should have `Dimensions` `{2,16,16,19}`. It can be seen from the part of a solution, that I want to add every element of a `tensorR` (defined by it's indices `i1,i2,i3`) to the corresponding elements of a `tensorS` `i1,i2,i3,i4`, for all indices `i3` of a `tensorS`. First `i1`, second `i2`, and third index `i3` of `tensorR` correspond to first `i1`, second `i2` and fourth `i4` index of `tensorS`, respectively. This is the solution I want to get, but without using Table:                   Table[Map[Plus[tensorR[[i, j]], #] &, tensorS[[i, j]], {1}], {i, 1, 2}, {j, 1, 16}];      $Q$: How to use the combination od `Thread`, `Map`, `MapThread`, `Transpose` and `Inner` functions to obtain the above result? I want to avoid using `Part` and `Table`. I'm sure that there's elegant solution that can be written in one line, but I'm not that good with deeply nested lists, so I decided to ask for your help. I've searched the forum and couldn't find the solution. I apologize if my question is a duplicate.


Request help for reading text data files with headers and 2 sections

I just started with _Mathematica_. I need it for many purposes, but the important one is to read a text data file and extract column values as variables. I have successfully tested the tab delimited data format. Now I have a problem with a file with this format: > 15 lines of comments with spaces and blank lines   >  7 col and 100 lines: Col haves headers.   >  The above is repeated after 3 blanks lines. Any comments and suggestions are welcome


Solving Intervals

In a recent question I posed, it was noted that by design, Sqrt[ blah] only returns the positive branch, even though we might want to obtain all possible symbolic solutions. So, taking care to avoid the Sqrt function here in my input :), suppose I am interested to find the intervals that, when squared, generate the Interval[{0,4}]:               Solve[Interval[{0, 4}] == y^2, y]      This returns:               {{y -> Interval[{-2, 0}]}, {y -> Interval[{0, 2}]}}      How should we then obtain the missing solution:               expr = Interval[{-2, 2}];  expr^2     Interval[{0, 4}]      … that nests all others? [P.S. I suppose a Union applied to the output might do the trick, but I'm not sure a trick is the real point to the question.]


Computing the volume and the curved surface area

I'm trying to compute this function $y=\frac{1}{2}e^x+\frac{1}{12}e^{-3x}$ to get the volume of the solid of revolution when the area under the curve is revolved once around the x axis. And than get the curved surface area of the solid of revolution from the previous part. This is the equation needed to get the volume $\int \pi y^2dx$. And this is how I computed the function in Mathematica               Pi*Integrate[((1/2)*Exp[x] + (1/12)*Exp[-3x])^2, {x, 0, 1}]      What did I do wrong? Because the solution comes out without $x$ and I can't differentiate it and get the covered surface area with this equation $2\pi \int_{a}^{b}y \sqrt{1+(\frac{dy}{dx})^2}dx$


Why is FindInstance failing when I relax a set of constraints?

I'm attempting to use FindInstance to generate coordinate sets for plausible triangles with edge length distance constraints. E.g.:               PlaneDimensionXYnm = 1000;     TriangleEdgeDistance = 400;          TriangleSolution = {};     While[Length[TriangleSolution] == 0,       x1 = RandomReal[{200, PlaneDimensionXYnm - 200}];       y1 = RandomReal[{200, PlaneDimensionXYnm - 200}];          TriangleSolution = FindInstance[           EuclideanDistance[{x1, y1}, {x2, y2}] == TriangleEdgeDistance &&           EuclideanDistance[{x1, y1}, {x3, y3}] == TriangleEdgeDistance &&           EuclideanDistance[{x2, y2}, {x3, y3}] == TriangleEdgeDistance &&           x2 >= 200 && y2 >= 200 &&           x3 >= 200 &&  y3 >= 200 &&           x2 <= PlaneDimensionXYnm - 200 &&           y2 <= PlaneDimensionXYnm - 200 &&           x3 <= PlaneDimensionXYnm - 200 &&           y3 <= PlaneDimensionXYnm - 200, {x2, y2, x3, y3}];         ];          TriangleCoordinates = N[{x2, y2, x3, y3} /. TriangleSolution[[1]]];      While the above script works fine (albeit inefficiently, but it doesn't matter for me), the below script fails:               TriangleSolution = {};     TriangleEdgeDistance = 400;          While[Length[TriangleSolution] == 0,       x1 = RandomReal[{200, PlaneDimensionXYnm - 200}];       y1 = RandomReal[{200, PlaneDimensionXYnm - 200}];            TriangleSolution = FindInstance[           EuclideanDistance[{x1, y1}, {x2, y2}] > TriangleEdgeDistance &&           EuclideanDistance[{x1, y1}, {x3, y3}] > TriangleEdgeDistance &&           EuclideanDistance[{x2, y2}, {x3, y3}] > TriangleEdgeDistance &&           x2 >= 200 && y2 >= 200 &&           x3 >= 200 && y3 >= 200 &&           x2 <= PlaneDimensionXYnm - 200 &&           y2 <= PlaneDimensionXYnm - 200 &&           x3 <= PlaneDimensionXYnm - 200 &&           y3 <= PlaneDimensionXYnm - 200, {x2, y2, x3, y3}];         ];          TriangleCoordinates = N[{x2, y2, x3, y3} /. TriangleSolution[[1]]];      All I've done here is relax the constraint that the triangle edges should be the same length, and required that the edges all be greater than a certain length. Why does FindInstance now fail?


How to change Compiled->False to Method->{Compiled->False} in multiple notebooks?

I have a collection of about 40 notebooks where the options for ParametricPlot and ParametricPlot3D have:               Compiled->False      and I need to switch any/all instances to               Method->{Compiled->False}      Is there a way to do this via Mathematica v.9? One challenge is that I do not know all the notebooks which may or may not have this. Perhaps Mathematica is not the proper tool and this is more of shell scripting exercise? Any thoughts on the best way to approach this would be greatly appreciated. Cheers, t. PS - Mac OS X, Mathematica v.9 (latest update)


How do I create a graph with randomly directed edges starting from a undirected graph?

I have an undirected graph $G$. How would I randomly assign directions to some fraction $p$ of the edges? How might I do this efficiently / quickly provided I have a large graph structure? For example, to assign a graph random edge weights, I might write:               GraphWithRandomWeights = Graph[EdgeList[G], EdgeWeight -> Table[RandomReal[{-1, 1}], {abc, 1, Length[EdgeList[G]]}]];


Changing a tag when one function is passed into another using UpValues

I have two complicated functions `f[x,y]` and `g[t]`. Before the main evaluation code in `g[expr]`, I run some computationally expensive tests to check that `expr` has correct syntax. If `expr` does not have correct syntax, it gives an error to the user. But otherwise, it continues. Now, the output of `f[x,y]` can be used as input of `g` (as in `g[f[x,y]]`). The result of `f[x,y]` is usually very _very_ complicated, but _always_ has correct syntax for the function `g`. Thus to save time I want to bypass the computationally expensive but pointless checks in `g`. For this I invented a tag: `$needsErrorChecking`, which is supposed to by switched to `False` if `f` and `g` are called in the nested form `g[f[x,y]]`. Otherwise it is `True`, in which case the error checking routines take place. Here is my toy example:               Clear[f, g]      f[x_, y_] := x + y          $needsErrorChecking = True;         g[f[z__]] ^:= "Nothing" /; ($needsErrorChecking = False);         g[t_] := Module[{variables}, Print[$needsErrorChecking];        If[$needsErrorChecking,(*Complicated Code*) Null, $needsErrorChecking = True]; 2*t];      However, Running               g[f[x, y]]      yields `True` and `2(x+y)`. So it gives the correct answer, but the error checking code isn't bypassed. What can I do to fix this? Or, is there a totally different way to go about accomplishing this task?


How do I write a function that can be used in a rule to modify both sides of an equation?

I sometimes need fine grain control over equations in _Mathematica_ in order to help me understand how to solve a problem manually. A greatly simplified example of a session might be something like this:               2x + 3 == 5x - 7      > 2 x + 3 == 5 x - 7               % /. lhs_ == rhs_ -> lhs - 2x == rhs - 2x      > 3 == 3 x - 7               % /. lhs_ == rhs_ -> lhs + 7 == rhs + 7      > 10 == 3 x               % /. lhs_ == rhs_ -> lhs / 3 == rhs / 3      > 10 / 3 == x Instead of constantly writing expressions like `lhs_ == rhs_ -> lhs - 2x == rhs - 2x`, I would like to write function calls like `eqnx[e - 2x]` where the `e` represents the expression being modified and is applied to both the lhs and rhs of the equation. My intuition leads me to believe that this is exactly inline with _Mathematica_ 's strengths, but my rational mind cannot deduce anything close to a correctly working function. Is this possible? Or, should I be taking a different approach? **Edit** : Xerxes gives an excellent method below for accomplishing this task using the built-in `Distribute[expr, g]` function. Now that I understand how `Distribute` works, I can see that it is very useful. I have been using his technique with a small tweak to reduce the amount of typing required and here is a sample session:               eqx[e_] := Distribute[e, Equal]          2 x + 3 == 5 x - 7     eqx[% - 2x]          3 = -7 + 5 x     eqx[% + 7]          10 = 3 x     eqx[% / 3]          10/3 = x      The intention of my original question, however, was a rule based technique so that I could more easily work with lines of input or output that already existed (I think my question states this but my detailed description did not reiterate that point). The function approach is efficient as long as you can use `%`, but in most of my work I am iteratively trying different things on the same input and I cannot reliable use `%` and must be remember to grab the correct `In[#]` or `Out[#]`. Based on the answers to this question and others on this forum, I was able to figure out a rule based solution. While the functionality is similar, the specifics of using the function make for a different user experience. Here is a sample session:               reqx[e_] := lhs_ == rhs_ -> (e /. expr -> lhs) == (e /. expr -> rhs)          2 x + 3 == 5 x - 7 /. reqx[expr - 2x]     3 == -7 + 3 x /. reqx[expr + 7]     10 == 3 x /. reqx[expr / 3]     10/3 == x      The one issue that I don't understand how to address relates to the placeholder `expr` that I use in calls to the `reqx` function. Inside the function this symbol gets replaced by the `lhs` and `rhs` expressions to produce the result. Its only function is to serve as a placeholder in the expression given to the `reqx` function. As long as `expr` does not have a value (or rule in Mathematica parlance), everything works fine. Is there something I can do to mitigate or eliminate this potential snafu in usage? **Edit 2:** I believe the following definition appropriately protects the placeholder from evaluation:               reqx[e_] := lhs_ == rhs_ -> (Unevaluated[e] /. HoldPattern[expr] -> lhs)          == (Unevaluated[e] /. HoldPattern[expr] -> rhs)     SetAttributes[reqx, HoldAllComplete]


Using citations with Workbench

I have written a tutorial (.nb file) for a package using Workbench. In the tutorial there are some citations created with the recently introduced citation management system. They are simply numbered links to footnoted text. Nothing fancy. It works well initially: I click on the link and the .nb file scrolls to the corresponding footnote. However, after I create a build, the links no longer work in the built tutorial file. The n-th link target appears to be :paclet/ref/n and it does not work anymore. Can someone please confirm this (possible) bug and/or suggest workarounds?


How to expand tan(x+y) as normal form?

TrigExpand@Tan[x + y]      gives $\frac{\sin (x) \cos (y)}{\cos (x) \cos (y)-\sin (x) \sin (y)}+\frac{\cos (x) \sin(y)}{\cos (x) \cos (y)-\sin (x) \sin (y)}$ but I expected $\frac{\tan (x)+\tan (y)}{1-\tan (x) \tan (y)}$ Evaluating `TrigExpand` with arguments $\tan (x-y)$ or $\tan (3*x)$ also returns results in terms of sine and cosine. What should I do to get results in terms of the tangent?


Simplifying the derivative of $|x|$

## Context               In[855]:= D[Abs[x], x] /. x -> 1          Out[855]= Derivative[1][Abs][1]          In[856]:= D[x, x] /. x -> 1          Out[856]= 1      ## Question Why is `Derivative[1][Abs][x]` not simplifed to 1 when `x -> 1`?


Different determinants on 2 different computers

Is there any way to force `Det` to do itself in a certain way? I've been running the same notebook on 2 differents computer, one MacOSX Lion and one W7 (both 32bit) with _Mathematica 8.0.0.0_ on the two of them, and we don't get the same `Det` expression and `Solve[Det[F[x]]==0,x]` doesn't give the same solutions either. How to know which one says the truth? How could we calculate the `Det` in order the have the same solutions on both computers?   Note: as its the same nb the matrices (26*26) are exactly the same.


Why am I not getting a numeric response?

## Code               In[830]:= curvature[x_, y_, z_, t_] :=      With[{s = {x, y, z}},       With[{v = D[s, t]},        With[{ fT = v / Norm[v]},         With[{fK = D[fT, t] / Norm[v]},          Norm[fK]          ]         ]        ]       ]     curvature[ Cos[t], Sin[t], t, t] /. t -> 1 // N          Out[831]= \[Sqrt](0.5 Abs[-0.59501 -            0.0955129 (-0.909297 Derivative[1][Abs][0.540302] +               0.909297 Derivative[1][Abs][0.841471])]^2 +         0.5 Abs[-0.382051 +            0.148752 (-0.909297 Derivative[1][Abs][0.540302] +               0.909297 Derivative[1][Abs][0.841471])]^2 +         0.015625 Abs[-0.909297 Derivative[1][Abs][0.540302] +            0.909297 Derivative[1][Abs][0.841471]]^2)      ## Question I have a // N there. Why do I not get a numerical answer. Instead, why do I have Derivative[1][Abs] all over the place? Thanks! ## EDIT The following "fixes" the code. Why?               myNorm[lst_] := Sqrt[lst . lst]     curvature[x_, y_, z_, t_] :=      With[{s = {x, y, z}},       With[{v = D[s, t]},        With[{ fT = v / myNorm[v]},         With[{fK = D[fT, t] / myNorm[v]},          myNorm[fK]          ]         ]        ]       ]     curvature[ Cos[t], Sin[t], t, t] /. t -> 1 // N      This returns 0.5


Matrix Rational Canonical Form

Is there a way to calculate the _Rational Canonical Form_ of an $n\times n$ integer matrix using _Mathematica_? I have been perusing the documentation and web, but nothing so far.


Anti-aliasing not working in Mathematica 10 and Linux

While this works fine in version 9, in version 10.0 the Antialiasing setting has no visible effect any more > ![enter image description here](http://i.stack.imgur.com/cZhBG.gif) I'm here on Ubuntu 12.04 64-bit with Gnome 3.4.2 and an NVidia GeForce GTX 590 with NVidia driver. Do others experience this and is there any known solution to the problem?


How can I get Mathematica to simplify $\Vert\{1,\sin(t),\cos(t)\}\Vert_2$ to $\sqrt{2}$?

## Context               Norm[{1, Sin[t], Cos[t]}]     Norm[{1, Sin[t], Cos[t]}] // Simplify     (*     Sqrt[1 + Abs[Cos[t]]^2 + Abs[Sin[t]]^2]         Sqrt[1 + Abs[Cos[t]]^2 + Abs[Sin[t]]^2]     *)      ## Question: How do I coax _Mathematica_ to output `Sqrt[2]`?


When do I use Mathematica, when do I use Gephi, and how do I use them together?

Mathematica has great operations for analyzing graphs but when the graphs are a bit bigger, Gephi seems to be more efficient (at least on my computer) at drawing and analyzing, i.e. visualizing the graph. So my question is: **What is the "best practice" (white papers, web pages or similar) for how to divide the work between Mathematica and Gephi?** Here is an example, I have a graph from an analysis of all offerings and the biggest clients of a midsize telecom operator, if a client has been invoiced for the offering, there is an edge between the client and the offering. The bipartite graph (see http://mathworld.wolfram.com/BipartiteGraph.html) has about 540 nodes (clients and offerings) and about 14900 edges.   ![enter image description here](http://i.stack.imgur.com/BfoSO.png) In the image - Gephi visualization of "Force Atlas" layout - you see that the core offerings gravitate to the middle. Clients (blue nodes) become grouped around some key offerings (name of clients are removed), e.g. in the upper right corner of the graph you have all the multinationals that are buying international calls and data offerings. Seeing the clients and offerings in this way is useful for reasoning around a number of business questions such as market segmentation, bundling of offerings, solution building and reasoning around strategic options. ## Background I started doing the experiments in Gephi but after learning more about Mathematica, I would like move more of the work (if not all) to this environment. However, importing the graph to Mathematica using .gml file from Gephi failed for me. The symptom was that the evaluation of the Import function in Mathematica failed to terminate. The reason for wanting to import to Mathematica is for more control of normalizing data, annotations, analysis, and simulations based on the graph. This cannot be done in Gephi. Same question posted on the Gephi forum Gephi - MMA ## Miscellaneous notes Gephi (or similar programs) seems to be faster than Mathematica for the visualization. Key points for using Gephi initially was the ability to handle the large amount of nodes and edged and the layout algorithms. The "tags" that seem to be relevant for finding our more are:   * import   * export   * graphs-and-network   * graph-theory


Setting the Accuracy of calculations

I am optimizing an equation that involves a number of trigonometric functions and `Exp[]`. How do I make sure that all my calculations have an accuracy of 120-200 digits after the decimal point? This includes the accuracy of `Exp[]` and trig functions. To get my point across, here is part of the equation: `z[x_, y_]:= Exp[Sin[60.0*x]] + Sin[50.0*Exp[y]]` Mathematica lets you control `Precision` of computations (which is total number of digits in the number) with two global variables - `$MinPrecision` and `$MaxPrecision`. However, I am not looking for precision.


How can I get this Graphics3D to rotate around a particular sphere?

I made this `Graphics3D` of the Sun with the plotted orbits of a few astronomical objects.               otherCelestials = AstronomicalData["MinorPlanet"][[;; 10]];     Graphics3D[{       {Yellow, Sphere[AstronomicalData["Sun", "Position"], 0.05]},       AstronomicalData[#, "OrbitPath"] & /@ otherCelestials       }, Axes -> True, SphericalRegion -> True]      ![enter image description here](http://i.stack.imgur.com/6VPII.png) I would like it to rotate around the sphere representing the sun's position though. At the moment the `ViewCenter` is somewhere next to the sun, which means that when you rotate the plot, it rotates around that point and not the sun. How can I make it so that it rotates around the sun? (The obvious thing to do would be set the `ViewCenter` of the plot to the coordinates of the sun, but in this case the sun's coordinates are given as `{0, 0, 0}`, but that just makes the `ViewCenter` point to the corner of the graph.)


Sending RObject to RFunctions

I want to realize function from some R package in Mathematica. First load RLink and package what I need               Needs["RLink`"]     InstallR["RHomeLocation" -> "c:\\R-2.15.3\\"]     REvaluate["library(\"randomForest\")"]      then create RObject               rf=REvaluate["randomForest(Species~ .,data=iris,importance=TRUE,proximity=TRUE)"];      create RFunction that takes an RObject as input               treeSize = RFunction["treesize"]      Here start a problem. When I call this fuction               treeSize[rf]      its return following error message               RSet::puterr: Error putting the expression ... into a variable myRandomVar123456782845 in R. The last error message issued by R was Error in attr(myRandomVar123456782845[[10]], "dimnames") <- myRandomVar123456751330: 'dimnames' must be a list


Long running time

I gave this data as input:               Integrate[((x+z) EllipticE[-((4 Subscript[b, 1] Subscript[b, 2])/((x+z)^2+(Subscript[b,1]-Subscript[b, 2])^2))])/(Sqrt[(x+z)^2+(Subscript[b, 1]-Subscript[b, 2])^2] ((x+z)^2+(Subscript[b, 1]+Subscript[b, 2])^2)),{x,a,-a}]      However, It took forever to process the input and calculate the definite integral. After an hour or so it gave me the outpust same as input. I know it is a bit complicated bu I have no idea how to simplify the input. I also use Assuming command to help processing but it didn't change anything. It again took forever to compute the input and gave me the output same as input. What should I do? P.S:I am running Mathematica 10.0


Exporting and reimporting a list of lists changes the dimensions

Could anyone explain to me what in the world is going on here and please help me in reading in `dummy.dat` properly?               dummy = Table[{k, 2*k/m}, {k, 1, 10}, {m, 1, 10}];         Dimensions[dummy]         (*{10, 10, 2}*)          Export["dummy.dat", dummy];         dummyImport = Import["dummy.dat", "Data"];         Dimensions[dummyImport]         (*{10, 20}*)      **Edit:** Just in case anyone exports their precious data as above and needs to read it in properly, the following simple fix worked for me:               dummyReconst = Table[     {     ToExpression[StringJoin[StringCases[dummyImport[[m, k]], RegularExpression["[^{},]"]]]],     ToExpression[StringJoin[StringCases[dummyImport[[m, k + 1]], RegularExpression["[^{},]"]]]]},      {m, 1, Dimensions[dummyImport][[1]]     }, {k, 1, Dimensions[dummyImport][[2]], 2}     ];          Dimensions[dummyReconst]     (*{10, 10, 2}*)


Getting lengths of sublists that sum to more than one

I have a long list of numbers, and I'm interested in finding the length of each sublist that totals to more than 1, so for the list               {0.423768, 0.157558, 0.675251, 0.685209, 0.580772, 0.0230333,       0.927156, 0.506085, 0.0516773, 0.485349}      I would get the lengths `{3, 2, 3}`, as               Total[{0.423768, 0.157558, 0.675251}] == 1.25658     Total[{0.685209, 0.580772}] == 1.26598     Total[{0.0230333, 0.927156, 0.506085}] == 1.45627      The last two numbers total to 0.537026, so we ignore them. This has an easy imperative solution:               thresholdFor[nums_List] :=       Module[{i = 0, sum = 0, k = 0},        Reap[          For[i = 1, i <= Length@nums, ++i,           sum += nums[[i]];           ++k;           If[sum > 1,            Sow[k];            k = 0;            sum = 0]]][[-1, 1]]];     thresholdFor[{}] = {};      In addition to being kind of ugly and needing the `For`, it's also pretty slow, as functions that index into lists so often are. It takes about 0.04 seconds to process a list of 10000 random numbers (picked uniformly between 0 and 1). I futzed around with `LengthWhile`, `TakeWhile` and the like before deciding tha I really needed the full generality of `Fold` to accomplish what I needed to do:               thresholdFold[nums_] :=      Flatten@Last@Fold[         With[{sum = #[[1]] + #2, length = #[[2]] + 1, acc = #[[3]]},           If[sum > 1,            {0, 0, {acc, length}},            {sum, length, acc}]] &,         {0, 0, {}},         nums]      This is arguably more idiomatic, but it's even a bit slower than `thresholdFor`. I can speed `thresholdFor` up _a lot_ by compilation (with a suitable adaptation to get rid of the `Reap`/`Sow` pair) and a little wrapper to handle the empty list properly:               compiledBody =       Compile[{{nums, _Real, 1}},        With[{n = Length@nums},         Module[{result = ConstantArray[0, n], sum = 0.0, k = 0, fill = 0, i},          For[i = 1, i <= n, ++i,           sum += nums[[i]];           ++k;           If[sum > 1.0,            result[[++fill]] = k;            k = 0; sum = 0]];          Take[result, fill]]]];          thresholdCompiled[nums_List] := compiledBody[nums];     thresholdCompiled[{}] = {};      This is dramatically faster after compilation--it runs in about 10 ms for the list of 100000 numbers, and is only about 10 times slower than `Mean` or `Total` on the same data. Still, I always think I'm going down a bit of a blind alley when I start using `Compile` to make imperative list-processing algorithms fast enough to use. Finally, I did come up with something more Mathematica-esque, but it's actually much slower than the compiled solution (taking about 130 ms):               thresholdClip[nums_] :=         Differences@Flatten@Position[             FoldList[Clip[Plus[##], {0.0, 1.0}, {0.0, 0.0}] &, 0.0, randoms],              0.0]      I've tried a couple tweaks for speeding up `thresholdClip`, including one which replaces `Position` with `Pick` so I can compile the whole thing, but that didn't seem to do a lot of good.


Integral of the Sinc product

Let as consider the following integral $$ B_n = \int_0^\infty \prod_{k=1,3,5,\dots}^n\frac{\sin (x/k)}{x/k}dx $$ By definition, `Sinc[x]=Sin[x]/x` therefore               B[n_?OddQ] := Integrate[Product[Sinc[x/k], {k, 1, n, 2}], {x, 0, Infinity}]          B /@ Range[1, 13, 2]      > >     {Pi/2, Pi/2, Pi/2, Pi/2, Pi/2, Pi/2, Pi/2} >   OK, everything is fine. But...               B[15]      > >     467807924713440738696537864469 Pi/935615849440640907310521750000 >   What's going on?


Discrete coloring in Plots

I would like to have a plot that is filled to the axis with `Green` if the `y` value is greater than 10, and `Blue` if it is less than 10. I attempted to do the following: `Plot[x, {x, 0, 20}, Filling -> Axis, ColorFunction -> Function[{x, y}, Piecewise[{{Green, y > 10}, {Blue, y < 10}}]]]` The produces an all blue filling. The frustrating thing is that it seems that conditionals are allowed in `ColorFunction`s, but the test is evaluated only once, and the result is evaluation for each point plotted. How can I have the test evaluated repeatedly to get a discrete color filling? **Note:** I am simply trying to fill the space under a curve by determining where a point would fall in a given set of intervals.


Checking if the roots of a function are real

I'm trying to determine if the roots of a function are real. How would you do that? (In particular I'm interested in verifying that the roots of `LegendreP[6, x]` are real.)


CreateDialog opening two windows instead of one

I'm having issues working with code from Mathematica 9.0.1 since I've updated to 10.0.0. My previous code involved using packages to set functions, and then those packages were loaded and the functions called using a front-end notebook. These functions mainly involved the user inputting a file and selecting certain variables to end up with a final output of several plots. My issue is that my code is now generating two dialog boxes when running the code, stacked on top of each other. Is there any way to get this to stop without adding "Abort" to the end of all my set functions with dialog boxes? Sample Code:               importSpectra:=(          (*Creates a dialogue box which asks the user to input the file      location and name of the data they wish to input. *)     DialogInput[DialogNotebook[{         Grid[{             {TextCell["File to be Imported:"],Button["Select File",file=SystemDialogInput["FileOpen",directory]]},             {Button["Clear File",Clear[file]],Dynamic[file]}         },Alignment->Left],         DefaultButton[]     },WindowTitle->"Import Spectra"]];          (*Cancels the command if the user does not enter a file name. *)     If[file===$Canceled,Abort[]];          (*Imports the file and starts a new dataset. *)     import=Import[file];          (*runs another pre-set function*)     processData;          );      I've checked that this isn't due to any bugs with the functions called later on. Even just setting a simple dialog box that has DefaultButton[] to close generates two dialog boxes.


Manipulate, Import external table, save as CDF, mail presentation

For my work I do data analysis. Most of these analysis are done on big databases with milions of records. **I would like to make a manipulate (or animate) using a external dataset and create a CDF without sending this external dataset to other people.** As import syntax I use:               data = Import["E:\\file\\filename.TXT",        "Table", {"FieldSeparators" -> "|", "CharacterEncoding" -> "ASCII",         "HeaderLines" -> 1, "EmptyField" -> "",         "RepeatedSeparators" -> False}]      Examples of the imported dataset are: > {{0, 1, 0, 0, 0, 5}, {1, 1, 1, 1, 1, 297}, {1, 2, 0, 1, 1, 5}, {1, 3, 1, 1, > 1, 1}, {2, 1, 2, 2, 2, 1310}, {2, 2, 1, 2, 2, 51}, {2, 3, 1, 2, 2, 5}, {3, > 1, 3, 3, 3, 1894}, {3, 2, 1, 3, 2, 164}, {3, 3, 1, 2, 2, 23}, {3, 5, 1, 1, > 1, 1}, {4, 1, 4, 4, 4, 2656}, {4, 2, 2, 4, 3, 295}, {4, 3, 1, 3, 2, 34}, {4, > 4, 1, 2, 2, 5}, {4, 5, 1, 1, 1, 1}, {4, 7, 1, 1, 1, 1}, {5, 1, 5, 5, 5, > 2693}, {5, 2, 2, 5, 4, 400}, {5, 3, 2, 4, 3, 70}, {5, 4, 1, 3, 2, 16} I wrote this syntax to create a `Manipulate`               Manipulate[      ListLinePlot[       {Select[data[[All, {1, 2, 3}]], #[[1]] == bonbedrag &][[All, {2, 3}]],         Select[data[[All, {1, 2, 4}]], #[[1]] == bonbedrag &][[All, {2, 3}]],         Select[data[[All, {1, 2, 5}]], #[[1]] == bonbedrag &][[All, {2, 3}]]},       Filling -> {1 -> {2}}, FillingStyle ->  LightBrown,        PlotStyle -> {{Red, , Thick}, {Blue, Thick}, {Green, Dashed, Thick}},       PlotLegends -> Placed[{"ondergrens", "bovengrens", "gemiddeld"}, Below],        InterpolationOrder -> 2,       AxesLabel -> {Style["aantal artikelen gekocht", Bold, Red],          Style["prijs duurste artikel", Bold, Blue]}, ImageSize -> Large,        PlotLabel -> Style[Framed[StringForm["Bonbedrag = Euro `1`", bonbedrag]]],       GridLines -> Automatic,        GridLinesStyle -> Directive[Orange, Dashed],        PlotRange -> {{0, 20}, {0, 200}}, AxesOrigin -> {0, 0}       ],      {bonbedrag, 1, 200, 1}]      The result is the next picture ![example manipulate](http://i.stack.imgur.com/fZjW7.jpg) Then I save the presentation in CDF format, without the import-syntax. When I send the presentation it doesn't work. **Can somebody help me how to deal with external files in a manipulate syntax?**


Grid Lines in ListPlot

Why is Mathematica plotting a horizontal line at $y=2$ in the following example:               ListPlot[Table[i,{i,1,10}],Frame->True,GridLines->None]      ![Output](http://i.stack.imgur.com/MObqJ.jpg) How to get rid of this line?


How to clean up messy data

The start of my question is about one specific situation - I have some erroneous lat/long values in a dataset which I need to clean up. But I'd like it to cover the overall topic of cleaning up messy data for analysis work. The task at hand. I'm importing the NGA anti-shipping activity message database to do some analysis work with it. The problem comes when I try to extract lat/long value - there are a few invalid values in my dataset. Sometimes Mathematica can make it difficult to tell what sort of data something is. Is it a Null, or "Null" (string)? What are some ways to identify bad data, and correct it (or delete it)?               (* First import all the piracy events between 1990 and aug 1st, 2014 *)     (* This will take a minute or so *)     asamjson =       Import["http://msi.nga.mil/MSI_JWS/ASAM_JSON/getJSON?typename=\     DateRange_AllRefNumbers&fromDate=19900101&toDate=20140801", "JSON"];     Needs["GeneralUtilities`"]     asamdataset = Dataset[ToAssociations@asamjson];          (* Then we define some helper functions *)     getLong[ds_] := fixstr[ds["Longitude"]];     getLat[ds_] := fixstr[ds["Latitude"] ];     getPos[ds_] := {getLat[ds], getLong[ds]};     fixLong[ds_] := StringReplace[ds["Longitude"], "°" -> "\[Degree]"];     fixstr[str_] := StringReplace[str, "°" -> "\[Degree]"];          (* However, if we try to use our dataset we have some erroneous lat/long*)      (* values.   How can we correct these values (Zero the particular values,      (* make something up, ?), without resorting to deleting the entire record. *)     piracyLocations =       Map[GeoPosition[ {fixstr[#["Latitude"]],        fixstr[#["Longitude"]] }]   &, asamdataset]      EDIT: PatoCriollo's solution below is elegant. But sooner or later we'll come across data that doesn't have a nicely cleaned duplicate of itself waiting to be used. In fact even the ASAM dataset has bogus values in the lat/lng data.               dat = Map[ ToExpression@{#["lat"], #["lng"] }   &,      Take[asamdataset, 1000]];     Show[SmoothDensityHistogram[dat, .3, ColorFunction -> "SunsetColors",        PlotPoints -> 150, Mesh -> 20, MeshStyle -> Opacity[.1],        PlotRange -> All],        Graphics[{FaceForm[], EdgeForm[Directive[White, Opacity[.7]]],        CountryData["World", "Polygon"]}], AspectRatio -> Automatic]      ![ASAM data heatmap](http://i.stack.imgur.com/1nya6.png)


Extracting graphics primitives from a Graphics expression with ReplaceAll

If we have a graphics object,               plt = Plot[Sin[x], {x, 0, Pi}]      and we need to retrieve the discrete point data from it. This can be easily done by using `Extract` and `Position`,               First@Extract[plt, Most@First@Position[plt, Line]]      Or using `Cases`,               First@Cases[plt, Line[data_] -> data, Infinity]      However, my question is, might this be done via generic pattern matching? For example, some code like               plt /. (patterns-for-any-nested-or-parallel-heads) __ [ ___, Line[data_], ___] :> data      It might not be difficult to handle the parallel heads, but I do not see a obvious way to deal with the nested heads in a generic manner. Of course we can manually type all the nested heads, but this is rather specific. I am exploring the capacity of pattern matching in Mathematica. Is it possible to figure a general way to make Mathematica does it by itself? Actually I think this might be part of the algorithm under the hood of `Cases`.


Conditional search along the columns of a matrix

I want to implement the following algorithm in _Mathematica_.   1. Get element along main diagonal of a matrix.   2. If the element along the main diagonal is positive, then return the positions of the elements in the corresponding column that are negative. If the element along the main diagonal is negative, then return the positions of the elements in the corresponding column that are positive. The positions returned are the positions in the table. If neither of the two conditions above are true, do nothing. Here is example of what I want Given the matrix               {{1, 1, 1}, {2, -2, 2}, {-3, 3, 3}}      the algorithm should produce > >     {{3, 1}, {1, 2}, {3, 2}} >   In the above, the first element of each pair is the row of an off-diagonal element, the second element of the pair is its column) I'm currently trying to do this with a For-loop, but I can't get it to work. Besides, because _Mathematica_ is so good with lists, I'm sure that a functional solution is possible.


NMinimize go out of bounds on some linear constraints

I'm trying to minimize a non-linear function of four variables with some linear constraints. NMinimize on Mathematica 8 seems to go out of bounds on some constraints giving complex values of the function at some point in the iteration. The function to minimize is               ff[lxw_, lwz_, c_, d_] := - J1 (lxw + lwz) - 2 J2 c +     T (-Log[2] - 1/2 (1 - lxw) Log[(1 - lxw)/4] -      1/2 (1 + lxw) Log[(1 + lxw)/4] -      1/2 (1 - lwz) Log[(1 - lwz)/4] -      1/2 (1 + lwz) Log[(1 + lwz)/4] + 1/2 (1 - d) Log[(1 - d)/16] +      1/8 (1 + 2 c + d - 2 lwz - 2 lxw) Log[     1/16 (1 + 2 c + d - 2 lwz - 2 lxw)])      where               T = 10;     J1 = 1;     J2 = -0.2;      are constant parameters. The constraints are               var = {lxw, lwz, c, d};     cons = And @@ Cases[ff @@ var, Log[x_] -> x > 0, Infinity] // Simplify      which amounts to               d < 1 && lwz < 1 && 1 + lwz > 0 && 1 + 2 c + d > 2 (lwz + lxw) &&      lxw < 1 && 1 + lxw > 0      Then               NMinimize[{ff @@ var, cons}, var, Method -> "DifferentialEvolution"]      gives               NMinimize::nrnum: The function value 7.60939\[VeryThinSpace]-3.87314 I     is not a real number at {c,d,lwz,lxw} =  {-0.267966,0.319033,0.899803,-0.0151082}. >>     {-12.5741, {c -> -0.236255, d -> -0.978425, lwz -> -0.681637,      lxw -> -0.939595}}


Identical code, different answers?

I'm having some trouble with identical code giving different answers. On a fresh kernel (MM 9.0.0.0, Windows 64-bit), running the same code, copy-paste, gives two different answers:               In[1]:= Integrate[       E^(-\[Rho]^2/2) \[Rho]^(        p + m + 1) (\[CapitalDelta]z^2 + \[Rho]^2)^-(m + 1/2)       , {\[Rho], 0, \[Infinity]},        Assumptions -> {{m, p} \[Element] Integers, m >= 0,          p >= 0, \[CapitalDelta]z > 0}] // FullSimplify          Out[1]= 1/2 \[Pi] (2^(1/2 (1 - m + p))      Hypergeometric1F1Regularized[1/2 + m, 1/2 (1 + m - p), \[CapitalDelta]z^2/2]      - (\[CapitalDelta]z^(1 - m + p) Gamma[1/2 (2 + m + p)]      Hypergeometric1F1Regularized[1/2 (2 + m + p), 1/2 (3 - m + p), \[CapitalDelta]z^2/2])/        Gamma[1/2 + m]) Sec[1/2 (m - p) \[Pi]]          In[2]:= Integrate[       E^(-\[Rho]^2/2) \[Rho]^(        p + m + 1) (\[CapitalDelta]z^2 + \[Rho]^2)^-(m + 1/2)       , {\[Rho], 0, \[Infinity]},        Assumptions -> {{m, p} \[Element] Integers, m >= 0,          p >= 0, \[CapitalDelta]z > 0}] // FullSimplify          Out[2]= 2^(1/2 (-1 - m + p))       Gamma[1/2 (2 + m + p)] HypergeometricU[1/2 + m, 1/2 (1 + m - p), \[CapitalDelta]z^2/2]      Subsequent runs of the same code consistently churn out, as far as I can tell, the second expression. To make things even weirder, the first answer contains a global factor of $$\sec\left(\frac\pi2(m-p)\right),$$ which is singular for $m-p$ an odd integer. This makes useless in half the cases covered in the assumptions I explicitly gave to Integrate (`{m, p} \\[Element] Integers, m >= 0, p >= 0`). I also get analogous behaviour, with a slightly different first answer, if I drop the `FullSimplify`. Could someone shed some light on this?


Add text before TraditionalForm

Using Print[], I know it is possible to print out "helping text" to better understand a solution:               Print["The solution is: ", x]      if x holds some value. Now, this text is displayed using typewriter's font and OutputForm (I think: correct me if I'm wrong...). Is it possible, and if so, how, to display this outcome using TraditionalForm for `x` and using non typewriter's font for the text?               "The solution is: " x // TraditionalForm      doesn't give the desired result, as once `x` holds a value, it is moved to the front of the expression. Thanks for all help!


Visualize Pascal's triangle and other triangle shaped lists

How can Pascal's triangle be visualised like this in Mathematica? ![enter image description here](http://i.stack.imgur.com/IYMmu.png) Or more generally, how can a 'triangular' list like               {{1},{1, 1}, {1, 2, 1}}      be visualized in this way. Also I would like to do 'conditional things' like colouring the number two red.


How to draw this kind of plot?

Apologies if the question is too basic; I've searched the manual and the web but couldn't find a solution. I would like to present some data on a discrete plot. The data is divided into $K$ series or numbers, $y_{k,1}, y_{k,2},\dots, y_{k,r_k}$ (with length $r_k$ depending on $k$, but is small). I would like to plot points corresponding to numbers in one series on a vertical line corresponding to the series. So, on the line ${x=1}$, one unit left of the $y$-axis, I would like to place all the points $y_{1,1}, y_{1,2},\dots, y_{1,r_1}$; then on the line ${x=2}$ I would like to place all the points $y_{2,1}, y_{2,2},\dots, y_{1,r_2}$; and so on. Thus, the points I need on the plot have coordinates $(i,y_{k,i})$. I'm fairly sure Mathematica has something like this as a built in type of plot, but I can't find it. Any help will be appreciated.


Are there Min and Max functions that work properly on Intervals?

Mathematica overloads the `Min` and `Max` functions to retrieve the lower and upper bounds of an interval. I need functions that work properly on `Interval` arguments. For example, the minimum of `Interval[{3,4}]` and `Interval[{2,5}]` should be `Interval[{2,4}]`. To clarify based on comments, I'm looking for the tightest possible bounds for the `Min` and `Max` functions, given the constraints of the intervals. For example, the `Max` function of the intervals {2,3} and {7,8} will be {7,8}, because all values in the interval {7,8} are greater than any value in the interval {2,3}. (Note: I'm not looking for an ordering relation for intervals. The `Min` and `Max` operations often produce new intervals. See the first example, above.) I've written my own functions to do this, that only work for simple intervals:               intervalopf[a_Interval, b_Interval, op_] :=       Flatten[Outer[op, {Min[a], Max[a]}, {Min[b], Max[b]}]]     intervalop[a_Interval, b_Interval, op_] :=       With[{v = intervalopf[a, b, op]}, Interval[{Min[v], Max[v]}]]      Are there built-in functions I should be using? And, how can I generalize this to intervals that are unions?


Maple like collect command in Mathematica

In Maple I often simplify expressions for functions of same argument using the collect command:               > collect(a*f(x)+f(y)+x*f(x), f, factor)     (a+x)*f(x)+f(y)      where the extra option factor will factor the coefficients. In contrast Mathematica:               > Collect[a*f[x] + f[y] + x*f[x], f]     a f[x] + x f[x] + f[y]      Is there some command in Mathematica which achieves the same?


How can I properly Partition "IntensityData" output from "ComponentMeasurements"? (Recovering the (x, y) dimensions of a rect. morph. component?)

When I ask `ComponentMeasurements` to return "IntensityData" for some set of rectangular morphological components:               m = MorphologicalComponents[image, Method -> "BoundingBox"];     intensityDataArray = ComponentMeasurements[{m, image}, "IntensityData"][[All, 2]];      The pixel value data is returned as an unpartitioned one-dimensional array. This makes it difficult for me to understand where a particular pixel is in the image. Now, if I know the exact dimensions of each morphological component, I suppose I could fix the problem using `Partition`. I could also fix the problem with `Partition` if I could ask for something like a bounding square instead of a bounding rectangular box, though I don't think this is possible (is it?). Besides manually measuring the dimensions of each rectangular morphological component, is there a workaround to fix this problem? Letting `m` consist of strictly rectangular morphological components, it would, for example, be very nice to be able to write something like:               ComponentMeasurements[m, "Dimensions"][[All, 2]]      And have this return something like:               {{5,8}, {87, 40}, {7, 7}, ...}      Meaning that we have morphological components of dimensions $(x, y) = (5 \times 8)$, $(87 \times 40)$, $(7 \times 7)$, and so forth. Here, we're provided ordered values for the extent of the component along the $x$- and $y$-axes, respectively, allowing us to trivially use `Partition` to restore the cropped section of an image underlying a morphological component (i.e. the image one would have if a morphological component is used as a "cropping mask"). * * * Clarification: Masking approaches are really neat, but not quite what I'm looking for here unless they're part of a larger approach. I need a method of grabbing the pixel data strictly underlying a morphological component (for a set of morphological components) and retaining $(x, y)$ data for each pixel. My downstream procedure then does further image processesing on this rectangular matrix. If I do a matrix multiplication masking procedure, I still need to trim away the dark space to get down to a bounding box (the size of the morphological component mask). Also, it seems a little wasteful to have to perform multiplication operation on all pixels in the image to accomplish my goal?


Skip the revert dialog

When saving a file and making changes to it one can revert using `File->Revert` in the menu or by entering `FrontEndExecute[FrontEndToken["Revert"]]` before reverting a dialog window opens to ask if you are sure. I would like to skip this dialog by automatically answering with yes. Is that possible? **Edit:** Here is a picture of the dialog. ![enter image description here](http://i.stack.imgur.com/11PLp.png)


Outline Numbering for Mathematica Section/Subsection Cells

I am trying to create a LaTex-style document with Section numbers of the form 1.0 and then subsection numbers 1.1, 2.1, etc. I need the numbering to be automatic such that if I insert a new subsection, the numbering of subsequent subsections will automatically adjust. Is there an easy way to do this (presumably by editing the stylesheet??). I've looked at a bunch of options but can't seem to find the appropriate one.


Number format in Legend Labels

I would like to use the usual (new and nice) `BarLegend[]` with something like               BarLegend[{"LakeColors", 1/10000 {-2, 2}}]      which looks like ![Example BarLegends-Plot](http://i.stack.imgur.com/PzQny.png) I don't like the numbers, i would like to use `ScientificForm[]` on them, hence get $0.0002 = 2\times10^{-4}$ or even better - get just $2$ at the label and $\times 10^{-4}$ in the bottom right or something like that. Is there a way to obtain `ScientificForm[]` for these labels? I searched the Documentation of the new `~Legends` and haven't found anything. And the very best would be, to be able to specify the number of digits used (where i would like to have 3, e.g. $2.00\times10^{-4}$, so best would be `ScientificForm[#,3] &` to be applied to every number of the Legend. ## Update Surprisingly - following the approach of @Nasser M. Abbasi the two lines               f[x_] := ScientificForm[x, 2];     BarLegend[{"LakeColors", 1/10000 {-2, 2}}, LegendFunction -> f]      produce a Legend like ![second approach](http://i.stack.imgur.com/yR5uN.png) Though the second argument of `ScientificForm[]` gets ignored. Any further ideas why that does happen? ## Update #2 Changing `f` to `f[x_] := ScientificForm[N[{x} /. {DirectedInfinity -> Identity}], 2];` actually _does_ change the number of digits, but returns the `BarLegend` in an Array and produces errors, that `(1.,4.}` is not a List of positive Integers (though they look quite Integer to me). Why there is an `DirectInfinity` approaching, I haven't found out yet, without the replacement, the `1.` is a `DirectedInfinity[1.]`


Mathematica: how to make Z transformation of data from CSV File

I have a discrete Signal in my CSV File and I want to transform it in Z. I import the data with                Data=Import["T:/data.csv","CSV"]      and I try to transform it               ZTranform[Data[n],n,z]      but I get this Error:               $RecursionLimit::reclim : Recursion depth of 256 exceeded >>      What is the meaning of this?


How to Chop correctly?

I want to count degeneracies in a list called `spectrum`. The list contains numbers of double (~ 15digits) precision. So it makes no sense if the noise below this precision is taken into account since it falsifies the result of degeneracy counting using `Tally[]`. So I applied `SetPrecision`.               degList = Tally[{#1, SetPrecision[#2, 15]} & @@@ spectrum];      But I still get e.g. {-0.047063080371693544`, 4} {-0.047063080371693294`, 4} (last number is the degeneracy level) which should be seen as equal numbers but are counted by `Tally[]` as different ones. What am I doing wrong?


Can Depth be used as an equivalent for MatrixQ?

Given an expression `x`, are the following two statements interchangable with no exceptions?   * `Depth[x] - 1 == 2`   * `x // MatrixQ` If they are, which is evaluated faster? Other than for speed, is there a reason one should be used rather than the other?


Using mesh for a single function inside Plot

Plot[{Sin[x], Cos[x]}, {x, 0, 10}, Mesh -> {{0, \[Pi]}},           MeshShading -> {Black, Red}]      In the above, how can I specify that I want the mesh for just, say the Sine function and not the Cosine? I know I can use two plots and combine them with Show, but this is not what I want.


Find asymptotics of a function

Can _Mathematica_ find the asymptotics of a function in the following sense? I have               Log[1/n^2]/Log[4^(-Sqrt[Log[n]]) + (2^(-Sqrt[Log[n]]) - 1)^2]      and I would like to know an asymptotic approximation when $n$ is large. That is a simple function that is within a constant multiplicative value in the limit when $n \rightarrow \infty$. If instead it was               Log[1/n^2]/Log[4^(-Sqrt[Log[n]]) + (2^(-Sqrt[Log[n]]))^2]      then I know that               Log[1/n^2]/Log[4^(-Sqrt[Log[n]]) + (2^(-Sqrt[Log[n]]))^2]/Sqrt[Log[n]]       tends to a constant value. My question is how could you use _Mathematica_ to discover that $\sqrt{\log{n}}$ is the right answer in the second case and to find whatever the right solution is in the first case? By trial and error I happen to know that the right answer in the first case is somewhere between $2^{\log^{1/2}{n}}$ and $2^{\log^{1/2+\epsilon}{n}}$.


keeping parentheses size the same in Input cells when using 2D math

I like to group the 2 parts of the `If` statement and others like it by using `()` to help me be able to still understand what my code is doing the next day I look at it. I started to use 2D math in input cells, and it is a nice feature of Mathematica. But noticed that `()` changes size depending on what is inside them. So I end up with non-symmetrical (different size) parentheses within the same logical grouping. An example will help show this: ![enter image description here](http://i.stack.imgur.com/l4Z0U.png) Notice how the top `()` are small compared to the lower `()`. The code will look better on the screen if the sizes of these `()` are kept the same. (either both large, or both small, is not important, as long as the size is the same) This happens with `With` and any other such command. I know the `()` are not needed. I just use them to make the code easy to read. When I have complicated logic, these help me see the parts more clearly. Here is the actual code that generated the above converted to `InputForm` in order to paste it here               Clear["Global`*"]     If[x == 1, x = 0, x = Sqrt[y^2] ];       Question is: Is there a way to control this aspect of the display in input cells for 2D math so that parentheses are the same even if using 2D math?


Clustering 3D Data Points on a Periodic Cubic Grid

I have a set of 3D data points on a cubic grid. The data can be downloaded from here https://skydrive.live.com/redir?resid=F96524B72DCD75FB!14240 and read into a variable `lis` using `lis = ReadList["filename", {Number, Number, Number}]`. How can one cluster the points into groups such that the points in each group are related by the fact that they are only one grid point away from their nearest neighbor in all directions (taking periodic boundaries in all directions into account). By all directions I mean the six faces of a cube. The `EuclideanDistance` between grid points is `0.055089` . Here is a plot of the data (well solution, see below). ![enter image description here](http://i.stack.imgur.com/wWZ5X.jpg) Actually, I was able to solve this problem using object-oriented programming in _C#_ , but I've come up short trying to reproduce it in _Mathematica_. I've tried a combination of `FindClusters` and `Nearest` with no success. Any help will be much appreciated. I have tried to include as much information as I think is needed to solve this problem but if more information is needed I'll gladly provide it. Note: In the plot above, I've removed groups that has less than 20 points.


Checking differential equation solution

I have this differential equation:               eq=D[ψ[r],r]+A*ψ[r]-(B/(A*r))ψ[r]==0;      And `DSolve` sucessfully solves it:               sol = DSolve[eq,ψ[r],r];      But when I check by replacing all, in this case it doesn't replace the derivative of the function:               Simplify[eq/.sol]      Derivative still must be replaced too. If I do:               Simplify[eq/.sol/.D[sol,r]]      Then this gives `True`. In other cases _Mathematica_ replaced the function and its derivatives in one shot. What's happening in this case?


Window ▶ Show Handwriting Input

How might I force Mathematica to display the Handwriting Input menu? Currently I'm on W7 using a Wacom Tablet and unable to find the Handwriting Input option. It doesn't display under Windows>.


How Do I Convert A Binomial Distribution to a Smooth Histogram in a Manipulate?

Manipulate[BarChart[Table[PDF[BinomialDistribution[n, p], i], {i, 0, 20}],       PlotRange -> {{-.5, 21.5}, {-.1, 1}},       Epilog -> {PointSize[0.03], RGBColor[1, 0, 0], Point[{n*p + 1, 0}]},       ImageSize -> {450, 350}],        {{n, 10, "Variables"}, 1, 20, 1,Appearance -> "Labeled"},        {{p, .5, "Skew"}, 0, 1, Appearance -> "Labeled"}]      Ladies and Gentlemen! How do I convert the binomial distribution inside this `Manipulate` (above) to a `SmoothHistogram`? Or, more simply put, where do I insert the term `SmoothHistogram` in this script?


Recursion evaluate Table power exceeded limit

I wrote 2 simple recursive functions for calculating the power of a table.               pol3[Tb_List, n_Integer?Positive] := If[n == 1, Tb, Tb.pol3[Tb, n - 1]]      and               pol4[A, 1] := A      pol4[A, n_Integer?Positive] := A.pol4[A, n - 1]      Tb, A are 3x3 arrays. Functions works for n<255 but if I try to call them for n=256 or greater then I take wrong results and the message:               $RecursionLimit::reclim: Recursion depth of 256 exceeded      I'm not very familiar with the Mathematica so I would appreciate any ideas on what I'm doing wrong.


Plot complex path (essentially a 2D path) expressed in one real parameter

Consider a complex path expressed in one real parameter, such as $$f(\alpha)=\frac{1}{e^{i \alpha} + 1},$$ which is a Möbius transformation of the unit circle. I know I can expand it all out and use the parametric plot, but it is cumbersome and not very easy (sometimes practically impossible) to do so. Therefore, I want to know if there is some plotting function specifically designed for this. (I searched for it in the documentation but did not find it; sorry if it's all obvious.)


Display ALL keys in dataset

I created a dateset (estimates) with 25 keys (my columns), and about a hundred rows. I'd like to be able to list the keys from the dataset. I did this:               estimates[Keys]      which returned: ![enter image description here](http://i.stack.imgur.com/jsMAQ.png) I also tried:               estimates[1]      which returned: ![enter image description here](http://i.stack.imgur.com/yBwlb.png) How can I display the entire list of keys? My code is below:               Module[     {fileTemp, header, data},      fileTemp = Import[NotebookDirectory[] <> "test.xlsx", {"Sheets", "estimates"}];     header = fileTemp[[1]];     data = fileTemp[[2 ;;]];     estimates = Dataset@Map[AssociationThread[header, #] &]@data;      ] The following is part of the Excel sheet: ![enter image description here](http://i.stack.imgur.com/N2lyK.png)


How to convert sine wave into square wave? (analog to digital signal)

I've got this plot with two sine waves ![enter image description here](http://i.stack.imgur.com/cykyF.png) and what I need is follow: ![enter image description here](http://i.stack.imgur.com/GfuJB.jpg) Amplitude values can diverge from time to time like here min 100 and max 700 but another time it's 300 600. I guess I will not be able to get these nice phased waves from those on my picture.. But let's assume we have only one sampled sine wave. How to translate it to 001111110000011111 where 1s are for sine above "zero"(that's the main problem, every time it will be different point, like here it's around 400) and 0s for below zero. And another difficulty it would be nice to get this conversion on the go/online. Like I don't have whole sampled signal but only let's say 100 last values(10-60 these sine slopes). Please, can you at least say what I should google? Thank you :) **UPDATE** I've asked a little wrong.. How can I get zero line from signal like this? To apply suggested Sign[]. It's vary bad scenario sine wave.. In my case it's bouncing not around zero but some changing Y. It lasts around one value only few slopes.. ![enter image description here](http://i.stack.imgur.com/6N726.png) **ANSWER** Well, that's up to how you want to treat the data. I suppose the simplest way is to take the Mean of the data streams, and treat that as the "zero" - so just subtract it from the stream and then do the Sign. Also take a look at Rescale, Clip, and Standardize - all can be used to good effect here, e.g. waveSquared[[All, 2]] = Sign@Standardize@waveSquared[[All, 2]];... – @rasher Now it looks like this ![enter image description here](http://i.stack.imgur.com/eQfJc.png)


Workaround for automatic replacement of "\r" to "\n"

When I run the following code in an empty notebook               SetOptions[EvaluationNotebook[], testOption -> "\n\r"]      and then open the notebook in Notepad, I find > $CellContext`testOption -> "\n\n" (1) Can you confirm this bug/feature in other versions/operative systems? I am using Mathematica 9.0.1 in Win8Prox64. (2) Is there a workaround?


Importing Output from Linux mpstat to Calculate Aggregate and Per-CPU Averages, Creating Tables and Graphs

I'm a Mathematica noob, running a trial version for the moment, but have run into the wall trying to handle this in Excel and am looking for other options. While running a benchmark application I'm gathering output from the Linux command "mpstat -P ALL 1" and exporting it to a CSV. The data is as follows:               Time, CPU, %usr, %nice, %sys, %iowait, %irq, %soft, %steal, %guest, %gnice, %idle      10:11:04 AM, all, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 100.00     10:11:04 AM, 0, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 100.00     10:11:04 AM, 1, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 100.00     10:11:04 AM, 2, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 100.00     ...     more interesting data in the middle     ...     11:18:55 AM, 12, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 100.00     11:18:55 AM, 13, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 100.00     11:18:55 AM, 14, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 100.00     11:18:55 AM, 15, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 100.00      There are 21 unique tests in the benchmark which are clearly visible when each sample with "CPU = all" is graphed. (The Y axis is calculated as (100 - %idle). ![Excel Graph of "ALL" CPU utilization over Time](http://i.stack.imgur.com/sePMO.png) What I need to do is the following:   * Separate the idle periods from the periods when the benchmark is running. (There are short idle periods before testing starts, in-between each test, and an idle period after all tests are complete.) This is the part that gives me the biggest problem since the number of idle samples between tests is not entirely predictable.   * For each period when the performance test is running, find the average CPU utilization for each CPU (0, 1, 2, ..., 14, 15, all).   * Create a table that indicates the test name (e.g. Test 1, Test 2, etc.) and the average CPU utilization for each CPU sampled. > >     +--------+---------+-------+-------+-------+-------+ >     |  Test  | CPU ALL | CPU 0 | CPU 1 | CPU 2 | CPU 3 | >     +--------+---------+-------+-------+-------+-------+ >     | Test A |   30%   |  25%  |  35%  |  24%  |  36%  | >     +--------+---------+-------+-------+-------+-------+ >     | Test B |   25%   |  20%  |  31%  |  24%  |  30%  | >     +--------+---------+-------+-------+-------+-------+ >     ... >   The full data source can be found here: mpstat.zip


Interpolation problem on the list

I have a List of Latitude, Longitude and Measurement.               a = {{{93, 104}, 290}, {{94, 103}, 292}, {{95, 105}, 291}, {{97, 109},          294}, {{97, 102}, 295}};      And, I want to Interpolate this list and plot them using ContourPlot and CountryData. However, error has occured when I use Interpolation:               Interpolation[a]     Interpolation::udeg: Interpolation on unstructured grids is currently only supported for InterpolationOrder->1 or InterpolationOrder->All. Order will be reduced to 1.     Interpolation::umprec: Interpolation on unstructured grids is currently only supported for machine numbers. The data will be coerced to machine precision.      The list is a just peace of my full list. I don't know how to solve this.


Counting multiplications (complexity function)

I'm trying to count the number of times multiplication appears in an expression (for the purpose of constructing a ComplexityFunction that would help me simplify a terrible algebraic expression for later numerical crunching in matlab). For example, I consider the following expression to involve 3 multiplications:               a b c + d e      two in "abc" and one in "de". I've tried Level, but unfortunately mathematica sees the term "abc" as one "Times" with three arguments:                In:= Level[a b c + d e, {-1}, Heads->True]     Out:= {Plus, Times, a, b, c, Times, c, d}      In principle I could reverse-engineer the multiplicity of arguments of "Times" from the above, but that seems like an unnecessarily cumbersome way. i'd greatly appreciate any help.


How to get a country's official languages?

According to Wikipedia > Of the 193 widely recognized countries, 178 have an official language at the > national level (NB:or more than one) The only exceptions are: > Cyprus, Czech Republic, Denmark, Eritrea, The Holy See, Luxembourg, San > Marino, Sweden, Tuvalu, Ukraine, United Kingdom, United States, Uruguay, > Uzbekistan, and Yemen `CountryData[]` supports three language related properties: > "Languages", "LanguagesDialects", "LanguagesFractions" But none of them seems to return the "Official Languages". Is there a way to get a country's official languages within Mathematica?


What does rule 30 mean in this example?

This starts with the list given, then evolves rule 30 for four steps.               In[1]:= CellularAutomaton[30, {0, 0, 0, 1, 0, 0, 0}, 4]          Out[1]= {{0, 0, 0, 1, 0, 0, 0}, {0, 0, 1, 1, 1, 0, 0}, {0, 1, 1, 0, 0, 1,        0}, {1, 1, 0, 1, 1, 1, 1}, {0, 0, 0, 1, 0, 0, 0}}


Projection of a set of 4D points to the 3D space

Consider the following set of points in the 4D space:               points = {{Log[5], Log[2], Log[8/5], Log[23/16]}, {Log[5], Log[2], Log[23/17],        Log[17/10]}, {Log[5], Log[16/11], Log[11/5], Log[23/16]}, {Log[5],        Log[17/12], Log[23/17], Log[12/5]}, {Log[5], Log[23/18], Log[11/5],        Log[18/11]}, {Log[5], Log[23/18], Log[3/2], Log[12/5]}, {Log[5/3],        Log[6], Log[8/5], Log[23/16]}, {Log[5/3], Log[6], Log[23/17],        Log[17/10]}, {Log[11/7], Log[16/11], Log[7], Log[23/16]}, {Log[3/2],       Log[17/12], Log[23/17], Log[8]}, {Log[11/7], Log[23/18], Log[7],        Log[18/11]}, {Log[3/2], Log[23/18], Log[3/2], Log[8]}, {Log[4/3],        Log[6], Log[2], Log[23/16]}, {Log[17/13], Log[6], Log[23/17],        Log[13/6]}, {Log[4/3], Log[12/7], Log[7], Log[23/16]}, {Log[17/13],        Log[13/8], Log[23/17], Log[8]}, {Log[9/7], Log[23/18], Log[7],        Log[2]}, {Log[9/7], Log[23/18], Log[7/4], Log[8]}, {Log[23/19],        Log[6], Log[2], Log[19/12]}, {Log[23/19], Log[6], Log[19/13],        Log[13/6]}, {Log[23/19], Log[12/7], Log[7],        Log[19/12]}, {Log[23/19], Log[13/8], Log[19/13],        Log[8]}, {Log[23/19], Log[19/14], Log[7], Log[2]}, {Log[23/19],        Log[19/14], Log[7/4], Log[8]}}      All the points lie on a 3D hyperplane since `MatrixRank[# - points[[1]] & /@ points]` returns 3. How can I show the points in a 3D space (e.g., using `Graphics3D`) so that the distance of points are kept intact?


Improve the performance of solutions to Project Euler (#14)

Problem I have following code, when n<=10^5 it's not slow, but n>2*10^5 it's became very slow. I think maybe some temp value greater than 2^31-1, so make compile invalid. Could you give any idea make it can be compiled? As far as possible not to use recursive algorithm.               pe14 = Compile[{},        Module[{n1, len, maxLen = 0, res = 0},         Do[n1 = n;          len = 1;          While[n1 != 1,           n1 = If[EvenQ@n1,  n1~Quotient~2, = 3 n1 + 1];           len++           ];          If[len > maxLen, maxLen = len; res = n],          {n, 1, 10^6}];         {maxLen, res}         ]        ];          pe14[] // AbsoluteTiming


What does Internal`InheritedBlock do?

What does the function `Internal`InheritedBlock` do? How is it different from the regular `Block`?


How can I imitate the style of a certain 3D bar chart?

I would like to get a 3D visualization of a given matrix. Here is a figure which may come from _Mathematica_. I want to plot something like it. When I use `ListPlot3D` or `BarChart3D` to plot my matrix, it does not have the style of one shown below, which is what I'm look for. How can I do a nice 3D visualization of my matrix? ![visualization of a matrix](http://i.stack.imgur.com/XRlCG.png)               data = ( {         {1, 2, 3},         {5, 4, 8},         {2, 5, 7}        } );          data = ArrayPad[data, {0, 1}];     xTicks = {{1.5, "A"}, {2.5, "B"}, {3.5, "C"}};     yTicks = {{1.5, "X"}, {2.5, "Y"}, {3.5, "Z"}};     zTicks = {{0, "0"}, 0, {4, "4"}, {8, "8"}};          pic = ListPlot3D[data,        Mesh -> None,        InterpolationOrder -> 0,        ColorFunction -> "Rainbow",       Filling -> Bottom,       FillingStyle -> {Opacity[0.9]},       PlotRange -> {Min[data] - 0.5, Max[data] + 0.2},       BoxRatios -> {1, 1, 0.5},       Ticks -> {xTicks, yTicks, zTicks},       DataRange -> All,       Boxed -> False,       FaceGrids -> {Bottom, Back, Left},       ImageSize -> 400]      this is the code that I plot a matrix using `ListPlot3D`. The cuboids in it are not separate from each other, and the edges of the cuboid are fuzzy. ![my figure for matrix from the above code](http://i.stack.imgur.com/DkBUL.png)


Speed of ConvexHullMesh

Pick $N$ random points on the surface of the sphere, then use `ConvexHullMesh[]` to compute their convex hull. Empirically, this takes time quadratic time in $N,$ whereas the state of the art as of 1996 is $N \log N.$ Is Mathematica doing something extra, or is its algorithm just 18 years out of date? In the interest of "politeness".               randpt[n_]:= Module[{prept = RandomVariate[NormalDistribution[], 3]}, prept/Norm[prept]]     experiment[n_]:= ConvexHullMesh[Table[randpt[3], {n}]//AbsoluteTiming      **EDIT** Here is the experimental data (the first element in each pair is the number of points, the second the AbsoluteTiming [this on a very fast Windows PC])               {{10000, 6.133357},       {20000, 17.791034},      {30000, 50.460951},      {40000, 106.783207},      {50000, 182.384594}}      This looks awfully quadratic to me. I point out that experiments for small $n$ are meaningless, since there is linear overhead, which has a none-too-small constant, so swamps the quadratic growth. $50000$ points is not that many (and certainly would be a modest number for any FEM mesh), so this is clearly a major performance bug. **ANOTHER EDIT** for comparison purposes, I also installed qhull on the very same machine, and ran `qconvex` on 50000 cospherical random points. The running time was, umm, well, it started spewing output at me the moment I hit return, so I am seeing a roughly three order of magnitude speedup.


Mathematica ncurses support

I occasionally `ssh` into machines that have _Mathematica_ installed. I then operate _Mathematica_ through the command-line interface. Often, the command-line interface isn't the ideal way to operate _Mathematica_ , but it does have incredible convenience and speed advantages. Is there a ncurses library (maybe even a 3rd party one) to add additional functionality when accessing _Mathematica_ through `ssh`? ### Edit List of ideas for additional functionality   1. Cursor clicking support, so I don't have to use the arrow keys   2. Ability to rerun command (`Shift`+`Enter`)   3. Support for Save As


Join a piecewise plot

I wrote some code to get a piecewise plot which is displayed correctly. Now I'd like to join the various parts of the plot, using some kind of interpolation, to get a continuous chart even though it's actually a piecewise one. Let me to give you an example. Assuming $f_1(2) = 3$ and $f_2(2) = 1$, how can I join the points $(2,3)$ and $(2,1)$ in the plot?


Discrete distribution binomial set up

I hope one of you guys can help me out. I am trying to visualize a discrete distribution based on a binomial distribution and a mixed binomial distribution. In the first step I started to determine the parameters:               Remove["Global`*"];     m = 45; (*total number*)     n = 3;  (*target number*)     AV = 55605000;     DV = 52474000;     μ = 0.06     σ = 0.10;     T = 5;     ρ = 0.22;       Then I started with the binomial distribution which is given by _Mathematica_. In order to calculate the probability that `x ≥ 3`, I need the single probability which is calculated by:               p = (CDF[NormalDistribution[], -(Log[AV/tV] + (μ - 0.5*σ^2)*T)/(σ*Sqrt[T])])      the result for p is 0.068 than I want to calculate the probability that x ≥ 3 to to so I enter the following:               probBDAW = Probability[x >= 3, x \[Distributed] BinomialDistribution[m, p]]      and the result is 0.60. then I want to have a table of the probabilites when x≥1,x≥2,≥´x≥3..etc...in order to do so I entered this:               dataBDAW =       Table[Probability[x >= n1, x \[Distributed] BinomialDistribution[m, p]], {n1, 0, 45, 1}]      this also works and I get a table. In the next step I want to plot the discrete distribution of this probabilites by using the DiscretPlot function. Therefore I enter:               pdfBDAWXX =        DiscretePlot[         PDF[BinomialDistribution[m, p]], n1], {n1, 0, m},          PlotRange -> All, AxesLabel -> {"y", "x"}, ImageSize -> 500,          PlotLabel -> Style["Text", Bold]]      this also works well and I get the follwoing chart: ![enter image description here](http://i.stack.imgur.com/x76ol.jpg) Now I want to use a mixed binomial set up. I already calculated p so want to calculate again that x ≥ 3. To do so I enter:               probMBD =       1 - CDF[NormalDistribution[], ((1/Sqrt[            1 - ρ])*(((Sqrt[ρ])*(InverseCDF[                NormalDistribution[], (3/m)]) - (InverseCDF[               NormalDistribution[], (CDF[                 NormalDistribution[], -(Log[                      AV/DV] + (μ -                         0.5*σ^2)*                      T)/(σ*Sqrt[T])])]))))]      thus I get the probability that x ≥ 3 is 0.187 as before I want to generate a list with the probabiliest x≥1,x≥2,≥x≥3..etc. Hence I enter:               dataMBDAW =       Table[1 -         CDF[NormalDistribution[], ((1/Sqrt[             1 - ρ])*(((Sqrt[ρ])*(InverseCDF[                 NormalDistribution[], (n1/m)]) - (InverseCDF[                NormalDistribution[], (CDF[                  NormalDistribution[], -(Log[                       AV/DV] + (μ -                          0.5*σ^2)*                       T)/(σ*Sqrt[T])])]))))], {n1,         0, m, 1}]      As a result I get a nice table. But when I want to plot the discrete distribution I have some problems. I did something but I am far from sure that this is right. so could please anyone look at this and say if it is corret and if not could you please write me how it is done correctly? ok so I just said that               testx = (dataMBDAW)      then I wrote this function in oder do caputre the discrete density:               ftest[jk_] := testx[[jk]] + testx[[jk + 1]]      In the next step I did the following:               H1 =       ListPlot[Table[testx[[jk]] + testx[[jk + 1]], {jk, 2, 45}],         PlotStyle -> Black, PlotRange -> All, AxesLabel -> {"y", "x"},         ImageSize -> 500, PlotLabel -> Style["text", Bold], Filling -> Axis,        FillingStyle -> Directive[Opacity[0.2], Black]]      and the result is this chart: ![enter image description here](http://i.stack.imgur.com/RRtOm.jpg) I am not sure if this is correctly done. I would be thankful if you could help me out and say if it is correct and if not provide me with a solution for my problem.


How do I remove a bounding box (i.e. set Boxed -> False) after rendering a 3D graphic?

I have an old notebook with an output from Graphics3D, however, I've lost the data behind the output and recomputing it would take days. I simply want to remove the bounding box Mathematica usually displays unless you specify that "Boxed -> False". Is it possible for me to still do this without having to recompute the graphic? E.g. I want to transform an output generated from running this example command:               Graphics3D[{Sphere[{0, 0, 0}, 1], Sphere[{2, 3, 5}, 1]}]      To an example output generated from running this example command (but without having to regenerate the image since I no longer have access to the sphere coordinates):               Graphics3D[{Sphere[{0, 0, 0}, 1], Sphere[{2, 3, 5}, 1]}, Boxed -> False]


How to not include data value outside plot range in the plot

Consider this list plot               ls = Table[Sin[t], {t, 0, 100, 0.1}];     p = ListPlot[ls, PlotRange -> {{0., 0.1}, All}, DataRange -> {0, 1}, Joined -> True]      ![enter image description here](http://i.stack.imgur.com/8wlGZ.jpg) If we look at the data in the plot, we see that all the data in `ls` are included in the plot.               ls2 = p[[1, 2, 1, 3, 3, 1]];     Dimensions[ls2]     (* {1001, 2} *)          ListPlot[ls2, Joined -> True]      ![enter image description here](http://i.stack.imgur.com/mvGPJ.jpg) Sometimes this is really helpful because we can just retrieve the data at a later time from the plots and don't need to regenerate the data again. But sometimes I'm only intreated in the range set in the ListPlot, and saving all the data is kindly of wasting of space, especially when I have many plots in a notebook, the notebook size becomes very large and not very responsive. So are there simple ways to tell `ListPlot` to not include the data outside the plot range, other than manually select the data before plot? P.S. Sometimes, ListPlot does drop the data outside the range, see example here.


Fastest way to calculate matrix of pairwise distances

It is a very common problem that given a distance function $d(p_1,p_2)$ and a set of points `pts`, we need to construct a matrix `mat` so that `mat[[i,j]] == d[ pts[[i]], pts[[j]] ]`. What is the most efficient way to do this in Mathematica? * * * Let's assume that the points are in $\mathbb{R}^n$ for simplicity, and because that's the case I'm dealing with now, but theoretically the points could be any type of object, e.g. strings with $d$ being an edit distance. For the specific problem I have right now I need to calculate the `EuclideanDistance` and `ManhattanDistance` of 2D points. The simplest way to do this is               pts = RandomVariate[NormalDistribution[], {1000, 2}];          mat = Outer[ManhattanDistance, pts, pts, 1]; // AbsoluteTiming          (* ==> {0.595327, Null} *)      This obviously calculates all distances twice, which is wasteful. So I was hoping for an easy $2\times$ speedup, but it isn't as easy as one would hope. Doing the same operation the same number of times in a `Do` loop takes considerably longer (probably because of indexing):               Do[ManhattanDistance[pts[[10]], pts[[20]]], {Length[pts]^2}]; // AbsoluteTiming          (* ==> {1.902417, Null} *)      So what programming pattern do you typically use when calculating such a distance matrix and which one would you recommend for this specific problem?


A basic problem with Solve

I have this equation:               4b*Cos[2t]-4a*Sin[2t]==4Cos[2t]+8Sin[2t]      Which I would like to solve. Without using mathematica, you can pretty easily see that a = -2 and b = 1, but when I solve it with mathematica it gives me various long results including sometimes tan, sec cot etc. I can break it up into to parts like this:               Solve[4b*Cos[2t]==4Cos[2t],b]     Solve[-4a*Sin[2t]==+8Sin[2t],a]      However, the point with mathematica isn't to make everything manually, and I would hope there is a method to use, without manually editing the equations. So my question is: How do I solve this for a and b, with the results of a = -2 and b = 1?


Creating a "Live" Index Notebook --to load other Notebooks

I am new here, so let me know if this question is inappropriate. I've been stuck for many hours on this puzzle. I know it should be easy, but for me...? I want to create a Notebook (call it "Index of Related"), located in directory "C:\somewhere\strange" (not necessarily in $Path) which contains a list of notebooks I use at the same time, but quite independently of one another. One application might be a list of all the Mathematica notebooks I use in my microeconomics course. From inside "Index of Related", if I click on a button, I want Mathematica to load some other notebook, just as if I had used File/Open in Mathematica. I can't seem to create buttons to execute simple File/Opens! Every coding I've tried adding to Index of Related" seems to load the other notebooks into or inside Index of Related or generate $Failed. Example X: Example of an application:   * File 1, located in C:\directory1 : Slide show for the talk....   * File 2, located in c:\dogs\small : My text for the talk....   * File 3, located somewhere in $Path : Handouts for the talk....   * File 4: References for the talk....   * Files 5-8, located all over the place: Examples for the talk, created for other projects, so in various other directories.... Now, while creating the talk I first load "Index of Related". I stumble on a reference, so I open Files 2 and 4 and make changes. In a later session, I want to create from this reference a slide, so I open and work in File 2.


Inverting a Spline-Function (Bezier or BSpline)

I would like to use a Spline-Function to describe a transformation from one range of reals to another, that is I would like to have a function which maps a value $y$ on $x$ and for simplicity let us assume that $x,y \in [0,1]$. The idea was to define a smooth, nonlinear function which is to be within the boundary points $\{(0,0),(\alpha,\beta),(1,1)\}$ with $\alpha,\beta \in [0,1]$, also. Thus a Bezier- or BSpline-Function seemed to be appropriate. Unfortunately I can't see how I can use the Spline-Function directly to map $y$ on $x$ (or vice versa for that). The Spline-Function will one parameter $t$ with $t \in [0,1]$ and will give all points on the curve, e.g. $spline(0) = (0,0), spline(1) = (1,1)$. So to find say the corresponding $x$ value for $y=0.6$, I tried something like this:               f = BSplineFunction[{{0, 0}, {0.2, 0.7}, {1, 1}}];     FindInstance[Last@f[t]==0.6,t]      But what I am getting is the false answer $\{\{t\rightarrow 0.6 \}\}$. The correct answer should have been $t = 0.5$. So far I have also tried Reduce, Solve, NSolve, FindRoot (giving a start value for t) and have of course given the domain to be Reals. But nothing works. Is there a way to do this without having to substitute a simpler function for the Spline-Function (e.g. using `Interpolation[]`)?


When using GraphPlot with an adjacency matrix, how can I make Mathematica draw exactly one self loop for any non-zero weight?

I have tried using the option `MultiedgeStyle->None`, but apparently Mathematica doesn't treat self loops in the same way it treats edges. For example, I find               GraphPlot[{{1,2},{2,0}}, SelfLoopStyle->All, MultiedgeStyle->None]      ![Graph with one self loop](http://i.stack.imgur.com/KSvNh.jpg) while the same command, but with twice the weight on the self loop gives               GraphPlot[{{2,2},{2,0}}, SelfLoopStyle->All, MultiedgeStyle->None]      ![enter image description here](http://i.stack.imgur.com/xiCHt.jpg) I would like the output from both commands to be the same. I know I could write a function to replace all non-zero values on the diagonal with `1`, but I'd prefer not to for two reasons. One is that it seems as if this should be possible without resorting to that, and the other is that I'm actually using this inside another routine to draw graphs with edge weights displayed, to get output such as ![enter image description here](http://i.stack.imgur.com/r7xC2.jpg) where the label inside the self loop should list the correct weight, taken from the diagonal of the adjacency matrix. Removing the diagonals for later labeling then changing them in the adjacency matrix just seems like a hack.


How can I combine my 3D graphics and animate them?

I'm just a beginner but can someone tell me how I can take my image of an Elf and put it together with a 3d background and I'm trying to animate it snowing but I wanna use a "play" button. Trying to do a short ten second one. Any ideas? Import["http://i1.ytimg.com/vi/woHs5kFd3dI/maxresdefault.jpg"]               Graphics3D[{Red, Cone[], White, Sphere[{0, 0, -1.5}, 1.03], Red,        Sphere[{0, 0, -3}, 1.09], Red, Sphere[{1, 0, -2.8}, 1/4],        Sphere[{1.4, 0, -2.85}, 1/4.5], Sphere[{1.7, 0, -2.95}, 1/4.9],        Sphere[{-1, 0, -2.8}, 1/4], Sphere[{-1.4, 0, -2.85}, 1/4.5],        Sphere[{-1.7, 0, -2.95}, 1/4.9], Yellow,        Sphere[{1.9, 0, -3.1}, 1/5.3], Sphere[{-1.9, 0, -3.1}, 1/5.3],        Black, Sphere[{-.5, -.80, -1.2}, 1/6],        Sphere[{.5, -.80, -1.2}, 1/6], Black,        Sphere[{-.3, -.84, -1.8}, 1/9], Sphere[{.3, -.84, -1.8}, 1/9],        Sphere[{.15, -.84, -1.9}, 1/9], Sphere[{-.15, -.84, -1.9}, 1/9],        Sphere[{0, -.84, -1.92}, 1/9], Green, Sphere[{0, 0, 0}, .457],        Green, Sphere[{0, 0, -.5}, .68], Green, Sphere[{0, 0, -1}, .901],        Sphere[{0, 0, 1}, 1/6], Green, Sphere[{0, 0, .5}, .235],        Sphere[{0, -1, -3}, 1/7], Green, Sphere[{0, -.87, -2.5}, 1/7],        Green, Sphere[{0, -.87, -3.5}, 1/7], White,        Sphere[{.9, 0, -1.5}, 1/4], Sphere[{-.9, 0, -1.5}, 1/4]}]          Graphics3D[{Translate[flake,        Dynamic[With[{time = Clock[{0, 10, .05}]}, #@time & /@ funs]]]},        Boxed -> False, Lighting -> "Neutral", AxesLabel -> {"x", "y", "z"},        Background -> LightBlue, PlotRange -> {{-10, 10}, {-10, 10}, {0, 20}}


Abort not aborting

I have a relatively simple bit of code that looks like the following:               ---some code here---     If[statement, Abort[]];     ---more code following---      However, while `$Aborted` appears as output, the evaluation of the rest of the cell does not abort, continuing execution of code beyond the `If` statement. How do I actually get the running cell to cease evaluating the rest of the cell? **Edit:** It seems that one way to accomplish this is to wrap the entire cell in parenthesis, e.g., but this is a fairly ugly solution, especially with auto-formatting turned on (my cell has many lines of code, and the parenthesis are huuuuuge). Anyone have a more elegant solution?               (     ---some code here---     If[statement, Abort[]];     ---more code following---     )


Issues with a Counter that is tallying term appearances

I am working with an array of textfiles, trying to see how frequent certain terms are. However, I am running into some difficulty with my running counts of bigram frequency. Here is a snippet of my code that has been giving me trouble:               SetDirectory[       "/users/ianmilligan/desktop/project/blah/blah/"];          filelist = FileNames["*bigrams.txt"];     citizenCounter97 = {};          Do[       citizenchecker97 = Get[file];       Clear[bigramHash];       (bigramHash[Sequence @@ #1] = #2) & @@@ citizenchecker97;       count = bigramHash["ottawa", "citizen"];       Print[ToString[file] <> ":" <> ToString[count]];       AppendTo[citizenCounter97, count];       , {file, filelist}];      The file that is being checked looks like this `citizenchecker97`=                 {{{"owner", "further"}, 262}, {{"on", "the"}, 206}, {{"the",        "women"}, 204}, {{"women", "s"}, 197}, {{"maritime",        "baptist"}, 195}, {{"and", "the"}, 193}, {{"for",        "the"}, 189}, {{"the", "maritime"}, 186}, {{"by",        "the"}, 180}, {{"with", "the"}, 170}, {{"the",        "missionaries"}, 146}, {{"that", "the"}, 142}, {{"the",        "mission"}, 141}...}}      As it stands, my `bigramHash` (which stems from an earlier exceptionally helpful SO answer) generates a number if the file contains that bigram (if it appears twice, it generates '2', which I want to `AppendTo` `citizenCounter97`. If it _doesn't_ contain the bigram, however, it generates `bigramHash[ottawa, citizen]`. My plan was to just generate a list, subsequently just `Cases[citizenCounter97,_Integer];` the thing, and have a sense of how often the given term appeared. Problem is, the results did not make sense. When I went in and started de- bugging, I realized that the counts that come out of `Print` were completley different than the lists it was generating! The result for `citizenCounter97` would be like this:               {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \     1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, \     2, 2, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, \     2, 2, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2,       bigramHash["ottawa", "citizen"], bigramHash["ottawa", "citizen"],       bigramHash["ottawa", "citizen"]}      Whereas the real `Print` output would show that the first 12 results were nothing, the 13th was 2, and then nothing again until 27, when it became 1. So basically, I am confused as to what's happening, why my counter is completely divergent from the reality as I do it manually/debug with `Print`. Thanks in advance, and happy to clarify as best I can. **---- edited to add ----** I suspect one solution lies in an `If` statement - i.e. `If` count is an integer, then append that; if the 'If' ends up being not an integer, then return 0. I've tried a variety of calls using `Head` however, and am still hitting a brick wall.


Assign variables automatically to a function

Lets consider that I've this function:               fn = a*x^2 + b*x + c;      The idea here is to assign automatically the variables `a`, `b`, `c` and `x` to a function so it becomes something like that:               fn[x_,a_,b_,c_] := a*x^2 + b*x + c      In order to do this I've tried to extract the varibles from `fn` using `Variables`:               Sort@Variables@fn      > {a, b, c, x} Then in order to apply it to the function `fn` I do the following:               fn1@Variables@fn /. List -> Sequence      > fn1[a, b, c, x] **Questions:**   * Is it possible to add the `Blank`s to the former expression in order to have `fn1[a_,b_,c_,x_]`?  > One of my fail attempt to do this was to use `Blank@#&/@Sort@Variables@fn` > but it's obviously not working.   * One other point is that if you consider that you've found a way to automaticly have `fn1[a_,b_,c_,x_]`, how to assign the value of `fn` to `fn1[a_,b_,c_,x_]` without having the `fn1[a_,b_,c_,x_] is protected` message?


Packed Graph or GraphPlot output with non-square layout?

Graph or GraphPlot produce square layouts for disconnected graphs:               Graph[Table[i -> Mod[i^3, 100], {i, 1, 100}]]      ![Mathematica graphics](http://i.stack.imgur.com/bFqCB.png) I´d like to get a rectangular layout with e.g. aspect ratio 1/2, preferably in combination with the `PackingMethod -> "ClosestPackingCenter"` option. Setting `AspectRatio` does not do what I want, because the graph is only rescaled/distorted and not redrawn on a rectanglular grid with said `AspectRatio.` ![Mathematica graphics](http://i.stack.imgur.com/XCfq2.png) Is there a way to achieve something like this (emulated by a gridded copy of the first graph)? ![Mathematica graphics](http://i.stack.imgur.com/f194y.png) Addition: Because of the added interactive graph functionality in newer versions, a solution leaving this functionality intact would be preferrable (and probably more compatible with future developments).


Where can I find example of good webMathematica programming?

Just now I started to work on webMathematica. I surprised that I can't do whatever I do with mathematica. Can any one suggest me where I can get good practice on webMathematica.


How to make Mathematica re-evaluate a cell after some event?

I am doing a little project to demonstrate something:               a = 2; b = 5000;      d = 10000; l1 = {};       rc := RandomChoice[{a, b} -> {0, 1}]     c = 1; While[c <= d, AppendTo[l1, rc];c++]      e = ((Count[l1, _] - Count[l1, 0])/d)*100//N      f = 100 - e      I want to insert two InputFields for the values of A and B, but I want it to re-evaluate the rest of the cell whenever I input new values for A and B - I'm also curious for A or B. **Note** - Inserting the inputfields is not my problem, my problems is only the reevaluation of the cell after some event.


How to import non-text data from std input in a Mathematica script?

Or maybe a better question is - how can I get a `stdin` stream? I need to run on Linux. I did look at Reading from STDIN, or: how to pipe data into Mathematica, but that talks about text data. I need to import an image, sent to standard output by another program. According to Mathematica documentation, there is no pre-defined standard input stream, there's only `$Output`, which is standard output, and `$Input`, which is the script being executed. There are only 2 functions that read from standard input in the expected way - `Input`, which tries to read a Mathematica expression, and `InputString`, which tries to read a string till it gets a newline. Neither of these is good for reading non-text data. What I would prefer to do is read from a stream, preferably using `Import`. I want to use this Mathematica script in a shell script, and pipe data to it. I tried `Import[OpenRead["/dev/stdin"]]`, but this only seems to work if I have an actual file on disk and I redirect input using `<`. It doesn't work if I pipe data to the Mathematica script.


Constrained maximum likelihood

Trying to solve a MLE with nonlinear constraints that need to be satisfied. However, the given solution do not match the constraints. Am I doing it correctly?               (* Construct Probability Model *)     \[ScriptCapitalD]1 =  NegativeBinomialDistribution[r, \[Alpha]/(\[Alpha] + 1)];     \[ScriptCapitalD]2 =   ParameterMixtureDistribution[BetaBinomialDistribution[a, b, n], n \[Distributed] \[ScriptCapitalD]1];     (* Test for one set of data *)     T = 598; R = 333; A = 78; U = 893; (* X=106; assumed unknown *)     data = {3, 1, 9, 1, 4, 2, 12, 2, 3, 1, 2, 1, 3, 2, 2, 2, 39, 3, 1, 7, 2, 1, 5, 1, 2, 1, 1, 64, 1, 2, 1, 18, 2, 1, 2, 11, 4, 3, 5, 2, 1, 4, 8, 2, 10, 16, 2, 2, 1, 5, 1, 1, 1, 1, 1, 2, 2, 4, 1, 4, 1, 1, 1, 1, 2, 1, 2, 4, 2, 4, 2, 1, 8, 1, 1, 1, 1, 1};     CC = {FullSimplify[Mean[\[ScriptCapitalD]1]] == T/U, Mean[\[ScriptCapitalD]2] == R/U, Probability[z == 0, z \[Distributed] \[ScriptCapitalD]2] == 1 - (A/U)}; (* Constraints *)     CP = {a > 0 && b > 0 && r > 0 && \[Alpha] > 0}; (* Parameter constraints *)     MLE = NMaximize[{LogLikelihood[\[ScriptCapitalD]2, data], Flatten[{CC, CP}]}, {a, b, r, \[Alpha]}]     (* Do they match the constraints? Expressed in terms of known values *)     U*{CC[[1, 1]] , CC[[2, 1]], 1 - CC[[3, 1]]} /. MLE[[2]]     (* X_estimate *)     U*(1 - Probability[y == 0, y \[Distributed] \[ScriptCapitalD]1]) /. MLE[[2]]      When I ran the code received a lot of warnings, including "Simplify::fas: Warning: one or more assumptions evaluated to False." with final output being:               {-338.828, {a -> 4.46969*10^-8, b -> 3.49161*10^-8,  r -> 0.112262, \[Alpha] -> 0.167517}}     {598.446, 335.984, 98.1873}     174.889      However, with trial and error found that the constraints can be satisfied with               {a -> 0.79170676874115343262052276450750130908150706082622,  b -> 0.63003691806728426319650273891989981624150723094542,  r -> 0.045708496520516912401968683076575539420378914371680, \[Alpha] \-> 0.068257002329133115008291066471192704521037320465721}      being one answer. Whether those are the maximum likelihood estimates I am not sure.


Default FontFamily for PlotLabel

This is probably a rather basic question and I presume I am simply unable to make proper use of the `Options[]` function: I am trying to figure out what the default font (or `FontFamily`, I guess) is for `PlotLabel`. I tried e.g. `Options[PlotLabel, FontFamily]` and some variations, but to no avail. Many thanks.


How to prepare (copy/paste) data from Matlab?

What is the best way to get data from Matlab to Mathematica? For a new project I want to copy/paste a table (or part of it) of datas from Matlab to Mathematica. Copyed from Matlab it is:               0   0     1,00000000000000e-20    0,100000000000000     1,78810000000000e-09    0,300000000000000     2,94930000000000e-09    0,500000000000000     4,37810000000000e-09    0,700000000000000     5,58330000000000e-09    0,900000000000000     5,60570000000000e-09    1      In Mathematica I get the following:               0 0     1, 00000000000000 e - 20 0, 100000000000000     1, 78810000000000 e - 09 0, 300000000000000     2, 94930000000000 e - 09 0, 500000000000000     4, 37810000000000 e - 09 0, 700000000000000     5, 58330000000000 e - 09 0, 900000000000000     5, 60570000000000 e - 09 1      (In my Mathematica, there are little "x"s between the exponents and the zeros, I guess it is the columns seperator.) So now I have to replace the "," by "." and the "e-" by "*10^-" and so on ... I could, but I don't want to do it manualy, but till now I had no success with any Mma functions. Or is there a better way to do things like this? ... in the end it should look like this:                {{0, 0},      {1.00000000000000*10^-20, 0.100000000000000},      {1.78810000000000*10^-09, 0.300000000000000},      {2.94930000000000*10^-09, 0.500000000000000},      {4.37810000000000*10^-09, 0.700000000000000},      {5.58330000000000*10^-09, 0.900000000000000},      {5.60570000000000*10^-09, 1}}


Correlation test issues

When using `Correlation[]` function I sometimes get the strange warning:               CorrelationTest::nortst: "At least one of the p-values in {0.0527317}, resulting from a test for normality, is below 0.05`. The tests in \!\({\"PearsonCorrelation\"}\) require that the data is normally distributed."      But take a look that there's only one p-value and it is actually greater than $0.05$:               0.0527317 < 0.05     False      The code that causes this:               x = RandomReal[{-5, 5}, 100];     y = 2 x + 1 + RandomReal[{-0.1, 0.1}, 100];     X = Transpose[{x, y}];     ListPlot[X]     Correlation[X] // MatrixForm     CorrelationTest[X, 99995/100000, "PearsonCorrelation"]      Why this happens? (to reproduce the issue a few repetitions are usually required)