title: Text with date, how to convert?

text: I use this script to recognise a date in a textfile and write the result in another file.               For[i = 1, i < 20, i++,       test1 = Import["E:\\data\\MC1 Data\\MC1 Data\\articles\\" <> ToString[i] <>".txt", "Text"];       test2 = {StringCases[test1, DatePattern[{"Year", "Month", "Day"}]],              StringCases[ToLowerCase[test1], RegularExpression["\\w(?<!\\d)[\\w'-]*"]]};     Write[s, test2]];      The result is a file like this: ![example data file](http://i.stack.imgur.com/vIfRf.gif)               test3 = ReadList["E:\\data\\MC1 Data\\MC1 Data\\articles\\testfile3.txt"]      Then I would like to make a selection on the date/first column. In this example, mathematica don't recognise it as a datastring. I tried to convert it like               DateString[test3[[All, 1]]]      but that didnt work. Who has a suggestion?


title: How do you plot the same function with different options over different intervals?

text: Here is the motivation for my question. I want to plot `Sin[x]` over the interval `0` to `2 π`, with the part from `π/2` to `2 π` as a dashed curve. I want to plot this with a legend so that it shows the solid part is for acute angles, and the dashed part is for, say, other angles. Perhaps using `Show` and `ShowLegend` will work, but I couldn't figure out how to get the legend boxes to match the curves (solid and dashed curves). It seems `PlotLegend` takes care of this for you, but I couldn't figure out how to use this in `Show`. So I thought using `PlotLegend` in `Plot` will be easiest, except I don't know how to use `Plot` for the same function with different options on different intervals. I tried using the suggestions from Plotting piecewise function with distinct colors in each section, but I think my problem is that the same function is being used for both parts of the piecewise function I defined.


title: Multiple curves plotted with different colours

text: I am trying to use `ColorFunction` for 2 functions on the same plot. I only want the cubic equation to change colour.               Plot[{-x^3 + 3.5*x + 0.5, y = 2.9*Tanh[5 x] + 0.3}, {x, -2.5, 2.5},            PlotRange -> {-3, 3.5}, Axes -> False, Frame -> True, FrameTicks -> None,            PlotStyle -> {{Darker[Green], Thick}, {Blue, Thick}},            ColorFunction -> Function[{x, y}, If[x > 1, Red, Black]],            ColorFunctionScaling -> False, PlotStyle -> Thick]      This is what the code above produces: ![enter image description here](http://i.stack.imgur.com/1Q6T6.jpg) This is ideally how i would like it to be displayed. Is this possible in _Mathematica_ without using the drawing tool? ![](http://i.stack.imgur.com/vNC8Y.jpg)


title: Simple question about AxesLabel

text: I am plotting a function and for labeling the axes I use:               AxesLabel -> {Style[y, FontSize -> 21], Style[{Subscript[f, i], Subscript[q, i]}, FontSize -> 21]}      here $y$ is for the $x$-axis and $\\{f_i,q_i\\}$ is for the $y$-axis. The problem is that I dont want to have $\\{\\}$. I only want to have $f_i,q_i$ at the $y$-axis. How can I manage this? Thank you very much.


title: Replacement rules in combination with pure functions to make a change of variables

text: I have defined my function in this way               w = f[r,Θ] ;      After some calculations i obtained my results with respect to the previous function. For instance:               Set[lapla1, -(1/(2 μ)) (1/r D[w r, {r, 2}] - 1/r^2 (D[w, {Θ, 2}] + Cot[Θ] D[w, {Θ, 1}]))] // ExpandAll      In this moment i don't need to work with the previous function $w$, instead i need to keep my previous result, multiply lapla1 by $r$ and work with a new $w$               w = f[r, Θ]/r ;      I'm trying to use pure functions to accomplish this, however i don't know if i'm proceeding correctly.               Set[lapla11,lapla1*r /. f -> (f[#, #2]/r &) // ExpandAll ]      **EDITED:** When you make this transformation, the term $\frac{1 }{rμ }\frac{\partial f}{\partial r}$ must disappear from lapla1. This is the only way i found to prove it               Set[lapla12, -(r/(2 μ)) (1/r D[w/r r, {r, 2}] - 1/r^2 (D[w/r, {Θ, 2}] + Cot[Θ] D[w/r, {Θ, 1}]))] // ExpandAll


title: Cancellation of common terms

text: Can someone explain why the term A in case 2 does not get canceled out when case 1 does? I use "9.0 for Microsoft Windows (64-bit) (January 25, 2013)"               case1 = A*(E^(-λ) + α) == A;     Simplify[case1, A > 0]      gives `1 + E^λ α == E^λ`               case2 = A*(E^(-2*λ) + α) == A;     Simplify[case2, A > 0]      gives `A (E^(-2 λ) + α) == A`


title: Update a function avoiding infinite recursion

text: I am quite new to _Mathematica_ and not completely familiar with functional programming. I am currently working with a function (call it foo) and wish to change its behaviour, for example, by adding 1 to its output. Obviously writing               foo = (foo[#]+1)&;      or               foo[x_] := foo[x] + 1;      leads to an infinite recursion as soon as I try to evaluate the function. To be more explicit, if at the beginning `foo[1]` returns 1 and `foo[2]` returns 3, I would like the output to be 2 and 4 respectively after the change. Is there any way to easily obtain this behaviour with _Mathematica_? I apologize if the question is a duplicate, but I did not find anything similar already posted.


title: Using Mouseover to change the appearance of a button without writing the button specification twice

text: When I code in _Mathematica_ , I often find myself having to repeat large chunks of code for a function to work. The latest example of this is a color changing button that prints when clicked, code shown below.               Mouseover[      Style[       Button[        Pane["Print", FrameMargins -> {{4, 4}, {4, 4}},          ImageSize -> {34, 24}],        Print["Print"],        Appearance -> None        ], Background -> Red       ],      Style[       Button[        Pane["Print", FrameMargins -> {{4, 4}, {4, 4}},          ImageSize -> {34, 24}],        Print["Print"],        Appearance -> None        ], Background -> Green       ]      ]      The only thing that is changing on the mouse over is the button color, but for this to work I need to repeat a whole chunk of code. A simpler way of doing this is to define a button color function, and then use that in the Mouseover function, code shown below.               ButtonColor[color_] :=      Style[       Button[        Pane["Print", FrameMargins -> {{4, 4}, {4, 4}},          ImageSize -> {34, 24}],        Print["Print"],        Appearance -> None        ], Background -> color       ]          Mouseover[      ButtonColor[Red],      ButtonColor[Green]      ]      This is better, but what if i only have to refer to the button color changing function for one mouse over button? Should I really have to define a function to use it for one instance? I think the ideal way to code this would be to use Table or something similar, code shown below.               Mouseover[      Table[       Style[        Button[         Pane["Print", FrameMargins -> {{4, 4}, {4, 4}},           ImageSize -> {34, 24}],         Print["Print"],         Appearance -> None         ], Background -> color        ],       {color, {Red, Green}}       ]      ]      The only problem, Table doesn't work because it creates EXTRA BRACES! Is there a better way of coding this color changing button?


title: Finding a fixed vector which minimizes the pairwise distance between noisy elements in two unordered arrays

text: Let $A$ and $B$ be two sets of $d$-dimensional coordinates of comparible (though not necessarily equal length). For example, here we can set $d = 3$ and have normalized values like:               A = {{0.446362, 0.811292, 0.0922594},{0.244159, 0.260142, 0.304582}, {0.122547, 0.269019, 0.0644819},          {0.448114, 0.828661, 0.733406},{0.347111, 0.296056, 0.398861}, {0.219952, 0.653454, 0.09107},          {0.592839, 0.0333978, 0.210341},{0.0970157, 0.132429, 0.366429}, {0.294297, 0.527056, 0.403706},          {0.196355, 0.115887, 0.636247},{0.993047, 0.51482, 0.229379}, {0.251266, 0.135959, 0.178469},          {0.789068, 0.182785, 0.338934}, {0.42705, 0.151849, 0.671407}, {0.796922, 0.229053, 0.946328},          {0.292144, 0.148314, 0.116313}, {0.589524, 0.474425, 0.0958731}, {0.181622, 0.140052, 0.958391},          {0.0376616, 0.614436, 0.394617}};          B = {{0.690322, 1.17215, 0.961834}, {0.271458, 0.942832, 0.745714}, {0.508862, 1.03457, 0.3475},           {0.81515, 0.378891, 0.465227}, {0.6036, 1.34974, 0.426426}, {0.405347, 0.463069, 1.27554},          {1.12031, 0.604772, 1.19204}, {0.373017, 0.343105, 0.595875}, {0.642332, 0.602587, 0.678469},          {0.884344, 0.746337, 0.38915}, {1.22961, 0.47189, 0.712069}, {0.56058, 0.755362, 0.648201},          {0.596699, 0.465542, 0.646428}, {0.48087, 0.522362, 0.315634}, {0.752854, 1.17231, 0.421088},          {0.693156, 0.546617, 0.9851}, {0.507197, 0.426626, 0.847138}, {0.584263, 0.452749, 0.422986},          {0.545495, 0.427736, 0.494085}};      (Note that the order of the elements in $A$ and $B$ are of no consequence.) While a bijection isn't possible, I would like to find the best possible "rigid mapping" between the elements in $A$ and $B$ where we add some fixed real number vector $Q=(q_1,q_2,q_3)$ to each coordinate in $B$ to minimize a weighted distance between pairs of coordinates in $A$ and $B$ according to some axis-specific cost function. Consider that in the above example, I've rigged things to make $Q = (q_1,q_2,q_3) \approx (0.3,0.3,0.3)$ about optimal (the largest error is of magnitude $\approx 0.1$). To specify this cost function, we select array $A$ if it has more points than $B$ and vice versa. For convenience, let's say this array is $A$. Now let $(d_{(1,i)},d_{(2,i)},d_{(3,i)})$ be the shortest distance between a point $b_i \in B$ and $a_j \in A$. I'd like to have a cost function that looks something like: $C = \sum_{i=1}^{||B||} || ((d_{(1,i)})^{z_1},(d_{(2,i)})^{z_2},(d_{(3,i)})^{z_3}) ||$ Where $(z_1,z_2,z_3)$ represents an arbitrary set of exponents. For a single real numbered value cost, we could compute the Norm of the above sum.


title: How do I obtain an intersection of two or more list of lists conditioned on the first element of each sub-list?

text: Given two lists like               list1 = {{1, 1}, {2, 4}, {3, 9}, {4, 16}};     list2 = {{2, 6}, {3, 9}, {4, 12}, {5, 15}};      I would like to produce an output like               listout = {{2, {4, 6}}, {3, {9, 9}}, {4, {16, 12}}}


title: Combining two lists

text: > **Possible Duplicate:**   >  How do I obtain an intersection of two or more list of lists conditioned on > the first element of each sub-list? I would like to combine two lists.               list1 = {{134, 12}, {136, 14}, {140, 45}}      and               list2 = {{134, "B"}, {135, "A"}, {136, "E"}, {137, "A"}, {138,"I"}, {139, "B"}, {140, "G"}}      the result should be:               result = {{134, 12, "B"}, {136, 14, "E"}, {140, 45, "G"}}      Thank you very much!


title: Sparse Principal Component Analysis

text: I'd like to run sparse PCA on some economic data. There appear to be several R functions available including elasticnet and PMA but I wanted to check if anyone had something coded up directly in MMA they might be willing share? Thanks, Peter


title: How to put some values from a list into a function in a Do loop

text: I want to program a code in MATHEMATICA in order to calculate some values in different iteration. For example, assume this list: `list={1,2,3,4,5}` Now assume that the function is : `f1=Function[u,3+u][x]` I want to use a `Do` loop to orderly put each integer from the `list` into `f1` function and `Do` loop uses 5 iteration (`{i,1,5}`) and gives 5 answers using the values in the list. For this example, The results will be : `4 5 6 7 8` I wonder if anyone could help me with this problem.


title: Filling a curve to a vertical axis

text: I am preparing a figure for an article, and I would like very much to be able to fill a curve, but not under it, but to the vertical axis, i.e. to the left. Due to the meaning of the data I present, I cannot exchange the axes. Here is a minimal example:               Plot[ArcCot[x], {x, 0, 1}, PlotRange -> {{0, 1.1}, {0.5, 2}}, AxesLabel -> {x, y}]      Can anyone think of a way of filling the curve to the`y` axis? I find no mention of this kind of filling in the standard documentation.


title: Poor results with ImageLines function

text: I'm trying to get my mind wrapped around _Mathematica's_ image feature recognition functions. I'm intrigued by the `ImageLines` function for a couple future ideas I have but generally get very poor performance from it. ...as I will now demonstrate: Let's import some very basic gridlines, surely this will be easy.               pic = Import[         "http://www.samplewords.com/docthumbs/home-graphpaper-thumb.jpg"]      ![enter image description here](http://i.stack.imgur.com/AVXQh.jpg) Straight out of the box, here's how _Mathematica_ recognizes the lines at different thresholds (parallelized because of my impatience):               Row@ParallelTable[Graphics@Line@ImageLines[pic, i], {i, .1, 1, .1}]      ![enter image description here](http://i.stack.imgur.com/M5jv1.png) Interesting... not what I would've expected. Even if I dilate and binarize the image, I still get pretty bad results: ![enter image description here](http://i.stack.imgur.com/fKWuR.png) Playing with the distictness parameter, it gets a little better but still pretty weird. ![enter image description here](http://i.stack.imgur.com/WkJnj.png) So, Wolfram shows some pretty neat examples, and it seems to work well there. How can I get improved results from the `ImageLines` function?


title: Marking points of intersection between two curves

text: I'm trying to illustrate the solutions numerically and graphically for an equation such as `Tan[x] == x`. I think I did everything ok except I wanted to mark each intersection between `Tan[x]` and `x`. Does anyone know how such a thing can be done?


title: Binomial[-1,-1]

text: According to various sources e.g. http://www.proofwiki.org/wiki/Definition:Binomial_Coefficient and Wolfram themselves http://functions.wolfram.com/GammaBetaErf/Binomial/02/ , the binomial coefficient ${n\choose k}$ is is defined as 0 whenever $k$ and $n$ are negative integers and $k\le n$. But when I type               Binomial[-1,-1]      Mathematica returns               1      I looked up the documentation for the definition of `Binomial` and it says > In general, ${n\choose m}$ is defined by > $\Gamma(n+1)/\Gamma(m+1)\Gamma(n-m+1)$ or **suitable limits** of this. Apparently, when $n=-1$ or $m=-1$ since $\Gamma(0)$ is not defined the suitable limit case is applied. So, why does Mathematica return 1 for ${-1\choose -1}$? What precisely is the "suitable limits"?


title: What are the best tips in Michael Trott's beer/whiskey Wolfram Blog post?

text: Michael Trott posted this incredible tour-de-force on the wolfram blog: http://blog.wolfram.com/2014/08/19/which-is-closer-local-beer-or-local- whiskey/ The length of the post is overwhelming, so I'm trying to crawl through it with a fine toothed comb looking for some Mathematica tricks and techniques that are new to me. I would be very interested to see what others noticed, since I doubt I will find everything in there. Some of the things I noticed were:   * use of TimeSeries, which is a new discovery for me in MMA 10   * {Except["Alaska"], "UnitedStates"} as a pattern for Cases ... I regularly struggle with using Cases, so this is mysterious to me   * the StringReplace / Shortest / StringCases constructs when parsing the distillery information is not something I had seen before and seems powerful


title: Estimating a distribution using binned data

text: I have data from which information has been irretrievably lost through binning and I am trying to find a plausible distribution from which it derives. There is an academic paper suggesting that the underlying data is Zipf or Pareto distributed, but I believe that the paper is wrong. Just because one can fit a line to the log-log transform of survival data does not mean that the data is really Zipf or Pareto distributed! The data (which you can see here, table 2b) is in an $n\times 2$ table in which the first column is a discrete range defining a "bin" and the second relevant column is an integer count. It thus states that there are y1 firms that have between min1 and max1 employees, that there are y2 firms that have between min2 and max2 employees, etc. I thus know that there are y1+y2+ ...+ yn firms that have at least min1 employees, that there are y2+y3 + ... + yn firms that have at least min2 employees, etc. I would, of course, love to be able to use `EstimatedDistribution` with various guesses as to functional form and then use `DistributionFitTest` to see if the guess was plausible. But I can not figure out how to get _Mathematica_ to find the best parameters for a distribution where all I have is binned data. I've floundered about with `SurvivalModelFit`, `WeightedData`, all to little avail. All help appreciated.


title: How to checkpoint computations?

text: Suppose I do some big experiment, presumably in a `Table[]`, or a `ParallelTable[]`. Experience shows that there is a non-zero probability of Mathematica (or the computer) crashing part-way through (usually through excess of ambition by the user, but whatever), so it would be nice to export the results of the individual computations as soon as they become available. Is there any preferred way of doing that? (`Reap[]` and `Sow[]` seem like they could do the right thing, but it seems likely that they wait for the whole computation to finish). (and, by the way, I have no idea what the right tag for this is, maybe someone can help).


title: Package for representation of groups (group theory)

text: I wanted to know if there is a package which allows to compute representations of a group like the definition representation, adjoint and so on (for example the Pauli matrix for $SU(2)$ if I specify that I want the definition representation of $SU(2)$). Which allow also to compute the structure constants of a particular group and, given a set of matrix, to test if these matrix form a representation of a particular group.


title: Interpolating a sparse list of two-dimensional coordinates

text: I've run into a problem where I have an ordered array of sets of coordinates, for example:               OrderedArray = {{{70.8938, 216.539},{70.89,216.54}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{71.0656,216.573}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{67.6546, 220.338}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{70.9211, 216.364}}, {{70.9184, 216.346}}, {{70.9079, 216.349}}, {{70.9046, 216.335}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {},{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{70.951, 216.705}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{70.9621,216.586}}, {{70.918, 216.576}}, {{70.9116, 216.559}}, {{70.9189,216.581}}, {{70.9115, 216.565}}, {{70.9294, 216.552}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{67.0276, 218.154}}};      Note that some elements (here the first) contain more than a single coordinate. And I need to fill in the blanks, i.e. the {} positions, via some interpolation procedure. What would be the best way to do this? Reading through the instructions for InterpolatingPolynomial (for example), and playing around a bit, it isn't immediately clear how to do this. Ideally I'd like to be able to specify that the "gaps" should be filled in assuming a linear curve, or a polynomial of some order.


title: Generating a "best fit" curve to a set of noisy data corresponding to a moving object

text: Please note that this is an extension of a previous question: Interpolating a sparse list of two-dimensional coordinates We have an ordered array of coordinates corresponding to the position of an object in a set of camera frames $(f_1,...,f_N) \in F$, which we're tracking with an imperfect object recognition algorithm. As a result, in any given frame, we sometimes fail to identify the object, and we sometimes identify multiple copies of the object. We're left with noisy data that looks something like this:               OrderedArray = {{{70.8938, 216.539},{70.89,216.54}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{71.0656,216.573}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{67.6546, 220.338}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{70.9211, 216.364}}, {{70.9184, 216.346}}, {{70.9079, 216.349}}, {{70.9046, 216.335}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {},{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{70.951, 216.705}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{70.9621,216.586}}, {{70.918, 216.576}}, {{70.9116, 216.559}}, {{70.9189,216.581}}, {{70.9115, 216.565}}, {{70.9294, 216.552}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{67.0276, 218.154}}};      Where the position of a coordinate in the array corresponds to a particular image frame. Here's a listplot output for a larger version of my data set: ![enter image description here](http://i.stack.imgur.com/Ub1DT.png) I'd like to generate a "best guess" for the motion of my object from frame to frame provided this noisy data, and with the constraint that the object cannot move more than a Euclidean distance $D$ from frames $f_i$ to $f_{(i+1)}$. How might I best use the intepolation tools in Mathematica 9 to "guess" the shape of the curve followed by the object? I'd ideally like to specify that the object follows a linear trajectory, or, say, a trajectory characterized by a polynomial of bounded degree. * * * Update: In response to Thies Heidecke's comment on filters, here, I'm tracking a moving object that changes direction fairly slowly. The curve fitting the data should be fairly smooth.


title: Filling between quantile ranges

text: Following code plots Quantiles for a GBM process.               ranges = {.01, .05, .25, .5, .75, .95, .99};     Manipulate[      Plot[       Quantile[         GeometricBrownianMotionProcess[\[Mu], \[Sigma], 100000][t],ranges],      {t, 1, 30},PlotRange -> {0, 1500000}],      {\[Mu], .07, .1}, {\[Sigma], .07, .20}]      I would like to shade the area between between the ranges .01 to .05 and .95 to .99 say lt. blue .05 to .25 and .75 to .95 say med. blue .25 to .75 say dark blue with the .5 quantile line thick black Plot options seems to allow filling between curves using               Filling->{{1}->2}       syntax but not sure how or if that can be applied here?


title: Solve-ing with initially unassigned parameters and Solve-ing using their numerical values produces different results

text: I am trying to solve an equation using the following piece of code:               f[t_] = Aa*t^4 + Bb*t^3 + Cc*t^2 + Dd;          s = Solve[f[t] == 0, t];          t1 = t /. s[[1]];     t2 = t /. s[[2]];     t3 = t /. s[[3]];     t4 = t /. s[[4]];        And it gives me four symbolic formulas. Then, I try to give numbers to the `Aa`, `Bb`, `Cc`, `Dd` parameters:               Aa = 1.2347931365926803*10^30 ;     Bb = 4.6356322739291924*10^23 ;     Cc  = 4.350806821541392*10^16 ;     Dd = -1.2562823055999998*10^6 ;      and the formulas provide the results:               -7.18016*10^-7 - 6.17065*10^-7 I     5.30307*10^-7 + 6.17065*10^-7 I     -7.18016*10^-7 + 6.17065*10^-7 I     5.30307*10^-7 - 6.17065*10^-7 I      But, if I solve using the numerical values of `Aa`, `Bb`, `Cc`, `Dd` from the beginning, I get:               -1.10255*10^-6     -9.38545*10^-8 - 9.99928*10^-7 I     -9.38545*10^-8 + 9.99928*10^-7 I      9.14844*10^-7      I have also noticed that this behavior is sensitive to the values I give to the parameters. Using these instead,               Aa = 2.8262007068794462*10^25;     Bb = -5.389762192271189*10^21;     Cc = 2.5696632603084144*10^17;     Dd = -1.2213607220736102*10^6;      the problem seems to still be there, but not as serious. Any ideas on what might be causing this and maybe a way to avoid it?


title: A function that accepts a pair or a list of pairs

text: Probably a duplicate, but it's not easy to search on "lists". I have a function that accepts a list of lists, say `{{a1, b1}, {a2, b2}, {a3, b3}}` and performs some computation on `{ai,bi}` for each `i`. (We may assume that none of the `ai` or `bi` are themselves lists). I would like this function to also accept simply `{a1,b1}` as its argument list and operate on this as if it were the only member of the (nonexistent) outer list. That is, I would like               f[{a1,b1}]      to behave the same way as               f[{{a1,b1}}]      What I have done is the following:               f[list_] := Module[{nlist},        nlist = If [ListQ[list[[1]]], list, {list}];        <do other stuff...>     ]      This works fine, but seems pretty inelegant. Is there a better way?


title: Find an inverse matrix, regarding a parameter as real

text: I have the matrix               {{3, 2, 1}, {3, 1, 2}, {2, 3, -1},      {-(3/b), -(3/b^2) - 2/b, -(3/b^3) - 2/b^2 - 1/b},      {-(3/b), -(3/b^2) - 1/b, -(3/b^3) - 1/b^2 - 2/b},      {-(2/b), -(2/b^2) - 3/b, -(2/b^3) - 3/b^2 + 1/b}}      and I want to compute its inverse (or pseudoinverse). The problem is that _Mathematica_ solves this regarding `b` as a complex number. How do I change this to set `b` as real? I tried `Assuming` but that didn't work. Maybe I am writing it wrong. Any ideas? It should be fairly simple, but I am not really good at `Mathematica` and I couldn't find a solution elsewhere. I would be greatful for a general answer, not one specifically for this example; e.g., `Pseudoinverse[a] /. Reals[b] -> ...` (this didn't work). Thanks


title: Formatting a number with fixed number of significant digits

text: I need a formatting function (say `format[x_, n_]`) which outputs numbers with fixed `n` _significant_ digits without unnecessary dot. Examples:               format[.02,3] -> "0.0200"     format[.2,3] -> "0.200"     format[1,3] -> "1.00"     format[100,3] -> "100"         format[1000,3] -> "100\[Times]10^1"     format[10000,3] -> "100\[Times]10^2"      Any ideas? The shorter - the simpler!


title: Finding a subsequence in a list

text: I have a list and I want to find (in this particular case the first) appearance of a any of some subsequences, of possible different lengths. None of the subsequences is a subsequence of each other. In my particular case I could do this translating the list to a string and using `StringPosition`. But I could do it because all elements on my list were one-character-long. Before realizing this I had implemented a not-nearly-one-liner that did the trick without recurring to Strings. It didn't do any useless comparison but it did lots of useless coping of the list as a whole, and it turned out to be 50 times slower than the `StringPosition` version. It can be improved, avoiding that issue, making it even less one-liner. The task just seems too easy to describe so as to be so not-easy to program well... Is there an efficient way to do it for the general case? "Find the first appearance of one of many subsequences (possible different lengths, perhaps could be patterns, or not) in a list" (Wow, I think I just thought of a good way, I'll give it a shot... If it works I'll auto-answer. But I'd still like your input, I'm afraid I'm missing some options)


title: Printing Block Matrices

text: I have a 2D matrix, such as:               d=2;     M=Array[a, {d^2,d^2}];      and I would like to print it in a way which emphasizes its dxd block matrix structure. If `MatrixForm` had a `Dividers` option like `Grid`, then this is what I would use. But it doesn't. The first thing I tried was:               With[         {div={False, Join[Table[False, {n, d - 1}], {Dashed}], False}},         {{Grid[M,Dividers->{div,div}]}}//MatrixForm     ]      where the `{{stuff}}//MatrixForm` is simply to get the parentheses. The problem with this is that if your matrix is big (d>2) and certain entries of your matrix are big expressions, then they do an ugly line wrap thing. To counter this, I call `{{TableForm[#]}}&` on each element of the matrix first:               With[         {div = {False,Join[Table[False, {n, d - 1}], {Dashed}],False}},          {{             Grid[Map[TableForm[{{#}}] &, M, {2}],Dividers -> {div, div}]         }} // MatrixForm     ]      but this is a hack. So I suppose my questions are: What Form do `TableForm` and `MatrixForm` use on each of their elements, and can I use this here? I've tried `StandardForm` but that's not it. Next, is there in general some better way to do what I am trying to do? **Edit:** As requested, here is an example that illustrates the "ugly line wrap thing":               d = 3;     M = Table[Expand[(a + b)^RandomInteger[4]], {i, d^2}, {j, d^2}];


title: NDSolve::ndsz problem

text: I'm using NDSolve to solve a set of coupled differential equation which depend on a variable x. I noticed that when I set the range of x from a small value to a large value, I obtain solutions. But when I do the opposite I get a problem! For example when I consider this,               t1 = 3000;     t2 = 4*^16;     f = 1/(16 Pi^2);     NDSolve[{y'[x] == f/x * 16 y[x]^3, y[t1] == 0.37}, y, {x, t1, t2},     Method -> {"ExplicitRungeKutta", "DifferenceOrder" -> 4}];      No errors and I can find:               y[t2] /. %          {0.920385}      Then I use this value of y[t2] as the initial condition for the following case, where I swap the range of x:               t1 = 3000;     t2 = 4*^16;     f = 1/(16 Pi^2);     NDSolve[{y'[x] == f/x * 16 y[x]^3, y[t2] == 0.92}, y, {x, t2, t1},     Method -> {"ExplicitRungeKutta", "DifferenceOrder" -> 4}]      I get the error:               NDSolve::ndsz: At x == 4.`*^16, step size      is effectively zero; singularity  or stiff system suspected.      I tried to switch off the StiffnessTest to see if the problem goes away, which would mean that it's a stiffness problem, but the error message still shows. Also tried to use:               Method -> {StiffnessSwitching, Method -> {ExplicitRungeKutta, Automatic}}      And it didn't work either. Considering that this is a typical differential equation encountered in physics (renormalization group equations) I'm pretty sure that there should be no singularity at x = t2, and I should be able to solve from the high-scale to the low-scale. Any insights on why this is happening and how to deal with it?


title: Where is the "Insert > Citation> Bibliographical Reference" Command?

text: I don't have the command for inserting citations described in the documentation: "Insert > Citation> Bibliographical Reference" is not present in my menus: ![enter image description here](http://i.stack.imgur.com/QZg4E.png) That's the entire contents of my "Citation" menu: no "Bibliographical Reference" item anywhere to be seen. How do I restore this item to my menus? What could I have done that would have removed it?


title: List of supported units in Mathematica 9

text: Is there a list of supported units in Mathematica 9 documentation? I personal haven't found any; even the physical constants (newly supported as units in 9) can only be found in compatibility information. It is quite strange that Wolfram didn't even compile a list of units for the documentation.


title: Where to see all Mathematica units

text: Is there a tutorial page that have all Mathematica units? I sometimes have hard time figuring out the correct unit spelling when using quantities


title: Interactive Graph Editing with Animation

text: I want to make a simple interactive user interface like this: ![gui](http://i.stack.imgur.com/cxrvJ.png) Such that when the user clicks on the "Add Edge" button, the edge specified by _from_ and _to_ fiels is added to the graph. The new graph may have a new layout and I want to make an animation between the old and new graphs (see my other question and my answer to the question). Most of the examples I found, change the graph/plot just on change of the inputs without waiting for a click from the user. I know how to add the edge to the graph and generate the frames of the animation, but how can I do the rest?


title: Why does $\frac{\partial}{\partial x}O\left(\left(\frac{1}{x}\right)^0\right)$ equal $O\left(\left(\frac{1}{x}\right)^0\right)$ in a series expansion?

text: When taking the derivative of a series expansion around a finite point, the $O(x^n)$ part is differentiated as expected. $O(x^n)$ becomes $O(x^{n-1})$ except $O(x^0)$ which stays $O(x^0)$. When expanding around infinity, things do not work out that nicely. $O\left(\left(\frac{1}{x}\right)^n\right)$ in general becomes $O\left(\left(\frac{1}{x}\right)^{n+1}\right)$. So far so good but $O\left(\left(\frac{1}{x}\right)^0\right)$ stays the same as in the expansion around a point that is finite. This doesn't seem to make sense because the leading constant term should drop out and the second one should be differentiated so we should get $O\left(\left(\frac{1}{x}\right)^2\right)$. Am I missing something? Is this behavior to be expected?               D[O[x, Infinity] x, x]     (* Out[1]= SeriesData[x, DirectedInfinity[1], {}, 0, 0, 1] *)


title: Solving a single equation with multiple parameters

text: If I wanted to solve equations like Cos[x]^2 = A Cos[Bx + C] + D what function should I use? The Solve function seems to only solve for as many variables as there are equations. Please note that my given equation is only an example of what I would like to do. I am not asking for the solution to that specific equation. I know I could use TrigReduce, but I would like to know how to do this more generally for expressions that aren't even trigonometric. I also know I could sample Cos[x]^2 and just do a fit with those parameters, but I was looking for a cleaner, non-numeric way of solving this. Is this possible? edit: It now looks like SolveAlways is the right function for the task, but unfortunately it doesn't solve my example equation.


title: Access pairs of vectors, rather than the matrices, in partitioned data structure at a levelspec

text: I have some old code to analyze correlation between 2 time series by looking at windows of different lengths shifting across the time series data. The code:   * gets 2 sets of time series data (in this case using `FinancialData[]` for convenience);   * sets a list of windows on which to calculate the correlations;   * partitions the data into matrices by applying each window over time;   * calculates correlations;   * pads the data; and   * plots Code:               data = Transpose[Drop[FinancialData[#, "Aug. 4, 2006"] & /@ {"SPY", "GLD"}, None, None, 1][[All, All, 1]]];     windows = Range[100, Round[Length[data], 100], 100];     partitionedData = Partition[data, #, 1] & /@ windows;     correlations = Map[Correlation, partitionedData, {2}];     plotData = PadLeft[correlations[[All, All, 1, 2]]];     ListPlot3D[      plotData,      ImageSize -> 400,      AxesLabel -> {"Days", "Window", "Correlation"},      PlotRange -> {Automatic, Automatic, {-1, 1}},      BoxRatios -> {1, 1, 0.75},      ViewPoint -> {2, 0, 1}]      Output ![ListPlot3D](http://i.stack.imgur.com/lkAS9.png) Now typically I'd run these correlations on log returns rather than price, but I wanted to keep the example as simple as possible. In this case the windows have lengths of 100, 200, 300, ... 1500 corresponding to the 15 windows in the plot. This all works fine, but now I want to look at other correlation measures:               SpearManRankCorrelation[]     KendallRankCorrelation[]      Neither of these take a matrix as input, they both take 2 vectors: ![enter image description here](http://i.stack.imgur.com/LYK2j.png) ![enter image description here](http://i.stack.imgur.com/DAGPZ.png) So my problem comes down to this single line of code:               correlations = Map[Correlation, partitionedData, {2}];      I need to alter this line of code so that it will map to the pairs of vectors in each of the matrices at level 2 of `partitionedData`. As `Correlation[]` can also use vectors as inputs this will give me a more generalized approach. Some additional background... The structure of `partitionedData` looks like this:               Dimensions[partitionedData]     {15}          Dimensions[#] & /@ partitionedData     {{1410, 100, 2}, {1310, 200, 2}, {1210, 300, 2}, {1110, 400, 2}, {1010, 500, 2}, {910, 600, 2}, {810, 700, 2}, {710, 800, 2}, {610, 900, 2}, {510, 1000, 2}, {410, 1100, 2}, {310, 1200, 2}, {210, 1300, 2}, {110, 1400, 2}, {10, 1500, 2}}      I've fiddled around with this all morning, but keep confusing myself. I don't see a clear way to use the same form of `Map[]` using `levelspec`, so I keep trying variations on pure functions but keep getting into a muddle. I've tried lots of variations of this basic approach:               Correlation[#[[1]], #[[2]]] & /@ partitionedData[[All, 2]];      but I don't get myself anywhere. Thoughts and guidance appreciated.


title: Death of parallel sub-kernels

text: EDIT : Finally, the new Mathematica 10.0 seems to fix it. I have a little parallelization problem. I wrote a code to generate a quasicrystal by dynamical generation. Here the code:               (*===================================================================================*)         time1 = DateList[] ;         Print[time1];     (*Constants*)     (*===================================*)     ITERMAX = 9; (* Maximum = 9 *)     (*===================================*)     MIN ={0.9999999999999999`, 0.6180339887498947`, 0.3819660112501049`,      0.38196601125010465`, 0.23606797749978875`, 0.23606797749978836`,         0.23606797749978836`, 0.14589803375031407`, 0.14589803375031385`}[[       ITERMAX]];     MAX = {1.`, 0.618033988749895`, 0.38196601125010554`,          0.38196601125010576`, 0.23606797749979036`, 0.2360679774997906`,          0.23606797749979072`, 0.1458980337503173`, 0.1458980337503173`}[[ITERMAX]];      Clear[x, xx, zz]     x = 0;     sig := Exp[2*Pi*I/5];     tau := N[GoldenRatio];     CiT := 2*tau^4;          (*Functions*)     complexSplit := Function[z, {Re@z, Im@z}, Listable];     dP[w_, z_] := 1/2*(w*z\[Conjugate] + w\[Conjugate]*z);     zGen[x_] :=       Module[        {         zPlus = Table[x + Exp[2*Pi*I*j/5], {j, 0, 4, 1}],         zMinus = Table[x - Exp[2*Pi*I*j/5], {j, 0, 4, 1}]         },        Return[Join[zPlus, zMinus]]        ];      fctTest[seed_] :=        1/11*(1 + Sum[Exp[2*Pi*dP[dP[I, sig^i], dP[CiT, seed]]], {i, 4}] +           Sum[Exp[-2*Pi*dP[dP[I, sig^i], dP[CiT, seed]]], {i, 4}]);     zTest[x_] :=       If[Re[fctTest[x]] >= 0.38232,        x]; (*Real part for the computation error*)          Generator[x_] := Generator[x] = zTest /@ zGen[x];          (*Point generation*)     zz[0] := {x};     For[i = 0, i < ITERMAX, i++,       zz[i + 1] = DeleteDuplicates[Flatten[ParallelMap[Generator, zz[i]]]];       ];     z = DeleteDuplicates[Flatten[Table[zz[k], {k, 0, ITERMAX}], 1]];          (*Line generation*)     Lz = Length[z];     zCart = ParallelTable[{N[Re[z[[i]]]], N[Im[z[[i]]]]}, {i, 1, Lz}];     zline = Cases[Flatten[ParallelTable[          Table[           If[zCart[[i]] != zCart[[j]] &&              MIN <= EuclideanDistance[zCart[[i]], zCart[[j]]] <=               MAX, {zCart[[i]], zCart[[j]]}, 0]           , {j, i, Lz}],          {i, 1, Lz}], 1],        Except[0]];          (*PLOT*)     quasicrystal =        Graphics[{{PointSize[0.004], Red,           Point[complexSplit@z]}, {Thickness[0.00009], Line[zline]}},         ImageSize -> {2000, 2000}];         time2 = DateList[];         time3 = DateDifference[time1, time2, "Second"];         Show[quasicrystal]         Print[time2];         Print[time 3];     (*===================================================================================*)      So when I try to run my code for nine or more iterations, I have the following sequence of errors :               LinkObject::linkd: Unable to communicate with closed link LinkObject[/usr/local/Wolfram/Mathematica/9.0/Executables/math -subkernel -noinit -mathlink,250,9]. >>     KernelObject::rdead: Subkernel connected through KernelObject[6,local] appears dead. >>     Parallel`Developer`QueueRun::req: Requeueing evaluations {1162} assigned to KernelObject[6,local,<defunct>].     LaunchKernels::clone: Kernel KernelObject[6,local,<defunct>] resurrected as KernelObject[6,local]. >>     LinkObject::linkd: Unable to communicate with closed link LinkObject[/usr/local/Wolfram/Mathematica/9.0/Executables/math -subkernel -noinit -mathlink,249,8]. >>     KernelObject::rdead: Subkernel connected through KernelObject[5,local] appears dead. >>     Parallel`Developer`QueueRun::req: Requeueing evaluations {1163} assigned to KernelObject[5,local,<defunct>].     LaunchKernels::clone: Kernel KernelObject[5,local,<defunct>] resurrected as KernelObject[5,local]. >>     LinkObject::linkd: Unable to communicate with closed link LinkObject[/usr/local/Wolfram/Mathematica/9.0/Executables/math -subkernel -noinit -mathlink,251,10]. >>     General::stop: Further output of LinkObject::linkd will be suppressed during this calculation. >>     KernelObject::rdead: Subkernel connected through KernelObject[7,local] appears dead. >>     General::stop: Further output of KernelObject::rdead will be suppressed during this calculation. >>     Parallel`Developer`QueueRun::req: Requeueing evaluations {1161} assigned to KernelObject[7,local,<defunct>].     General::stop: Further output of Parallel`Developer`QueueRun::req will be suppressed during this calculation. >>     LaunchKernels::clone: Kernel KernelObject[7,local,<defunct>] resurrected as KernelObject[7,local]. >>     General::stop: Further output of LaunchKernels::clone will be suppressed during this calculation. >>      My PC can also crash and I don't understand the problem because I can run my code without problem on institutional version, but not on my computer with the student version. Not having any idea, I hope someone will have an idea.


title: JacobiCN inaccuracy

text: For my calculations I need `JacobiCN[s,k]` for `s` near 0 from the left and `k` near 1 from the left. The function $(s,k) \mapsto \mathrm{cn}(s,k)$ is smooth on $]{-1},0[ \times ]0,1[$, yet Mathematica 7 gives me very different plots for `k=0.999` and values of `k` above:               Plot[JacobiCN[s, 0.999], {s, -1, 0}]     Plot[JacobiCN[s, 0.9990001], {s, -1, 0}]      ![k=0.999](http://i.stack.imgur.com/Bjf67.png) ![k=0.9990001](http://i.stack.imgur.com/voEAV.png) WolframAlpha does not seem to have this problem. Is this a numerical artifact in Mathematica 7 that you can circumvent somehow, or do I have to reimplement $\mathrm{cn}$?


title: Resources on Mathematica and strong AI (a.k.a. AGI)

text: David Deutsch (physicist / quantum computing theorist) wrote an article for _Aeon Magazine_ last year: On Artificial Intelligence that got me thinking. The article assesses and critiques the achievements in AI and articulates criteria one needs to meet to realize strong AI or what he calls Artificial General Intelligence (AGI). Some key ideas from the article:   * _What is needed is nothing less than a breakthrough in philosophy, a new epistemological theory that explains how brains create explanatory knowledge and hence defines, in principle, without ever running them as programs, which algorithms possess that functionality and which do not._   * _...the ability to produce new explanations._   * _...brain in a vat_.    * _Because genuine knowledge, though by definition it does contain truth, almost always contains error as well._   * _...it is simply not true that knowledge comes from extrapolating repeated observations. Nor is it true that ‘the future is like the past’, in any sense that one could detect in advance without already knowing the explanation._ The article inspired a number of discussions among my colleagues. We see a thread of rather obscure work across the entire history of information theory that looks like it addresses many of Deutsch's concerns. We use this stuff in a variety of sequential decision problems. **Mathematica and AGI** So naturally the question came up: > _Can we model AGI in Mathematica?_ This is a broad question, however, so below the question will be narrowed down. But first, here are some reasons why I think _Mathematica_ may be suitable for this purpose. A lot of work in AGI gets programmed in Lisp and other homoiconic and/or functional languages. Homoiconic languages internally represent code and data in the same way. This could provide a program the capability to modify itself, perhaps even to evolve or adapt to a new problem. _Mathematica_ sees everything as an expression. It has the ability to generate functions. Wolfram Alpha certainly has some kind of AI calculation/search underpinning it, but I don't see it as attempting AGI. **The question is** : Can anyone direct me to: >   * _examples of Mathematica used in work on AGI_ ; >   * _individuals using Mathematica for work on AGI_ ; >   * _resources about using Mathematica for work on AGI_ ; > Also, if anyone has an interest in thinking through this in greater detail, just ping me (email in my profile) and I'll forward more background information on our ideas.


title: clean functional way to get first n rows that yield maximum rank

text: I have a matrix A and want the matrix consisting of the first n rows of A, having the same rank as A, where n is minimal. More generally, I want the shortest "start piece" of a list, such that some criterion on the start piece gives True. For the more general problem, I wrote myTake below, but I'm very dissatisfied with the procedural nature of my implementation.               myTake[list_, crit_] := Catch[         Do[With[{candidate = list[[Range[i]]]},              If[crit[candidate], Throw[candidate]]]         , {i, Length[list]}];      "fail"     ];     firstFullRank[matrix_] := With[{fullRank = MatrixRank[matrix]},          myTake[matrix, MatrixRank[#] == fullRank &]     ];     firstFullRank[{{1,0,0},{0,1,0},{2,3,0},{1,2,3},{9,8,7}}]          (gives {{1, 0, 0}, {0, 1, 0}, {2, 3, 0}, {1, 2, 3}})      In short, I'm looking for a **fast** and functional one liner implementation of myTake and/or firstFullRank **Edit** Please assume that the matrix has lots of rows (> 1000) and not many columns (<10), and that the result has significantly fewer rows than the full matrix. Is there a way to do this functionally without using Range[Length[matrix]] or (even worse) a table of all start pieces.


title: Failed to connect remote Mathematica kernel using J/Link

text: I'm trying to connect to a remote _Mathematica_ 8 kernel (on a Windows machine) using J/Link. On the client machine, I put the `JLinkNativeLibrary.dll` file in `C:\Documents and Settings\User\My Documents`. But, it gives me the error message "cannot find the required native library named `JLinkNativeLibrary`". Here is my code               public static void main(String[] args) {             KernelLink link;             try {                 String jLinkDir = "C:\\Documents and Settings\\User\\My Documents";                 System.setProperty("com.wolfram.jlink.libdir", jLinkDir);                             link = MathLinkFactory.createKernelLink("-linkmode connect -linkprotocol tcpip -linkname 8080@172.20.48.113");             } catch (MathLinkException ex) {                 ex.printStackTrace();             }         }      Exception : > Fatal error: cannot find the required native library named > JLinkNativeLibrary. Exception in thread "main" > java.lang.UnsatisfiedLinkError: > com.wolfram.jlink.NativeLink.MLOpenString(Ljava/lang/String;[Ljava/lang/String;)J > at com.wolfram.jlink.NativeLink.MLOpenString(Native Method) at > com.wolfram.jlink.NativeLink.(NativeLink.java:117) at > com.wolfram.jlink.MathLinkFactory.createMathLink0(MathLinkFactory.java:281) > at > com.wolfram.jlink.MathLinkFactory.createMathLink(MathLinkFactory.java:194) > at > com.wolfram.jlink.MathLinkFactory.createKernelLink0(MathLinkFactory.java:171) > at > com.wolfram.jlink.MathLinkFactory.createKernelLink(MathLinkFactory.java:65) > at mathematica.Sample.main(Sample.java:21) I also wrote the following code where `KernelLink` gets created but there is some problem with establishing the connection. It gives an error "MathLinkException: 1: MathLink connection was lost."               public static void main(String[] args) {             KernelLink ml = null;             try {                 ml = MathLinkFactory.createKernelLink("-linkmode connect -linkprotocol tcp -linkname 1234@172.20.48.113");             } catch (MathLinkException ex) {                 Logger.getLogger(MathematicaSample.class.getName()).log(Level.SEVERE, null, ex);                 return;             }             try {                 ml.connect(1000000); // Wait at most 10 seconds             } catch (MathLinkException e) {                 // If the timeout expires, a MathLinkException will be thrown.                 e.printStackTrace();                 ml.close();                 return; // Or whatever is appropriate.             }                 try {                 // Get rid of the initial InputNamePacket the kernel will send                 // when it is launched.                 ml.discardAnswer();                 ml.evaluate("<<MyPackage.m");                 ml.discardAnswer();                 ml.evaluate("2+2");                 ml.waitForAnswer();                 int result = ml.getInteger();                 System.out.println("2 + 2 = " + result);                         } catch (MathLinkException e) {                 System.out.println("MathLinkException occurred: " + e.getMessage());             } finally {                 ml.close();             }         }     }      Does anyone know how to connect to the kernel?


title: How can I log in to my Wikipedia account and access my watch list?

text: Wikipedia's "Edit Watchlist" page (for logged in users) has a list of hyperlinks to the user's watchlist (here is an example from my account). ![enter image description here](http://i.stack.imgur.com/7bYtZ.png) I've tried to use `URLFetch` and `URLSave` as follows               URLFetch["http://en.wikipedia.org/wiki/Special:EditWatchlist"]     URLSave["http://en.wikipedia.org/wiki/Special:EditWatchlist","test.html"]      but it seems that they cannot grab the links in the watchlist. I thought `URLSave` is the same as saving a webpage as a HTML file by hand in Internet Explorer... Am I wrong? Even `Import`, with               Import["http://en.wikipedia.org/wiki/Special:EditWatchlist","Hyperlinks"]      (and also with `"Source"`), cannot get the hyperlinks. How can I log into Wikipedia and get these links using _Mathematica_?


title: Using MatchQ (or other means) to parse an expression using sums of COS or SIN correctly

text: I am writing a function that will take an expression as input. I want to make sure the expression is valid first before processing it. Looking for a correct to use `MatchQ` (or if you have better method) to use which will return `True` or `False` when given the expression. ## Specifications The expression will have the following form               a1 Cos[x+b1] + a2 Cos[x+b2] + a3 Cos[x+b3] + ....      _OR_               a1 Sin[x+b1] + a2 Sin[x+b2] + a3 Sin[x+b3] + ....      So if you can parse one, then with some trick, can use the same parser with the other using `OR`. There can one or more terms there. Also, the amplitudes (the $a_i$) can be there or not there. Also, there is no need to check what is used for argument to the trig functions. So if expression is `Cos[Cos[x]]` then that is ok, only FIRST level needs to be validated. The expression will be passed by `TrigReduce[]` before. Your parser only needs to check for the above top level form. Hence the following are all valid expression and should return `True`               Sin[x]     a Sin[x]     a Sin[x] + Sin[x +b]     Sin[x] + Sin[x + b] + c Sin[x]      These are NOT valid:               Sin[x] + Cos[x]  (*mixed*)     a + Sin[x]  (*first term has no sin nor cos *)     Sin[x]+ b + Sin[x + v]       So the function needed will have this specification               parse[expr_]      and will return either `True` or `False`. What is the most efficient way to do this? ## Test suite To help you in making the parser, here are few expressions that should return `True` and another set that should return `False`               ClearAll[x, a1, b1, a2, b2, a3, b3];     trueTests = {       3 Cos[x],       a1 Cos[x + b1],       Cos[x] + a1 Cos[x + b1],       a1 Cos[x] + a1 Cos[x + b1] + a2 Cos[x + b2],       3 Sin[x],       a1 Sin[x + b1],       Sin[x] + a1 Sin[x + b1],       a1 Sin[x] + a1 Sin[x + b1] + a2 Sin[x + b2]       }          falseTests = {       a1,       a1 Cos[x + b1] + Sin[x],       Cos[x] + b1,       a1 Cos[x] + a1 Cos[x + b1] + a2 Sin[x + b2],       Cos[x] + Sin[x]       }


title: NestWhile application

text: I have the function which take the last list in nested list, reduce it somehow in several ways so the length of list reduces and output new list wherein input list appended with defferent reduced lists. Maybe my explanation a little bit illegible but here is an example code:               cov = {{0, 3, 1, 2}};     l = 2;     detach = Function[{cov, l},        s = Last[cov];        Table[Append[cov,           Delete[ReplacePart[s, i -> l + Total[s[[i ;; i + 1]]]],            i + 1]], {i, 1, Length[s] - 1}]        ];     detach[cov, l]          Output: {{{0, 3, 1, 2}, {5, 1, 2}}, {{0, 3, 1, 2}, {0, 6, 2}}, {{0, 3, 1, 2}, {0, 3, 5}}}      Now I need to apply recursively the same function to all lists of output list so for proposed example I shoud get the following result:               {{{0, 3, 1, 2}, {5, 1, 2}, {8, 2}, {12}},       {{0, 3, 1, 2}, {5, 1, 2}, {5, 5}, {12}},       {{0, 3, 1, 2}, {0, 6, 2}, {8, 2}, {12}},       {{0, 3, 1, 2}, {0, 6, 2}, {0, 10}, {12}},       {{0, 3, 1, 2}, {0, 3, 5}, {5, 5}, {12}},       {{0, 3, 1, 2}, {0, 3, 5}, {0, 10}, {12}}}      I tried to apply NestWhile or FixedPoint but did not succeed to get desired result.


title: Calculating error of the approximate formula in calculations

text: I have an exact equation: \begin{equation} a = \sqrt{1 + x^2 - \sqrt{(1 + x^2)^2 - 2 x^2 \cos^2\theta}}\tag{1} \end{equation} and its approximation: \begin{equation} a = \dfrac{x \cos^2\theta}{\sqrt{1 + x^2}}\tag{2} \end{equation} I'm doing most theoretical calculations using equation $(2)$ and to check the outcomes I'm doing numerical calculations of $(1)$ in Mathematica. For example, finding $\left.\frac{da}{dx}\right|_{x = 0}$ dividing by $\left.\frac{da}{d\theta}\right|_{\theta = 0}$ and integrating: \begin{equation} \int\limits_{0}^{A}\frac{\left.\frac{da}{dx}\right|_{\theta = 0}}{\left.\frac{da}{d\theta}\right|_{\theta = 0}}dx \end{equation} And I want to check that this (or any other) procedure doesn't differ much from the same for precise and approximate function. How can I verify that the use of the approximate formula doesn't make the calculations inaccurate?


title: Change the behaviour of a LocatorPane

text: Normally, `LocatorPane` detects any single click as in the following example:                   DynamicModule[{pt = {1, 1}/2},           {LocatorPane[Dynamic[pt], Graphics[{Gray, Disk[]}]], Dynamic[pt]}]      My goal is to redefine the behaviour of `LocatorPane` to detect only double clicks (i.e., the value of `pt` is returned only when the user double-clicks in the `LocatorPane`) I tried the following definition, but with no success!               doubleclickPane[pt_, back_, opts : OptionsPattern[]] :=        DynamicModule[{ptt = pt},         Deploy @ EventHandler[           LocatorPane[Dynamic@ptt, back, ,Evaluate[FilterRules[{opts}, Options[LocatorPane]]]],           {"MouseDown" :> (             ptt = MousePosition["Graphics"];              If[Mod[CurrentValue["MouseClickCount"], 2] == 0, pt = MousePosition["Graphics"]]           )}         ]       ]


title: Smoothing/Averaging 2D Vector Fields

text: I have a list of 2D vectors defined by `{{x,y},{u,v}}` and would like to smooth or average the vectors. For example here are 2 vector fields, the second has noise added to the orientation of each list item:               f = Sin[2 x + 2 y];     data = Flatten[Table[{{x, y}, {Cos[f], Sin[f]}}, {x, -1, 1, 0.1}, {y, -1, 1, 0.1}], 1];     noisydata = Flatten[ Table[         theRand = RandomReal[{-π/6, π/6}];         {{x, y}, {Cos[f + theRand], Sin[f + theRand]}}         , {x, -1, 1, 0.1}, {y, -1, 1, 0.1}], 1];     {ListVectorPlot[data], ListVectorPlot[noisydata]}     {ListStreamPlot[data], ListStreamPlot[noisydata]}      ![enter image description here](http://i.stack.imgur.com/Cj4Mh.png) Any suggestions about smoothing the field in _Mathematica_? I am trying to interpolate the data (creating an interpolating function using `Interpolation`), but the resulting vector fields are very noisy. Any help would be appreciated!


title: Tridiagonal symmetric matrix eigenvalue using bisection

text: I know that `Eigenvalues` is already quite well implemented in Mathematica, nor am I foolishly trying to improve on it. In order to improve my programming skills, I am trying to write Mathematica-style code to locate eigenvalues of a tridiagonal symmetric matrix using bisection. This is what I came up with.               tridiagbisec[diag_List, subdiag_List, tol_Real] :=       Module[{diagonals =           Split[Transpose[{diag, Join[{0}, subdiag]}], #2[[2]] =!= 0 &]},        Flatten[         bisecnonzero[-myNorm[Sequence @@ Transpose[#]],             myNorm[Sequence @@ Transpose[#]], tol, #] & /@ diagonals]] /;        Length[diag] - Length[subdiag] == 1      `tridiagbisec` is the main function I will be calling. It builds an array (`diagonals`) from the arrays containing the matrix elements of both the leading diagonal and the subdiagonal, then `Split`s it wherever a zero is found so that each block is evaluated separately, using `bisecnonzero`.               bisecnonzero[\[Lambda]min_Real, \[Lambda]max_Real, tol_Real, diagonals_List] :=       Module[{\[Lambda]med = (\[Lambda]min + \[Lambda]max)/2,         nmin = numeig[diagonals, \[Lambda]min],         nmax = numeig[diagonals, \[Lambda]max], nmed},       nmed = numeig[diagonals, \[Lambda]med];       {Which[(nmin > nmed) && (\[Lambda]med - \[Lambda]min > tol),          bisecnonzero[\[Lambda]min, \[Lambda]med, tol, diagonals],         (nmin > nmed) && (\[Lambda]med - \[Lambda]min <= tol),          ConstantArray[(\[Lambda]med + \[Lambda]min)/2, nmin - nmed],         True, {}],        Which[(nmed > nmax) && (\[Lambda]max - \[Lambda]med > tol),          bisecnonzero[\[Lambda]med, \[Lambda]max, tol, diagonals],         (nmed > nmax) && (\[Lambda]max - \[Lambda]med <= tol),          ConstantArray[(\[Lambda]max + \[Lambda]med)/2, nmed - nmax],         True, {}]}       ]      This, I believe, is where I may have built my program in a suboptimal way. Are two `Which` the right way to iterate bisection?               numeig[diagonals_, \[Lambda]_] :=        numeig[diagonals, \[Lambda]] =         Unitize[#].UnitStep[#] &@         Rest@FoldList[           If[Not@PossibleZeroQ@#1, #2[[               1]] - \[Lambda] - #2[[2]]^2/#1, +\[Infinity]] &, 1, diagonals];      `numeig` computes the number of eigenvalues greater than `\[Lambda]` (cfr. (5) in Barth, Martin and Wilkinson (1967).               myNorm = Max[Abs@#1 + Abs@#2 + RotateLeft@Abs@#2] &;      I know that I am also reimplementing `Norm[#,Infinity] &`, but for scholastic purposes I think it may be useful, since for a tridiagonal matrix it has a particularly simple form and this way I can avoid building a `SparseArray` structure at all. Since I am trying to be performance-conscious, how could the whole algorithm be improved upon with reasonable effort? ...Besides using `Eigenvalues`, that is! :D


title: Can I limit PlotRange for 1 function in a Plot?

text: I have a 2D Plot of 3 functions               Plot[ { f1[x], f2[x], f3[x] }, { x, 8, 18 } ]      where I want f3[x] only plotted for the range [10, 18] instead of [8, 18]. Is that possible?


title: Integral returns function of variable that was integrated over

text: When I enter               Integrate[1/Sqrt[(y1)^2 + (y2)^2 + (y3)^2]*1/(1 + (y3)^2)     * Exp[-2*((y1)^2 + (y2)^2)/(1 + (y3)^2)],      {y1, -\[Infinity], \[Infinity]}, {y2, -\[Infinity], \[Infinity]}, {y3, -10, 10}]      into Mathematica, I get the result               ConditionalExpression[(      E^((2 y3^2)/(1 + y3^2)) \[Pi]^(3/2) Sqrt[y3^2] (-1 + Sqrt[1/y3^2] y3       + Erfc[(Sqrt[2] y3)/Sqrt[1 + y3^2]]))/(Sqrt[2] y3 Sqrt[1 + y3^2]), Re[y3^2] > 0]      However, this is a function of y3, which can't possibly be right. Apparently when other people execute this, they get a different and more sensible result. Does anybody know what setting in Mathematica might be causing this? If it helps, I am using Mathematica 9 on Ubuntu 14.04.


title: remove quotes in a combination of a text with graphics in the JournalArticle Style

text: I have a puzzling and very specific question. It may be of limited interest to community. I apologize in advance in this case. Let us see. I am making an illustration to a text that I write in the StyleSheet _Journal Article_. Here is the code:               Column[{   Row[{Rotate[Text[Style["Name of y variable", 18, Bold]], \[Pi]/2], im}],     Row[{Spacer[50], Text[Style["Name of x variable", 18, Bold]]}]   }]      Here is an image with `ImageSize->200` copied from somewhere. For example this: ![enter image description here](http://i.stack.imgur.com/mevtv.png) It is fine, while I keep the result of the above code as an output. However, for the sake of numeration of images through the long document I transform the output cell style into the Figure cell style. Such a cell style does not exist in the default stylesheet, but one finds it in the document prepared with the help of the JournalArticle StyleSheet. My problem is that as soon as I transform the output into the Figure style, the texts "Name of y variable" and "Name of x variable" appear with explicit quotes. It is not unacceptable, but boring, since the unnecessary information is misleading to the reader. I would be grateful for a suggestion, if there is an easy way to remove the quotes.


title: How to change the base of logarithmic-scale plots?

text: Mathematica provides a score of convenient functions to make plots with various logarithmic scale axes, for instance I am using `ListLogLinearPlot` to have a discrete plot with a logarithmic x-axis and a linear y-axis. My issue however is that I would like the x-axis to be on a binary logarithmic scale, instead of the default logarithmic scale (natural? with decimal ticks?). In particular I need 2, 4, 8, 16, 32, etc. to be equally spaced on the x-axis to highlight the periodic nature of the function I'm plotting. How may I proceed?


title: Using LaunchKernels to launch kernels with lower priorities

text: On windows the kernels launched with `LaunchKernels` are starred with "Below Normal" priority. **Is there a way to start them with even lower priority (eg. "Idle")?** I'm doing some intensive numerical analysis on my computer, which becomes really unresposive while the analysis is running. If I manually lower the priority of the kernels (eg from ProcessExplorer) then I'm able to work normally. But manually finding the processes every 10 minutes becomes tedious. Of course I could just launch fewer kernels than I have cores, but that seems inelegant. Bonus points for a cross-platform solution:)


title: Mathematica Plot: Inconsistency when plotting large values

text: I am working with a function in Mathematica and I am getting some inconsistencies when I plot it. As I really need to understand were this comes from I would appreciate any help. I am working with a function of the following form: `f2b[b_] = Exp[-1000 - 2 Sqrt[1000*b] - b]*(Erfi[Sqrt[1000]] - Erfi[Sqrt[1000] + Sqrt[b]])` From my understanding this function should go to zero for very small b because both parts, the Exp function as well as the difference between the imaginary error functions, should vanish. Mathematica calculates: `f2b[E^-30] // N = -3.4517046881*10^-7` as expected. BUT if I plot this function: `Plot[{f2b[E^b], 0}, {b, -50, 0}, PlotStyle -> {{Blue, Thick}, {Red, Thick}}]` ![Mathematica graphics](http://i.stack.imgur.com/TH6M2.png) Mathematica shows me a plot which is approaching a value of about -0.0175 for small b and has therefore an absolute value much larger the the value at E^-30 calculated above. If I tabulate, interpolate and plot the function: `t = Table[{b, f2b[E^b] // N}, {b, -50, 0}]; f = Interpolation[t]; Plot[{f[b], 0}, {b, -50, 0}, PlotStyle -> {{Blue, Thick}, {Red, Thick}}]` ![Mathematica graphics](http://i.stack.imgur.com/w86Nb.png) The plot is looking much different and is approaching zero as expected. I am wondering whether this has to do something with overflow problems in graphics but I am not sure.


title: CDF Infokit question

text: In the _CDF Infokit_ , one finds the `BriggsCochraneCalculus.cdf` document, which shows a textbook on calculus. I've got two questions about how it was made:   1. How has the bar at the top been made? Instead of the usual _CDF_ commands, like zoom, etc., one finds the title ( _Calculus_ , etc), the name of the author,...   2. How have the different subsections been made, so they could open and close while clicking on the text of the subsection (`"Tangent Lines"`, `"Tangent Lines and Rates of Change"`, etc)? I have tried looking into the `Opener` and `Button` documentation, but I couldn't remake this functionality...


title: decomposing a complex equation

text: I have an equation such as:               a*z^2 + b*(z - c)^2 == d       where `z` is a complex variable and `a`, `b`, `c`, `d` are all complex parameters. I want to put `x+I*y` instead of `z` and decompose this equation into two pure real and imaginary part for further analysis, but I don't know how to do it by _Mathematica_! Can anybody help me? Thanks in advance


title: Filling Between Curves

text: I want to fill in the region between the curves. So far I have this:               Plot[{x + 7, 9 - x^2}, {x, 0, 1.5}, Filling -> {1 -> {2}}]      ![enter image description here](http://i.stack.imgur.com/ma4uA.png) But I want something like this: ![enter image description here](http://i.stack.imgur.com/b6DHN.png)


title: Filling the area between two curves, only where and if the second lies above the first one

text: I would like to make a filling of a plot between two curved dynamically.I have two lines depending upon parameters. They may cross one another, and may not in different domains of the parametric space. I would like to plot them and make filling between these lines, but only if the line 2 lies above the line one, and not otherwise. To be specific, consider a simplistic example:                k = -0.5;     Plot[{0.5*x^2, x^2 + k}, {x, -2, 2}, Filling -> {1 -> {2}}]      here k is parameter. This yields the expected plot where the area between the two curves is filled everywhere. I need, however, that it would be filled only at x>1 and x<-1. Further I would like to wrap all this with Manipulate statement varying k to have all in dynamics. In addition the real problem that I have is rather complex. These two curves can have none or multiple intersection points depending upon parameters. Thus, the idea to divide the curves into parts between points does not help. This:                   k = -0.5;     Plot[{0.5*x^2, x^2 + k}, {x, -2, 2},       Filling -> If[0.5*x^2 < x^2 + k, {1 -> {2}}]]      makes no filling. Any other ideas?


title: Filling only when one curve is below the other

text: I want to fill the area between two curves only when curve-1 (Black) is _below_ curve-2(Blue). So In this example, I don't want the middle portion shaded but just the left and right tails to be shaded. It is not possible for me to always solve for the points of intersection since it might involve using `FindRoot` and stuff and may not be worth the trouble. Can someone please tell me how to do that. Thanks.               Plot[{0.8333*H + 16.928*H^0.25 - 85,        Max[-9 + Max[H - 80, 0], H - 80]}, {H, 0, 700},       PlotStyle -> {Directive[Black, Thick], Black}, Filling -> {1 -> {2}}]      ![enter image description here](http://i.stack.imgur.com/Lv6oB.jpg)


title: An error in converting matrix to quaternion

text: Here is an old quaternions package. There is a function named `MatrixToQuaternion`, References are here Matrix in that document is `1 2 3 4 5 6 7 8 9 10 11 12 13 14 15`; you can see it in the top of the page. `m1` is a test matrix               m1={{-0.825927,-0.56376,0.00445629,-166.077},{-0.56376,0.825813,-0.0144323,-109.866},{0.00445629,-0.0144323,-0.999886,200.868},{0.,0.,0.,1.}};      Part of the `MatrixToQuaternion` function in the package `Quaternions.m` You can check this according the web page.               S =  2*Sqrt[1 + m1[[2,2]] - m1[[1,1]] - m1[[3,3]]];               Quaternion[m1[[1,3]] + m1[[3,1]],              m1[[1,2]] + m1[[2,1]],                      1/2, m1[[2,3]] + m1[[3,2]]         ]/S      gives value1 (you can simply `Total[#^2]&` to see it's wrong unit quaternion)               Quaternion(0.00233201,-0.29502,0.130827,-0.00755253)      The right value should be some order of value2               {-0.29502,0.955461,-0.00755253,0.}      It looks two components of value1 are wrongly calculated. Where does it go wrong?


title: A faster way to do sums?

text: I found out that,it is INCREDIBLY(like 100 times) faster to use `Dot` instead of `Sum`,to perform long sums. But I have not been able to use this alternative to perform the following sum:               a={{b,c},{d,e}};          a[[1]]+a[[2]]      I want to get this output: > >     {b,c}+{d,e}={b+d,c+e} >   I tried:               a.{1,1}      but did not work. The easy way to do it is:               Sum[a[[i]],{i,1,2}];      But I want to avoid this slow way. Any faster alternative?


title: Dynamic [ NotebookEvaluate ["_"] ]

text: A nice way to centralize various tasks in one notebook is the `NotebookEvaluation` function. For instance I can evaluate ten notebooks from a single notebook (e.g. allnotebooks.nb) like this:               NotebookEvaluation["nbpath_1.nb"]     NotebookEvaluation["nbpath_2.nb"]     ...     NotebookEvaluation["nbpath_10.nb"]      I would like to update this automatically, e.g. every six hours, but it doesnt work. My idea is to create a master notebook with the following code (here: 15 seconds):               Dynamic[NotebookEvaluate[       "C:\\Users\\myname\\Desktop\\allnotebooks.nb"],       UpdateInterval -> 15]      And it works without using dynamic. Using dynamic gives the following error: > >     An unknown box name (ToBoxes) was sent as the BoxForm for the > expression. >     Check the format rules for the expression. >   Does someone have an idea about the reason? Is `Dynamic` not an adequate function to do this? Thanks a lot for any ideas! P.S. I tested it with this code for the sub notebooks, e.g. for nbpath_1.nb:               path = "C:\\Users\\myname\\Desktop\\";     time = DateString[{"YearShort", "Month", "Day", "_", "Hour", "Minute",          "Second"}];     data = Table[RandomInteger[{1, 10}], {10}];     Export[path <> "nb1_" <> time <> ".xls", data];


title: Blank VectorPlot

text: I'm trying to draw a `VectorPlot` of a function that admittedly probably is not very well suited for such a plot. But at the moment I just get a white sheet and I would expect something more than that. Some definitions:               G = 6.67 10^-11;     Subscript[m, sun] = 1.988425 10^30;      Subscript[m, 1] = 0.1 Subscript[m, sun]; Subscript[m, 2] = 0.4 Subscript[m, sun];     Subscript[x, 1] = -7 10^5/(Subscript[m, 1]/Subscript[m, 2] + 1);      Subscript[x, 2] = -(Subscript[m, 1]/Subscript[m, 2]) Subscript[x, 1];     ω = {0, 0, Sqrt[G (Subscript[m, 1] + Subscript[m, 2])/Abs[Subscript[x, 1] - Subscript[x, 2]]^3]};      I'm sorry about the amount of subscripts (if there is an easy way to convert them I don't know about it, though `Hold[expr]` will render the subscripts.) Here's the plot:               ϕ[r_] := -(G Subscript[m, 1])/Norm[r - {Subscript[x, 1], 0, 0}] - (G Subscript[m, 2])/Norm[r - {Subscript[x, 2], 0, 0}] - 0.5 (ω\[Cross]r).(ω\[Cross]r)          VectorPlot[Evaluate[-Grad[ϕ[{x, y, 0}], {x, y}]], {x, -10^6, 10^6}, {y, -10^6, 10^6}]      The function has singularities in it so I've considered what's been said in this post and have also been playing with the various options, but haven't been able to get anything other than the blank, white sheet: ![blank](http://i.stack.imgur.com/q30LP.png) In so far that the gradient i orthogonal to level sets, the contour plot can tell us a bit about what kind of arrows we could expect to see. The contour plot: ![contourplot](http://i.stack.imgur.com/JwJZ0.png) There is something fishy about the `Grad` which makes me suspect `VetorPlot`, though it does not complain, does not get any values:                   N[Grad[ϕ[{x, y, 0}], {x, y}] /. {x -> 1, y -> 2}]      > `{-193.335 + 2.70673*10^9 Derivative[1][Abs][-139999.] + 4.22919*10^7 > Derivative[1][Abs][560001.], -386.67 + 38818.9 Derivative[1][Abs][2.]}` It leaves a derivative in there.


title: How to use Assumptions in a Series Expansion

text: I want to series expansion the expression $\frac{1}{2} \left(e_1+e_2-\sqrt{e_1^2-2e_1e_2+e_2^2+4V_{12}^2} \right)$ up to second order in $V_{12}$ using the assumption $e_1>e_2$. So I tried               Series[1/2 (e1 + e2 - Sqrt[e1^2 - 2 e1 e2 + e2^2 + 4 V12^2]), {V12, 0, 2},      Assumptions -> e1 > e2] // FullSimplify      But there is still $\sqrt{(e_1-e_2)^2} $ terms in the results. What should I do to make the assumption $e_1>e_2$ work?


title: ?function-name does not return function help

text: For some reason when I use ? _function-name_ to ask for help on a function, I got a very clinical breakdown of that function with its options and attributes instead of the blurb about the function: ![?Function](http://i.stack.imgur.com/QjGUv.png) To fix this, I evaluated `ClearSytemCache[]`, killed the kernel (Evaluation > Quit Kernel > Local), and restarted _Mathematica_ \-- it's possible that I had to do only one of these steps -- after which the problem went away. ![?Function fixed](http://i.stack.imgur.com/4z7Eo.png) However, I was just curious about what brought it on.


title: How to determine numeric equivalent of Tiny, Small, etc. image sizes for Graphics?

text: Is there a way to find the numeric equivalents of `Tiny`, `Small`, `Medium`, and `Large` for for `ImageSize`? In other words, what are the integers `t`, `s`, `m`, and `l` such that, for `Graphics` objects, the directives               ImageSize -> t     ImageSize -> s     ImageSize -> m     ImageSize -> l      are equivalent, respectively, to the directives               ImageSize -> Tiny     ImageSize -> Small     ImageSize -> Medium     ImageSize -> Large      ?


title: How to nest the output of FindRoot in a table of Derivative evaluations?

text: I am using ParametericNDSolveValue to numerically solve an ODE system, which I then use to find the definite integral of one of the variables in the solution for different values of a parameter. Here is a simpler (and faster!) version of my code:               eqns={y''[t] + d y[t] == 3 a Sin[y[t]], y[0] == y'[0] == 1};     pfun[din_]:=ParametricNDSolveValue[eqns/.{d-> din}, With[{b=1},b NIntegrate[y[t],{t,0,5}]],{t,0,5},{a}];      which if plotted for three values of "d" looks like this ![enter image description here](http://i.stack.imgur.com/aDPye.png) I am using FindRoot to find the "a" values at which these curves meet the line y=3.               Table[a /. FindRoot[pfun[din][a] == 3.0, {a, 0, 2}], {din, 1, 3, 1}]      What I would like to do next is find the value of the first derivative at each of these points (with the ultimate aim of plotting the derivatives w.r.t. the d parameter values used to make each curve). What I'm stuck on is: do I (1) first generate a list of "a" values using the code above and then somehow plug each element into code like this               Evaluate[Table[Derivative[1][pfun[din]][a], {din, 1, 3, 1}]]      (I'm not clear how to get the derivative function to call a subsequent element in the list for each din value). or do I (2) embed the FindRoot function somehow into the derivative function? (I don't know how to do this, or do I use Table or Map?)


title: What is the principle behind Dispatch?

text: I want to know what `Dispatch` actually does to rule the list. Why is it so fast? The documentation says > Dispatch generates a dispatch table which uses hash codes to specify which > sets of rules need actually be scanned for a particular input expression. What is a hash table? How does it specify which sets of rules need actually be scanned for a particular input expression? What about `DeleteCases`? Since it is fast too, Does it use hash table too?


title: Can a LatticeData image be displayed in a space filled fashion

text: I'd like a FaceCenteredCubic image as in the in LatticeData docs, but space packed, and cropped on all the boundaries, so that it illustrates the geometry of the calculation that leads to the $\pi/\sqrt{18}$ density result. The call that produces the plot is               LatticeData["FaceCenteredCubic", "Image"]      but this has small spheres, and probably doesn't have a way to crop on the boundaries. I see that there's a PackingRadius listed in the documentation. I thought it might be possible to use the PackingRadius property, to display the spheres in the lattice in a space packed fashion (so that they touch), but that wouldn't handle the cropping part of the problem. Is there any easy way to do this, perhaps using the lattice data to draw spheres using the Graphics drawing options, and then using the various ViewAngle type options to crop that appropriately?


title: How can I make CurrentValue for font characteristics pick up the font of the output not the input cell?

text: The command `CurrentValue` (documentation) allows you to access various properties of fonts, such as x-height, line height, and various measures of width such as n-width and m-width. This has obvious applications in determining appropriate sizes of objects so that the text contained within them fits. However it is not obvious how to pick up the characteristics of the font of styled output. For example, the following uses the width of the font in the input cell, not the selected style in the code (example adopted from this question).                Framed @ Graphics[Text[       Style["how quickly daft jumping zebras vex",         FontFamily -> "Verdana", FontSize -> 20]],       ImageSize -> CurrentValue["FontNWidth"]*35]      ![enter image description here](http://i.stack.imgur.com/CnHLj.png) If I select the whole input cell (by its bracket, not just the text) and change the font, it works better, although of course `"FontNWidth"` is not a perfect indicator of actual width of characters: ![enter image description here](http://i.stack.imgur.com/cMrfw.png) How can I concisely get the `CurrentValue` dimensions from an arbitrarily chosen font?


title: How to improve the accuracy of this Monte Carlo simulation

text: A friend of mine went on an interview and he was asked to calculate the angle between the hour hand and minute hand of an analog clock when the time was **3:15**. Arguably, this is a trivial problem that can be easily solved analytically. 15 minutes is the 1/4th of an hour, and an hour is the 1/12th of a full circle, therefore the angle is $(1/4)\times(1/12)\times 360 = 7.5 \deg$. I was wondering whether a Monte Carlo simulation could do well. **EDITED** : As suggested by @kuba here is the image of a **"real"** clock hopefully at **3:15** precisely. ![enter image description here](http://i.stack.imgur.com/oSIqP.png) Source: http://etc.usf.edu/clipart/33000/33069/clock-03-15_33069.htm My code that follows operates on the mask of an **ideal** clock at **3:15** (angle between two hands at `7.5` degrees) and **not** on a mask generated by the above image. It takes more than $10^6$ points to derive an answer of $\sim 7 \deg$. Could the experts here improve the accuracy of the simulation?               ClearAll["Global`*"];     (* Generate some random points. Use 0.98 instead of 1.00 or otherwise        some points will be half-inside the circle and half-outside.        This will hurt our results in left untreated. *)     points = Show[       Graphics[{Pink,         Point /@          Select[           Partition[RandomReal[{-1, 1}, 10000], 2],           ({a, b} = #; a^2 + b^2 <= 0.98) &]}]]      ![enter image description here](http://i.stack.imgur.com/oCrJb.png)               (* In reality the mask below should have been generated by a real clock *)     disk = Graphics[{Pink, Disk[{0, 0}, 1, {0, 2π - 7.5π/180}]}]      ![enter image description here](http://i.stack.imgur.com/HI1TE.png)               finalImage = ImageSubtract[disk, Show[disk, points]]      ![enter image description here](http://i.stack.imgur.com/wmdCB.png)               (* Count the number of points inside the slice and outside the slice.        If I use "Count" as the property in ComponentMeasurements[], I get worse results.        EDITED: As noted by @MichaelE2 the following statement for 'outArea'        might calculate the whole rectangular area and not only the points! *)     inArea  = Last /@ ComponentMeasurements[finalImage, "Area"] // Total;     outArea = Last /@ ComponentMeasurements[points, "Area"] // Total;          (inArea/outArea) * 360 // N      **EDITED** : With the point set by @DanielLichtblau, I get $\sim 7.3$ degrees with $10^4$ points! `finalImage` looks like this: ![enter image description here](http://i.stack.imgur.com/MCGzg.png)


title: Functions that remember their values

text: Can someone explain what is going on with the following ...               func[y_] := func[y] = (Print["Hello world !!!"];)          func[1]      > Hello world !!!               func[2]      > Hello world !!!               func[1] (*nothing printed*)          func[2] (*nothing printed*)      As I understand it () are used so the function remembers its values, but as you see when I repeat `func[1]`, nothing. If I take out the `y` in `f[y]`, it prints. If I define the function as `f[y_] := (...)` (without `f[y] =` ), it prints. I'm sure there is a simple explanation, any help is appreciated.


title: ListPlot multiple datasets over same x-values

text: Is there a better way to enter my data into a list plot?               ListPLot[{{{1.1, 2.2}, {2.3, 4.3}, {2.9, 5.5}},               {{1.1, 2.1}, {2.3, 4.6}, {2.9, 5.9}},               {{1.1, 2}, {2.3, 4.8}, {2.9, 6.2}}}]      I think there should be a more efficient way, but cannot find it. I've read the documentation on `ListPlot` and `DataRange`.


title: Better code to find Narcissistic number

text: My code finding Narcissistic numbers is not that slow, but it's not in functional style and lacks flexibility: if $n \neq 7$, I have to rewrite my code. Could you give some good advice?               nar = Compile[{$},        Do[         With[{            n = 1000000 a + 100000 b + 10000 c + 1000 d + 100 e + 10 f + g,            n2 = a^7 + b^7 + c^7 + d^7 + e^7 + f^7 + g^7},           If[n == n2, Sow@n];           ],          {a, 9}, {b, 0, 9}, {c, 0, 9}, {d, 0, 9}, {e, 0, 9}, {f, 0, 9}, {g, 0, 9}],        RuntimeOptions -> "Speed", CompilationTarget -> "C"        ];          Reap[nar@0][[2, 1]] // AbsoluteTiming          (*{0.398023, {1741725, 4210818, 9800817, 9926315}}*)


title: Expected sum of largest 3

text: I pick 4 numbers from the Uniform Distribution. I need the expected value of the sum of the 3 largest. I am pretty sure that the answer is 9 / 5 which agrees with a simulation. I would like to get mathematica to do this. I have tried this:               Assuming[a >= b >= c >= d,        Expectation[a + b + c, {a, b, c, d} \[Distributed] UniformDistribution[{{0, 1},{0, 1}, {0, 1}, {0, 1}}]]]      which returns 3 / 2. What am I doing wrong?


title: Linear interpolation of a list between periodic anchorpoints

text: I have a list of the form:               list = {1,1,1,2,2,2,3,3,3,4,4,4,7,7,7,19,19,19};      Where we can see that there are an ordered set of integer values that repeat themselves some fixed number of times N. Is there a nice one-liner to transform this list into something like:               transformedList = {1,1+1/3,1+2/3,2,2+1/3,2+2/3,3,3+1/3,3+2/3,4,4+1/3,4+2/3,7,7+1/3,7+2/3,19,19+1/3,19+2/3}      Where we essentially choose each new element we come by in the list as an anchorpoint, and replace the repeats of that element as equispaced points along a line the anchor integer value and the next higher integer?


title: Draw graph wherein vertices are ArrayPlots

text: I need to place ArrayPlots in the vertices of graph. i.e. in graph                Graph[{1->2, 2->3, 3->1}]      I have to replace vertex 1 with ArrayPlots[{{0,0,1}}] and so on basing on the following list               {{1,{0,0,1}},{2,{0,1,0}},{3,{1,1,0}}}


title: implement the ZOH in mathematica

text: well I'm trying to implement the ZOH in Mathematica, but I can't. Take a look, this is my script:               utt[t_] :=        Sum[If[k <= t < k + 1,          k*T*UnitStep[k*T] - (k*T - 6 T)*UnitStep[k*T - 6 T], 0], {k, 0,          10}];      And when I plot: ![zoh](http://i.stack.imgur.com/ZkhYx.jpg) the problem is that in wanting to continue working with the new function you can not, because this is a function of the conditioning "if", please look at the output of utt [t]:               If[0 <= t < 1, k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T],        0] + If[1 <= t < 2,        k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T], 0] +       If[2 <= t < 3, k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T],        0] + If[3 <= t < 4,        k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T], 0] +       If[4 <= t < 5, k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T],        0] + If[5 <= t < 6,        k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T], 0] +       If[6 <= t < 7, k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T],        0] + If[7 <= t < 8,        k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T], 0] +       If[8 <= t < 9, k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T],        0] + If[9 <= t < 10,        k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T], 0] +       If[10 <= t < 11, k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T],        0]      I want an answer in one expression (not "if"), in order to continue working with her freely. If anyone can calculate the ZOH otherwise, I would appreciate forever. Thanks and sorry for my bad English.


title: Plotting velocity vectors for pressure driven pipe flow

text: So I find the velocity profile for Pressure driven pipe flow and it looks like: $$u = \frac{h^2}{2 \mu} \frac{\mathrm{d}P}{\mathrm{d}x}\left[1 - \left(\frac{y}{h}\right)^2\right]$$ Here, a fluid flows between two walls separated by a distance $h$. The pressure gradient $\mathrm{d}P/\mathrm{d}X$ drives the flow. The vertical coordinate axis is $y$. How do I plot this as a velocity profile (`VelocityPlot`)? When I try do plot this with               μ = 0.02; Px = -0.5; h = 1.0;     VectorPlot[{(h^2/(2 μ)) Px (1 - (y/h)^2), 0}, {x, 0, 3}, {y, -3, 3}]      I get the following figure: ![enter image description here](http://i.stack.imgur.com/9kLPr.jpg) However, the velocity profile is parabolic and should look like: ![enter image description here](http://i.stack.imgur.com/xBl12.png) I apologize for the low quality vector plot from ansys but what went wrong with my `VectorPlot[...]` definition?


title: Border on part of ArrayPlot

text: I need to outline with border the group of cells in ArrayPlot. More precisely in my case I would like to outline all blocks of two black squares in the following line.               ArrayPlot[{{0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1}}, Mesh -> True]


title: Use Style on list elements

text: I have a list like this:               list = {0, 0, 0, 1, 1, 1}      I want to color all the 0's in red, but I dont want to count through all the elements, like in my solutions, which seems awefully complicated:               Table[If[list[[x]] == 0, Style[list[[x]], Red], list[[x]]], {x, 1, Length@list}]      How else could I do this without using Table? In other words, a simpler way, if possible.


title: How can the behavior of InterpolationOrder->0 be controlled?

text: In `ListPlot` and `Interpolation`, the option `InterpolationOrder->0` uses two different conventions. `Interpolation` gives the y-value from the nearest _greater_ x-value.               Plot[Quiet@Interpolation[{{0,0},{1,1},{2,2}},InterpolationOrder->0][x],{x,-1,3}]      ![enter image description here](http://i.stack.imgur.com/fJmLg.png) `ListLinePlot` gives the y-value from the nearest _smaller_ x-value.               ListLinePlot[{{0,0},{1,1},{2,2}},InterpolationOrder->0,PlotRange->{{-1,3},All}]      ![enter image description here](http://i.stack.imgur.com/Gl11k.png) How can I make `Interpolation` use the `ListPlot` convention?


title: Limitations of ParametricNDSolve family w.r.t objective functions

text: **Observation:** I can see even for very simple modification in case of an scalar objective involving an definite integral in time `ParametricNDSolve` fails. Here is an example!               eqns = {y''[t] + y[t] == 3 a Sin[y[t]], y[0] == y'[0] == 1};     pfun =ParametricNDSolveValue[eqns,Integrate[y[s] - a s, {s, 0, 5}], {t, 0, 5}, {a},     Method -> {"ParametricSensitivity" -> "ForwardSensitivity"}];     pfun[1.5]      > Meaningless output! Same kind of output for `pfun'[1.5]` but from `pfun''[1.5]` onwards for higher derivatives we get numerical values which I guess are totally wrong. However everything will be fine if one uses `Integrate[y[s], {s, 0, 5}]`! So I tried `{"ParametricSensitivity" -> "AdjointSensitivity"}` which is most suitable for integrated objective functions. Again failure but this time for both the cases. We get the following error > ParametricNDSolveValue::adjsens: The adjoint sensitivity method cannot be > used for the output function {t,0,5}. It can only be used for output > functions that are at a particular time or are a definite integral over > time. >> I feel this is a major inconsistency of implementation internal. Using `Trace` I found some esoteric `Integrate`ImproperDump`` and`Internal`DependsOnQ`. **What should be`pfun[1.5]`:** We know               Distribute[Integrate[y[s] - a s, {s, 0, 5}], Plus] ===      Integrate[-a s, {s, 0, 5}] + Integrate[y[s], {s, 0, 5}]      > True So we first can find `pfun[1.5]` using               eqns = {y''[t] + y[t] == 3 a Sin[y[t]], y[0] == y'[0] == 1};     pfun = ParametricNDSolveValue[eqns,      Integrate[y[s], {s, 0, 5}], {t, 0, 5}, {a},      Method -> {"ParametricSensitivity" -> "ForwardSensitivity"}];     (pfun[1.5] + Integrate[-a s, {s, 0, 5}]) /. a -> 1.5      > -7.86673 and the first order sensitivity will be               (pfun'[1.5] + D[Integrate[-a s, {s, 0, 5}], a]) /. a -> 1.5      > -7.87591 Crosschecking the first order sensitivity below!               fun1[aval_?NumericQ] :=NIntegrate[Block[{a = aval},      Evaluate@(y /. First@NDSolve[Evaluate@eqns, y, {t, 0, 5}])[t] -a t] , {t, 0, 5}];     Needs["NumericalCalculus`"];     ND[fun1[x], x, 1.5]      > -7.87604 Pretty much as expected. **Question:**   * It will be great to know if we can use `ParametricNDSolve` family to find parameter dependency of integrated objective like the following: $$ G(p)=\int_a^{b} g(y(s),s,p) \,ds$$ where $g$ is a function of the dependent variable $y(s)$ of the underlying differential equation system and $p$ represents the parameter with respect to which the sensitivity $\frac{dG}{dp}$ is sought (i.e `a` in the above example).   * Also why `{"ParametricSensitivity" -> "AdjointSensitivity"}` fails in the above example? For some math reference check here. BR


title: What range of ports do remote kernels use?

text: I'm trying to run a remote kernel, but my local system administrator is wary of opening up ports for incoming connections. > Is there are particular range of ports that Mathematica uses to communicate > with remove kernels? Even if it's a wide range (e.g. 40000-70000), such an answer would still be helpful to me.


title: NExpectation behaves oddly with EmpiricalDistribution

text: Note: this is fixed in version 9. * * * My question concerns the usage of `NExpectation` and `Expectation` and why I see the behavior I see in the following example. First take some data and derive an `EmpiricalDistribution`:               data = {4, 104, 96, 80, 22, 76, 106, 18, 98, 44, 112, 78, 50, 120, 2, 6,              100, 10, 68, 80, 42, 66, 100, 58, 4, 76, 18, 102, 6, 16, 52, 32, 62,              36, 18, 4, 54, 98, 38, 74, 16, 22, 102, 2, 2, 4, 22, 72, 100, 82, 48,              16, 34, 44, 130, 50, 48, 74, 60, 96, 8, 118, 30, 58, 84, 4, 70, 66,              40, 14, 92, 68, 42, 56, 56, 16, 40, 12, 22, 26, 98, 4, 80, 100, 36,              88, 48, 26, 28, 94, 22, 26, 78, 16, 52, 8, 10, 2};          dist = EmpiricalDistribution[data];      You can plot `PDF`s and `CDF`s of the distribution:               Row[{DiscretePlot[PDF[dist, x], {x, data}, Joined -> True, ImageSize -> 300],           DiscretePlot[CDF[dist, x], {x, 0, Max@data, 1}, Joined -> True, ImageSize -> 300]}]      They look like this: ![PDF & CDF plots](http://i.stack.imgur.com/ft7hC.png) That covers the background. Now execute the following and it gets a little odd:               Expectation[X \[Conditioned] X > 4, X \[Distributed] dist]     NExpectation[X \[Conditioned] X > 4, X \[Distributed] dist]     N[Expectation[X \[Conditioned] X > 4, X \[Distributed] dist]]          620/11     NExpectation[X \[Conditioned] X > 4, X \[Distributed]DataDistribution[<<"Empirical">>, {51}]]     56.3636      So, what gives? How come `NExpectation[...]` doesn't calculate an answer, but `N[Expectation[...]]` does? Clearly, `Expectation` handles `EmpiricalDistribution` without a problem. One would think that `NExpectation` would as well. Doesn't this seem odd? Just hoping that understanding why Mathematica does this might yield additional insights into Mathematica itself.


title: Extracting the coordinates of a point of interest from a ListDensityPlot

text: How can I extract coordinates from a list density plot. Example plot of interest: ![1](http://i.stack.imgur.com/VAcSs.png) I need to place two points on either side of the center white circle and calculate the distance between them. My idea was to use two locators that gives their dynamic coordinates and connect a straight line between them. And calculate the different between them and output it to the user. How can I do this with? So far the only thing I figured out is to use a locators as a line to give me dynamic position.               Module[{v1 = {0, 0}, v2 = {2, 0}},       Graphics[{Locator[Dynamic[v1]], Line[{Dynamic[v1], Dynamic[v2]}],         Locator[Dynamic[v2]]}, PlotRange -> 3, Frame -> True]]      Screenshot of output: ![2](http://i.imgur.com/Ql0xoeF.png)


title: NMaximize problem

text: Could anybody explain to me why the following code fails ?                Reap[      NMaximize[{x1^2 + x2^2 + x3^2, 0.001 <= x1 <= 0.002,         0 <= x2 <= 0.002, 1 <= x3 <= 10, x3 \[Element] Integers }, {x1, x2,         x3}, Method -> "SimulatedAnnealing",        EvaluationMonitor :> Sow[{x1, x2, x3}]]      ]      In fact it outputs :               {{-\[Infinity], {x1 -> Indeterminate, x2 -> Indeterminate,         x3 -> Indeterminate}}, {}}      If i put x1's lower bound to 0 then it works but it uses only 0 values for x1 I suppose it has something to do with the integer x3. Thanks in advance.


title: Graph from binary matrix (not adjacency) respecting the original matrix positions

text: ![What to do](http://i.stack.imgur.com/pTuzi.png) I have a binary matrix. My objective is to connect every close (without "jump") elements with value equal to 1, but I must keep the point positions, just like it's shown at the image. Can somebody help me with it, please? Test input thanks to @hftf:               {{0,1,0,0,1,0,1,0},      {0,1,0,0,1,0,1,0},      {0,0,1,0,1,0,1,0},      {0,0,0,1,0,0,1,0},      {0,0,0,0,1,1,0,0},      {0,0,0,0,1,0,0,0}}


title: Extract the real components from a very large expression

text: Suppose I have a very long expression (>500,000 characters) which contains a mixture of real and imaginary terms. e.g `x = g*m*o*p*q*s*v + a*c*f*g*m^2*o*p*q*s*v + c*g*h*m^2*o*p*q*s*v - a*c*g*h*m^2*o*p*q*s*v - B*g*m*o*p*q*s*v*w - g*m*o*p*s*v*x - (1-I*Sqrt[3])*(2*g*o*p*s*v + 2*a*c*f*g*m*o*p*s*v) + 2*c*g*h*m*o*p*s*v + (1+I*Sqrt[3])*(2*g*p*q*v + m*g*f*q*m*o*s*v)...` etc. I would like to seperate the real and imaginery terms and work with the real terms only. I am using `ComplexExpand[Re[x],TargetFunctions->(Re)}]` but I keep getting the message 'No more memory available. Mathematica has shut down.Try quitting other applications and then retry'. Is there a better way to discard the imaginary terms and group the real terms together without this problem?


title: Plot data from txt file?

text: I have data in file.txt which can be expressed by 20000x11 matrix. I do not want to import all of these data. How can I plot graph of the column 1 & column 4?