Infinite expression encountered when simplifying ArcTan sums although the result is finite

If I attempt to simplify the sum `ArcTan[1/x] + ArcTan[x]` with               ArcTan[ Simplify[ TrigExpand[ Tan[ ArcTan[1/x] + ArcTan[x]]]]]      _Mathematica returns_ > >     During evaluation of In[103]:= Power::infy: Infinite expression 1/0 > encountered. >> >   >     During evaluation of In[103]:= Power::infy: Infinite expression 1/0 > encountered. >> >   >     During evaluation of In[103]:= Infinity::indet: Indeterminate expression   >                                     ComplexInfinity + ComplexInfinity > encountered. >> >   >     Indeterminate >   even though the result is $\pm\pi/2$. The error messages occur during the call to `TrigExpand`, and I can't think of a way to avoid them. Also, I tried in vain the assumption `x > 0`, so that the result is not ambiguous. The full expression to simplify is               (1/(16 a))Q^2 (-16 ArcTan[r1/a] + 1/(2 r1^2)(16 \[Pi] r1^2 + 32 r1 a     + \[Pi] a^2 + 8 \[Pi] r1^2 Log[r1] + 4 ArcTan[a/r1] (7 a^2 - 8 r1^2 Log[r1])     - 2 ArcTan[r1/(2 a) - a/(2 r1)] (a^2 + 8 r1^2 Log[r1])))      I know that the `Log`s vanish after simplification and I was trying to prove this with Mathematica. It is possible if I split the expression into several parts, then simplify with the transformation rule for the addition of `ArcTan`, because none of the other methods work in this case, but the transformation rule aborts when it meets an infinite expression.


How to replace all occurrences of an element in a list?

Consider the following:               list={1,2,2,2,3};      I would like to replace all `2` with the string "Test". `Replace[list,2->"Test"]` does not do it. Result must be: `{1,"Test","Test","Test",3}`.


FullSimplify does not work on this expression with no unknowns

I can't reproduce this simple example from Habrat, 2010 (" _Mathematica_ : a Problem-Centered Approach"). It is supposed to demonstrate the functionality of `FullSimplify`, however I can't make it work in _Mathematica 9_. When I try this:               FullSimplify[ Cot[ (5 Pi)/22 ] + 4 Sin[ (2 Pi)/11 ]]      _Mathematica 9_ returns the input unchanged:               Cot[ (5 Pi)/22 ] + 4 Sin[ (2 Pi)/11 ]      As shown in the book however, I would rather have expected `Sqrt[11]`. On the other trying               FullSimplify[ Cot[ (5 Pi)/22 ] + 4 Sin[ (2 Pi)/11 ] == Sqrt[11] ]      _Mathematica 9_ returns               True      so why not return `Sqrt[11]` in the first place?


MathGraphicsJPanel no output

I am trying to create a Java frontend for Mathematica. Following examples from J/Link guide and looking around the API manual I came up with this code:               public class Mathematica extends MathJFrame {     public Mathematica(String[] args) {         initComponents();               try {             ml = MathLinkFactory.createKernelLink(args);         } catch (MathLinkException e) {             System.out.println("Fatal error opening link: " + e.getMessage());         }              try {             ml.discardAnswer();                  ml.evaluate("2+2");             ml.waitForAnswer();                  int result = ml.getInteger();             System.out.println("2 + 2 = " + result);                  graphic1.setLink(ml);             graphic1.setMathCommand("Plot[x,{x,0,1}]");             graphic1.repaintNow();             System.out.println(graphic1.getMathCommand());              } catch (MathLinkException e) {             System.out.println("Fatal error opening link: " + e.getMessage());         } finally {             ml.close();         }         private KernelLink ml = null;     }      Graphics.java:               public class Graphic extends MathGraphicsJPanel {        public Graphic() {             }     }      I know the link is working because I get 2 + 2 = 4 displayed in console but the panel where the graph output is expected is empty. Also, does J/Link not ship with sample programs anymore? Thanks for any suggestions.


Find the value by using FindRoot command

The equation x^4-3 x^3 = cos(3x)+3 has two real solutions on the interval from -10 to 10. Lets call these two solutions r and s. Use Mathematica's FindRoot command to find r and s. Now let M equal the sum of these two solutions, M=r+s. Enter the value for M in the space provided below.


Behavior of Reduce with variables as domain

When using `Reduce`, I accidentally put a set of variables as the domain. To my surprise, it not only seems that `Reduce` expects this sort of input, but I found the output to be very useful. Let me explain with an example. In a system of equations with multiple variables, I am often interested in the conditions placed on certain variables. Suppose I have `x + y == 1 && x y == 2` and want to know what conditions this places on `x`. Normally, I would do this:               In[1]:= Reduce[x + y == 1 && x y == 2, x]     Out[1]= (y == 1/2 (1 - I Sqrt[7]) || y == 1/2 (1 + I Sqrt[7])) && x == 1 - y      This output is not in the best form for what I want. Namely, `Reduce` has given me specific values for `y` and then expressed `x` and a function of `y`. I would have preferred if this had been the other way around, then I would have exactly what I want after ignoring `y`. (Oddly enough, `Reduce` gives specific values for `x` and expresses `y` as a function of `x` if you ask it to solve for `y`.) Recently, I was working with a system of equation like this and accidentally put the other variables (in this case, just the variable `y`) as the domain.               In[2]:= Reduce[x + y == 1 && x y == 2, x, {y}]     Out[2]= x == 1/2 (1 - I Sqrt[7]) || x == 1/2 (1 + I Sqrt[7])      Fantastic! This is exactly what I was looking for: the constraints placed on `x`. As far as I can tell, this behavior is not described in the documentation for `Reduce`. ## Question: Is this expected behavior from `Reduce`? If so, where is this behavior described?


Is Mathematica really getting this limit wrong?

I'm trying to calculate: $$ \lim_{\beta \to \infty} \tanh \left( \beta A \right) = \mathrm{sgn} \left( A \right) $$ for $A \in \mathbb{R}$, $\mathrm{sgn} \left( \# \right)$ being the sign function. The problem is that Mathematica evaluates the integral to something different:               In[1] := Assuming[Element[A, Reals], Limit[Tanh[\[Beta]*A], \[Beta] -> Infinity]]     Out[1] := 1      which is clearly not true for negative values of A. Am I overlooking something really obvious? Is it a bug?


Combining graphics & lists / tables

I have: ![enter image description here](http://i.stack.imgur.com/9kOuC.gif) created with:               With[{stdOpt = {InterpolationOrder -> 0,      GridLines -> {Range[10], Range[10]},      GridLinesStyle -> Directive[GrayLevel[0.8], Dashed],      Joined -> True, AspectRatio -> 1}},      ListPlot[{0}, stdOpt, PlotRange -> {{0, 10}, {0, 10}}, Axes -> False,     Frame -> False, Epilog -> {          Black, Opacity[1.0],          Text[Style[1, Large, FontFamily -> "Times"], {0.5, 0.5},       FormatType -> Bold],     Text[Style[2, Large, FontFamily -> "Times"], {0.5, 1.5},       FormatType -> Bold],     Text[Style[3, Large, FontFamily -> "Times"], {0.5, 2.5},       FormatType -> Bold],     Text[Style[4, Large, FontFamily -> "Times"], {0.5, 3.5},       FormatType -> Bold],     Text[Style[5, Large, FontFamily -> "Times"], {0.5, 4.5},       FormatType -> Bold],     Text[Style[6, Large, FontFamily -> "Times"], {0.5, 5.5},       FormatType -> Bold],     Text[Style[7, Large, FontFamily -> "Times"], {0.5, 6.5},       FormatType -> Bold],     Text[Style[8, Large, FontFamily -> "Times"], {0.5, 7.5},       FormatType -> Bold],     Text[Style[9, Large, FontFamily -> "Times"], {0.5, 8.5},       FormatType -> Bold],     Text[Style[10, Large, FontFamily -> "Times"], {0.5, 9.5},       FormatType -> Bold]          }]]      and I would like to place (& correctly align) a column of numbers (from pre- made lists) for each of the 10 columns (rather than the manully placed numbers as they appear above).


ReplaceAll performance problem: packed arrays on the LHS are unpacked when the RHS is too long

The following is one of the most mysterious performance problems I encountered and came up while extending the `booleval` function mentioned here. I am looking for a workaround since the whole purpose of writing `booleval` was to increase performance. ### The problem `ReplaceAll` will unpack packed arrays that appear on its left-hand-side if the right-hand-side contains more than rules. Example:               In[1]:= On["Packing"]          In[2]:= AbsoluteTiming[      Range[1000000] /. {x -> 0, a -> 1, b -> 2, c -> 3, d -> 4, e -> 5,          f -> 6, g -> 7, h -> 8, i -> 9(*,j -> 10*)};      ]          Out[2]= {0.003741, Null}      Up to here it works fine. Now let's uncomment the last rule to have 11 rules in total.               In[3]:= AbsoluteTiming[      Range[1000000] /. {x -> 0, a -> 1, b -> 2, c -> 3, d -> 4, e -> 5,          f -> 6, g -> 7, h -> 8, i -> 9, j -> 10};      ]          During evaluation of In[3]:= Developer`FromPackedArray::punpack1: Unpacking array with dimensions {1000000}. >>          Out[3]= {0.655815, Null}          Developer`FromPackedArray::punpack1: Unpacking array with dimensions {1000000}. >>      This was very frustrating to debug when I encoutered a performance problem because performance was only bad when I put my code in a function. Originally I had code similar to this:               Unevaluated[Range[1000000]] /. {x -> 0, a -> 1, b -> 2, c -> 3, d -> 4, e -> 5, f -> 6, g -> 7, h -> 8, i -> 9, j -> 10}      The `Unevaluated` prevents unpacking without preventing `ReplaceAll` from working. I orignally needed `Unevaluated` for reasons unrelated to this problem. Now let's put this into a function:               In[46]:=      ClearAll[fun]     fun[arg_] := Unevaluated[arg] /. {x -> 0, a -> 1, b -> 2, c -> 3, d -> 4, e -> 5, f -> 6, g -> 7, h -> 8, i -> 9, j -> 10}          In[48]:= AbsoluteTiming[fun[Range[1000000]];]          During evaluation of In[48]:= Developer`FromPackedArray::punpack1: Unpacking array with dimensions {1000000}. >>          Out[48]= {0.608700, Null}      Now the problem is back, but only if the packed array is passed to the function as an argument, not if it's part of the function definition. ### Question Why does `ReplaceAll` unpack like this? More importantly, is there a workaround for the unpacking that I can apply in `booleval`? The `Unevaluated` workaround won't work when I package up the code as a function.


Problem importing URL with Greek characters

I'm considering buying a car. So I thought why not make a web-crawler in _Mathematica_ to pile-up car data? Brilliant idea. Then I found this Greek website, gocar.gr, which just so happens to have all the data I need in a convenient form, with URLs following a very consistent progression:               www.gocar.gr/cars/BRAND/MODEL/EDITION      e.g. `www.gocar.gr/cars/OPEL/MOKKA/1.7_CDTi_Edition_/`. The problem is when the model or edition contains Greek letters (but not the brand? Oh wait, there _are no_ Greek car brands), e.g. `www.gocar.gr/cars/BMW/ΣΕΙΡΑ_3/`, in which case `Import["URL", "Data"]` fails with a `FetchURL::conopen` error. It seems to me that this is some kind of encoding problem (it's consistent with Greek characters appearing in the URL and everything else works). I've seen the -kind of- relevant questions about copying non-Unicode text (this and this), but my problem is staying **within** _Mathematica_ , not copying something out of it (which, by the way, works fine). **So, to reproduce:**               Import["http://www.gocar.gr/cars/BMW","Data"]      works, but               Import["http://www.gocar.gr/cars/BMW/ΣΕΙΡΑ_3","Data"]      doesn't. And my question is: any ideas? **Additional info:**   1. This is a Windows 7 / 64-bit computer; formats and location are set to Greek/Greece, Greek keyboard is installed (duh), display language is set to English, _Mathematica_ version 8.   2. I also tried going directly through the JLink with a Java module I found in some other post (can't find it right now; may credit go where credit is due):              Needs["JLink`"]          httpGet[url_String] :=JavaBlock @     Module[{http, get},             http = JavaNew["org.apache.commons.httpclient.HttpClient"];            get = JavaNew["org.apache.commons.httpclient.methods.GetMethod", url];            http @ executeMethod[get]; get @ getResponseBodyAsString[]]      followed by:              ImportString[httpGet[URL - HERE], {"HTML", "Data"}]      No luck. Thank you for reading my rant.


How to define function that can change patterns

Given time series data as follows:               data =        {{{2011, 1, 13}, 10}, {{2011, 2, 14}, 17}, {{2011, 3, 15}, 20},         {{2012, 1, 16}, 30}, {{2012, 2, 17}, 40}};      Evaluating               Cases[data, {{year_, month_, day_}, val_} /; year == 2011]       will return the data that are in year 2011. Are there any ways that I can define a function that can change the criteria of matching patterns? For example,               TimeSelection[data_, pattern_] := Cases[data, {{year_, month_, day_}, val_} /; pattern]        If the pattern is `month == 2`, the return will only be the data in February.


FindFit for dimension reduction?

Given an n-dimensional function, can I use FindFit to produce an approximate (n-k)-dimensional function?   Here is a simplified illustration of what I am trying to do. I have $$f(x,a,b,\mu,\sigma) = \frac{g(x,a)\,g(x,b)}{\sigma\sqrt{1+x^2}}\phi(\frac{x-\mu}{\sigma})$$ where $\phi$ is the $\mathcal{N}(0,1)$ density, $a,b\in[-1,1]$, $\mu\in\mathbb{R}$, $\sigma\in\mathbb{R}^{*+}$ and $$ g(x,a) = \max(0, -ax+\sqrt{1-a^2}). $$ Here is the code to build such a function with Mathematica:               ND[x_]:= Exp[-x^2/2] / Sqrt[2*Pi]     G[x_, a_] := (-a*x + Sqrt[1 - a^2]) * UnitStep[(-a*x + Sqrt[1 - a^2])];     F[x_, a_, b_, m_, s_] := G[x, a] * G[x, b] * ND[(x - m)/s] / (s * Sqrt[1 + x^2])      I would like to approximate $f$ with the following Gaussian function $$g(x,\alpha,\beta,\gamma) = \frac{\alpha\gamma}{\sqrt{\pi}} \exp(-(\gamma x-\beta)^2)$$ where $\alpha,\beta,\gamma$ are functions of $a,b,\mu,\sigma$. So if I create a table               Flatten[Table[{x, m, F[x, a, b, m, s]}, {x, -15, 15}, {a, -1, 1}, {b, -1, 1}, {m, -1, 1}, {s, 0.125, 2, 0.125}]]       can I use FindFit to yield $\alpha, \beta, \gamma$ which will approximate $f$ ?


Why BarChart3D plot of Mathematica 9 is not working similar to Mathematica 7 version?

Mathematica 7               Needs["BarCharts`"]          BarChart3D[{{1, 6, 8}, {2, 7, 1}, {3, 1, 4}}]      ![enter image description here](http://i.stack.imgur.com/tujlt.gif) While in Mathematica 9 it is not plotting in this manner. Please help me to plot this fig. in Mathematica 9.


How to Check Spelling strings written inside input cells

Is it possible to check the spelling of strings? Strings are often used to show messages in my user interfaces, and I would like to have an automatic checking. Methods that export all the strings to a different notebook are also fine (if it can help). In this case, extracting things like \n would be a plus.


Integration and Fourier transform

I would like to calculate the distribution function from the characteristic function. There is a formula given as $$F_X(x)=\frac{1}{2}+\frac{1}{2\pi}\int_{0}^\infty \frac{e^{i w x}\phi(-w)-e^{-i w x}\phi(w)}{i w}\mbox{d}w$$ Actually, I want to evaluate $F_X(x)$ at some real number $b<0$. I wrote some codes in Mathematica with unfortunately no success. The codes give some results but they seem to be incorrect. Here are my codes:               opts = {Method -> {Automatic, "SymbolicProcessing" -> None}, AccuracyGoal -> 8}     b = -2;     f1[x_] := PDF[NormalDistribution[2, 2], x]     ff1[\[Omega]_] := InverseFourierTransform[f1[x], x, \[Omega]]     qn1 =1/2 + 1/(2*Pi) NIntegrate[(Exp[I \[Omega] b]*ff1[-\[Omega]] -Exp[-I \[Omega] b]*ff1[\[Omega]])/(I \[Omega]), {\[Omega], 0,Infinity}, Evaluate@opts]     NIntegrate[f1[x], {x, -Infinity, b}]      What I expect is $qn1$ to be equal to the last line of my code. But it just $0$. I cannot see the problem. Perhaps someone can? Thanks in advance


Is there a giant AND symbol/How to solve tons of equations simultaneously

$$\sum_{k=1}^na_k=a_1+...+a_n$$ $$\prod_{k=1}^na_k=a_1\cdot...\cdot a_n$$ $$\large{?}\small{_{k=1}^na_k=a_1~\&\&...\&\& ~a_n}$$ What in mathematica would allow me to index logical statements in an operation like AND or OR? I'm trying to solve a system of n vector equations, so I can't afford to type them all in manually into the argument of Solve[]. Someone suggested that I take the product of the equations, i.e. if $a_i=(x_i=y_i)$, then $$a_1~\&\&...\&\& ~a_n\leftrightarrow \prod_{k=1}^n(x_i- y_i)$$ However, $x_i,y_i$ are vectors, and even their lengths vary, depending on $i$. Does anyone know how to solve this issue?


Formatting Ticks and FrameTicks labels with a function

Is there a convenient way to format tick labels? In this example I would like to use the default Mathematica tick intervals, but simply convert the X axis labels to strings with "s" added. As you can see below, by default Mathematica shows six X axis labels, with three subticks, although for different plot ranges both can vary:               plotA = Plot[Sin[x], {x, 6, 16}, Frame -> True]      ![enter image description here](http://i.stack.imgur.com/0osxu.png) A basic function can be defined to add the "s" formatting, but it doesn't vary as the Mathematica range would. Adding subticks would be further work, and the upper X frame would have to be defined too, to match the intervals.               frametickfunction[xmin_, xmax_] :=      {#, ToString[#] <> "s"} & /@ FindDivisions[{xmin, xmax}, 6]          plotB = Plot[Sin[x], {x, 6, 16}, Frame -> True,      FrameTicks -> {{True, True}, {frametickfunction, True}}]      ![enter image description here](http://i.stack.imgur.com/0oXs5.png) It would be convenient if I could obtain the X axis specification produced in plotA, modify it, and use it in plotB. Is this possible, or are there other methods?


Result of NIntegrate ploting to list

I've been working on a project where I need to make two `Plots`. Those plots are of the form:               Plot[        NIntegrate[f[x],{x,0,r}],        {r,0,1}        ]     Plot[        NIntegrate[-f[x],{x,0,r}],        {r,0,1}        ]      Indeed one of the plots is just the minus the other and I'm wasting computational time doing both the numerical integrals. I then thought that I could create a list of the values of the first plot and then plot that list. Here's what I did:               s = {};     Plot[      Last[Last[        s = Append[s, {r, NIntegrate[f[x], {x, 0, r}]}]        ]],      {r, 0, 2}]     ListLinePlot[s/. {x_, y_} -> {x, -y}]      This however doesn't work the way I wanted. The problem is that aside the values given by `NIntegrate[f[x],{...}]` there are other values in the list `s`. Let me present a working example. Consider that the the function that I'm integrating is `f[x]=x`. Substituting in my code I get the following values for the list `s`:               {{0.0000408571, 8.34653*10^-10}, {4.08163*10^-8,        8.32986*10^-16}, {0.0392573, 0.000770569}, {0.0818167,        0.00334699}, {0.121556, 0.0073879}, {0.160515,        0.0128826}, {0.202777, 0.0205592}, {0.242218, 0.0293348}, {0.284962,        0.0406016}, {0.326926, 0.0534402}, {0.366069,        0.0670033}, {0.408515, 0.0834422}, {0.44814, 0.100415}, {0.486986,        0.118578}, {0.529134, 0.139991}, {0.568461, 0.161574}, {0.611091,        0.186716}, {0.652941, 0.213166}, {0.691971, 0.239412}, {0.734303,        0.2696}, {0.773815, 0.299394}, {0.816628, 0.333441}, {0.858662,        0.368651}, {0.897876, 0.403091}, {0.940392, 0.442169}, {0.980088,        0.480286}, {1.019, 0.519184}, {1.06122, 0.563096}, {1.10062,        0.605682}, {1.14332, 0.65359}, {1.18524, 0.702397}, {1.22434,        0.749505}, {1.26674, 0.802319}, {1.30632, 0.853242}, {1.34513,        0.904683}, {1.38723, 0.962206}, {1.42652, 1.01747}, {1.4691,        1.07913}, {1.50887, 1.13834}, {1.54785, 1.19793}, {1.59014,        1.26428}, {1.62961, 1.32782}, {1.67238, 1.39843}, {1.71437,        1.46954}, {1.75354, 1.53745}, {1.79601, 1.61283}, {1.83567,        1.68484}, {1.87454, 1.75695}, {1.91671, 1.8369}, {1.95607,        1.9131}, {2., 2.}, {0.0196287, 0.000192643}, {0.060537,        0.00183237}, {0.101686, 0.00517005}, {0.141036,        0.00994551}, {0.181646, 0.0164977}, {0.222498, 0.0247526}, {1.97803,        1.95631}, {0.00981436, 0.0000481608}, {0.0498972,        0.00124486}, {0.0917515, 0.00420917}, {0.131296,        0.00861927}, {0.171081, 0.0146343}, {0.212637, 0.0226073}, {1.96705,        1.93465}, {0.029443, 0.000433445}, {0.0711769,        0.00253307}, {0.111621, 0.00622962}, {0.150775,        0.0113666}, {1.98902, 1.97809}, {0.0049072,        0.0000120403}, {0.0445772, 0.000993565}, {0.0867841,        0.00376574}, {0.126426, 0.00799173}, {0.165798,        0.0137445}, {0.207707, 0.0215711}, {1.96156, 1.92386}, {0.0245358,        0.000301004}, {0.0658569, 0.00216857}, {0.106654,        0.0056875}, {0.145905, 0.0106442}, {1.98353, 1.96719}, {0.0147215,        0.000108362}, {0.0552171, 0.00152446}, {0.0343502,        0.000589967}, {1.99451, 1.98903}, {0.00245362,        3.01013*10^-6}, {0.0419173, 0.000878529}, {0.0843004,        0.00355328}, {0.123991, 0.00768685}, {0.163157, 0.01331}, {0.205242,        0.0210621}, {1.95881, 1.91848}, {0.0220823,        0.000243813}, {0.063197, 0.00199693}, {0.10417,        0.00542569}, {0.143471, 0.0102919}, {1.98078, 1.96174}, {0.0122679,        0.0000752512}, {0.0525571, 0.00138113}, {0.0318966,        0.000508696}, {1.99176, 1.98356}, {0.00736078,        0.0000270905}, {0.0269894, 0.000364214}, {0.0171751,        0.000147492}, {1.99725, 1.99451}, {0.00122683,        7.52557*10^-7}, {0.0405873, 0.000823665}, {0.0830586,        0.00344936}, {0.122773, 0.00753664}, {0.161836,        0.0130954}, {0.204009, 0.0208099}, {1.95744, 1.91579}, {0.0208555,        0.000217475}, {0.061867, 0.00191376}, {0.102928,        0.0052971}, {0.142253, 0.010118}, {1.97941, 1.95903}, {0.0110412,        0.0000609535}, {0.0512272, 0.00131211}, {0.0306698,        0.000470318}, {1.99039, 1.98083}, {0.00613399,        0.0000188129}, {0.0257626, 0.000331857}, {0.0159483,        0.000127174}, {1.99588, 1.99177}, {0.00368041,        6.77271*10^-6}, {0.0134947, 0.0000910539}, {0.00858757,        0.0000368732}, {1.99863, 1.99726}, {0.000613436,        1.88152*10^-7}, {0.0399223, 0.000796896}, {0.0824376,        0.00339798}, {0.122165, 0.00746208}, {0.161176,        0.0129888}, {0.203393, 0.0206844}, {1.95676, 1.91445}, {0.0202421,        0.000204871}, {0.061202, 0.00187284}, {0.102307,        0.00523338}, {0.141644, 0.0100316}, {1.97872, 1.95767}, {0.0104278,        0.0000543691}, {0.0505622, 0.00127827}, {0.0300564,        0.000451694}, {1.9897, 1.97946}, {0.0055206,        0.0000152385}, {0.0251492, 0.000316242}, {0.0153349,        0.00011758}, {1.99519, 1.9904}, {0.00306702,        4.70329*10^-6}, {0.0128813, 0.0000829644}, {0.00797418,        0.0000317937}, {1.99794, 1.99588}, {0.00184023,        1.69322*10^-6}, {0.00674739, 0.0000227636}, {0.00429381,        9.21838*10^-6}, {1.99931, 1.99863}}      So after the first digit of the list of lists reaches $2$ - the plot ranges from $r=0$ to $r=2$ - the list has other values... What am I doing wrong?


Changing the MouseAppearance on the entire notebook front end

Using `MouseAppearance` one can change the cursor image when passing over an expression. Is it possible to change the cursor image for the entire notebook front end (not just one expression within it)?


Impossible to bypass evaluation on returned values?

Following all the great advice on this other question, I'm now fluent with `HoldAllComplete` and `Unevaluated` on the **input** side of quote-type functions. I continued my investigations and produced the following attempt at a generic conversion from expression to captive (or quoted) expression:               ClearAll[captive];     SetAttributes[captive, HoldAllComplete];     captive[expr_ /; AtomQ @ Unevaluated @ expr] := expr     captive[head_[args___]] :=          {captive @ head} ~Join~ (captive /@ (Unevaluated @ {args}))     captive[x___] := Throw[{x}];      This is really great and handles **almost** all my scenarios. To wit, the following abbreviated test set produces the desired results               testSet = {"foo", foo, 12, 0, 3/4, 3.14, 2.72 + 3.14 I,        Infinity, {1, 2, 3}, {1, "a", b}, f, f[b], f[1, "a", b], f[{}],        f[{1, "a", b}], f[a][b], f[a][1, "a", b], f[a][{}],        f[a][{1, "a", b}], Hold[Plus @@ {}], Hold[Plus @@ {1, 2, 3}],        Plus @@ {1, "a", b}, 1 + "a" b, a + b*c};      as we can see in the output of               MapThread[List, {       InputForm /@ testSet,        InputForm /@ captive /@ testSet}] // TraditionalForm      (input on left, output on right) $\left( \begin{array}{cc} \text{foo} & \text{foo} \\ \text{foo} & \text{foo} \\ 12 & 12 \\ 0 & 0 \\ 3/4 & 3/4 \\ 3.14 & 3.14 \\ 2.72 + 3.14*I & 2.72 + 3.14*I \\ \text{Infinity} & \{\text{DirectedInfinity}, 1\} \\ \{1, 2, 3\} & \{\text{List}, 1, 2, 3\} \\ \{1, \text{a}, b\} & \{\text{List}, 1, \text{a}, b\} \\ f & f \\ f[b] & \{f, b\} \\ f[1, \text{a}, b] & \{f, 1, \text{a}, b\} \\ f[\{\}] & \{f, \{\text{List}\}\} \\ f[\{1, \text{a}, b\}] & \{f, \{\text{List}, 1, \text{a}, b\}\} \\ f[a][b] & \{\{f, a\}, b\} \\ f[a][1, \text{a}, b] & \{\{f, a\}, 1, \text{a}, b\} \\ f[a][\{\}] & \{\{f, a\}, \{\text{List}\}\} \\ f[a][\{1, \text{a}, b\}] & \{\{f, a\}, \{\text{List}, 1, \text{a}, b\}\} \\ \text{Hold}[\text{Plus} \text{@@} \{\}] & \{\text{Hold}, \{\text{Apply}, \text{Plus}, \{\text{List}\}\}\} \\ \text{Hold}[\text{Plus} \text{@@} \{1, 2, 3\}] & \{\text{Hold}, \{\text{Apply}, \text{Plus}, \{\text{List}, 1, 2, 3\}\}\} \\ 1 + \text{a} + b & \{\text{Plus}, 1, \text{a}, b\} \\ 1 + \text{a}*b & \{\text{Plus}, 1, \{\text{Times}, \text{a}, b\}\} \\ a + b*c & \{\text{Plus}, a, \{\text{Times}, b, c\}\} \\ \end{array} \right)$ I get into trouble, however, when a **return value** of a captive expression has a value. For instance, something as simple as               x = y     (* Out[10]= y *)     captive[x]     (* Out[11]= y *)      traceView2 reveals that captive inspects the Held input, as required, but that the evaluator apparently snatches it on the way out, and we don't get `x`, the desired result. ![captive fail](http://i.stack.imgur.com/86Ux2.png) In hindsight, I suppose I shouldn't expect more, since the ever-present term- rewriter (evaluator) is just the way MMA is supposed to work. On a guess, I tried               captive[expr_ /; AtomQ @ Unevaluated @ expr] := Unevaluated @ expr      which doesn't seem to make any difference (and, after reading the docs, I'm not surprised, since `Unevaluated` only seems to have an effect when supplied in a function-argument slot (see this other question in progress related to behavior of Unevaluated). I could do               captive[expr_ /; AtomQ @ Unevaluated @ expr] := Hold @ expr      or, better,               captive[expr_ /; AtomQ @ Unevaluated @ expr] := If[ValueQ @ expr, Hold @ expr,expr]      but now my output will always have `Hold` wrapping symbols that have values. I am beginning to suspect **that this may be the best I can do** , and I'm prepared to accept that answer (it means that my other function, which frees the captive, will have to have to release the particular holds inserted by this process (and not the Holds that were in the original source expressions!?! which means I probably have to mark them specially, but that's for another topic!) But before giving up, I thought I'd consult you all, who have already been so generous.


Equating matrices (or higher order tensors) element-wise

Say I have two matrices (or, as in my case, higher order tensors) $A,B$, and I want to solve the equation $A=B$. To do so , I need a list of equations that equate entry-wise the elements of $A$ and $B$ (then I can pass this list to `Solve` or `DSolve` or whatnot). Is there a simpler way to get this list than `Thread /@ Thread[A == B] // Flatten` Because this only works for matrices and I need to add another `Thread` for each rank. I'm sure some of you code-golfers will come up with somehting elegant and unreadable...


BVP system of nonlinear coupled ODEs

Here I am, trying to solve this system of coupled ODEs (up to a minus sign): $ u''=6u^5-(8+4a)u^3+(2+4a)u+\frac{2u((w^2-s)^2+bw)}{(u^2+c)^2}$ $ w''=\frac{4w^3-4bw+b}{u^2+c}$ with the boundary values being $u(0)=0, u(7)=1, w(0)=s, w(7)=-s$ and the parameters being $a=1/10, b=1/10, c=1/20, s=1.1$. Now I want to use the shooting method to solve these problems, but all I did in the interim was to write a code to solve the problem via conventional NDSolveValue:               eps = 1/10;     eps2 = 1/10;     eps3 = 1/20;     anti = 1.1;     {phi6m, phi6n} =       NDSolveValue[{D[u[x], x, x] == -(-6 u[x]^5 + (8 + 4 eps) u[x]^3 - (2 + 4 eps) u[x] +      (v[x]^4 - 2 *anti*v[x]^2 + eps2*v[x] + anti^2)*2 u[x]/(u[x]^2 + eps3)^2),      D[v[x], x, x] == (4 v[x]^3 - 4 *anti*v[x] + eps2)/(u[x]^2 + eps3),     u[0] == 0, Derivative[1][u][0] == 0.3, v[0] == anti,      Derivative[1][v][0] == -0.005}, {u, v}, {x, 0, 7}]      Plot[phi6m, {x, 0, 0.3}, PlotRange -> All]      Plot[phi6n, {x, 0, 0.3}, PlotRange -> All]


Trouble plotting a function constructed using NIntegrate and FindRoot

Here is my code:               f0[y_] := 1/(E^((1 + y)^2/2)*Sqrt[2*Pi])     f1[y_] := 1/(E^((-1 + y)^2/2)*Sqrt[2*Pi])     l[y_] := f1[y]/f0[y]     opts = {Method -> {Automatic, "SymbolicProcessing" -> None}, AccuracyGoal -> 8}     h0[ϵ0_?NumericQ, ϵ1_?NumericQ] :=        -(ϵ1/(1 - ϵ0)) +        NIntegrate[f0[y]*Boole[l[y] < (1 - ϵ0)/(1 - ϵ1)], {y, -∞, ∞},          {Method -> {Automatic, "SymbolicProcessing" -> None},AccuracyGoal -> 8}] -        ((1 - ϵ1) *          NIntegrate[f1[y]*Boole[l[y] < (1 - ϵ0)/(1 - ϵ1)], {y, -∞,∞},          {Method -> {Automatic, "SymbolicProcessing" -> None}, AccuracyGoal -> 8}])/(1 - ϵ0)     hh0[ϵ0_] :=        FindRoot[h0[ϵ0, ϵ1] == 0, {ϵ1, 0.5},          StepMonitor :>Print["Step to ϵ0 = ", ϵ0, Evaluate@opts]]     Plot[hh0[ϵ0], {ϵ0, 0, 1}]      I am able to get all the values that are necessery to plot, but the plot doesnt output any graphics. How can I fix this problem?Improved formatting


Contour plot show value change

data = Reverse[Reverse /@ Partition[dem[[All, 1]], 121]];     ListContourPlot[GaussianFilter[data, 10],       Contours -> {1580, 1670, 1480, 1715}, ContourShading -> None,       ColorFunction -> "Pastel",       DataRange -> Transpose[dem[[{-1, 1}, {3, 2}]]]]      How to contour plot show value in graphic ? if value=1580 change 350 in show graphic.If value 1670 I want show this value show in picture 370. Thank you


How to reverse the direction of the y axes

I have a similar question to this one. Unfortunately, the answers there didn't help me. I would like to plot a simple function with the normal `Plot` function. However, I want the origin of my plot to be in the upper left corner, the x-axes to grow to the right and the y-axes to grow down. How can I do this?


Automatically Recording Sound

I was hoping I could recreate a noise cancelling set-up by recording sound from the microphone in my headset or from the computer and play it back in my speakers or headphones with the appropriate phase shifts (I understand it may not be a simple as that but it would be a start). That is what I want to achieve, let's start with some small goals. Is it possible to record sounds automatically in Mathematica (or even in Mathematica for Rpi) ? I am familiar with `SystemDialogInput`                SystemDialogInput["RecordSound"]      It pops a dialog which allows you to press a button to record a sound. However I can't seem to find an option, or maybe another way, to have the sound record automatically. So that this can automatically processed


How to have a special grid as background of a plot?

I want to have a grid background for the function `(2/5)*x+3/5` but with one small detail. I want the coordinates of the points to be in the centres of the background squares, not on their corners. I am playing with Bresenham's line algorithm so I want to see nearest to the centre of which squares a line goes through.


spherical polar plot of radial function

Can you please tell me how to plot $\sqrt{r}$ in 3d sph polar plot? In the spherical plot 3d there is no option I can put variable r. So how should I proceed.


Why does Evaluate fail?

If i use this code:               bindeaa[e0_] := e0;     c[e0_] := 40 e0;     bindeab[e0_] := 1.27 e0;           alpha[gamma_, p_, epsilon_] := p (gamma  - epsilon);     beta[b_, epsilon_, n2_] := b epsilon^2 n2^(3/2);                 eisl[b_, e0_, g_, gamma_, p_, epsilon_, n2_, x_] :=                  g c[e0] (epsilon)^2 - bindeaa[e0] +                  e0 ((-2 Log[E^(1/2) x])/x^2 + alpha[gamma, p, epsilon]/x +                  beta[b, epsilon, n2]/x^(3/2));               eislminx[b_, e0_, g_, gamma_, p_, epsilon_, n2_]:=      (minxzwischen = FindMinimum[{eisl[b, e0, g, gamma, p, epsilon, n2, x], 0 < x},x];                   minx = x /. minxzwischen[[2]];                             eisl[b, e0, g, gamma, p, epsilon, n2, minx]);           Plot[eislminx[10, 1, 0.7, 0.3, 4.9, 0.05, n2], {n2, 0, 10},       PlotPoints -> 2]      It works just fine, but it is slow. If i try to speed things up with the function "Evaluate" i get error messages and don't know how to fix that.               bindeaa[e0_] := e0;     c[e0_] := 40 e0;     bindeab[e0_] := 1.27 e0;           alpha[gamma_, p_, epsilon_] := p (gamma  - epsilon);     beta[b_, epsilon_, n2_] := b epsilon^2 n2^(3/2);                 eisl[b_, e0_, g_, gamma_, p_, epsilon_, n2_, x_] :=                  g c[e0] (epsilon)^2 - bindeaa[e0] +                  e0 ((-2 Log[E^(1/2) x])/x^2 + alpha[gamma, p, epsilon]/x +                  beta[b, epsilon, n2]/x^(3/2));               eislminx[b_, e0_, g_, gamma_, p_, epsilon_, n2_]:=      (minxzwischen = FindMinimum[{eisl[b, e0, g, gamma, p, epsilon, n2, x], 0 < x},x];                   minx = x /. minxzwischen[[2]];                             eisl[b, e0, g, gamma, p, epsilon, n2, minx]);           Plot[eislminx[10, 1, 0.7, 0.3, 4.9, 0.05, n2], {n2, 0, 10},       PlotPoints -> 2, Evaluated -> True]      If i use the function "ArgMin" instead of               minx = x /. minxzwischen[[2]];       I get error messages, too.               bindeaa[e0_] := e0;     c[e0_] := 40 e0;     bindeab[e0_] := 1.27 e0;           alpha[gamma_, p_, epsilon_] := p (gamma  - epsilon);     beta[b_, epsilon_, n2_] := b epsilon^2 n2^(3/2);                 eisl[b_, e0_, g_, gamma_, p_, epsilon_, n2_, x_] :=                  g c[e0] (epsilon)^2 - bindeaa[e0] +                  e0 ((-2 Log[E^(1/2) x])/x^2 + alpha[gamma, p, epsilon]/x +                  beta[b, epsilon, n2]/x^(3/2));               eislminx[b_, e0_, g_, gamma_, p_, epsilon_, n2_?NumericQ] :=       eisl[b, e0, g, gamma, p, epsilon, n2,         ArgMin[{eisl[b, e0, g, gamma, p, epsilon, n2, x], 0 < x }, x]];           Plot[eislminx[10, 1, 0.7, 0.3, 4.9, 0.05, n2], {n2, 0, 10},       PlotPoints -> 2, Evaluated -> True]      Does anybody know how to fix that? Evaluate works just fine with this small working sample that has in my understanding the same basic structure as my actual code up there:               start = SessionTime[]     a[x_] := x^2     g[b_, x_, y_, z_] := b a[x] + x y^2 + x z^2;     f[b_, x_, y_, z_] := (buffer = FindMinimum[g[b, x, y, z], x];        xmin = x /. buffer[[2]];        g[xmin, y, z]);          Plot3D[Evaluate@f[2, x, y, z], {y, 0, 4}, {z, 0, 4 - y},       PlotPoints -> 3]


Graph databases / Nosql with Mathematica

I am very new to mathematica but it looks like an interesting language and I would like to explore it for a future project to create a web search engine. It seems like it would be fairly well suited for this as it seems to already be powering wolfram alpha. I was wondering if the only databases you can hook into are SQL like databases. I can't see anywhere that talks about hooking into Mongo or a graph database like Neo4j. Why is this? Does this not make sense for some reason? Any thoughts would be great. Thanks. Edit: So ya. If you have examples of ways to connect Mathematica to MongoDB that would be awesome. If possible I would also like to see an example of connecting it to Neo4j. (Or reasons why that would not make sense). I guess I am wondering why everything for Mathematica is being used to connect to SQL databases thus far? Is there a reason for that?


Impose an specific Trigonometric expansion with TrigExpand

Is there a way to impose in mathematica an specific trigonometric expansion with `TrigExpand`? I have various double-angle expressions for cosine and sine in my problem and i need to rewrite them in terms of cosines and sines functions. With this code you can get the same expressions than me.               ClearAll["Global`*"]     SetOptions[$FrontEndSession, PrintingStyleEnvironment -> "Condensed"]         $PrePrint = # /. {Csc[z_] :> 1/Defer@Sin[z],           Sec[z_] :> 1/Defer@Cos[z],           Cot[z_] :> Defer@Cos[z]/Defer@Sin[z]} &;     Derivative /:       MakeBoxes[Derivative[\[Alpha]__][f1_][vars__], TraditionalForm] :=       Module[{bb, dd, sp},        MakeBoxes[dd, _] ^=         If[Length[{\[Alpha]}] == 1, "\[DifferentialD]", "\[PartialD]"];       MakeBoxes[sp, _] ^= "\[ThinSpace]";       bb /: MakeBoxes[bb[x__], _] := RowBox[Map[ToBoxes[#] &, {x}]];       TemplateBox[{ToBoxes[bb[dd^Plus[\[Alpha]], f1]],          ToBoxes[Apply[bb,            Riffle[Map[bb[dd, #] &,              Select[({vars}^{\[Alpha]}), (# =!= 1 &)]], sp]]],          ToBoxes[Derivative[\[Alpha]][f1][vars]]}, "ShortFraction",         DisplayFunction :> (FractionBox[#1, #2] &),         InterpretationFunction :> (#3 &), Tooltip -> Automatic]]          Subscript[w, 1] =        f[Subscript[r, 1], Subscript[r, 2], \[Alpha], \[Beta], \[Gamma],         Subscript[\[CapitalTheta], 12]];     Set[J, -(D[Subscript[w, 1], {\[Beta], 2}] +            1/Sin[\[Beta]]^2 (D[Subscript[w, 1], {\[Alpha], 2}] +               D[Subscript[w, 1], {\[Gamma], 2}]) +            Cot[\[Beta]] D[Subscript[w, 1], \[Beta]] -            2 Cot[\[Beta]]/            Sin[\[Beta]] D[Subscript[w, 1], \[Alpha], \[Gamma]])] //        TraditionalForm ;     Set[Subscript[a, 1],         2 D[Subscript[w, 1], {\[Beta], 2}] +          D[Subscript[w, 1], {\[Gamma], 2}] + J] // TraditionalForm ;     Set[Subscript[a, 2],         2 Cot[\[Beta]]/          Sin[\[Beta]] D[Subscript[w,            1], {\[Alpha], 1}] - (1 + 2 Cot[\[Beta]]^2) D[Subscript[w,            1], {\[Gamma], 1}] -          2/Sin[\[Beta]] D[Subscript[w, 1], \[Beta], \[Alpha]] +          2 Cot[\[Beta]] D[Subscript[w, 1], \[Beta], \[Gamma]]] //        TraditionalForm ;     Set[Subscript[f, 1],          1/(2 Sin[Subscript[\[CapitalTheta], 12]]^2) (-J +              Cos[Subscript[\[CapitalTheta],                12]] (Sin[2 \[Gamma]] Subscript[a, 2] -                 Cos[2 \[Gamma]] Subscript[a, 1]) +              Sin[Subscript[\[CapitalTheta],                12]] (Sin[2 \[Gamma]] Subscript[a, 1] +                 Cos[2 \[Gamma]] Subscript[a, 2])) -           D[Subscript[w, 1], Subscript[\[CapitalTheta], 12], \[Gamma]] -           1/2 Cot[Subscript[\[CapitalTheta], 12]] D[Subscript[w,             1], {\[Gamma], 1}] + (1/4 - 1/(             2 Sin[Subscript[\[CapitalTheta], 12]]^2)) D[Subscript[w,             1], {\[Gamma], 2}] ] // ExpandAll // TraditionalForm ;     Set[lapla1, -(1/(           2 Subscript[\[Mu], 1])) (1/Subscript[r, 1]             D[Subscript[w, 1] Subscript[r, 1], {Subscript[r, 1], 2}] -            1/Subscript[r,              1]^2 (D[Subscript[w,                1], {Subscript[\[CapitalTheta], 12], 2}] +               Cot[Subscript[\[CapitalTheta], 12]] D[Subscript[w,                 1], {Subscript[\[CapitalTheta], 12], 1}]) - Subscript[f,            1]/Subscript[r, 1]^2)] // ExpandAll // TraditionalForm      In this specific case, when I use `TrigExpand` for lapla1, mathematica does not use a unique relation for doing the expansion of each of the terms and is quite difficult to follow it by hand. So, I would like to impose these two specific trigonometric expansions in order to check the results. $$\sin(2x)= 2\cos x \sin x$$ $$\cos(2x)= \cos^2 x-\sin ^2x$$ Yo can check that those expressions above can be written in several ways: ![enter image description here](http://i.stack.imgur.com/geHre.png) ![enter image description here](http://i.stack.imgur.com/izh48.png)


Removing trailing zeros from a list

If I have a list like               list1={2334.,342.,0.,0.,2322.,0.,0.,0.,0.,,,,,,};      it's easy to remove to trailing blanks with `Select[list1,NumberQ[#]&]`, and it's easy to remove all the zeroes, but how do I remove only the _trailing_ zeros? I want to leave the mid-list zeroes in place.


How can I multiply matrix and vector element wise like Numpy?

I have an $M \times K$ matrix $C$ and a length $K$ vector $v$. I want to form the $M \times K$ matrix $S$ where $s_{ij} = C_{ij}/v_j$. To do this in numpy I simply divide the two objects like this                 S = C/v      but that fails in _Mathematica_. What is the most efficient way to do this?


Why doesn't FrameTicks work with Histogram?

An example:               Histogram[RandomVariate[NormalDistribution[], 1000],      PlotRangePadding -> 0,      Frame -> True,      FrameTicks -> {{{0, 0}}, {}}]      I expected this to produce a histogram without ticks. However: ![Histogram with incorrect ticks](http://i.stack.imgur.com/e7xlG.png) Meanwhile, if I use the same tick specification with `Plot`:               Plot[PDF[NormalDistribution[], x], {x, -\[Pi], \[Pi]},      PlotRangePadding -> 0,      Frame -> True,      FrameTicks -> {{{0, 0}}, {}}]      ![Plot with correct ticks](http://i.stack.imgur.com/GLUCS.png)


Recurrences of lists

Assume we have a multi-dimensional recurrence, e.g. $\qquad\begin{align*} a_1 &= (1,2) \\ a_n &= (1,2) + a_{n-1} \quad, n>1 \end{align*}$ with the easy solution $a_n = (n,2n)$. How can I solve such recurrences in Mathematica? The expression               RSolve[{a[1] == {1, 2}, a[n] == {1, 2} + a[n - 1]}, a[n], n]      evaluates to               {}      in Mathematica 9.0.0.0. Naturally,               RSolve[{       a1[1] == 1, a1[n] == 1 + a1[n - 1],        a2[1] == 2, a2[n] == 2 + a2[n - 1]     }, {a1[n], a2[n]}, n]      works, but this strikes me as inconvenient. Given that the translation is this immediate (provided all occurring lists have the same length) I suspect there might be a way to do it without boilerplate.


Indeterminate expression. Where?

Consider the following:               a[m_, n_, x_] :=          1/2^n (-1)^n/((2 n)!) Sum[Binomial[m, l] (m - 2 l)^(2 n), {l, 0, m}] x^(2 n)          a[m_, 0, x_] := 1          f[m_, x_] := Sum[a[m, n, x], {n, 0, Infinity}]      ![Indeterminate expression](http://i.stack.imgur.com/6MNvX.png) I'm totally clueless why Mathematica fills in $0$ for $x$ while I feed it $x = 1$!


Loop function question

I'm new to Mathematica. Below is the code I have trouble with.               Do[Print[         Subscript[C, k][x_, y_]: =                Subscript[q, 2 k - 1] + x*Subscript[q, 2 k] - (Subscript[q, l] + y*Subscript[q, l + 1])        ],       {k, 3, 5}, {l, 3}]      In this loop, I want k=3 map to l=1, k=4 map to l=2, and k=5 map to l=3. However in this loop function, it loops through l=1,2,3 when k=3 and so on. So is there an automatic way or code to stop the certain looping?


How Do I Plot Histograms and Binomial Distributions Side by Side?

Here is the code I thought might yield up two histograms and two binomial distributions plotted side by side:               Show[Histogram[dataA, {-0.5, 6.5, 1}, "PDF"],       Histogram[dataC, {4.5, 12.5, 1}, "PDF"],       DiscretePlot[PDF[BinomialDistribution[6, 0.5], x], {x, 0, 7},        PlotStyle -> PointSize[Large]],       DiscretePlot[PDF[BinomialDistribution[7, 0.65], x - 5], {x, 5, 13},        PlotStyle -> PointSize[Large]]]      No workee! I get the first Histogram and the first Binomial. But, unfortunately, the image terminates at a value of around 7.25.


Apply N only outside a certain function

1 + f[1] // N       gives                1. + f[1.]        I don't want the argument of `f` evaluated by N; I want to get               1. + f[1]      instead. In general, there is a large algebraic expression containing some subexpressions of type `f[__]`. `N` should not be applied inside `f`. `N` should be applied only outside. Mapping `N` at a certain level only is **not** OK, since the tree structure of expression is not know in advance. One possible trick is               1 + f[1] /. x_f :> 1. x + 0.       It would be good to know other options.


Ordering under assumptions

I have a three-element list which contains inverses of a function `u`, like so:               CEs = {(u^(-1))[0.448165 u[10]+0.551835 u[30]],(u^(-1))[0.296264 u[10]+0.703736 u[30]],30}      I would now like to obtain the ranking of the elements of this list under the assumption that `u` is strictly increasing but struggle even to understand the output of               Ordering@Ordering@CEs      , which gives               {2, 3, 1}      without Mathematica knowing anything about `u`. Could someone explain to me how this ranking comes about and how I might be able to teach Mathematica that `u` is strictly increasing and to order elements under this assumption? In the current case the ordering should be               {1, 2, 3}


How to transform transfer functions into differential equations?

is there a way with Mathematica to transform transferfunctions (Laplace) into differential equations? Let's say I have the transfer function $\frac{Y(s)}{U(s)}=\text{Kp} \left(\frac{1}{s \text{Tn}}+1\right)$. What I want to get is $\dot{y}(t)\text{Tn}=\text{Kp}(\dot{u}(t)\text{Tn}+u(t))$. On (I think) Nasser's page I found something I adapted:               sys = Kp (1 + 1/(Tn s))     sys = Together[sys]     rhs = Numerator[sys]     lhs = Denominator[sys]     rhs = rhs /. m_. s^n_. -> m Derivative[n][u[t]]     lhs = lhs /. m_. s^n_. -> m Derivative[n][y[t]]          eq = lhs == rhs      But this gives a wrong output for factors with $s^0$:               Input: eq          Output: Tn y[t]'==Kp (1+Tn u[t]')


How Can I Transform a Colored Image into Pre-defined Matrix?

I am new to _Mathematica_ and I would like to use it to postprocess some of the experimental data I measure. I would like to visualize voltage measurements over a non-uniformly segmented plate. I would like to read in the segmentation in terms of a colored scheme. The color scheme would define the segmentation in geometrical shapes. For instance, I would have a red rectangle, an orange triangle, a blue triangle and a green square. From what I know, I can represent the colors in terms of a `Matrix` using the `ImageData[]` command. However, with this, I obtain a `3X1` matrix for each color. I would like to know if there is a way to represent each color by one number. I ask this since I would like to take the `Matrix` I obtain and correlate it to the matrix which identifies the segment numbers according to the segmentation as follows:               Red --> Segment 1 (Rectangle)          Orange --> Segment 2 (Triangle)          Blue --> Segment 3 (Triangle)          Green --> Segment 4 (Square)


GeneralMiniMaxApproximation - Dividing out the zero

MiniMaxApproximation is used to generate minimax approximations. I'm interested in the "dividing out the zero" trick. The documentation discusses a nice example. Suppose we want to construct a minimax approximation of $\cos (x)$ on $x \in [1,2]$. Since the function `MiniMaxApproximation` uses the relative error the function being approximated can not have a zero in the interval of question ($\cos(\pi/2)=0$). However "it is still possible to deal with such functions, but the zero must be divided out of the function and then multiplied back into the rational function". So instead of approximating $\cos(x)$ we approximate $$\frac{\cos(x)}{x-\frac{\pi}{2}}$$ The mathematica code to do this is               MiniMaxApproximation[Cos[x]/(x - \[Pi]/2), {x, {1, 2}, 2, 4}][[2, 1]]      as in the documentation. I was wondering if there is a similar trick that can be used with `GeneralMiniMaxApproximation`. This function approximates parametrically defined functions of the form $(x(t), y(t))$. Note that $\cos (x)$ on $x \in [1,2]$ can be defined parametrically as $(\arccos(t),t)$ where $t \in (\cos(1),\cos(2))$. So the mathematica code to approximate this function looks like               GeneralMiniMaxApproximation[{ArcCos[t], t}, {t, {Cos[1], Cos[2]}, 3,      2}, x]      However it fails because of the zero occuring in the interval of approximation. I was wondering if there is a way to extend the above trick so that it will work with `GeneralMiniMaxApproximation`?? I would like to stick with using the relative error as opposed to the absolute error. My attempt: I thought maybe a shift in the y-axis would do the trick. ie. approximate $\cos (x) + 1$ on $x \in [1,2]$ (which has no zero in this interval). We can subtract the one after. This is equivalent to approximating the parametrically defined function $(\arccos(t-1),t)$ where $t \in (\cos(1)+1,\cos(2)+1)$. The mathematica code is then given by,               GeneralMiniMaxApproximation[ {ArcCos[t - 1], t}, {t, {Cos[1] + 1, Cos[2] + 1}, 2, 3}, x]      But this does not work for some reason. It complains the weight function $t$ could be disappearing. But this is not the case since $t$ is positive on $(\cos(1)+1,\cos(2)+1)$. Any ideas why this doesn't work?


Gradient/ColorFunction in Disk with transparent background

My goal is to make an iOS-like enable/disable switch like this: ![iOS sliders](http://i.stack.imgur.com/yxXCu.png) I use a `LocatorPane` for the slider with so-called "jumps" to only make two settings possible:               LocatorPane[Dynamic[pt], Graphics[{LightGray, Rectangle[{-.5, -.5}, {1.5, .5}]}],                 {{0, 0}, {1, 0}, {1, 1}},                 Appearance -> ImageResize[Graphics[{Gray, Disk[]},                                                    Background -> None], Scaled[.25]]]      Now, I want make the 'slider' better looking by adding a gradient to it but i cannot make it work. `ColorFunction` (probably the only way to add gradients in _Mathematica_ ) seems not available to `Disk`. I tried using Heike's solution for gradients in this question, but pasting the graphics from her function into my code does not work: the size of these graphics is way too large and rescaling it (using `ImageResize`) adds a white background which I cannot remove. I tried making a disk with a gradient myself using `Raster` and `ImageAdd`, but here the same problem of a none-removable background occurs again:               ImageAdd[     Graphics[Raster[Table[i, {i, 100}, {j, 200}],              {Scaled[{0, 0}], Scaled[{1, 1}]}, {1, 100}, ColorFunction -> "GrayTones"]],     Graphics[Disk[]]]      Can anyone give some tips about how to add gradients to disks?


How to solve a system of ordinary differential equations contain a interpolating function?

I'm wondering how I can solve a system of ODE that has a interpolating function? For example, `z` and `y` are `InterpolatingFunction`s generated by prior `NDSolve` commands. Now I need to solve a second ODE system:               {x2'[t] == -k1*x2[t]*y[t]/h2[t] + k2*z[t],      h2'[t] == -3*(-k1*x2[t]*y[t]/h2[t] + k2*z[t]),      x2[0] == 0, h2[0] == 1}      where `k1` and `k2` are constants.


Can my color function be written more simply?

The code shown below works well, but I think the pure function I'm supplying to the ColorFunction option could be more elegant. How can I simplify it?               f3[w_, h_, z_, d_: 0.04] :=        Reap[Do[If[Abs[i]/w + Abs[j]/h + Abs[k]/z == 1,            Sow@{i, j, k}], {i, -w, w, d}, {j, -h, h, d}, {k, -z, z,            d}]][[2, 1]];          ListPointPlot3D[f3[1, 1, 1], PlotStyle -> PointSize@0.02,      ColorFunction -> ({x, y, z} \[Function] Which[          z > 0 && x > 0 && y > 0, Red,          z > 0 && x > 0 && y < 0, Green,          z > 0 && x < 0 && y > 0, Blue,          z > 0 && x < 0 && y < 0, Orange,               z < 0 && x > 0 && y > 0, Cyan,          z < 0 && x > 0 && y < 0, Magenta,          z < 0 && x < 0 && y > 0, Yellow,          z < 0 && x < 0 && y < 0, RGBColor[0, 0.5, 1],          True, Black]), ColorFunctionScaling -> False,       BoxRatios -> {1, 1, 1}]


Edit AxesLabel from an existing plot

I have a really complex function that takes a few hours to plot as a function of a parameter. Few days later I realised that I named the axes wrong. Is there an easy way to edit the AxesLabels without running the plot again? (it takes too long!!) I tried `Show[%, AxesLabel-> {newname, newname2}]` but it doesn't change anything...


Solve system of ordinary differential equations that doesn't have an initial condition (t=0), but has an inifinity condition (t=infinity)?

I have a question for solving `t -> Infinity` on _Mathematica_. First, I have a system of ODEs:               feqn1 = {x'[t] == -k1*x[t]*y[t]/h[t] + k2*z[t],        y'[t] == 3*(-k1*x[t]*y[t]/h[t] + k2*z[t]),        z'[t] == k1*x[t]*y[t]/h[t] - k2*z[t],        h'[t] == -3*(-k1*x[t]*y[t]/h[t] + k2*z[t]),        x[0] == .001, z[0] == 0, y[0] == 0.2, h[0] == .001};      Then I solved the equations by `NDSolve`.               NDSolve[feqn1, {x, y, z, h}, {t, 0, 1000}];      and for the second part of the problem, I have another set of ODE.               seqn1 = {x2'[t] == -k1*x2[t]*y[t]/h2[t] + k2*z[t],              h2'[t] == -3*(-k1*x2[t]*y[t]/h2[t] + k2*z[t])}      The initial conditions are `h2[0] == 1` at `t = Infinity`, `x2 = 0.001`. Thanks.


Problem with WhenEvent

I am trying to add a time dependent fraction to a parameter in `NDSolve`, i.e. when `10 < t< 20`, add `s` to `k1`...               Manipulate[ sol = NDSolve[{A'[t] == k1*A[t], A[0] == 10,                                 WhenEvent[ 10 < t < 20, k1 -> (k1 + s)]},                                A, {t, 0, 100}],                 {k1, 0.0, 1.0}, {s, 0.0, 1.0}]      But I cannot get the code to work, and get the following error message. Does anyone have any suggestions, or can find the error in the code? > >     NDSolve::wenset: Warning: the rule FE`k1$$16->FE`k1$$16+FE`s$$16 will > not >     directly set the state because the left-hand side is not a list of state > variables. >> >


Set plot axes to be positive in both directions

How can I set the axes of a plot to be positive in both directions, along the lines of this image? ![enter image description here](http://i.stack.imgur.com/pbWOz.jpg) I've looked through some questions on how to change the axis direction (here, here and here) but they obviously don't fully answer my problem, and I've not got further than the options given in those questions. Presumably the answer lies in the `Ticks` function, but I'm not sure how to implement it. **Edit** I am aware of custom labels and tick positions from the documentation, but am curious about a more automatic way to do it. I was thinking along the lines of the accepted answer to How to change the axes' origin and direction?, where this is given as a way of reversing the axis direction.               x = Sin /@ Range[0, 2 π, 0.1];     ListPlot[-x, Ticks -> {Automatic, Function[{xmin, xmax},          Table[{i, -i, {0.02, 0}}, {i, N@FindDivisions[{xmin, xmax}, 10]}]]}]      Is there a similar method I could use based on `xmin`, `xmax` and `N@FindDivisions[]`, or is custom labels the way forward?


Switching among view points in a Manipulate expression

**Edit** : Some additional viewpoints were included to make it easier to test. Here's code for an alternative function, the graph of which is a bit less symmetric. Feel free to use either code set:               f = ArcCoth; Manipulate[      Plot3D[Abs[f[x + I y]], {x, -2, 2}, {y, -2, 2},        RegionFunction -> Function[{x, y, z}, x^2 + y^2 <= 4],            MeshFunctions ->         Function @@@ {{{x, y, z}, Re[f[x + I y]]}, {{x, y, z},            Im[f[x + I y]]}}, MeshStyle -> {Orange, Green},        BoxRatios -> {1, 1, 1},        ViewPoint -> Dynamic[vp]], {{vp, {5, 8, 4}, "viewpoint"}, {        {5, 8, 4} -> "mathematicians' default",        {1.3, -2.4, 2} -> "Mathematica's default",        {0, -2, 0} -> "in front",        {0, -2, 2} -> "in front and up",        {0, -2, -2} -> "in front and down",        {-2, -2, 0} -> "left-hand corner",        {2, -2, 0} -> "right-hand corner",        {0, 0, 2} -> "directly above",        {0, -Infinity, 0} -> "xz from y at -\[Infinity]",        {0, 0, Infinity} -> "xz from z at \[Infinity]"        },       ControlType -> PopupMenu}]      * * * It's easy to place preset `ViewPoint`s in a `PopupMenu` in order to switch among them. But if I manually rotate the graphics object, the program ceases to respond to changes in the `PopupMenu` selection. Is there a way to have both functionalities?: (1) the `PopupMenu` and (2) manual rotation. If the answer is no, is there at least a way to turn off manual rotation? Below is a simplified version of the code.               Manipulate[      Plot3D[{x^2 + y^2, -x^2 - y^2}, {x, -2, 2}, {y, -2, 2},        RegionFunction -> Function[{x, y, z}, x^2 + y^2 <= 4],        BoxRatios -> {1, 1, 1}, ViewPoint -> Dynamic@vp],       Control[{{vp, {5, 8, 4}, "viewpoint"}, {         {5, 8, 4} -> "mathematicians' default",         {1.3, -2.4, 2} -> "Mathematica's default",         {0, -2, 0} -> "in front",         {0, -2, 2} -> "in front and up",         {0, -2, -2} -> "in front and down",         {-2, -2, 0} -> "left-hand corner",         {2, -2, 0} -> "right-hand corner",         {0, 0, 2} -> "directly above",         {0, -Infinity, 0} -> "xz from y at -\[Infinity]",         {0, 0, Infinity} -> "xz from z at \[Infinity]"         },        ControlType -> PopupMenu}]]      ![viewepoints](http://i.stack.imgur.com/9fViz.png)


Support for Compressed Sparse Column sparse matrix representation

Is there native support for Compressed Sparse Column (CSC) format for sparse matrices, like importing and manipulating them?


Knowing when a notebook has changed programmatically

Is there any way I can programatically determine whether a notebook has unsaved edits? Is that asterisk on the right of the notebook name represented in a notebook option or something, like `HasUnsavedEdits`?


How to properly DumpSave & Get Global`s symbols inside packages while not touching Global context?

For efficiency reasons I prefer to use `DumpSave` instead of `Save`. For ease of access I prefer to save symbols in `DumpSaved` files inside Global` context. But when my code evolved and I moved it inside packages I found a lot of problems to read symbols from those `DumpSaved` files so that read & write process   * allows for use saved variables inside my package (and its context)   * does not affect variables in `Global``   * When user loads the file directly with `Get`, bypassing my package (and perhaps not even loading it), the symbol is available in `Global`` context for him or her   * symbol name is not hard-coded into function (but of course it must hard-coded into the file itself :-( ) Simply put: I want to use `DumpSave` & `Get` the way I use `Export` & `Import`, but with efficiency and flexibility benefits. I come up with the following code, but it still messes the Global context and has the symbol name hardcoded (`Global`myglobalname`):               SaveMySymbol[object_,path_String]:= Block[{},        OwnValues[Global`myglobalname] = HoldPattern[Global`myglobalname] :> object;        DumpSave[         path<>".mx", Global`myglobalname]];          LoadMySymbol[path_String]:= Block[{strfullpath},       strfullpath = path<>".mx";       If[FileExistsQ[strfullpath], Get[strfullpath]; Global`myglobalname,         Null]]      I guess the problem with messing the `Global`` context can be avoided by caching the maybe existing definition of `Global`myglobalname` symbol and returning it back after `Get`. But the code look already awfully complex (it took me a full day to figure out the trick with `OwnValues`) and I suspect that _there must be an easy way_... Well, so far there always was one with Mathematica...


Old values are not freed/garbage collected when you re-evaluate an assignment

For this code:               (* Cell 1 *)     generate := Module[{x}, x = Range[100 * 1000 * 1000]; x];          (* Cell 2 *)     g = generate[];     MemoryInUse[]      If I evaluate cell 2 repeatedly, the memory consumption keeps growing by 400 MB each time (as seen in the OS task manager). For some reason, it seems that Mathematica does not free the memory taken by the old value of `g`. Can someone please explain what is going on here? And is there a way to force the freeing of old `g` values? Due to this issue I need to keep on quitting the Mathematica kernel.


MathLink and writing *.tm files

My goal is to use MathLink to access the functions in sofa (Standards of Fundamental Astronomy) So far I have had mixed success. I have very little C programing experience so I am hoping to get access to these algorithms via MathLink. I have a very simple C code file that loads the sofa libraries:               #include "mathlink.h"     #include <stdio.h>     #include "sofa.h"     #include "sofam.h"          int main(int argc, char* argv[])     {     return MLMain(argc, argv);     }      Then, from the sofa documentation I find function definitions like:               double iauAnp(double a)      Which I then turn into inputs, in the sofa.tm file               :Begin:     :Function:       iauAnp     :Pattern:        iauAnp[i_Real]     :Arguments:      { i }     :ArgumentTypes:  { Real64 }     :ReturnType:     Real64     :End:          :Evaluate: iauAnp::usage = "iauAnp[x] Normalize angle into the range 0 <= a < 2pi."      I'm then able to compile this and load it into _Mathematica_ via the `Install[]` function. So I know I can turn the crank once for a simple case. The question: How do I write the lines for the sofa.tm file for the following function?               void iauC2i00a(double date1, double date2, double rc2i[3][3])      My understanding of the workings of this function is that `date1` and `date2` are inputs and the 2D array, `rc2i` is returned by reference. I would like the _Mathematica_ function to look like this:               rc2i = iauC2i00a[date1, date2]


RunScheduledTask didn't execute itself the first time, why?

I have a problem with RunScheduledTask (new in Mathematica 8). A task that I usually need to do is to set a cron to start at a specific time and repeat itself at the same time every day (or the same minute every hour, and so on...)! Let's make an example: suppose I have to run `Pippo[]` at 5:00 AM every day starting from tomorrow. These are the "logic" steps in my mind to do so:   * calculate the absolute time of tomorrow at 5:00 and save it to `ABSTIME`   * execute `RunScheduledTask[Pippo[], 60*60*24, ABSTIME]` Unfortunately I have discovered that if I make it this way IT WON'T EXECUTE tomorrow at 5:00, but it will start the day after. I tried to set as `ABSTIME` the absolute time of today at 5:00 but it doesn't work either ('cause the ABSTIME is in the past). The only work-around I found is:   * calculate the absolute time of tomorrow at 5:00 and save it to `ABSTIME`   * calculate amount of seconds from now to tomorrow at 5:00 and save it as `SECSREMAINING`   * execute `RunScheduledTask[Pippo[], {SECSREMAINING}]` for the execution of tomorrow   * execute `RunScheduledTask[Pippo[], 60*60*24, ABSTIME]` for all other executions I think this a very "an-elegant" way, do you have any other solution? Or should we mass-warn Wolfram about this and make it change? ;)


How to draw multiple coordinates on mathematica?

For example: ![enter image description here](http://i.stack.imgur.com/HCgBA.jpg) How can I draw such kinds of coordinates? Thank you~


Integral of x^p

Can anyone explain why Mathematica does not return a conditional expression that handles the case of `p=-1` for `Integrate[x^p,x]`? Mathematica returns `x^(1 + p)/(1 + p)`, which diverges for `p=-1`. In order for Mathematica to return `Log[x]`, `p` must be set to `-1` before the integration. Is there a subtle reason why this is actually correct behavior?


What is the cleanest way to prevent divide-by-zero warnings?

If I evaluate `{1, 2, 3, 4}/{5, 6, 0, 8}`, obviously I get one warning:               Power::infy: Infinite expression 1/0 encountered. >>      and one entry of `ComplexInfinity` in the third position of the result. I'd like to eliminate the warnings and get the output with instances of `ComplexInfinity` deleted. So far,               DeleteCases[Quiet[{1, 2, 3, 4}/{5, 6, 0, 8}], ComplexInfinity]      is the best way I have to do this. But I'd rather not suppress all messages with `Quiet`, in case I'm operating on something more complicated than this example. Rather than cleaning up the mess it causes, is there a clean way to prevent the divide-by-zero operation from happening in the first place?


Plotting the convolution of the same probability density function with itself

I would like to compute the integral $$q_n(x)=\int_{B}^A q_{n-1} (\omega)f(x-\omega)\mathrm{d} \omega,\quad q_1=f,\quad n\geq 1.$$ for a given density function $f$. Basically it is the convolution of a pdf with itself for $n$ times in the range $A$ and $B$. when $n=1$, I simply plot the original pdf $f$, if $n=2$, then I convolve it with itself only once and plot etc.. Eventually I would like to plot the densities $q_n$ for $n=1,2,3..,7$ in the same figure. My code with the help of some people from this forum is               f0[x_] := PDF[NormalDistribution[-2, 2], x]     f1[x_] := PDF[NormalDistribution[2, 2], x]          q[1, B_, A_, f_] := f          q[n_ /; n > 1, B_, A_, f_][x_] := Module[{\[Omega]},      tempIntegrate[Evaluate[q[n - 1, B,A, f]][\[Omega]] f[x - \[Omega]], {\[Omega],B, A}]]          p[n_, B_, A_, f_] :=      tempIntegrate[q[n, B, A, f][x], {x, -\[Infinity], B}]+tempIntegrate[q[n, B, A, f][x], {x,A, \[Infinity]}] //.      {s_ tempIntegrate[b_, a__] :>tempIntegrate[s b, a],      tempIntegrate[tempIntegrate[b_, a__], c__] :>tempIntegrate[b, a, c]} /.      tempIntegrate -> NIntegrate      I can not               Plot[q[2, -2, 2, f0][x],{x,-10,10}]       correctly and I cannot see the analytical formulation when I type               q[2, B, A, f0][x]      Could you please help me? Thank you very much. EDIT : My eventual intention was to calculate $$P[n]=\int_{(-\infty,B)\cup (A,\infty)} q_n (x) \mathrm{d}x$$ and p[2, -2, 2, f0] provides me a numerical value but I am also interested in some analytical values. To do this I tried to change ->NIntegrate to Integrate but then the code didnt function properly.


DownValues for Built-in Functions

N.B. I have bitten the bullet, and I am going through Leonid Shifrin's "Mathematica Programming: An Advanced Introduction." (Which needs no introduction in this forum) One question I have: could one establish that a symbol has a built-in rules, based on DownValues or related functions? For example:               Unprotect[Sin]     Sin[x_Integer] := Sin[N[x]]     Protect[Sin]          Sin[1]     (* 0.841471 *)     DownValues[Sin]     (* HoldPattern[Sin[x_Integer]] :> Sin[N[x]] *)      Hey, where are the built-in rules for Sin?


Custom Matrix product

I have a list:               list1 = {{{a1, a2, a3}, {b1, b2, b3}}, {{c1, c2, c3}, {d1, d2, d3}}};      ![](http://i.stack.imgur.com/6bbDh.png) I want an operation that gives me: ![](http://i.stack.imgur.com/GOtfL.png) Is there a built-in way of doing this? Basically, this is meant to be the `ImageData` of a picture and I want to double the resolution by increasing the number of pixels and doing further operations on it. I tried               KroneckerProduct[list1, {{1, 1}, {1, 1}}]      but it didn't give me what I wanted. If there is no built-in method of doing this, what is the most efficient way of this?


NDSolve finding solution when it shouldn't

NDSolve in mathematica drives me crazy and I'm seriously thinking about switching to Matlab because of strange bugs I run into.               ClearAll["Global`*"]     NDSolve[{-(2/x) y'[x] -           y''[x] - (2 Z/a0 1/x - L (L + 1) - Energy)*y[x] == 0,         y[350] == 0, y'[350] == -.0001}, y, {x, .01, 350}] // Flatten     y[1] /. %        Clearly this should be _unsolvable_ by mathematica because I haven't even defined L or Energy. But for some reason, I'm getting an interpolating function as an output, even after I've cleared all my variables! What on earth is going on!? I've been having issues trying to find the wavefunctions for the radial part of the schrodinger equation in mathematica, so additionally, if there are any physicists out there, your help showing me a working numeric integration of the radial part of the schrodinger equation would be greatly appreciated. My full code is:               SolverThingy[n_, L_] :=       (        Rydberg = .5;        En = -1*Rydberg/n^2;        Z = 1;        r0 = 2*n*(n + 15);        rfinal = .5;             solr =          NDSolve[{y''[x] + (L (L + 1)/(2 x^2) + Z/x + En) y[x] == 0,             y[350] == 0, y'[350] == -.0001}, y, {x, .01, 350}] // Flatten;        sol = y /. solr;             int = Integrate[Evaluate[sol[y]*sol[y]], {y, .01, 350}];        (*Normalization*)        normd = 1/int*sol[x]        );     Plot[Evaluate[SolverThingy[10, 1]], {x, .1, 350}, PlotRange -> All}]      For some reason this is NOT the same solution as the analytic solution for the radial equation. And I can't figure out why it doesn't work.


Is there a bug in AssociatePairs?

In **Version 10** , the `GeneralUtilities` package contain some useful functions. `AssociatePairs` is one of those functions included in the package and advertised to work as follows:               Needs["GeneralUtilities`"]          ?AssociatePairs      ![Mathematica graphics](http://i.stack.imgur.com/fGgLy.png) Well, here is an input that matches a `List` of pairs:               lis = Table[{k, k^3}, {k, 2, 10}];      Now,               AssociatePairs[lis]      Gives the following error: ![Mathematica graphics](http://i.stack.imgur.com/QVJ9N.png) Well, the included `PairQ` function disagrees with this assertion:               AllTrue[lis, PairQ]      > True So, is this a bug? Since I can't get any list of pairs to work with this function. I'm on **Windows 8.1**


How to find all subsets which the total of elements is the same?

I want to find all subsets which the total of elements is the same. For example, `Subsets[Range[30], {5}]` means all 5-element subsets and the range of each element is from 0 to 30. But I want to get the subsets which are only the total of elements equals to 30 (e.g., `{6, 6, 6 ,6, 6}`, `{7, 5, 6, 6, 6}`, ....


Concise way to generate multiset lists

I wrote the following to generate a multiset with the same number of items over a fixed range:               ConstantArray[#, 3]& /@ Range[9] // Flatten      > >     {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, > 9, 9, 9} >   This approach uses four named functions (`Range`, `Flatten`, `ConstantArray` and `Map` (`/@`)) and one pure function (ending with `&`).   Is there a way to do the same thing with fewer functions? Also, if I wanted to have variable numbers of items in my multiset how would I do that?   For example, let's say I wanted a multiset like `{ 1, 1, 1, 1, 2, 2, 3, 4, 4, 4, 6, 6, 7, 8, 8, 8 }`. By a "variable number of items" I do not mean random, I mean a specified variable number.


How to I get a nutrition facts chart from WolframAlpha?

When I try just a few items such as               WolframAlpha["1 whole wheat tortilla + 2 slices american cheese + 150 g steak + 2 tbsp beans + 150 g white rice"]      I get the following nutrition facts table: ![enter image description here](http://i.stack.imgur.com/37ait.gif) However, when I enter a longer query such as               WolframAlpha["1 whole wheat tortilla + 2 slices american cheese + 150 g steak + 2 tbsp beans + 150 g white rice + 100g bell peppers + 200 g chicken breast + 2 slices of whole wheat bread"]      I don't actually get a nutrition facts chart as before. Is there a way to force a nutrition facts output every time? Also, is there a way to limit the output pods to only a nutrition facts table, as I don't need any of the other pods?


Using Tooltip with Joined data on a plot

I have some data partitioned into three sublists:               data = {{2776.37, 2016.64, 1483.51, 1027.35, 500.878, 94.1385,          310.402, 282.548, 257.886, 224.359, 218.688, 209.312, 215.776,          198.78}, {40.5063, 24.633, 12.069, 8.3151, 6.35135, 15.0977,          8.74372, 15.5125, 9.34959, 9.70696, 11.125, 12.1457, 10.8075,          9.7561}, {113.08, 124.633, 75.9698, 59.5186, 55.9459, 7.81528,          57.4372, 69.5291, 80.4878, 88.2784, 105.563, 127.935, 148.571,          148.78}};      Each sublist can be represented by a label,               samp = {"x", "y", "z"};      I want to create a `ListLogPlot` with a `Tooltip` with the sample name that appears when the mouse hovers over each subset. I have tried,               ListLogPlot[Tooltip[data, samp], Joined -> True]      ![enter image description here](http://i.stack.imgur.com/5HP75.png) but this flashes "{x,y,z}" for each subset. How do I achieve the desired effect?


Missing: KeyGroupBy?

Especially in tree-structured data, keys and values, being two sides of the same coin, frequently interchange roles. The ability to aggregate by value but not by key upsets the balance. How to improve on this workaround query - here defined only in operator form?               keyGroupBy[f_][expr_] :=  expr // AssociationMap[First[#] -> # &] // GroupBy[First /* f] //            Map[Values /* Association]      For example, given:                   data = Range[5] // AssociationMap[foo]          (* <|1 -> foo[1], 2 -> foo[2], 3 -> foo[3], 4 -> foo[4], 5 -> foo[5]|> *)      The desired output is:               data // keyGroupBy[PrimeQ]          (* <|False -> <|1 -> foo[1], 4 -> foo[4]|>,       True -> <|2 -> foo[2], 3 -> foo[3], 5 -> foo[5]|>|> *)       A fundamental constraint is that keys are transparent to functions accessing `Association`. Further, `Association` supports only data with unique keys. For example, `GroupBy` nested in `AssociationMap` will drop all but the last key- value pair with a given key.


How can I construct and visualize a hypergraph?

A hypergraph is a generalization of a graph, in which an edge can connect more than two vertices. Thus you can think of an edge in an hypergraph as a subset of nodes. Since version 8, _Mathematica_ has supported the plotting of graphs, as well as graph algorithms. **Is there a way to plot hypergraphs on _Mathematica_?** I know there are ways in which an hypergraph can be represented as a graph, or a matrix. But what I want is a method that allows me to plot the hypergraph directly, where edges that connect multiple vertices are drawn as branching lines between those vertices (for example, think of a reaction network). See, for example, the first image in this question.


What's the difference between these two ways of specifying dependent packages? **Method 1:**               BeginPackage["foo`bar`", {"xxx`", "yyy`"}]      **Method 2:**               BeginPackage["foo`bar`"]     Needs["xxx`"]     Needs["yyy`"]      Do they always have the same effect? Note that these packages may be used in a big collection of packages which have complex interdependency.


How to separate paths from the output of EdgeDetect?

I have been trying to find a way to separate the various closed paths that can be output by `EdgeDetect`. For example, taking the output of:               ColorNegate@EdgeDetect@Graphics[Style[Text["8"], 400]]      ![enter image description here](http://i.stack.imgur.com/CRoh8.png) I'd like to be able to obtain a list like: ![enter image description here](http://i.stack.imgur.com/BCn8u.png) I'd really love to show some progress I made on this, but to be honest, I'm stuck at the beginning. I really don't know how to attack this one. The naïve approach might be to take one black pixel, then go around it registering adjacent pixels as part of the same path, while erasing them from the original image. But I don't expect this to be anything other than painfully slow, and there probably are some Mathematica image manipulation functions that I could leverage. So, how would you advise me to start?


Accessing the graph Thinning produces without losing all the edges' lengths/slopes

![overview](http://i.imgur.com/GMOm4.png) This is a follow up to the OCR question I had earlier. What I want to do is to use Thinning to create "skeletons" of images of characters and then compare their shapes, utilizing such properties as the slopes/lengths of the edges. The problem is however that I have not been able so far to access the graph Thinning produces. MorphologicalGraph is what I have found in the documentation but this removes a lot of information. And for comparing graphs so far I only have found IsomorphicGraphQ which doesn't seem to offer much customization (tolerances for matching). The code below demonstrates the problem I have with my current approach. Because MorphologicalGraph reduces the Thinned images to a very similar shape for all these characters, the code will deem a "C" character similar to "I" and "S":               Graphize[u_] := MorphologicalGraph@Thinning@ColorNegate[Import[u]]     whichQ = Graphize["http://i.imgur.com/2Fxyh.gif"] (* C *)     i = Graphize["http://i.imgur.com/SPp7R.gif"]  (* I *)     c = Graphize["http://i.imgur.com/SeXA7.gif"]  (* C *)     s = Graphize["http://i.imgur.com/aguQ6.gif"]  (* S *)     IsomorphicGraphQ[whichQ, i] (* -> True *)     IsomorphicGraphQ[whichQ, c] (* -> True *)     IsomorphicGraphQ[whichQ, s] (* -> True *)


Plotting a Gravity-Field

I try to plot a 2D gravity field or something similar in the form like $r/|r|^3$ with the standart builtin VectorPlot function:               VectorPlot[{-x/(x^2 + y^2)^(3/2), -y/(x^2 + y^2)^(3/2)}, {x, -5, 5}, {y, -5, 5}]      It should look like: ![what it should look like](http://www.euclideanspace.com/maths/geometry/space/fields/gravity.png) I get something strange when I run my command: ![what i get](http://i.imgur.com/Wq069rJ.jpg) Any suggestions? Thanks Cx


Wrong numerical value while exporting to a JSON string

The following code:               ExportString[{"a" -> 2000000., "b" -> 0.000001}, "JSON"]      Gives the results               {"a" : 2.e60,      "b" : 1.e-6}      The first one is obviously having a wrong numerical value. Also, 1.e-6 is not parsable by python, but 1.0e-6 and 1e-6 works, so I guess it is not following the standard. The same problem also exists for `Export[]`. I need it to exchange data with other programs. What is the easiest way to fix this kind of problem?


How do I interpolate a set of points with colour varying along the curve?

I have a table with 3 columns - x position, y-position and colour. I'd like to plot these points and join them with line segments, where the colour of the line segment is determined by 3rd variable. e.g.               T=Table[{n,n,n},{n,0,100}];      I can plot just the points like this               Graphics[{Hue[#3/Length[T]], Point[{#1, #2}]} & @@@ T, Frame -> True, AspectRatio -> 1]      How can I plot line segments instead? Thanks!


How to make vertical frame label read top down

In Mathematica, default frame label will put labels at the bottom and the left. The label on the left reads from the bottom to the top. I would like to also put label on the right of the frame, but this label also reads from bottom to top. How can I make the right label read from top down?


using rules to look up values

I have a lookup table with about 30 rows. Column 1 has the value I want to search for and column 2 has the value I want returned. It seemed like I should be able to use rules to do this, but clearly I don't know what I'm doing. Oh, the values are all strings I tried:               rule2 :> (#[[1]] -> #[[2]]) & /@ elrALobMap;      This didn't work. First, should I be doing this a different way? (I see that I can do it with Position and Pick, but that seemed awkward. Second, I'd appreciate any help in understanding how (if it's possible) what I did code should be coded.


Unexpected complex roots from solving a cubic

I am new to _Mathematica_ and there is a behavior that I don't understand. When I insert the code:               Solve[-(x - 2)^3 + 10 x - 10 == 0, x]      I obtain: > >     {{x -> 2 + (2 5^(2/3))/(3 (9 + I Sqrt[39]))^(1/3) + (5 (9 + I > Sqrt[39]))^(1/3)/3^(2/3)},   >     {x -> 2 - (5^(2/3) (1 + I Sqrt[3]))/   >       (3 (9 + I Sqrt[39]))^(1/3) - ((1 - I Sqrt[3]) (5 (9 + I > Sqrt[39]))^(1/3))/(2 3^(2/3))},   >     {x ->  2 - (5^(2/3) (1 - I Sqrt[3]))/ >       (3 (9 + I Sqrt[39]))^(1/3) - ((1 + I Sqrt[3]) (5 (9 + I > Sqrt[39]))^(1/3))/(2 3^(2/3))}} >   These are complex roots, but this polynomial has real roots, that in fact I can correctly find when I use Root. Why are this complex roots being displayed? Are these supposed to be approximations? **Edit:** Thanks for the answer, now I understand better the underlying process and that Solve is in fact finding exact solutions. The "approximate zero" in the imaginary component comes from the numerical solution to the exact root, not from Solve. It can removed by using `Chop` as described here.


How can I deal with a non-numerical value for a derivative at $t = 0$ when using NDSolve?

I want to solve two coupled equations with `NDSolve`,               t x'[t] == -x[t] + y[t], t y'[t] == -5 t^2/x[t]^2 + x[t] - y[t],      x[0] == y[0], x[1] == 1      It's easy to see that at `t = 0` the derivative is undetermined, so `NDSolve` fails. The _Mathematica_ help center told me one possibility is to start at a small `ε > 0` instead of 0, and another possibility is to use the option `SolveDelayed -> True` to avoid the singularity in the solved form of the equations. Unfortunately neither of the methods worked for me. What should I do?


Question about evaluation control

I want to make a function that takes a function as a parameter and prints an integral with the function inside. I've tried this:               L[f_, a_, b_] := HoldForm[Integrate[f[x], {x, a, b}]]          L[E^-Sqrt[#] &, 0, 1]      But it gives me this: $$\int_0^1 \left(e^{-\sqrt{\text{#1}}}\text{&}\right)[x] \, dx$$ I want the integrand to look normal, that's all, so I want the variable x to be substituted inside it, but not evaluated any further. Is this possible?


Manipulate Parametric Plot

Is it possible to plot the values of x and y in Mathematica?               x = (h m + h l n + k m t + k l z)/(m - k m + l n)          y = (h l n + (-1 + k) (m t + l z))/((-1 + k) m - l n)      x and y have the same parameters. This code doesn't work, but here's what I have so far:               Manipulate[ParametricPlot[(h m + h l n + k m t + k l z)/(m - k m + l n), (           h l n + (-1 + k) (m t + l z))/((-1 + k) m - l n), {t, 0, 200},            PlotRange -> {{0, 3000}, {0, 1200}}, AxesOrigin -> {0, 0},            AxesLabel -> {"x-axis", "y-axis"}], {{h, 200}, 0, 300}, {{k, .75},            0, 1}, {{t, 200}, 0, 300}, {{l, 25}, 0, 50}, {{n, 1}, 0,            3}, {{m, 100}, 0, 300}, {{z, 500}, 0, 2000}]      How can Manipulate be used to plot the values of x and y in Mathematica?


How to make MousePosition more reliable

This takes a little patience to reproduce, but I got a screenshot of it in version 9 on Mac OS X 10.7.5: With a small `Graphics` object, it occasionally happens that `MousePosition` doesn't get updated when your mouse enters the graphic from the _bottom_.               Dynamic[MousePosition["Graphics"]]          Graphics[{Orange, Rectangle[{0, 0}, {1, 1}]}, ImageSize -> 60,       PlotRange -> {{0, 1}, {0, 1}}]      ![mouseposition](http://i.stack.imgur.com/1ZdJ9.png) As the image shows, the mouse is clearly inside the orange square, but the line above shows `None` instead of the mouse coordinates relative to the `PlotRange`. If I leave the square toward the top and re-enter from the top, the mouse position starts following my movements. To see the effect of the frozen `None` mouseposition, it seems I have to enter the rectangle from the bottom. I have to try this a couple of times - it doesn't happen every time. Is there a way, perhaps by surrounding the `Graphics` command in some other environment, to insure that the `MousePosition` is recorded more reliably? **Edit** I've now reproduced it on _Mathematica_ version 9 _and_ 8.0.4, OS X 10.7.5 on two different computers. **Edit 2** Although I'm not 100% sure, I strongly believe that jVincent's observation is correct: to reproduce this, I have to set the zoom level of the notebook, or the Magnification setting in `Advanced Preferences > Global Preferences > Notebook Options > Display Options` to something _other than_ the default `100 %` (or `1`, respectively). In my case, the latter was set to `1.25` when I made the screen shot.


How to remove constant background from an image?

I'm not sure how to remove the paper background from this logo with v9. ![enter image description here](http://i.stack.imgur.com/LKZfw.png) This is really not the same as this question, but I think similar methods apply.


Plot the minimum of a list of functions

This is my first question on any stack-exchange site and I'm also very new to using _Mathematica_ software so please excuse/correct me if I mess up. I would like to take a list of functions of a single variable {$f_1, f_2, f_3, \ldots, f_n$}, and plot the minimum value that each of these functions takes on at any point over an interval $[x_0, x_f]$. So far this much is not so difficult (or has not been the difficult part for me to figure out). However, I would like for each of the intervals over which any function $f_i$ is the minimum to correspond to it's own color (like how Plot usually attributes different colors to different curves when you plot multiple functions) and further I'd like to include a legend that clearly denotes which function from the list corresponds to which color. I can do the first part fairly easily using the following:               Z[x_] = Min[x, x^2, x^3, x^4, x^5]     Plot[Z[x], {x, 0, 2}, PlotLegends -> "Expressions"]      ![Plotting the minimum value of a list of multiple functions ](http://i.stack.imgur.com/L7gbl.png) I would like something that would color the segment of the curve where $x^5$ is the minimum function in the list one color and the segment where $x$ is the minimum function in another color and denote the color representations on the legend on the right. I can plot each of the functions separately with the color-coding system like so:               Plot[{x, x^2, x^3, x^4, x^5}, {x, 0, 2}, PlotLegends -> "Expressions"]      ![Plotting multiple functions with color-coding and legend](http://i.stack.imgur.com/1TTnX.png) And in both cases the " PlotLegends -> "Expressions" " flag/option (not sure what the terminology is for _Mathematica_ functions) does nicely generate a legend as I'd like it. But I don't really have a sense of how to combine the two. Thanks in advance for the help, and while I didn't find any other questions that might help answer (or partially answer) this question please correct me if I missed any.


Automatically evaluate next cell

I am new to _Mathematica_. I am trying to achieve the following: I need one input cell in which I set parameters, then another input cell where functions are defined and calculations are performed. Finally one output cell for the result. I want to hide the second input cell which contains a lot of code. When I change the parameters in the first input cell and evaluate it, it should automatically evaluate the second hidden input cell and update the result. I wasn't able to achieve this as I have to evaluate the second input cell separately. Also, it would be a requirement that there be no additional code in the first input cell.


How to work with differentials explicitly?

When working with differential equations with independent (e.g. `t` )and dependent (e.g., `x[t]`) variables Mathematica expresses partial and 'regular' derivatives nicely, but not the derivative itself. Can anybody manage to do this? I give an example: Let `f` depend on `x`, `y` and `t`. `x` and `y` depend on `t`. So, the partial derivative ![enter image description here](http://i.stack.imgur.com/a4UTF.png) with e.g. respect to `x` is in Matheamtica expressed by > f^(1,0,0)[x,y,t] , the derivative with respect to the independent variable ![enter image description here](http://i.stack.imgur.com/a9dFo.png) as an example by               x'[t]      . But how can I make Mathematica to show the derivative e.g. ![enter image description here](http://i.stack.imgur.com/k9Gy6.png) explicitly?


How can I list all the 'countries 4000 km far from current location'?

A friend said to me on Facebook that she is 4000km away. So I want to try to guess where she is. How can I find which countries are a given distance from my current location?


How to use Union on list of lists without sorting them first?

If I do               ClearAll[a, d]     lsts = {{a, d}, {a, d}};     Union[lsts]      I get the expected answer               {{a, d}}      but if I do               lsts = {{a, d}, {d, a}};     Union[lsts]      I get               {{a, d}, {d, a}}      Since I am using `Union`, I thought the order of the lists would not matter. Hence to get around this, now I always add `Sort` first, like this               lsts = {{a, d}, {d, a}};     Union[Sort /@ lsts]      and now I get expected answer               {{a, d}}      **Question** : Is this the right way to approach this? or do you recommend a better way?


How to create regular (planar) graphs?

How to programmatically create and plot **regular planar graphs** with $k = 3, 4$ or $6$ (not hypercubes) and **regular nonplanar graphs** of $k = 8$ (see figure)? Note that what matters is the average connectivity, as nodes at edges and corners have smaller $k$ values. Is there any easy method to do this, or one has to write its own `VertexCoordinates` function and the method to generate the appropriate graph? ![planar and nonplanar graphs](http://i.stack.imgur.com/IFkih.gif) Also, how to create and plot **random** planar graphs, where only the average connectivity is given and nodes possibly have varying connectivity. Note that the Computational Geometry Package has some means to deal with planar graphs, but e.g. `PlanarGraphPlot` can only give the Delaunay triangulation of the given dataset. Thus edges cannot be specified for e.g. top-right and bottom- left graphs in figure.


Is it possible to invoke the OEIS from Mathematica?

I had always wondered if there might be a way to write a function, which I'll call `OEISData[]`, that more or less works as a curated data function for The On-Line Encyclopedia of Integer Sequences. I would imagine that the usage might be a little something like this:               OEISData["A004001"][9]     5          OEISData["A003418"][Range[8, 15]]     840, 2520, 2520, 27720, 27720, 360360, 360360, 360360          OEISData["A005849", "Keywords"]     {"hard", "nonn", "nice", "more"}      An API or something to retrieve data from the OEIS site might be needed for an implementation of this function. Is a function like this possible, with what _Mathematica_ is currently capable of?


Is there a way to Collect[] for more than one symbol?

Oftentimes you find yourself looking for polynomials in multiple variables. Consider the following expression:               a(x - y)^3 +  b(x - y) + c(x - y) + d      as you can see this is clearly a Polynomial in `x-y`. Is there an equivalent of Collect, that works on more complicated expressions than just a single variable? I would like to have something similar to               Collect[%,x-y] = a(x - y)^3 + (b+c)(x - y) + d      however. Collect can not work on `x-y`. Of course you could solve this first example by substituting `x-y -> z` then Collect the `z` and afterwards substitute backwards like so:               a(x - y)^3 +  b(x - y) + c(x - y) + d /. x-y->z      gives               a^3 + b z + c z + d      then               Collect[ a z^3 + b z + c z + d ]      gives               a z^3 + (b+c)z + d      now undo the substitution by running `% /. z -> x - y`. This gives the desired result:               a z^3 + (b+c) z + d      So this is good. For obvious polynomials, we can solve this. But what about real world examples? Would you have guessed that               d + b x + c x + a x^3 - b y - c y - 3 a x^2 y + 3 a x y^2 - a y^3      is exactly the same polynomial? How would you Collect `x-y` here, as you cannot do the substitution?


Example program for calling Mathematica from C

I want to call Mathematica from a C program. Suppose I have two numbers x =2 and y=3. I want to define the x, y in a C program and call Mathematica and I want Mathematica to do the sum and return me the result. I use Linux. I want to know how should I use MathLink here: what should be written in mathematica file and the c file and at last, the compiler command. I want a complete program.


How to keep Collect[] result in order?

For example,               Collect[(1 + x + Cos[s] x^2)^3, x]      gives the result               1 + 3 x + 3 x^5 Cos[s]^2 + x^6 Cos[s]^3 + x^2 (3 + 3 Cos[s]) + x^3 (1 + 6 Cos[s])           + x^4 (3 Cos[s] + 3 Cos[s]^2)      Terms of the form $x^n$ are in random order. I would like the result is to be as follows:                1 + 3 x + x^2 (3 + 3 Cos[s]) + x^3 (1 + 6 Cos[s]) +          x^4 (3 Cos[s] + 3 Cos[s]^2) + 3 x^5 Cos[s]^2 + x^6 Cos[s]^3      * * * Well, First Thank you very much, Jens! Second, I found there is something wrong with your statement "the HoldForm could be left out". I have tried on my mathematica 8, it turns out that the "HoldForm" is necessary . if "HoldForm" is not there, the order is still random in the output . And I tried to understand this as well as "rule" and "ruledelayed" stuff but can't figure it out. I have tried several input, each confused me. summarized as follows   1. `Replace[cx, List[x__] -> Plus[x]]` will give              Sequence[1, 3 x, x^2 (3 + 3 Cos[s]), x^3 (1 + 6 Cos[s]), x^4 (3 Cos[s] + 3 Cos[s]^2), 3 x^5 Cos[s]^2, x^6 Cos[s]^3]       But I suppose it should give the Plus result because              Replace[cx, List[x__] -> jjj[x]]      gives              jjj[1, 3 x, x^2 (3 + 3 Cos[s]), x^3 (1 + 6 Cos[s]),  x^4 (3 Cos[s] + 3 Cos[s]^2), 3 x^5 Cos[s]^2, x^6 Cos[s]^3]        2. `Replace[cx, List[x__] -> HoldForm@Plus[x]]` gives the right result              1 + 3 x + x^2 (3 + 3 Cos[s]) + x^3 (1 + 6 Cos[s]) +  x^4 (3 Cos[s] + 3 Cos[s]^2) + 3 x^5 Cos[s]^2 + x^6 Cos[s]^3        3. `Replace[cx, List[x__] :> Plus[x]]` gives              1 + 3 x + 3 x^5 Cos[s]^2 + x^6 Cos[s]^3 + x^2 (3 + 3 Cos[s]) + x^3 (1 + 6 Cos[s]) + x^4 (3 Cos[s] + 3 Cos[s]^2)      Although it gives the right plus result, the order is wrong.


Identifying and counting closely spaced particles

Following in the footsteps of this blog post: http://blog.wolfram.com/2011/09/09/building-a-microscopy-application-in- mathematica/, I took a microscope picture of some particles on a surface, and attempted to write a script to identify and count them automatically. However, I've been having a difficult time seperating closely spaced particles, and the MaxDetect method in the blog post seems to not work too well on this data set. Why I find this failure surprising: Picking out the dark spots by hand is fairly trivial, and I imagine that if one were to 3D print a surface where darker pixel values represent depressions, the problem could be solved by rolling some marbles around and seeing where they stick. Here's the picture / data: ![enter image description here](http://i.stack.imgur.com/FftJ9.jpg) The first thing I did was then to binarize (with the Kittler-Illingworth minimum error thresholding method) and color negate the data using the command:               ColorNegate[Binarize[image, Method -> "MinimumError"]]      Which yielded: ![enter image description here](http://i.stack.imgur.com/Q0Fac.jpg) I then attempted to apply ImageAdjust[DistanceTransform[...]] to the image, yielding: ![enter image description here](http://i.stack.imgur.com/9zOac.jpg) Which I then applied MaxDetect to, yielding: ![enter image description here](http://i.stack.imgur.com/MwcQA.jpg) So, interestingly, there seems to be a ring of local maxima around each particle. Even if you use Erosion extensively, there still seem to be significant clusters of local maxima corresponding to each particle. As such, I've been having a very difficult time using the MaxDetect method in the aforementioned blog post to individually identify and count each particle. Let's say that the precise centroid coordinates of each particle are not important to know exactly. Is there a "nice" method of assigning a distinct morphological component or coordinate to each particle without a lot of hands- on tuning? Where perhaps we can end up with something like this (where I've hand-identified particles)? ![enter image description here](http://i.stack.imgur.com/EFFwl.jpg)


How can I speed up my code?

For[n = 2500, n < 10000, n += 500,        sum = 0;       pp = N[1/HarmonicNumber[n, 2]];       A = Reverse[IdentityMatrix[n]];       H = IdentityMatrix[n];       For[i = 0, i < n, i++,          For[j = 1, j < n + 1 - i, j++,            H[[j, j + i]] = Sqrt[pp]/(N[Sqrt[n - i]*(i + 1)])]];       T := A.Orthogonalize[N[H].A, Dot];       Z = T.N[H].A.T\[Transpose].A;       sum = Total[(Flatten[UpperTriangularize[Z,1]])^2];       Print[sum]     ]      I have run this program for a long time to get the result for `n = 2500` (about 12 hours) and no more result till now (more than 3 days). I want to know how to make it more efficient. Any help or suggestion will be appreciated!


The UnitStep function and Intervals

For the input               UnitStep[Interval[{-4, 5}]]      I get               Interval[{0, 1}]      Why is this not `Interval[{0,0}, {1,1}]`?


Filling between two curves in Mathematica

I want to fill region between 2 curves, but in _Mathematica 8.0_ :               FilledListPlot[list1, list2, Fills -> {RGBColor[f, f, f]}]       doesn't work.


Collect the multiple of one determinant?

m = {{2, 6, 4}, {2, 6, 5}, {-3, 6, 6}};      Consider I'm doing calculation by hand. I want to collect the multiple 6 of second column, how to do that? I'd like the result something like the following. The main purpose is to show the solution steps(in Notebook or Latex) $$\begin{align*}det(m)=6~det\left(\begin{array}{ccc} 2& 1 & 4 \\ 2 & 1 & 5 \\ -3 & 1 & 6 \\\end{array}\right);\end{align*}$$ Maybe something `collect[m]` function, and generate all possible results? or $$\begin{align*}det(m)=2~det\left(\begin{array}{ccc} 1 & 3& 2\\ 2 & 6& 5 \\ -3 & 6& 6 \\\end{array}\right);\end{align*}$$