title: How to track dynamically generated manipulators?

text: In the code below the manipulators that are generated from the stakes buttons are not tracked by the `Manipulate` expression that contains them. How can I make the plot update with these sliders? If I add 'stakeWeights' and 'roi' (the values of the manipulators) to the tracked symbols, the manipulators won't move. My apologies for posting the complete code but I couldn't find an easy way to isolate this from the rest of the code.               RandomWalk[n_, roi_, bi_, rake_] :=      (*If errors return list with zero so ListPlot does not complain *)      Quiet@Check[(pwin = bi (1 + roi)/(2 (bi - rake));          NestWhileList[# + RandomChoice[{pwin, 1 - pwin} -> {1 - 2 rake/bi, -1}] &,            0, True &, 0, n]),          {0}]          trial = 0;     allStakes = {1.5, 3.5, 7, 15, 30, 60, 100, 200, 300, 500, 1000};     rakes = {0.06, 0.1, 0.15, 0.31, 0.63, 1.26, 1.88, 3.34, 4.49, 6.65, 11.2}     MapIndexed[(rakebyStake[#1] = rakes[[#2]]) &, allStakes]              Manipulate[trial;      data = RandomWalk[nrTournaments, avgROI/100, avgBI, avgRake];      (stakeWeights[#] = 100) & /@ allStakes;      (roi[#] = 1) & /@ allStakes;      avgBI =        Quiet@Check[         Total[(# stakeWeights[#]/Total[stakeWeights /@ stakes]) & /@             stakes // N], 0];      avgRake =        Quiet@Check[         Total[(rakebyStake[#][[1]] stakeWeights[#]/                Total[stakeWeights /@ stakes]) & /@ stakes // N], 0];      avgROI =        Quiet@Check[         Total[(roi[#] stakeWeights[#]/Total[stakeWeights /@ stakes]) & /@             stakes // N], 0];      biWon = Quiet@Check[Last[data], 0]; dollarWon = biWon avgBI;       pwin = Quiet@Check[avgBI (1 + avgROI/100)/(2 (avgBI - avgRake)), 0];      expectedBiWon =        Quiet@Check[((1 - 2 avgRake/avgBI) pwin - (1 - pwin)) nrTournaments, 0];      expectedDollarWon = expectedBiWon avgBI;      sampleROI = Quiet@Check[dollarWon/(nrTournaments avgBI), 0];      Dynamic@ListPlot[data, Joined -> True, PlotStyle -> {RGBColor[0, 0.2, 0.6]}],       {{nrTournaments, 3000, "tournaments"}, 0, 100000, 100, Appearance -> "Open"},      {{stakes, {60}, "stakes"}, allStakes, ControlType -> TogglerBar},      Dynamic[Column@{Grid[({#,               Manipulator[Dynamic[stakeWeights[#]], {0, 100, 1}],               Dynamic[Quiet@                Check[100 stakeWeights[#]/                   Total[stakeWeights /@ stakes // N], 0]],              "ROI",               Manipulator[Dynamic[roi[#]], {0, 75},                Appearance -> "Labeled"]}) & /@ Sort[stakes]]}],      {{avgROI, 1.5, "avg ROI (%)"}, 0, 75, 0.01, Appearance -> "Open"},       {{avgBI, 60, "avg BI ($)"}, 0, 10000, 1, Appearance -> "Open"},           {{avgRake, 1.26, "avg rake ($)"}, 0, avgBI/10, 0.01, Appearance -> "Open"},           {{rakeback, 37, "rakeback (%)"}, 0, 100, 0.01, Appearance -> "Open"},           Delimiter,           Panel[Grid[{{Dynamic[               Row[{"sample ROI: ",                  Style[ToString[sampleROI 100] <> "%",                   If[sampleROI >= 0, Darker[Green], Red]]}]]}, {Dynamic[               Row[{"# BI won: ", ToString[biWon], " (",                  Style["$" <> ToString[dollarWon],                   If[dollarWon >= 0, Darker[Green], Red]], ")"}]]},             {Dynamic[               Row[{"rakeback: ",                  Style["$" <> ToString[avgRake rakeback/100 nrTournaments],                   Darker[Green]]}]]}, {Dynamic[               Row[{"$ won after rakeback: ",                  Style["$" <>                    ToString[dollarWon + avgRake rakeback/100 nrTournaments],                   If[dollarWon + avgRake rakeback /100 nrTournaments >= 0,                    Darker[Green], Red]]}]]},             {Dynamic[               Row[{"expected # BI won: ", ToString[expectedBiWon], " (",                  Style["$" <> ToString[expectedDollarWon],               If[expectedDollarWon >= 0, Darker[Green], Red]], ")"}]]}},         Alignment -> Left]],       Button["Run again", trial++, ImageSize -> Medium],       SaveDefinitions -> True,       TrackedSymbols :> {nrTournaments, avgROI, avgBI, avgRake, trial,         stakes, rakeback}]


title: Override @ to mock Java Classes

text: This question appears impossibly long so apologies in advance (skip to the bottom if you want to see the actual questions). I want to be able to mock Java Classes in _Mathematica_ code. For example, I may have a simple Java bean `Point` that has two fields `x` and `y`. Using JLink, I would interact with objects of the point class as:                   obj = JavaNew["java.awt.Point"]         obj@x = 22         obj@y = 42      There are countless ways that this could be done in _Mathematica_ but to mock (so I can later swap out the _Mathematica_ code with the actual Java classes) I'd like to be able to do something along the lines of                   obj = Point[0, 0]         obj@x = 22         obj@y = 42         obj == Point[22, 42] (* evals to True*)       I have taken two stabs at this. First using the Notation package and overriding the following type of expressions:               Notation[      ParsedBoxWrapper[        RowBox[{RowBox[{"obj_", "@", "field_"}], "=", "val_"}]] [DoubleLongLeftRightArrow]          ParsedBoxWrapper[           RowBox[{"ApplySet", "[", RowBox[{"obj_", ",", " ", "field_", ",", "val_"}], "]"}]]      The above maps code like                   obj_@field_ = val         obj@x = -99    (* for example *)      to                   ApplySet[obj_, field_, val_]         ApplySet[obj, x, -99]   (* for example *)      `ApplySet` in turn is redirected to either a setter on the "class" or passed through to the usual _Mathematica_ handling on the basis of a conditional evaluation that checks that `obj` is a "class" or not.                    ApplySet[obj_, field_, val_] := set[obj, obj, field, val] /; MBeanQ[Head[obj]]          (* pass obj through twice, once in HoldFirst the second evaluated as the data *)          (* otherwise just pass through to normal handling for the Prefix @ *)          ApplySet[obj_, field_, val_] := obj[field] = val      This approach works well in the FrontEnd and it seemed to be able to do everything I needed and more. However, when I moved this to packages the `Notation` and related `MakeExpression`/`MakeBoxes` doesn't seem to work. I did use `Action -> PrintNotationRules` to get the the underlying `NotationMakeExpressions`/`NotationMakeBoxes`. For example, here is the `NotationMakeExpressions`:               NotationMakeExpression[       RowBox[{Notation`Private`lhs___,          RowBox[{obj_, "@", field_}], "=", val_,          Notation`Private`rhs___}], StandardForm] :=        MakeExpression[RowBox[{Notation`Private`lhs,          RowBox[{"ApplySet", "[",            RowBox[{obj, ",", field, ",", val}], "]"}],          Notation`Private`rhs}], StandardForm]         My second crack was to override the behaviour of `Set` and redirect in a similar way, testing for a "class". For example:               Set[obj_[field_], val_] := CallSet[obj, obj, field, Null, val] /; CallSetQ[Head[obj]];     Set[obj_[field_[idx_]], val_] := CallSet[obj, obj, field, idx, val] /; CallSetQ[Head[obj]];     Set[obj_, fieldUpdates__List] := CallSet[obj, obj, fieldUpdates] /; CallSetQ[Head[obj]];      This approach works well enough in both the FrontEnd and in packages, but of course it requires overriding something pretty fundamental. Even setting aside the potential performance concerns, it just doesn't seem right. I'm sure that this is documentation somewhere but I couldn't find it. Are `MakeExpression` and `MakeBoxes` really Frontend functions that aren't available in kernel to packages? Is there a smarter way to do this?


title: Mathematica 9 cannot solve this Integral. Mathematica 8 could. Is this a bug?

text: I was trying to (re)calculate a problem of an older Wolfram blog post (Problem 11457, by M. L. Glasser) with Mathematica 9.0.0.0 (on OS X 10.8.2).               Assuming[0 < a < b, Integrate[ArcCos[x/Sqrt[(a + b) x - a b]], {x, a, b}]]      Instead of the expected solution, it just returns the integral unevaluated. Is this a regression? **More details:** As pointed out in the commentes, the indefinite integral               Integrate[ArcCos[x/Sqrt[(a + b) x - a b]], x]      still gives the same result in Mathematica 8 and 9. The next two each returned ConditionalExpression in Mathematica 8 but return unevaluated in Mathematica 9:               Integrate[ArcCos[x/Sqrt[(a + b) x - a b]], {x, a, b}]     Integrate[ArcCos[x/Sqrt[(a + b) x - a b]], {x, a, b}, Assumptions -> 0 <= a <= b]      The actual problem               Integrate[ArcCos[x/Sqrt[(a + b) x - a b]], {x, a, b}, Assumptions -> 0 < a < b]      computes correctly to `((a - b)^2 \[Pi])/(4 (a + b))` in Mathematica 8 but still returns unevaulated in Mathematica 9.


title: What ProcessEstimator Options can I use with FractionalBrownianMotionProcess

text: I can generate an fBm process:               tlow = 0;     thigh = 1;     len = Sqrt[thigh];     tinc = 0.01;     hurst = 0.4;     DataZ = RandomFunction[        FractionalBrownianMotionProcess[hurst], {tlow, thigh, tinc}, 1];     dataz = Flatten[DataZ[[2, 1]]];      In the following post: Computing the Hurst exponent or fractal dimension of fractional Brownian motion it is described that you can use FindProcessParameters to estimate the Hurst exponent:               FindProcessParameters[dataz, FractionalBrownianMotionProcess[h]]      The documentation says that you can use the ProcessEstimator options... but it does not say which one you can use... I am guessing that such options would be similar to Box counting, Takens estimator, etc. What are the ProcessEstimator options that can be used with FractionalBrownianMotionProcess?


title: How to work with Application Project files in Wolfram Workbench?

text: I have figured out that in a basic project I simply have to call the main package (m file) from the notebook using               <<nameofmfile`       and then the notebook recognizes the functions I defined in the m file and I can use these function in the notebook. Unfortunately when I do the exact same thing in an application project the notebook doesn't recognize the main package (m file). I can't find proper help with this - the Workbench help doesn't seem too useful to me. I have a feeling that this problem occurs because the main package is not in the same folder as the notebook in the case of application projects. Please help!


title: Deleting Print results

text: While playing around with `$Pre` and `$Post` I created this very annoying piece of code:               $Post = If[# =!=       Null, (Print@"Are you sure you want to know the result?";       Print@Row@{Button["Yes", Print@#], Button["No", Null]}), Null] &;      I have not yet found a use for it (other than possibly playing pranks on Mma newbies) but it led me to the following question: How can one delete a certain cell that was created by `Print` (i.e. without selecting the cell manually)? And furthermore, how can one create a button that deletes itself upon being clicked (still evaluating the action)? Ultimately I want the button to delete both itself and the `"Are you sure..."` cell. I found out in the documentation that `PrintTemporary` objects can be deleted using `NotebookDelete`. Is there a similar way for `Print` cells? I think something similar to what I want could be done using `ChoiceDialog` and the like, but I'm really interested in deleting the `Print` cells.


title: Representation of product with exclusions

text: Is there a nice way to define output formatting for my expression, a product from `n = k` to `j` with `n ≠ m`? I would like to use something like this here (however _Mathematica_ doesn't evaluate it): $$\prod _{n=k,n\neq m}^j \frac{\lambda _n}{\lambda _n-\lambda _m}$$ My work around at the moment is: (adopted from Sum or Product with Exclusions) $$\prod _n^{\text{DeleteCases[Range[k, j], m]}} \frac{\lambda _n}{\lambda _n-\lambda _m}$$


How to systematically classify Mathematica expressions? I can think of using `Head[]`, `Depth[]`, `Length[]`, and some special pattern based on the problems at hand. What other key words, or functions should I consider? ## Update I mostly want to group symbols by how nested its list are, and what kinds of elements the lists have. For example               {_String, _Symbol}          {{_Integer}, _String}          _String      would be considered _three_ distinct types.


title: How do I save the values in a table?

text: I have written the following sequence. ![Sequence written with mathematica](http://i.stack.imgur.com/Q1ZeB.png) I would like to save the resulting values in a table such that I have a list of all the values at the end the For loop. How do I proceed? My goal is to sum up all the values at the end. I would like the table to look as follows: ![sample result](http://i.stack.imgur.com/g9F7G.png)


title: Find an equations of motion using Euler Eqution

text: I am a completely new to Mathematica, so my question and code may look silly. I need to find a equation of motion of a point particle of mass m moving in a potential V(x) = A abs[x]^n. (n=1,2,3,4,5,6. m=1, A=1, x(0)=2, x'(0)=0 ) I tried to find the equation using Euler method, so I made code below. I know somethings wrong with my code, but I have no idea. How can I make one equation with various n values? Can someone help me?               T = 0.5*x'[t]^2;     V = Abs[x[t]];     L = T - V     -Abs[x[t]] + 0.5 Derivative[1][x][t]^2     EulerEquations[%, x[t], t]     -Derivative[1][Abs][x[t]] - 1. (x^\[Prime]\[Prime])[t] == 0     NDSolve[{x''[t] + Abs'[x[t]] == 0, x[0] == 2, x'[0] == 0}, x, {t, 0,10}]     NDSolve::ndnum: Encountered non-numerical value for a derivative at t == 0.`. >>      And, additionally I need to plot the period as a function of n. How can I construct the plot?


title: Put results in multiple columns for comparison

text: One thing I would like to do in many instances is arrange input/output in columns for comparison. I expect that I need to use `Grid` to do this, but have not been able to figure out the right commands. For example, if I have the following type of function and two different possibilities:               Table[GCD[fun1[c^a], fun1[c^b]], {a, 1, 3}, {b, 1, 3}, {c, 1, 3}]          Table[GCD[fun2[c^a], fun2[c^b]], {a, 1, 3}, {b, 1, 3}, {c, 1, 3}]      Here, I have two custom functions `fun1` and `fun2` which take multiple inputs over ranges (27 possibilities in all). I want the output to be rearranged so I have the following columns:               a, b, c, GCD[fun1[c^a], fun1[c^b]], GCD[fun2[c^a], fun1[c^b]], difference      In otherwords I want to see the combination of inputs being used in the leftmost columns, the ouptuts from the two possible expressions, one using fun1, the other using fun2, then optionally a final column showing the difference between the two possible outputs for each of the 27 possibilities. How can I do this?


title: How to show values of points on surface plotted with ContourPlot3D

text: The help for ContourPlot3D starts with this example               ContourPlot3D[x^3 + y^2 - z^2 == 0, {x, -2, 2}, {y, -2, 2}, {z, -2, 2}]      This returns a Plots of the surface $x^2 + y^2 - z^2 = 0$: ![Surface](http://i.imgur.com/Ff4Fg.jpg). Now I have a function, and I would like to know how this function behaves on this surface. For example, take               f[x_,y_,z_] := {x^3 - 2 x y + z^2 x - 5 z^2 y^2 - 4 x y z,                      Sin[10x] + Cos[5y] + Cos[20z]}      I was thinking of making a list with some of the point that lie on this surface. Then it is easy to evaluate the function on these points. The way I would like to generate the list is to click with the mouse on a few points that I think are interesting. Is that possible? What are the alternatives to using the mouse? There most be some list available with all points that were used to draw this graph. How can I take some point of that list and add them as point to the 3D plot to visualize them? **Update** The methods of Szabolcs and Heike work fine on the example $x^3 + y^2 - z^2 =0$. Now I try to apply the same to $$ 2316 a^{12} c^6+500 a^{11} b c^5+10296 a^{10} b^2 c^4+1624 a^{10} c^5+656 a^9 b^3 c^3- \\\ \- 3856 a^9 b c^4+41 a^8 b^4 c^2+808 a^8 b^2 c^3+784 a^8 c^4+a^7 b^5 c+24 a^7 b^3 c^2- \\\ \- 176 a^7 b c^3+2 a^6 b^4 c+16 a^6 b^2 c^2+32 a^6 c^3 = 0 $$               f[a_, b_, c_] := 2 a^6 b^4 c + a^7 b^5 c + 16 a^6 b^2 c^2 + 24 a^7 b^3 c^2      + 41 a^8 b^4 c^2 + 32 a^6 c^3 - 176 a^7 b c^3 + 808 a^8 b^2 c^3      + 656 a^9 b^3 c^3 + 784 a^8 c^4 - 3856 a^9 b c^4      + 10296 a^10 b^2 c^4 + 1624 a^10 c^5 + 500 a^11 b c^5 + 2316 a^12 c^6     pts = {};      Substituting this function into Heike's solution does not work. Clicking does not result in points on the surface. Also Szabolcs's FindInstance does not work. What goes wrong here? ![Surface 2](http://i.imgur.com/MbVql.jpg).


title: How to write output in TraditionalForm into external text files?

text: I'd like to write output in TraditionalForm into external text files `ofile.txt`. I tried to use               s = OpenWrite["/home/tigerhead/log/ofile.txt", FormatType -> TraditionalForm];     $Output = s;     <run various Mathematica programs>     Close[s];      but get errors:               Intersection::normal:         Nonatomic expression expected at position 2 in          Intersection[{StandardForm, TraditionalForm}, FormatType].     Options::optnf:         FormatType is not a known option for          Intersection[OutputStream[/home/tigerhead/log/ofile.txt, 21], {OutputStream[/home/tigerhead/log/ofile.txt, 20], OutputStream[stdout, 1],            OutputStream[stderr, 2], OutputStream[/home/tigerhead/<<38>>.txt,             21], stdout, stderr}].      Any one has a clue?


title: How to set precision and format labeled Slider in Manipulate?

text: For my calculations, I need increased precision of parameter 'k' in my Manipulate:               Manipulate[      Plot[Cos[k x], {x, 0, 2 Pi}], {{k, 1}, 0, SetPrecision[4.0, 22],        SetPrecision[0.100, 22], Appearance -> "Labeled"}]      However, at the same time, for aesthetic reasons, I want the label to the right of the slider to display only couple of digits. How this could be done?


title: Question about Solve

text: I don't understand what _Mathematica_ is doing to get these solutions. I ask it to solve two equations, the left hand side of both expressions are the same, the right hand sides differ by a ± sign. I really don't think the solutions should be the same, but that is what _Mathematica_ returns, without any comment.               FullSimplify[{       Solve[1/2 E^(-((2 I l π)/k)) (-(-1 + E^(I ((4 l π)/k + δ))) Sqrt[ρ] + Sqrt[-2 E^(I ((4 l π)/k + δ)) (-2 + ρ) + ρ + E^(2 I ((4 l π)/k + δ)) ρ]) == E^(2 π I m/n), ρ],        Solve[1/2 E^(-((2 I l π)/k)) (-(-1 + E^(I ((4 l π)/k + δ))) Sqrt[ρ] + Sqrt[-2 E^(I ((4 l π)/k + δ)) (-2 + ρ) + ρ + E^(2 I ((4 l π)/k + δ)) ρ]) == -E^(2 π I m/n), ρ]     }]      _Mathematica_ returns > >     { >       {{ρ -> (-1 + Cos[(4 m π)/n - δ])/(-1 + Cos[(4 l π)/k + δ])}}, >       {{ρ -> (-1 + Cos[(4 m π)/n - δ])/(-1 + Cos[(4 l π)/k + δ])}} >     } >   Can anyone can shed some light on this, please?


title: Assigning Variables for Degree Distribution

text: So my code is divided into 3 different sections: 1) Calculating clustering coefficient, 2) Extracting degree distribution 3) Using the degree distribution to get the mean of 1000 networks.               N[GlobalClusteringCoefficient[Graph[{1\[UndirectedEdge]2, 2\[UndirectedEdge]3, 3\[UndirectedEdge]1}]]]          VertexDegree[Graph[{1\[UndirectedEdge]2, 2\[UndirectedEdge]3, 3\[UndirectedEdge]1}]]          Output: {2,2,2}      Then:               N[Mean[GlobalClusteringCoefficient/@RandomGraph[DegreeGraphDistribution[{1,2,4,3,5}],100]]]      So, I am copying and pasting the degree distribution generated in the second line into the third part. Instead of doing that, is there a way to assign a variable so it is done automatically? E.g               x = VertexDegree[Graph[{1\[UndirectedEdge]2, 2\[UndirectedEdge]3, 3\[UndirectedEdge]1}]]          N[Mean[GlobalClusteringCoefficient/@RandomGraph[DegreeGraphDistribution[{x}],100]]]      Obviously, this won't work but the idea is I save time, instead of copying and pasting the result from the output, can I make a variable assignment that automates this process?


title: Fixing Spline curves so as to not overlap with themselves - (Diagrams)

text: **Statement of the problem:** Conceptually, what I'm trying to achieve is pretty simple. I have some code that generates a set of diagrams from a list of sets of points using BSplineCurve. Certain conditions cause some of these diagrams to come out differently from what I need. With SplineDegree -> 1 the images look like: ![Spline Degree 1](http://i.imgur.com/GYuGVsE.png) and with SplineDegree -> 3 the images become: ![Spline Degree 3](http://i.imgur.com/HWiz39T.png) The problematic cases are images a7, a8 and a9, which I need to look like: ![Correct Images](http://i.imgur.com/us3oI3r.jpg) The general rule is that I need closed smooth curves through the specified points, but the curve must not lie on top of itself when the points all lie on a straight line (I also need the curves to pass directly through the points, but this is another issue that is probably fairly easily solved - I've tried clamping without much success so far). I have tried to solve this problem by implementing clunky IF statements that add additional guide points, but in addition to the fact that I struggle to make it work, it's very undesirable, because I need this to generalize to more complicated diagrams. For example, here is a preview of the higher dimensional case (the full list is very long): ![Higher Dimension Sample](http://i.imgur.com/Wjrob3N.png) The last five images are problematic and should look like ![Correct Higher Dimension Sample](http://i.imgur.com/jUPO5g3.jpg) I have also considered using Graph to try and do this, but I'm not really sure where to start. **Code:** I can't provide the full code, because the process of generating the list of points is exceptionally long. Here is the section that is relevant:               Clear[\[Delta]ToBirdTrack1];     Options[\[Delta]ToBirdTrack1] = {Background -> White, Trace -> Tr,         Scale -> 1};     \[Delta]ToBirdTrack1[expr_, A_: a, B_: b,         options___Rule] := \[Delta]ToBirdTrack1[expr, A, B, options] =         Module[{l, s, aa, bb, h, res, res1, hsep, vsep, samesep, bgcolor,       trace, scale, split},          (* options *)     bgcolor = Background /. {options} /. Options[\[Delta]ToBirdTrack1];     trace = Trace /. {options} /. Options[\[Delta]ToBirdTrack1];     scale = Scale /. {options} /. Options[\[Delta]ToBirdTrack1];          hsep = 5;     vsep = 2;     samesep = hsep/6;     l = (expr //           Cases[#, Subscript[A,  i], Infinity, Heads -> True] & //          Union // Length);     h = l*vsep;          (*line 1*)     res = (expr /.            Tr[aa__] :> m[Line[(*Append[*)aa(*,First[aa]]*)]] //.           m[aa__] m[bb__] -> m[aa, bb]) /. UP -> Sequence /.        Subscript[t, i_] -> i;          (*line 2*)     res = res // (# /. m[aa__] :> (m[aa] /. a_Line :> pos /@ a)) &;          (*line 3*)     res // (# /.           Line[aa__] :>            BSplineCurve[{aa}, SplineClosed -> True]) & // (# /.          m[aa__] :> Graphics[{aa}]) &     ];          ExplicitList[NgI[2]] //        Sum[Subscript[\[Alpha], i] #[[i]], {i,       Length[#]}] & // \[Delta]ToBirdTrack1[#] &      I can't provide the data being put into this code, again because of length, but I can however show what it looks like. At "line 1" res is being shaped into this list: ![Algebraic List](http://i.imgur.com/GAxxEit.png) At "line 2" it is shaped into this list: ![Line object list of coordinates](http://i.imgur.com/b4ALCHC.png) And at "line 3" the "aa's" that are being considered by the Spline Curve plotting look like this: ![Coordinates](http://i.imgur.com/qpGouUF.png) Any and all help would be greatly appreciated, with the most general solution being the goal.


title: Mathematica function intersection points with 3D grid

text: I need to produce a 3-dimensional equispaced grid over a given function in a way, that I can calculate intersection points of the function with the grids edges. So my first question is how to produce this grid in Mathematica. I don't really get if this is possible by modeling the grid by `Polygon`s? For this I might need some help then, too. Or can it be done by using more simple graphics objects like done here?


title: Export Table from Mathematica into specific cells Excel

text: How can I export a table to Excel - to specific cells, e.g. D1-E2? Background: I want to compare results, and it's easier to have the results on one spreadsheet. I'm using _Mathematica_ 6. This is my notebook so far:               ResultsV = Grid[{  {"result1", result1},  {"result2", result2}}]      Export["results.pdf", ResultsV]      This table should appear twice in the spreadsheet, as some parameters differ. Thanks a lot!


title: Count consecutive occurrences in a list above a certain value

text: I am trying to tally and sort the number of consecutive occurrences in a list above a certain value. For instance:               data={55.5, 65.3, 100.3, 100.1, 100.5, 98.7, 75.2, 101.3, 102.1}      The totals for this data set would be {3,2} if the tally criteria were all values greater than 100. As I have worked on this problem, I found the following code:               a = RandomInteger[1, {100}];     Cases[Split[a], {1, ___}] // Tally // Sort      Which is very close to what I am trying to do. In this case, the code provides a sorted list of consecutive integers equal to one. However, I can't seem to modify the decision criteria to only tally values above a certain criteria. How might I go about this?


title: Function to differentiate between date pattern and specific string format

text: I'd like to write a function that behaves one way when the argument is a _Mathematica_ date, such as `{2013,12,15}`, or with added hours, minutes and seconds if necessary. And the function needs to do something different with strings that will look like > 2013 Month 02 I see that I can specify List, as in `f[x_List]` and `f[x_String]` that will do what I want as long as I don't mess up the arguments. Is there way to be more specific about the patterns that are allowed?


title: Create continuous function from list

text: I have a list of data (measured per day) that I want to use as imput for another equation (say f). The problem is that the input I need for f needs to be a continuous function of time. Is it possible to change my data into a function? I would either like a function that is linear increasing or decreasing between the different timesteps (like the line you get when you use `Joined` in `ListPlot`) or a stepwise function that immediately jumps to another value the next day. I tried using `Interpolate` but then when I measured 0, I get negative values which is not possible for my measured values. Hope someone could help me. Simplified example:               tmin=1;     tmax=6;     data = {{1, 3}, {2, 0}, {3, 0}, {4, 5}, {5, 7}, {6, 10}};     ListPlot[data, AxesLabel -> {"time(day)", "data(mm)"}, Joined -> True]          f = Interpolation[data];     Plot[Evaluate[f[t]], {t, tmin, tmax}]      If you evaluate this: the first plot is the result I would prefer for my function, the second plot is not what I want as the values drop below 0. ![enter image description here](http://i.stack.imgur.com/nxFAO.png)


title: Why does importing a URL fail the second time and produce a FetchURL::conopen error?

text: I have _Mathematica_ code that uses `Import[]` to download URLs. I noticed that first time I use the `Import[]` command it works. Next time it fails. I'm using Windows 7, Mathematica 8.0.4. Here is an example. I start new sesssion of _Mathematica_ , and then type               Import["http://groups.google.com/group/comp.soft-sys.math.mathematica/about"]      No problem. Now I issue the same command again on the same URL (or different one)               Import["http://groups.google.com/group/comp.soft-sys.math.mathematica/about"]      and now this gives me an error > FetchURL::conopen: The connection to URL > http://groups.google.com/group/comp.soft-sys.math.mathematica/about cannot > be opened. If the URL is correct, you might need to configure your firewall > program, or you might need to set a proxy in the Internet connectivity tab > of the Preferences dialog (or by calling SetInternetProxy). For HTTPS > connections, you might need to inspect the authenticity of the server's SSL > certificate and choose to accept it. On the same Windows 7 PC, I start MATLAB, and type               data=urlread('http://groups.google.com/group/comp.soft-sys.math.mathematica/about')     data=urlread('http://groups.google.com/group/comp.soft-sys.math.mathematica/about')      and both work. I get the page fine the second time around. I open the browser, and type the URL, and I can see the page. This is the same PC. No proxy. home PC. Nothing special. P.S. This code used to work fine with _Mathematica_ on an earlier version (forgot which one now), becuase I used _Mathematica_ to generate this web page and all the `Import` commands I used are listed above and you can see them. I have list of many URL's that I loop over calling `Import[]` on them one by one. Again, **the problem is that I now get an error on a URL using`Import[]` and the problem seems to show up the second time I use the `Import[]`.** Any suggestions how to fix this? Is this a known issue? **update** I still have _Mathematica_ 7 and 6 installed. So I tried this on them. And I get the same problem there. This is strange, since this code worked before. I think now it is a google groups/server problem, becuase when I try different domain (i.e. not google groups), I do _not_ get this problem               data = Import["http://www.yahoo.com", "Data"];     data = Import["http://www.yahoo.com", "Data"];      No error in the second time. I do not understand why this problem (i.e. using the `Import` command again) gives an error on some URLs and not on others. **update** Thanks for everyone's help and for WReach solution. I have used WReach nice solution to bypass the problem and have just updated the currrent Mathematica code I was using to update the usenet programming languages trends charts. The updated charts are on this page if you are interested in seeing the result.


title: StiffnessSwitching controller for NDSolve

text: I have a question regarding NDSolve and StiffnessSwitching. StiffnessSwitching is a method to provide automatic means to handle switching between a stiff and nonstiff solver. The StiffnessSwitching can be activated using for example               Method -> {StiffnessSwitching, Method -> {ExplicitRungeKutta, Automatic}}      as an option to NDSolve. The inner list with the two methods is the method to use for the nonstiff and stiff solver respectively. My question is: Why can't I use the ordinary TimeIntegration methods (for example Adams) as a submethod options for the nonstiff solver. As followed by the example in the tutorial:               Needs["DifferentialEquations`NDSolveProblems`"];     Needs["DifferentialEquations`NDSolveUtilities`"];     system = GetNDSolveProblem["VanderPol"];     time = {T, 0, 10};     sol = NDSolve[system, time, Method -> {StiffnessSwitching, Method -> {Adams, Automatic}}, AccuracyGoal -> 5, PrecisionGoal -> 4]          NDSolve::mdata: An invalid NDSolve`StiffnessSwitching method data object was encountered at the point T == 0.`. >>      Is there a way to combine TimeIntegration with StiffnessSwitching?


title: Selecting for morphological components that do not border the edges of an image?

text: Is there an easy way to select for morphological components which do not border/touch the edges of an image? Taking this doodle as an example: ![enter image description here](http://i.stack.imgur.com/2fQ3j.png) We'd want to only select morphological components that stay at least some critical distance from the edges of the image.


title: Issue with Coefficient command

text: I'm trying to used the Coefficient command to extract the numerical values in front of a Chebyshev polynomial. I know that there is a numerical way to do this, presented in numerical recipes, which I have already done. But I think using the Coefficient function would be easier and possibly less prone to numerical issues. For example when I use the method from numerical recipes Mathematica thinks that some of my Chebyshev coefficients have an imaginary part, which I know they certainly do not. This is what I have so far:               test = {6.6358882978163365`, 2.12043877554564`, 7.221785806754298`, 8.556762565842575`,          0.8777943247026911`}          test2[y_] = Sum[test[[i + 1]]*ChebyshevT[i, y], {i, 0, 4}]          6.63589 + 2.12044 y + 7.22179 (-1 + 2 y^2) + 8.55676 (-3 y + 4 y^3) +      0.877794 (1 - 8 y^2 + 8 y^4)      Then I try               Table[Coefficient[test2[y], ChebyshevT[i, y]], {i, 0, 4}]      which resulted in an error, so I just trying getting the coefficients one by one to see if I could figure out the issue. Please bear with me,               In[38]:= Coefficient[test2[y], ChebyshevT[0, y]]          During evaluation of In[38]:= Coefficient::ivar: 1 is not a valid variable. >>          Out[38]= Coefficient[     6.63589 + 2.12044 y + 7.22179 (-1 + 2 y^2) +  8.55676 (-3 y + 4 y^3)      + 0.877794 (1 - 8 y^2 + 8 y^4), 1]          In[39]:= Coefficient[test2[y], ChebyshevT[1, y]]          Out[39]= -23.5498          In[40]:= Coefficient[test2[y], ChebyshevT[2, y]]          Out[40]= 7.22179          In[41]:= Coefficient[test2[y], ChebyshevT[3, y]]          Out[41]= 8.55676          In[42]:= Coefficient[test2[y], ChebyshevT[4, y]]          Out[42]= 0.877794      So, the Coefficient command is not working for the zeroth order and first order Chebyshev polynomial. I think I understand why it won't work for the zeroth order. The Coefficient function probably needs a symbolic argument and not a number like "1". Is there anyway to fix this? More confusing to me is why it fails for the first order Chebyshev polynomial. I can't figure that part out at all. * * * The code               Table[Coefficient[test2[y], z = ChebyshevT[i, y]; If[z === 1, Sequence @@ {y, 0}, z]], {i,         0, 4}]      provide by Nasser, seems to work, it gives               {0.291897, -23.5498, 7.22179, 8.55676, 0.877794}      But I'm starting to understand that there is a fundamental problem with what I'm trying to do. When I give the command               Coefficient[test2[y], ChebyshevT[1, y]]      Mathematica just interprets that as               Coefficient[test2[y], y]      and the adds together all of the numerical coefficients in front of anything that has a "y" in the term. Ideally I want Mathematica to output 2.12044, but it is adding up all of the terms that have a "y" in front of them. I guess I will just have to stick with the method found in numerical recipes.


title: Image's pixels GPU colour classes splitting

text: How can I split in color classes, the pixels of an image that I load in Mathematica? I would an output like this:               <Class1Name> 50%      <Class2Name> 30%      <Class3Name> 20%      The percentages refere to the amount of pixels of the image that are into that colour class. The definition of the classes would be something like this: `<Class1Name>` = All pixels that are into a RGB range of colours (for example from a dark green to a light green) I have tried a code like this:               Image[{List@@@DominantColors[<imagefile>, n]}, ImageSize -> 300]      But I don't know how to split the output in classes. By encreasing the value of $n$ I will have a better precision right? I would love also a plot of the normal distribution of the pixels, where in the $x$ axis lie the names of the classes and on the $y$ axis a normalized scale that go from 0 to 1. So the plot should look similar to this: ![enter image description here](http://i.stack.imgur.com/mqN8d.png) If is possible I would execute the computation of all this on the GPU or on both the CPU and GPU togheter, I would like to chose between an OpenCL and CUDA version of the code and if is not possible I would have a code optimized to perform the computation on all cores an threads of my CPU. P.S. I have used in the examples only three classes but actually I would like to choose the number of classes that I prefer every time that I run the code.


title: How can I get NotebookPrint to pass through the system print dialog?

text: As near as I can tell, `NotebookPrint` goes directly to the default printer, without employing the system standard process of opening a print dialog first. Specifically, I'd like to he able to use `NotebookPrint`, or an alternative function, `somePrintFunction` to print an arbitrary expression, `expr`, using the form               somePrintFunction[expr]      and have the standard system dialog for printing appear. Is there a way to force `NotebookPrint` to do this? Is there some other function that does?


title: How do I find line integrals?

text: For example, how can I calculate $$\int_{\left | z \right |=1}\frac{dz}{z}$$ I know that the answer is $2\pi i$ but how do I do it using _Mathematica_?


title: Why are my images not printing at the expected size?

text: I understand how (in theory) to get images to be a specific size in inches, but when I follow the documentation, all of my output seems to be scaled down by a factor of a bit less than 70% (e.g., `ImageSize -> 72x8` gives an image size of about 5.5 inches rather than 8). How do I ensure that my images print at a specified size in inches? Are there settings or additional options beyond those described in the documentation for `ImageSize` that I need to use? * * * In context, what I'm trying to do is print a generated graphic from within a Manipulate using a button using               Button["Print",  NotebookPrint[pat]]      or perhaps something like               Button["Print", NotebookPrint[Show[pat, ImageSize -> 72 patzise]]]      and I'd ideally like to apply whatever settings are needed to get a properly sized output, without messing with global or notebook level settings.


title: Intersection for lists of numeric data

text: I know that `Intersection` is a pattern matching function and will not evaluate list elements to determine if two or more list have equal elements. So my question is, what can be done to do this? Say, determine if two lists have numerically equal elements within some tolerance dx?


title: Maximizing functions with Which statements

text: I'd like to be able to find the maximum value that my Capex function (see below) generates. This is a fairly simple function so I could just add it up but I have more complex functions of a similar form that I'll need to maximize.               Capex[romSize_, CCSPsize_, washRate_, miningRate_] :=     Module[{val, rom = romSize, CCSP = CCSPsize, wash = washRate},     val = 0;     Which[CCSP > 500, val = val - 100];     Which[rom >= 200 && rom < 300, val = val - 5, rom >= 300,       val = val - 10];     Which[wash >= 1300 && wash < 1500, val = val - 10, wash >= 1500,      val = val - 20];     Which[miningRate >= 5.5 && miningRate < 5.7, val = val - 10,      miningRate >= 5.7, val = val - 20];     Return[val]     ];      The problem I have is that because it contains Which statements the Maximize function doesn't seem to work. I could spam the Capex function with values in the domain and pick the largest value but I was hoping Mathematica had some functionality to make it a little easier, kind of like Goal Seek in Excel. An example of a simple maximize call would be               Maximize[{Capex[x, 600, 1500, 6], 120 <= x <= 300}, {x}]      The max value of -240 is correct but x=300 is not


title: density/histogram plot for date-time data

text: I have date and time data and want to plot its frequency histogram. Ideally I want to be able to customize the bin size (for example, every 5 minutes or a day). Anybody has this experience?


title: How can I numerically solve for fractional functions and fractional derivatives?

text: I would like to plot fractional functions. Say $f=(\sin)^{1/2}(x)$. By that I mean that $f(f(x)) = \sin(x)$. Similarly I can define a half-derivative to be an operator such that $H[H[f(x)]] = \frac{df(x)}{dx}$. What I'd like to do, in an ideal situation, is to evaluate the function at different points and then plot it. How do I numerically solve such equations in Mathematica? Is it possible to get a Taylor series? Side question: Does Mathematica treat operators as separate entities?


title: ParametricPlot3D and Sphere Graphics

text: I'm trying to put a sphere into a 3D parametric plot, but I seem to have a strange problem. Here's the code:               ( _Gravitational Constant_ )     G = 6.672*10^-11     ( _Mass of Earth and rocket_ )     M = AstronomicalData["Earth", "Mass"]     m = 2800000     ( _Rocket thrust_ )     T = 34020000     ( _Radius of Earth_ )     r = AstronomicalData["Earth", "Radius"]     ( _Numerical solution modelling the gravitation interaction between Earth and a launching rocket_ )     ( _NOTE: Rocket mass will change over time; also, add in drag_ )     soln = NDSolve[{        x''[t] == -((G M x[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2)),        y''[t] == -((G M y[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2)) +           If[t > 1000, 0, 0.25 T/m],        z''[t] == -((G M z[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2)) +           If[t > 1000, 0, 0.75 T/m],        x[0] == 0, y[0] == 0, z[0] == r, x'[0] == 0, y'[0] == 0,         z'[0] == 0}, {x[t], y[t], z[t]}, {t, 0, 20000},        MaxSteps -> 1000000, Method -> "StiffnessSwitching"]                              Show[ParametricPlot3D[       Evaluate[{x[t], y[t], z[t]} /. soln], {t, 0, 20000},        AxesLabel -> {x, y, z}, AspectRatio -> 1, BoxRatios -> 1,        PlotStyle -> Automatic, ImageSize -> Large],       Graphics3D[{Green, Sphere[{0, 0, 0}, r]}]]      ` And this is the output that I get, not a sphere but a curved plane: ![Sphere Plot](http://i.stack.imgur.com/Z4m4m.jpg) Does anyone know what I'm doing wrong?


title: About multi-root search in Mathematica for transcendental equations

text: I have some questions for multiroot search for transcendental equations. Is there any clever solution to find all the roots for a transcendental equation in a specific range? Perhaps `FindRoot` is the most efficient way to solve transcendental equations, but it only gives one root around a specific value. For example,               FindRoot[BesselJ[1, x]^2 + BesselK[1, x]^2 - Sin[Sin[x]], {x, 10}]      Of course, one can first `Plot` the equation and then choose several start values around each root and then use `FindRoot` to get the exact value.   1. **Is there any elegant way to find all the roots at once?** Actually, I come up with this question when I solve the eigenequation for optical waveguides and I want to get the dispersion relation. I find `ContourPlot` is very useful to get the curve of the dispersion relation. For example,              ContourPlot[BesselJ[1, x]^2 + BesselK[1, x]^2 - Sin@Sin[a*x] == 0, {x, 0, 10}, {a, 0, 4}]      You can get ![enter image description here](http://i.stack.imgur.com/QMIrP.png)   2. **Is there any elegant way to get all the values in the`ContourPlot` for `x` when `a==0` ?**   3. **Is it possible to know how the`ContourPlot` gets all the points shown in the figure? Perhaps we can harness it to get all the roots for the transcendental equation.**


title: HighlightGraph with different styles

text: I want to highlight two different directed paths on a graph with two different style. I am using the following two code snippets:               HighlightGraph[      CompleteGraph[5], {PathGraph[{1, 2, 3}], PathGraph[{4, 5}]},       GraphHighlightStyle -> {"Dashed", "Thick"}]      and               HighlightGraph[      HighlightGraph[CompleteGraph[5], PathGraph[{4, 5}],        GraphHighlightStyle -> "Dashed"], PathGraph[{1, 2, 3}],       GraphHighlightStyle -> "Thick"]      But either of them results in the following plot: ![Highlighted Graph](http://i.stack.imgur.com/raJVY.png) It seems that highlighted paths use the same style (the last one applied to the graph) if we have more than one path. In addition, I want to make the highlighted paths directed, but If I add the option `DirectedEdges->True` to the path, it doesn't work.


title: Exporting plots with Cyrillic text elements to pdf

text: I'm trying to export a plot with some added notes which happen to be in Russian. Using Mathematica 8.04 and WinXP I evaluate               Export["smt.pdf", "Текст на русском", CharacterEncoding -> "WindowsCyrillic"]      Which gives nonsense as output. Is there a way to solve this?


title: A topoplot function for Mathematica

text: Matlab's EEGlab toolbox has a topoplot function: http://sccn.ucsd.edu/eeglab/ A typical topographical plot of an EEG signal is given below: ![enter image description here](http://i.stack.imgur.com/S4Dff.jpg) How can I reproduce this in Mathematica. I know that ContourPlot and ListCountourPlot provide such functionalities, however, the data is on a square grid... and I would like it on a circle like in the figure...


title: Counting paths of a certain length between a source and sink vertex

text: I have a graph $G$, which may be directed or not, and I was wondering if there was an efficient way of using, say, BreadthFirstScan[] and FindShortestPath[] to count the number of paths between some source vertex, $v(a)$, some sink vertex, $v(b)$, of a certain length $D$? As of right now, I'm simply sequentially running through all of the vertices in my graph, applying FindShortestPath[] to determine the distance of the vertex to my source and sink vertices, and then seeing if the total distance is $D$. If the total path distance is in fact $D$, I then put the path in a list which is later pruned for redundant paths or paths that revisit vertices. Assuming I have plenty of memory to spare, is there a better / faster solution? * * * Let me better specify what I'm looking for - Provided an undirected or directed graph $G$, I want to count the number of possible ordered sets, $(q_1,...,q_N)$, of all-unique vertices, $(v_{source}, ..., v_{sink}) \in q_i$, that one must visit to move from a source vertex, $v(source)$ to a sink vertex, $v(sink)$ s.t. $||q_i|| = D$ for all $q_i$, i.e. s.t. the total number of vertices along any path $q_i$ (including the source and sink) is $D$. Two paths, $(q_a, q_b)$, may have common vertices, but individual $q_i$ cannot have redundant vertices (i.e. they are not multisets). Please note, however, that I would be open to elegant/nice solutions that allow repeat vertex visits but forbid repeat edge traversals.


title: Compute symbolic Expectation of a summation

text: I am required to computed following Expectations : $E[\displaystyle\sum\limits_{i=1}^N \frac{X_{i}}{N}] = \bar{x}_{0}$ & $E[\displaystyle(\sum\limits_{i=1}^N \frac{X_{i}}{N})^2] = \frac{(N\bar{x}_{0}^2 + \sigma_{x}^2)}{N}$ with $ X_{i} \sim N(\bar{x}_{0},\sigma_{x}^2) \forall i = 1,2,\cdots,N$ & $X_{i} \bot X_{j} \forall i\not=j$ I'm looking to solve these expectation in symbolic as all these variable are unknown. Thanks for your help Alexandre


title: Convolution of a denstity function having a point mass with itself

text: My density function is as follows:               der[x_] :=Piecewise[{{E^((-4 - 4*x - x^2 - Log[2]^2)/8)/(2^(x/4)*Sqrt[Pi]*(2*Sqrt[2/E]*Erf[Log[2]/(2*Sqrt[2])]+Erfc[(-2 + Log[2])/(2*Sqrt[2])] +2*Erfc[(2 + Log[2])/(2*Sqrt[2])])), x > 0}, {0.2015152271993863, x == 0}},(2^(x/4)*E^((-4 - 4*x - x^2 - Log[2]^2)/8))/(Sqrt[Pi]*(2*Sqrt[2/E]*Erf[Log[2]/(2*Sqrt[2])]+Erfc[(-2 + Log[2])/(2*Sqrt[2])] + 2*Erfc[(2 +Log[2])/(2*Sqrt[2])]))]      This density has a point mass of               0.2015152271993863`      at $x=0$. Taking into account the point mass, I would like to calculate $P[n];$ $$P[n]=\int_{(-\infty,B)\cup (A,\infty)} q_n (x) \mathrm{d}x$$ with $$q_n(x)=\int_{B}^A q_{n-1} (\omega)f(x-\omega)\mathrm{d} \omega,\quad q_1=f,\quad n\geq 1.$$ and $f$ is some density function,which is $\mathrm{der}[x]$ here. To make these iterative calculations, I have the following code:               q[1, B_, A_, f_] := f     q[n_ /; n > 1, B_, A_, f_][x_] := Module[{\[Omega]},tempIntegrate[Evaluate[q[n - 1, B, A, f]][\[Omega]] f[x - \[Omega]], {\[Omega],B, A}]]      p[n_, B_, A_, f_] :=tempIntegrate[q[n, B, A, f][x], {x, -\[Infinity], B}] + tempIntegrate[q[n, B, A, f][x], {x,A, \[Infinity]}] //. {s_ tempIntegrate[b_,a__] :>tempIntegrate[s b, a],tempIntegrate[tempIntegrate[b_,a__], c__] :>tempIntegrate[b, a, c]} /.tempIntegrate -> NIntegrate      If the calculations are all correct, then the summation of all elements of the following table should (almost) add up to $1$               tab2 = Table[p[j, -2, 2, der], {j, 10}];      Since I cannot deal with the point mass it doesnt add upto $1$. If you want to see that it indeed adds up to $1$, you can consider for example               der[x_]:=PDF[NormalDistribution[-2, 2], x]      How can I deal with the point mass in the convolution and also in the integrations?


title: bulk initialization of associative array/hash implemented with function pattern matching?

text: I see that we can do associative arrays in Mathematica using functions that have implicit pattern arguments, as in               debyeTemperature[ "Aluminum" ] = 433 ;     debyeTemperature[ "Americium" ] = 121 ;     debyeTemperature[ "Antimony" ] = 220 ;     debyeTemperature[ "Argon" ] = 92.0 ;          debyeTemperature[ "Americium" ]      My guess is that ChemicalData[] uses something like this internally. Is there a syntax for bulk initialization of such a hash function with pairs of values, perhaps like a similar perl hash initialization:               my %debyeTemperature = ("Aluminum" => 433,                             "Americium" => 121,                             "Antimony" => 220,                             "Argon" => 92.0, ) ;          print "$debyeTemperature{'Americium'}\n" ;


title: Widget - GUI help

text: I was wondering if someone could explain me the code written below (example File Dialog from mathematica). Especially the part with `returnValue`and `InvokeMethod`. Also I want to ask how to actually save table from Table Widget(when I add Save button to the widget how to implement the method?). I really need help and any comment is appreciated.               ref = GUIRun[Widget["Panel", {Widget["Button", {"text" -> "Save File...",                         BindEvent["action",Script[         Widget["FileDialog", Name -> "saveFileDialog"];         returnValue =           InvokeMethod[{"saveFileDialog", "showSaveDialog"}, Null];         If[          returnValue ===            PropertyValue[{"saveFileDialog", "APPROVE_OPTION"}],           PropertyValue[{PropertyValue[{"saveFileDialog",               "selectedFile"}], "path"}],          Null          ]         ]]}],     Widget["Button", {"text" -> "Cancel"}]     }]       ]


title: Pure function inside another pure function

text: I have the following working expression:               In[15]:= Length[Select[IntegerPartitions[10],First[#1]==5&]]     Out[15]= 7      But, instead of using the constant 5 I want to map all values from 1 to 10 into this function. If I nest the pure function inside another it doesn't work:               In[18]:= Map[Length[Select[IntegerPartitions[10],First[#]==#&]]&,Range[10]]     Out[18]= {0,0,0,0,0,0,0,0,0,0}      What is the way to do this?


title: Problem enabling PlotLegends in Mathematica 8.0

text: I am trying to make a legend for a simple plot in _Mathematica_ 8, but does not seem to recognise the command PlotLegends. I declared beforehand `Needs["PlotLegends`"]`, and get this message: > Needs::nocont: Context PlotLegends` was not created when Needs was > evaluated. >> I also tried to install this pakage manually by going to File -> Install -> .... I am not very experienced with _Mathematica_ , so an answer for dummies will be appreciated.


title: Numerical simulation - getting slower the more data I have

text: I'm simulating the trajectory of a charged particle. I have the coordinates saved in the list $coor$ ({{0,0,0},{0.1,0.1,0.003}, etc}) as the time goes on this array is getting bigger and the computation slower. What is the usual way to solve this issue? I guess that using               coor=Append[coor,r]      is't the best way to save data on the way. Do you have any sugesstions? Thanks


title: How can I speed up my numerical integration?

text: Here is my code:               x0 = -50;      f[xe_] :=       NIntegrate[-1/(k^6 x1^4)         48 (k x1 Cos[k x1] -           Sin[k x1]) (-1/            x0^3 (-6 k x0 Cos[2 k x0 - k x1] + 3 k x1 Cos[2 k x0 - k x1] +              2 k^3 x0 x1^2 Cos[2 k x0 - k x1] +              k^3 x0^3 CosIntegral[               2 k x0] ((-3 + k^2 x1^2) Cos[k x1] - 3 k x1 Sin[k x1]) +              3 Sin[2 k x0 - k x1] + 6 k^2 x0 x1 Sin[2 k x0 - k x1] -              k^2 x1^2 Sin[2 k x0 - k x1] +              k^3 x0^3 (3 k x1 Cos[k x1] + (-3 + k^2 x1^2) Sin[                  k x1]) SinIntegral[2 k x0]) +           1/x1^3 (-3 k x1 Cos[k x1] + 2 k^3 x1^3 Cos[k x1] + 3 Sin[k x1] +              5 k^2 x1^2 Sin[k x1] +              k^3 x1^3 CosIntegral[               2 k x1] ((-3 + k^2 x1^2) Cos[k x1] - 3 k x1 Sin[k x1]) +              k^3 x1^3 (3 k x1 Cos[k x1] + (-3 + k^2 x1^2) Sin[                  k x1]) SinIntegral[2 k x1])), {x1, xe , x0},        AccuracyGoal -> 20, WorkingPrecision -> 200]     k = 1;      Plot[f[xe]/(24 Log[E, -xe]^2) , {xe, -10^-45, -10^-50}, PlotRange -> Full]      My problem is that solving and plotting takes a long time with this code. Could someone please help me to find a method to speed it up?


title: What should I expect for Fourier transform of Sinc?

text: I was expecting something I could interpret as a rect function. I don't think the Dirac delta function qualifies — for one thing, I think that would be the transform of a constant.               FourierTransform[Sinc[t], t, ω]      > >     2.50245 DiracDelta[ω] >   Is there a way to make sense of this? I'm using v.9.0 home


title: How to known exactly what color assign "TemperatureMap" to a particular value?

text: Usually               ColorData["TemperatureMap"]      is using to coloring graphs and show how near is any value to 0(Blue), 1(Red), or in the mean (White). The question is: How Can I do to obtain the RGB/CMYK code color, to a particualr value? for example,... to the value 0 is asigned BLUE=(0,0,100)%=(0,0,255)Hex but... What color-code asign the "TemperatureMap" to the value 0.123 ?, I know that it´s a close to blue, but... What exactly? I´ll use in other ranges like [0,8] or 1[12.45,45.85], not only in [0,1]


title: Minimize solution to linear system with singular system matrix

text: 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!


title: Mapping a function over the parts of a deeply nested Array

text: 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.


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

text: 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


title: Solving Intervals

text: 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.]


title: Computing the volume and the curved surface area

text: 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$


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

text: 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?


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

text: 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)


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

text: 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]]}]];


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

text: 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?


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

text: 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]


title: Using citations with Workbench

text: 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?


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

text: 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?


title: Simplifying the derivative of $|x|$

text: ## 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`?


title: Different determinants on 2 different computers

text: 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.


title: Why am I not getting a numeric response?

text: ## 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


title: Matrix Rational Canonical Form

text: 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.


title: Anti-aliasing not working in Mathematica 10 and Linux

text: 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?


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

text: ## 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]`?


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

text: 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


title: Setting the Accuracy of calculations

text: 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.


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

text: 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.)


title: Sending RObject to RFunctions

text: 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


title: Long running time

text: 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


title: Exporting and reimporting a list of lists changes the dimensions

text: 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}*)


title: Getting lengths of sublists that sum to more than one

text: 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.


title: Integral of the Sinc product

text: 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?


title: Discrete coloring in Plots

text: 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.


title: Checking if the roots of a function are real

text: 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.)


title: CreateDialog opening two windows instead of one

text: 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.


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

text: 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?**


title: Grid Lines in ListPlot

text: 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?


title: How to clean up messy data

text: 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)


title: Extracting graphics primitives from a Graphics expression with ReplaceAll

text: 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`.


title: Conditional search along the columns of a matrix

text: 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.


title: NMinimize go out of bounds on some linear constraints

text: 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}}


title: Identical code, different answers?

text: 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?


title: Add text before TraditionalForm

text: 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!


title: Visualize Pascal's triangle and other triangle shaped lists

text: 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.


title: How to draw this kind of plot?

text: 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.