Solving Killing equations

Is it possible to solve Killing equations in _Mathematica_ for a general vector? I am looking for a way to create Killing equations and then find what the vectors are, but I have a problem with this. * * * ### Introduction First of all what they are. Without going in to the all gory details of general relativity, in short, Killing vectors are vectors that satisfy Killing equations: $\nabla_\mu X_\nu+\nabla_\nu X_\mu=0$ Killing vector, according to the dimensions we are working in (3D, 4D etc.), and what coordinates, is a list with number of elements equating the number of dimension. So If I'm working in 2D sperical coordinate system, and I'm only interested in radial and polar coordinates, I'll have a Killing vector of the form               X = { Xθ[θ,ϕ], Xϕ[θ,ϕ]}      If I'm working in 4D spherical coordinate system with coordinates $\\{t,r,\theta,\phi\\}$, I'll have a Killing vector with components               X = { Xt[t,r,θ,ϕ], Xr[t,r,θ,ϕ], Xθ[t,r,θ,ϕ], Xϕ[t,r,θ,ϕ]}      The above equation is given in terms of covariant derivative, and for covariant vector (with indices down) is $\nabla_\mu X_\nu=\frac{\partial X_\nu}{\partial x^\mu}-\Gamma^\lambda_{\mu \nu}X_\lambda$ Now $x^\mu$ is just coordinate for $\mu=t,r,\theta,\phi$, so $x^t=t, x^r=r$ etc. And $\Gamma^\lambda_{\mu \nu}$ are Christofell symbols that I can easily find. Oh, and sometimes the partial derivative is noted as $\partial_\mu$. * * * ### Example I'm working on an easy example, a 2D sphere. It's metric is given by $\begin{pmatrix} 1 & 0\\\ 0 & \sin^2\theta \end{pmatrix}$ My code is this               xIN = {θ, ϕ};     n = 2;     met = {{1, 0}, {0, Sin[θ]^2}};     inversemetric := Inverse[met] // FullSimplify     coord = xIN;          (*Christoffel symbols*)          affine :=       affine = Simplify[        Table[(1/2) Sum[           inversemetric[[μ, ρ]] (D[met[[ρ, ν]],                coord[[λ]]] +               D[met[[ρ, λ]], coord[[ν]]] -               D[met[[ν, λ]], coord[[μ]]]), {ρ, 1,             n}], {ν, 1, n}, {λ, 1, n}, {μ, 1, n}]]          listaffine :=        Table[{Style[           Subsuperscript[Γ,             Row[{coord[[ν]], coord[[λ]]}], coord[[μ]]],            18], Style[affine[[λ, ν, μ]], 14]}, {λ,           1, n}, {ν, 1, n}, {μ, 1, n}] // FullSimplify;          data = {#[[1]], "=", #[[2]], #[[3]], "=", #[[4]]} & /@         Partition[DeleteCases[Flatten[listaffine], Null], 4];          data = Insert[data[[#]], #, 1] & /@ Range[Length[data]];     TableForm[data]          (*Derivations*)          der[f_, σ_] := D[f, xIN[[σ]]]          derxU[xU_, μ_, ν_] :=       Module[{λ},         der[xU[[μ]], ν] +          Sum[affine[[ν, μ, λ]] xU[[λ]], {λ,            1, 2}]] // FullSimplify          derxd[xd_, μ_, ν_] :=       Module[{λ},         der[xd[[μ]], ν] -          Sum[affine[[ν, λ, μ]] xd[[λ]], {λ,            1, 2}]] // FullSimplify          derxUup[xU_, μ_, ν_] :=       Module[{λ, ρ},         Sum[inversemetric[[ν, ρ]] (der[xU[[μ]], ρ] +             Sum[affine[[ρ, μ, λ]] xU[[λ]], {\     λ, 1, 4}]), {ρ, 1, 4}]] // FullSimplify          derxdup[xd_, μ_, ν_] :=       Module[{λ, ρ},         Sum[inversemetric[[ν, ρ]] (der[xd[[μ]], ρ] -             Sum[affine[[ρ, λ, μ]] xd[[λ]], {\     λ, 1, 4}]), {ρ, 1, 4}]] // FullSimplify      Now, I have specified the general form of my Killing vector:               ξ = { ξθ[θ, ϕ], ξϕ[θ, ϕ]};      And I've set up Killing equations:               Killeq = Table[ derxd[ξ, ν, μ] + derxd[ξ, μ, ν] == 0,                                       {μ, 1, 2}, {ν, 1, 2}] // Flatten      And I get my equations, in Table form $$ \begin{array}{c} 2 \xi \theta ^{(1,0)}(\theta ,\phi )=0 \\\ \xi \theta ^{(0,1)}(\theta ,\phi )+\xi \phi ^{(1,0)}(\theta ,\phi )-2 \cot (\theta ) \xi \phi (\theta ,\phi )=0 \\\ \xi \theta ^{(0,1)}(\theta ,\phi )+\xi \phi ^{(1,0)}(\theta ,\phi )-2 \cot (\theta ) \xi \phi (\theta ,\phi )=0 \\\ 2 \sin (\theta ) \cos (\theta ) \xi \theta (\theta ,\phi )+2 \xi \phi ^{(0,1)}(\theta ,\phi )=0 \\\ \end{array} $$ And that's what I should get, so the code is working (yaaaay! :D) Now, even though I could just specify `Killeq[[1]] = 0` and so on, is there an automatic way for _Mathematica_ to see if there are same, and just give me the list of the ones left (Some kind of `If` statement)? The problem could be identifying which equation is which later on, but I could just look at the original form of Killeq and see it from there. This would be useful if I need to make `TeXForm` later on. And the second part that is bothering me is: How do I solve this? I tried with               DSolve[{ Killeq[[1]], Killeq[[2]], Killeq[[4]]}, { ξθ[θ, ϕ], ξϕ[θ, ϕ]}, {θ, ϕ}]      But I got the error: > >     `DSolve::overdet: There are fewer dependent variables than equations, >     so the system is overdetermined.` >   Is there a way of finding these kind of things with _Mathematica_? :\ * * * ### Edit I tried by separately solving each equation               Flatten[ Table[         DSolve[ Killeq[[i]], ξθ[θ, ϕ], {θ, ϕ}], {i, 1, 4}]]      And I get this: $$ \begin{array}{c} \xi \theta (\theta ,\phi )\to c_1(\phi ) \\\ \xi \theta (\theta ,\phi )\to \int_1^{\phi } \left(2 \cot (\theta ) \xi \phi (\theta ,K[1])-\xi \phi ^{(1,0)}(\theta ,K[1])\right) \, dK[1]+c_1(\theta ) \\\ \xi \theta (\theta ,\phi )\to \int_1^{\phi } \left(2 \cot (\theta ) \xi \phi (\theta ,K[1])-\xi \phi ^{(1,0)}(\theta ,K[1])\right) \, dK[1]+c_1(\theta ) \\\ \xi \theta (\theta ,\phi )\to -\csc (\theta ) \sec (\theta ) \xi \phi ^{(0,1)}(\theta ,\phi ) \\\ \end{array} $$ Now, given that my 2nd and 3rd equations are repeating, is there any way of solving this with _Mathematica_? I am interested, because it would greatly help me find Killing equations in higher dimensions.


PostProcessing TraditionalForm output to append a vertical bar?

This simple task is giving me trouble. Suppose I'd like to take the output from               TraditionalForm[Integrate[x^2,x]]      and post-process it to append a vertical bar like $$ {x^3\over 3}\Bigg|_0^1 $$ or a set of left & right brackets like $$ \left[\frac{x^3}{3}\right]_0^1 $$ I am trying to figure out the best way to _approach_ this problem. Is to convert the output to a string and then use `StringJoin`?


Image Tooltip exported to HTML

Graphics@Tooltip[Hyperlink[{Purple, Rectangle[{0, 0}]}, "http://www.wolfram.com"],      Graphics[Disk[]]]      Is it possible to make image tooltip kept in the html? ![enter image description here](http://i.stack.imgur.com/ZGk7a.png)


Formatting text through pattern matching

I am trying to format some text based on some patterns.               Clear[highlight];     SetAttributes[highlight, HoldAll];     highlight[pattern_, style_] :=        s_String :> Row[List @@ StringReplace[s, t : pattern :> style[t]]]      This works fine and dandy if a match is found:               "foo bar baz" /. highlight["foo", Style[#, Red] &]      But doesn't if no match is found:               "fu bar baz" /. highlight["foo", Style[#, Red] &]      > `Row["fu bar baz"]` The failure to match has left us with an ugly `Row`. I'm having a bit of trouble fixing this case, perhaps you can help?


Write the equation as a polynomial in x and extract the coefficient of x^2

I need help solving this problem. Thank you.               (a*x^2 + b*x*Sin[y] + c*Sin[y])^2 + (a*Sin[y]^2 + b*x)^3      > Write the above as a polynomial in x and extract the coefficient of x^2. The answer is: > >     b^2 (3a + 1)*Sin[y]^2 + 2*a*c*Sin[y] >


How can I produce a list of solutions for a function which is updated with updated variables using for loop?

I need to loop over a set of equations, solving for X and adding the new X value to the old X value at each step. The output I need is a list `{x1, x1 + x2, x1 + x2 + x3, etc...}` where `xn` is the solution to the n`th equation. I have tried to do this using a `For` loop but I am getting errors. Here is a simplified version of my code: > $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >> > > $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >> > > $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >> > > General::stop: Further output of $RecursionLimit::reclim will be suppressed > during this calculation. >> How can I get the result I want? I am using _Mathematica_ 7


Behaviour of Locator

I seek advice regarding the constrained behaviour of the Locator: appears confined to square {0,0}->{1,1}. When I change starting position it snaps to this constrained region. The code I am referring to follows:               Manipulate[      Module[{cn, d}, cn = {c1, c2, c3};        d = Norm[# - pt] & /@ {c1, c2, c3};        Graphics[{{Black, Point[cn]},          MapThread[{#1, Circle[#2, #3]} &, {{Red, Green, Blue}, cn, d}]}]       ],      {pt, {1, 1}, ControlType -> Locator, LocatorRegion -> Full},      Initialization -> (c1 = {0, 0}; c2 = {3, 0}; c3 = {0, 3};)      ]      The constraint remains whether I define PlotRange, use `EuclideanDistance` or otherwise define the distance function. The following graphic shows (obviously) this is well defined outside the region of constraint of the `Locator`. Intersection point at {4,4}with fixed points at{0,0}, {1,0}, {0,1}. ![enter image description here](http://i.stack.imgur.com/CXlwI.jpg) Image generated by:               Graphics[{{Black, Point[cc = {{0, 0}, {1, 0}, {0, 1}}]}, {Red,         Point[{{4, 4}}]}, Map[Circle[#1, Norm[# - {4, 4}]] &, cc]}]      * * * I can get around the constraint using `Slider2D` but I am still uncertain about the Locator issue.               Manipulate[      Module[{cn, d}, cn = {c1, c2, c3};        d = Norm[# - pt] & /@ {c1, c2, c3};        Graphics[{{Black, Point[cn]}, {Red, PointSize[0.02], Point[pt]},          MapThread[{#1, Circle[#2, #3]} &, {{Red, Green, Blue}, cn, d}]},         PlotRange -> {{-5, 5}, {-5, 5}}]       ],      {pt, {-4, -4}, {4, 4}, ControlType -> Slider2D},      Initialization -> (c1 = {0, 0}; c2 = {1, 0}; c3 = {0, 1};)      ]      Thank you @Nasser I look forward to trying your code.


Replace content of selected cells, each getting different new content

Let's say I select 2 different cells and then attempt to replace their content using `NotebookWrite` inside a button. How might I replace each cell's content individually instead of the current functionality I am getting.               Button["Write", NotebookWrite[EvaluationNotebook[], "Write"]]     Dynamic[Refresh[NotebookRead[SelectedNotebook[]],UpdateInterval -> 1]]      ![enter image description here](http://i.stack.imgur.com/8XX3U.png) When I click on the `Write` button, only the last selected `Cell` gets replaced. ![enter image description here](http://i.stack.imgur.com/B15WN.png) Is there a safe technique to replace each cell with unique content?


Plotting best-response functions

I'm a newbie in Mathematica. I'm trying to solve for two functions (best- response functions in a simple game), and then to plot the functions on the same graph. One function is p1 = resp1(p2) and the other is p2 = resp2(p1). I'd like to plot them both such that p1 is the x-axis and p2 is on the y-axis. The goal is that I'd like to be able to alter the form of q1 and q2 and easily see how the shape of the best-responses functions change and how many equilibria exist (the intersections of the best responses).               q1 = A - a*p1 + c*CDF[GammaDistribution[\[Alpha], \[Beta]], p2];     q2 = B - b*p2 + c*CDF[GammaDistribution[\[Alpha], \[Beta]], p1];     r1 = (p1 - mc)*q1;     r2 = (p2 - mc)*q2;     BR1t = FullSimplify[Solve[ D[r1, p1] == 0, p1, Reals],Assumptions -> {p2 > 0, p1 > 0}];     BR2t = FullSimplify[Solve[ D[r2, p2] == 0, p2, Reals],Assumptions -> {p1 > 0, p2 > 0}];     A = 100; B = 100; a = 1;  b = 1; c = 30; mc = 1;     \[Alpha]= 4; \[Beta] = 2;      resp1 = p1 /. First[BR1t]     resp2 = p2 /. First[BR2t]          g1 = Plot[resp1, {p2, 1, 100}]     g2 = Plot[resp2, {p1, 1, 100}]      I'm not sure what comes next in terms of creating the single plot.... any help would be appreciated. Thank you.


Mathematica on Linux Gentoo

I'm not sure if this is the right place where to put this question. Sorry if it isn't. Is there anyone having experience with Mathematica and Linux Gentoo? I have a friend trying to install Mathematica 9 on a Linux Gentoo server machine and he has many troubles. First a missing graphics library (now apparently solved), then libasound.so.2 library error message. Any suggestion is welcome. Thanks in advance.


Is there a function similar to SQL's Iserror?

I have an output which I want to hide if there is an error otherwise display it. The output is a Dynamic[output] so I can't simply use something like               If[IntegerQ[output],output,""]      or               If[Head[output]==Integer,output,""]      becasue it seems that although this method would work for other items such as integers, text and so on, a dynamic object stays a dynamic object whether there is an error or not. What I am looking for is something that does the following               If there is an error occuring when I display this dynamic object, display nothing otherwise display the dynamic object.      I have tried the Check and Quiet functions together and what I get is below. I don't care about the typed error messages but I'm talking about the output cells that look like red blocks with writing inside of them. I hope this explains things better. I have put a picture instead of code becasue there are a lot of background definitions for all the things in the grid that would be too long to put here. ![Check and Quiet](http://i.stack.imgur.com/K8p8o.jpg)


How to capture implicit fails in Plot or Show?

How can I make a construct similar to C++ functions:               try{} catch{}      I want to use it to avoid showing a lot of errors in the plot area when for example one of the arguments becomes complex or overflows etc. I want to avoid of creating a plot if ANYTHING goes wrong, so it does not look like the one below:               Show@Graphics[Line[{{Complex[1, 1]}, {Complex[2, 2]}}]]      ![Mathematica graphics](http://i.stack.imgur.com/b7tJG.png) Approaches like:               Check[Show[Graphics[Line[{{Complex[1, 1]}, {Complex[2, 2]}}]]], Show[Graphics[{}]]]      or               Check[Graphics[Line[{{Complex[1, 1]}, {Complex[2, 2]}}]], Show[Graphics[{}]]      also fail.


Is it possible to construct a function to make a poor man's Mathematica database?

I have a function that is set up to write to a database with 10-20 standard variables with 10 fields each, but the application is going to a place where database access is not available. Can Mathematica read an Excel file and pick up the portions of the file that relate to one of these 20 variables, change them if needed and write the whole thing back again? If so, how would that be accomplished? Thanks!


Sum of Squares without multiplication

I want to sum the squares for a given number N from 1 without using Multiplication. Is it possible?


J/Link: getArray2() returns wrong array

I want to convert a matrix from Mathematica to an `int[][]` in _Java_. I use the code below:               KernelLink ml;     ml.evaluate(expr);     int[][] matrix= ml.getIntArray2();      As example: if `expr` is `{{1,0},{0,1}}` I get `[[1,0,0,1]]` instead `[[1,0],[0,1]]`. What's wrong? Did I misunderstand `getIntArray2()`?


Applying TextRecognize on alpha-numerical table

From time to time I have to extract data from scanned papers or rasterized PDFs. Imagine a table of the following kind (but much longer): ![enter image description here](http://i.stack.imgur.com/lP6Yt.jpg) A naive application of `TextRecognize` on the image fails spectacularly:               "OOE-     20B-     70E~     20E-     90E-     70E-     70B-     30B-     30B-     ZOE     .50E+O2     .50E+02     .0OE+02     .O0E+O2     .00E+O2     .OOE+02     18E+O4     .30E+O3     .70E+03     10E+03      Did anybody use `TextRecognize` successfully on similar images?


Ways to plot interpolating functions more economically?

I am interpolating a lot of data over geographic coordinates obtained via GPS, and frequently I need to plot these interpolated functions together. For example, I may have an interpolated elevation map that looks like this:               f0 = InterpolatingFunction[{{x0min, x0max},{y0min, y0max}}, <>]      and several other interpolated functions of other data sets that stretch over subregions of the rectangle `{{x0min, x0max}, {y0min, y0max}}`. So, say,               f1 = InterpolatingFunction[{{x1min, x1max},{y1min, y1max}}, <>]      where `{{x1min, x1max}, {y1min, y1max}}` lies entirely within `{{x0min, x0max}, {y0min, y0max}}` and so on. I need to plot these interpolated functions A LOT and in attempts to change the visualisations of my data sets, I need an efficient way to extract their limits and pass them on to plotting functions. For this I have written the following function:               intLimits[intF_ /; (Head@intF === InterpolatingFunction), x_: x, y_: y] :=           Module[{ArgList},             ArgList = First@intF;             Which[Length@ArgList < 2,                   ArgList~Prepend~x,                   Length@ArgList == 2,                   {First@ArgList~Prepend~x, Last@ArgList~Prepend~y}             ]           ]      which I use with plotting functions like so               f0plot= Plot3D[f0[x,y], Evaluate@First@intLimits[f0], Evaluate@Last@intLimits[f0]];     f1plot= Plot3D[f1[x,y], Evaluate@First@intLimits[f1], Evaluate@Last@intLimits[f1]];      This works well if used to plot a list of interpolation functions (replacing `f0` with `#` and mapping at the list) but it seems a bit ugly and the length of adding `Evaluate@First@intLimits` doesn't help with the readability of my notebook although seems necessary given the `HoldAll` `Attribute` of all plotting functions. So my question is: is there a more clever way to define the function `intLimits` or a better way in general to be able to pass on the range of variables of interpolated functions to plotting functions?


Fastest way to concatenate many text files in a given directory

I have about 1 million .txt text files in a directory which I would like to all concatenate in one single text file (separated by a newline character "\n"). Because of the number of files and their size I would rather not like to read everything in memory first. So I was wondering - what is the fastest way to do this in Mathematica, without having to resort to read everything in memory first? cheers, Tom


Matrix multiplication that includes a tensor

How would I best express the following in Mathematica: $\begin{pmatrix}2 & 4\end{pmatrix} \begin{pmatrix}r_1 & r_2\\\r_3 & r_4\end{pmatrix} \begin{pmatrix}6 \\\ 8\end{pmatrix}$, where $r_i$ are 3-element vectors? Is there a more elegant way than this?               r1 := {1, 2, 3}     r2 := {3, 2, 1}     r3 := {2, 3, 1}     r4 := {2, 1, 3}     res := {2, 4} . {{r1//Hold, r2//Hold}, {r3//Hold, r4//Hold}} . {{6}, {8}} // ReleaseHold     res[[1]]          Out= {172, 160, 172}


Combinatorica vs Built-in functions: Use of MinimumSpanningTree

What kind of argument is expected by `MinimumSpanningTree` (from the package `Combinatorica``)? Is it possible that I am providing the right kind of argument, but that conflict between usual definitions and definitions from the package `Combinatorica`` prevents correct evaluation? Note that, conform the documentation page of `FindShortestPath`,               graph = System`PetersenGraph[4, 1, EdgeWeight -> {4, 0, 3, 1, 3, 2, 7, 8, 5, 2, 1, 6}]      Produces some weighted graph. We can then do               FindShortestPath[graph, 1, 3]      which works as expected. Note that if we use `Combinatorica`PetersenGraph` this will not work. Anyway, I would expect `MinimumSpanningTree` to work on at least one of the two graphs generated this way. Unfortunately, I cannot get it it to work. I have been unable to get `MimimumSpanningTree` to work on any graph so far. Remarks The documentation center provides very little information on `MimimumSpanningTree`. The `PetersenGraph` may not be a very nice example, as _Mathematica_ seems to point out an error in the syntax even before the package `Combinatorica`` is loaded. However, upon asking the `FullForm` of the result, everything seems to be as we expect it to be. **Edit** : Can I assume there is no efficient way to let `MinimumSpanningTree` calculate a minimum spanning tree between many points in $\mathbb{R}^2$? I suppose that for this, one should refer to How to speed up Minimum Spanning Tree algorithm?. As a test I entered a huge graph in `MinimumSpanningTree`, but an algorithm by Daniel Lichtblau was faster.


How can I rewrite this with NestList or FoldList?

The original code used `For`:               {x, y} = {1, 1};     For[i = 0, i < 5, i++,       x = x + 2 y;       y = y + 2 x;       Print[{x, y}]       ];     Clear["`*"]      I am trying to use `NestList` to replace `For`, but the result is not as I expected. How can I rewrite it?               func[{x_, y_}] := {x + 2 y, y + 2 x};     NestList[func, {1, 1}, 5]


How can a 3DBarChart be made to be fixed size and proportions?

I have a 3DBarChart that adds bar graphs as would be required by the dataset, but as it gets wider runs off the page and can not be printed. Is there a way to fix the height & width of the 3DBarChart so that it maintains it's size and proportions and will not become too large to print regardless of the dataset it receives? Thanks!


Entering Sum in traditional form

The documentation for `Sum` says that it is possible to replace `Sum` by `Esc``sum``Esc`. The limits ($i_\max$ and $i_\min$) should be entered as underscript $i=i_\min$ below $\sum$ and overscript $i_\max$ over $\sum$ Following the aforementioned rules, I entered the formula as:                Cell[BoxData[      UnderscriptBox[       RowBox[{        OverscriptBox["\[Sum]", "10"], "q"}],        RowBox[{"q", "=", "1"}]]], "Input",      CellChangeTimes->{{3.572528196734789*^9, 3.572528215609144*^9}},      EmphasizeSyntaxErrors->True]      which gives an error > Syntax::sntxi: Incomplete expression; more input is needed . How do I fix this? ![](http://i.stack.imgur.com/6SxcA.png)


Using a user defined NormFunction in FindFit or NDSolve

I would like to use a different norm instead of the 2-norm in `FindFit` ( _Mathematica_ 9). For example, instead of using $$\sqrt{\sum (x_{\mathrm{model}} - x_{\mathrm{data}})^2}$$ I'd like to use $$\sum \frac{x_{\mathrm{model}}}{x_{\mathrm{data}}}$$ I can tell `FindFit` to use a user-created function as the `NormFunction`. However, I am unsure of the syntax to use when defining $x_{\mathrm{model}}$. Can anyone point me to example code for using a user-defined `NormFunction` in `FindFit` or `NDSolve`?


simplification rule with symmetry

What rule can you think of to replace the first line by the second? ![Mathematica graphics](http://i.stack.imgur.com/9do96.png) ![Mathematica graphics](http://i.stack.imgur.com/gCt1h.png) I have a bunch of expression like these, which I would like to simplify. All dependent cross terms must be written in the same order, using $\epsilon^{i j} A_i \times B_j = \epsilon^{i j} B_i \times A_j $. The other expressions look like this, but there are a few differences:   * The names of the fields in the crossproduct differ; e.g. $e_{2 i}$ and $\omega_{2 i}$ instead of $e_{1 i}$ and $e_{2 i}$   * The sum can contain more terms. In particular it can contain more cross products   * Terms that are dependent may not appear right after each other in the sum Which rule would cover all such expressions? This is the input for the first line.               \[Epsilon]^ij*((\[Sigma]*Cross[Subscript[Subscript[e, 1], i], Subscript[Subscript[\[Omega], 1], j]]*Subscript[M, 1])/4 + (\[Sigma]*Cross[Subscript[Subscript[\[Omega], 1], i], Subscript[Subscript[e, 1], j]]*Subscript[M, 1])/4)


How to extract the coefficient from an expression

Here is the expression. ![the expression](http://i.stack.imgur.com/KAXgt.jpg) I want to extract the coefficient just as the table showing below. ![the coefficient](http://i.stack.imgur.com/RcENY.jpg) I can do it by hand, but I expect a code that can automatically identify how many differenct terms there are ,what is its coefficient and show them all in a table. this is the expression for Mma. > expr= (3 Subscript[1, b] Subscript[2, a])/8+1/8 E^(I [Theta]) Subscript[1, > b] Subscript[2, a]+1/8 E^(2 I [Theta]) Subscript[1, b] Subscript[2, a]+3/8 > E^(3 I [Theta]) Subscript[1, b] Subscript[2, a]-(3 Subscript[1, a] > Subscript[2, b])/8+1/8 E^(I [Theta]) Subscript[1, a] Subscript[2, b]-1/8 > E^(2 I [Theta]) Subscript[1, a] Subscript[2, b]+3/8 E^(3 I [Theta]) > Subscript[1, a] Subscript[2, b]-(Sqrt[3] Subscript[3, a])/8-1/8 Sqrt[3] E^(I > [Theta]) Subscript[3, a]+1/8 Sqrt[3] E^(2 I [Theta]) Subscript[3, a]+1/8 > Sqrt[3] E^(3 I [Theta]) Subscript[3, a]+(Sqrt[3] Subscript[3, b])/8-1/8 > Sqrt[3] E^(I [Theta]) Subscript[3, b]-1/8 Sqrt[3] E^(2 I [Theta]) > Subscript[3, b]+1/8 Sqrt[3] E^(3 I [Theta]) Subscript[3, b] * * * I think of a example as below:               tab[expr_] := {#,           Coefficient[           expr, #]} & /@ (expr //             List @@ # & // # /. {Power[_, _] -> 1, Rational[_, _] -> 1,               E -> 1} & // Union) // Grid[#, Frame -> All] &      so, `expr//tab` will get the table above.


Transforming an image as an object

The problem is following: I have a following animation:               Animate[      Graphics[{Translate[Rotate[Rectangle[], ψ Degree], {x, 0}],         Translate[Rotate[Rectangle[], -ψ Degree], {1.75 - x, 0}]}],      {x, 0, 1},      {ψ, 0, 90},      AnimationRunning -> False      ]      For rectangles it works perfectly, but when I try to put instead of these rectangles any image, it shows me "Image is not a Graphics primitive or directive" error. How to put any image(raster-, vector- based) and transform it the way like it does with primitives?


Should eigenvalues be ordered?

When I run Eigensystem on a symmetric matrix, the list of eigenvalues (and so, the corresponding eigenvectors) is ordered by absolute values, which is quite bizarre (it does make sense if you view the symmetric eigenvalue problem as a special case of the general eigenvalue problem, where the eigenvalues are complex, so modulus is as good a way to order them as any). Has it always been thus? Is this considered a feature? If one wants the "obvious" ordering, the following function works fine, but it's a bit annoying.               sortify[es_] := Module[{pp = FindPermutation[es[[1]]]}, PermutationReplace[#, pp] & /@ es]      **EDIT** My personal view is that this is a bug. Mathematica (or any system, for that matter) should always return things in canonical order, which happens to be the one coming from the total ordering on the real line for real numbers.


Finding the square root of a squared number?

# Taking the square root of the square of a number **Variable set to a real value** I'm wondering why these examples               a = -4.3;          Sqrt@a²     Sqrt@(a^2)     Sqrt[a^2]     Sqrt[a²]      each return > 4.3 the `FullForm` of which is               %//FullForm      > 4.3` yet               Sqrt@a^2      returns the complex number, > -4.3 + 0. I the FullForm of which is               %//FullForm      > Complex[-4.299999999999999`,0.`] Why is the last case output as a complex number (with a slightly different real component)? * * * **With an unbound variable**               ClearAll[b]          Sqrt@b²     Sqrt@(b^2)     Sqrt[b^2]     Sqrt[b²]      each of the above returns ![b](http://i.stack.imgur.com/TMsZG.png) the `FullForm` of which is > Power[Power[b,2],Rational[1,2]] yet               Sqrt@b^2      returns > b the `FullForm` of which is               %//FullForm      > b Why is the last case treated differently? * * *


How to ignore terms containing in the summation of multiplications

n=4;L=3;     p0[n_Integer]:=     Product[     Sum[Subscript[r, k][l, l], {l, L - 1}], {k, n}] //      Expand;      How to ignore terms containing three or more multiplications of [2, 2] in this sum. Example, I want to ignore this term...               Subscript[r, 1][1, 1] Subscript[r, 2][2,      2] Subscript[r, 3][2, 2] Subscript[r, 4][2, 2]


Define a function on a parameter argument set to zero

Say I have an expression (matrix) that depends on several variables.               f= {{a, b+c},{2a-b^2,c^5+a b}}      I want to define new matrices with the single parameter dependencies removed. For example, I want:               ma = f - Block[{a=0}, f]     mb = f - Block[{b=0}, f]     mc = f - Block[{c=0}, f]      or perhaps I should be using               ma = f - (f/.a->0)     mb = f - (f/.b->0)     mc = f - (f/.c->0)      Thusfar, these implementations work as expected. But in my actual problem, there are many more parameters than three so I would like to design something such as:               m[var_]:= f - Block[{var=0}, f]      or               m[var_]:= f - (f/.var->0)      The goal here is to create one general function matrix that I can specify a parameter, and it removes the parameter-free part. These methods give errors and don't work. Another method I've tried is to simply create a Table of individual matrices rather than a matrix function. e.g.:               Table[m[z]] := f - Block[{z=0}, f], {z, {a, b, c}}]       which should make individual expressions for m[a], m[b], and m[c]. This also doesn't work correctly. My last idea would be to make a rank 3 tensor m using Table which has subdivisions that are the matrices I want (a list of matrices, essentially). This would be implemented, it seems, by simply adding one extra set of square brackets around z in the code above, resulting in a rank 3 tensor for m, with m[[a]], m[[b]], and m[[c]] as the appropriate matrices. No luck here either. Actually, this Table method of defining many functions has not worked for me in the past in simpler contexts either. What is the proper way of solving a problem like this?


Using ChemicalData to make molecule graphics

I would like to take the acetone $((CH_3)_2CO)$ and chloroform $(HCl_3)$ molecules that Mathematica's chemical data provides, and plot them together. I want to show how chloroform can hydrogen bond to acetone. Right now I have them plotted on top of each other :/               Show[ChemicalData["Chloroform", "MoleculePlot"],       ChemicalData["Acetone", "MoleculePlot"]]      ![acetone and chloroform](http://i.stack.imgur.com/FhGDS.jpg)


Defining a new Function using RegionPlot

I'm trying to make images like this: ![int picture](http://i.imgur.com/2Q7fNvs.png) to illustrate 2D integrals to a calculus class. I used the code               f1[x_,y_]=x^2+x y;     region1 = (x - 1.5)^2 + (y - 1.5)^2 < 1 && y > 1.5;     fig1 = Plot3D[f1[x, y], {x, 0, 3}, {y, 0, 3}, Mesh -> None,         PlotStyle -> Opacity[0.25]];     fig2 = Plot3D[f1[x, y], {x, 0, 3}, {y, 0, 3},         RegionFunction -> Function[{x, y, z}, region1], Filling -> Axis,         Mesh -> None, PlotStyle -> {Opacity[.25]},         FillingStyle -> {Gray, Opacity[.5]}];     Show[fig1, fig2]      to make this but would like to automate the procedure, defining a new plot function that takes as input the integration region used by RegionPlot:               IntRegionPlot[f_, region_] :=        Module[{background, volume},         background =          Plot3D[f[x, y], {x, 0, 3}, {y, 0, 3}, PlotRange -> {0, Automatic},           Mesh -> None, PlotStyle -> Opacity[.25], BoxRatios -> {1, 1, 1}];        volume :=          Plot3D[f[x, y], {x, 0, 3}, {y, 0, 3},           RegionFunction -> Function[{x, y, z}, region], Filling -> Bottom,           Mesh -> None, PlotStyle -> Opacity[.25],           FillingStyle -> {Gray, Opacity[.5]}];        Show[background, volume]];     IntRegionPlot[f1, region1]      But this yields the error > Plot3D::invregion: "(-1+x)^2+(-1+y)^2<1 must be a Boolean function." What have I done wrong with RegionPlot?


is it possible to combine a step monitor with a 3d contour plot

ph = 80;     pc = 20;     kp = 0.5;     kc = 0.5;     kh = 0.778;     rt = 0.25;     rd = 0.1;     td = 10;     cfc = 10;     cfh = 10;     cobr0 = 68000;     ios0 = 75488.9;               c = {(120 - t1)*cfh == (t2 - 70)*cfc,        fic == (t1 - 60)*cfh,        fih == (140 - t2) + cfc,        cobr == (pc*fic) + (ph*fih),        ap == (cfh*(120 - t1))/(kp*(120 - t2)),        ac == fic/(kc*dtc),        ah == fih/(kh*dth),        dtp == (((120 - t2)*(t1 - 70)*(((120 - t2) + (t1 - 70))/2)))^(1/3),        dtc == (((t1 - 35)*40*(((t1 - 35) + 40)/2)))^(1/3),        dth == ((40*(179 - t2)*((40 + 179 - t2)/2)))^(1/3), t1 >= 80,         t2 <= 110, dtp > 30, dtc > 30, dth > 30, ap >= 0, ah >= 0, ac >= 0};          ios = 6110*((ap + 0.00000001)^0.65 + (ac + 0.000000001)^0.65 + (ah +              0.000000001)^0.65);          pts = NMinimize[{ios, c}, {ap, ac, ah, dtc, dth, dtp, cobr, fih, fic,           t1, t2}, Method -> "NelderMead",          StepMonitor :> (Sow[{ac, ah, ap}])] // Reap;          ContourPlot3D[ios, {ac, 0, 2}, {ah, 0, 2}, {ap, 0, 2},       Contours -> 10,       Epilog -> ({Red, PointSize[0.01], Line[pts[[2, 1]]], Yellow,          Point /@ pts[[2, 1]], Blue, PointSize[0.02],          Point[pts[[2, 1, 1]]]})]      So here is my problem. I can get the global optimum and i can create a 3d contour plot, but i can't figure out how to combine a step monitor with all of the above (or if it's even possible)


Can I force a function to quit and return some value after a certain amount of time has passed during its evaluation?

Imagine I provide some random input to function like `FindInstance[]`, and I observe that, despite the existence of good solutions, the function will, with some probability, indefinitely evaluate without success. For an example, please see my earlier question: Why is FindInstance failing when I relax a set of constraints? Can I somehow force the function to return, say, an empty list {} after some time $T$ has passed?


Trouble with links to symbol pages generated by Wolfram Workbench

I am having some troubles with documentation generated by wolfram workbench. When i try to open symbol page created with workbench by pressing `F1` I get a search page instead of my symbol page. When I try to open page with make template (`Ctr`+`Shift`+`K`) I get the message that the page does not exist, even though I can find it through search. My guess is that page is not linked with symbol, but I don't know why it happens. Is there any way to fix it ? UPD: My Mathematica version is 9; By using `Ctr`+`Shift`+`K` i mean this: ![enter image description here](http://i.stack.imgur.com/p6Ozz.png) The message with will show up only if notebook was launched with workbench, in other cases Mathematica will just ignore this attempt. If I set PackletInfo.m like this:                   Paclet[           Name -> "TheoryOfComputation",           Version -> "1.0.0",           MathematicaVersion -> "9+",           Description -> "Theory of Computation package",           Creator -> "Me",           Extensions -> {           {             "Kernel",              Context -> {"TheoryOfComputation`"}           },           { "Documentation",              Resources-> {"Guides/TheoryOfComputation"},             Language -> "English",             MainPage->"Guides/TheoryOfComputation",             LinkBase->"TheoryOfComputation"           }        }]      I can type something like MyPackage`MySymbol, press F1 and this works fine. But with this i can't use function templates. Also, typing MySymbol and pressing F1 leads to search page again, even thought result of ?MySymbol have link to documentation page


Revert FullForm-ed text to prettyprinted

Sometimes strings in a notebook/package file end up garbled due to some unknown/unintentional conversion of the expression/cell/notebook. I could not find a way to revert such unreadable text to its original version. When I convert such a cell to `OutputForm` (via the menu option), the result looks similar to the original, but then I cannot copy the text anymore. From this (inserted as image to maintain formatting): ![Mathematica graphics](http://i.stack.imgur.com/NgQLD.png) To this:               "Set.\!\(\*     StyleBox[\"obj\",\nFontSlant->\"Italic\"]\).\!\(\*     StyleBox[\"new\",\nFontSlant->\"Italic\"]\), Set.\!\(\*     StyleBox[\"obj\",\nFontSlant->\"Italic\"]\).\!\(\*     StyleBox[\"field\",\nFontSlant->\"Italic\"]\).\!\(\*     StyleBox[\"new\",\nFontSlant->\"Italic\"]\) or Set.\!\(\*     StyleBox[\"obj\",\nFontSlant->\"Italic\"]\).\!\(\*     StyleBox[SubscriptBox[\"f\", \"1\"],\nFontSlant->\"Italic\"]\).\!\(\*     StyleBox[SubscriptBox[       StyleBox[\"f\",\nFontSlant->\"Italic\"], \"2\"],\n\     FontSlant->\"Italic\"]\).(\[Ellipsis]).\!\(\*     StyleBox[\"new\",\nFontSlant->\"Italic\"]\) is interpreted as \     SetField[\!\(\*     StyleBox[\"obj\",\nFontSlant->\"Italic\"]\), \!\(\*     StyleBox[\"new\",\nFontSlant->\"Italic\"]\)], SetField[\!\(\*     StyleBox[\"obj\",\nFontSlant->\"Italic\"]\), \!\(\*     StyleBox[\"field\",\nFontSlant->\"Italic\"]\), \!\(\*     StyleBox[\"new\",\nFontSlant->\"Italic\"]\)] or SetField[\!\(\*     StyleBox[\"obj\",\nFontSlant->\"Italic\"]\), \!\(\*     StyleBox[SubscriptBox[       StyleBox[\"f\",\nFontSlant->\"Italic\"], \"1\"],\n\     FontSlant->\"Italic\"]\), \!\(\*     StyleBox[SubscriptBox[\"f\", \"2\"],\nFontSlant->\"Italic\"]\), \     \[Ellipsis], \!\(\*     StyleBox[\"new\",\nFontSlant->\"Italic\"]\)] respectively. Note that \     Set modifies the behaviour of Dot."      I don't really know what the `Cell > Convert To` menuoptions do, as both cells are in `StandardForm` and are also set to `StandardForm Display`. Is there a way to revert the garbled text to its original without manually editing it? Anyone knows the cause of this behaviour? You are welcome to edit the title of this post as I had no idea how to make it informative. **Edit:** These conversions mostly happen in package files (.nb) when I comment out some usage messages or other formatted text. The text immediately converts to raw form when I remove the comment markers. Sadly, when I use kguler's answer below, and copy the text reverted by `Normal`, the pasted text appears _again_ in raw form.


LibraryLink Documentation

The documentation for LibraryLink has the following example               DLLEXPORT int demo_TI_R(WolframLibraryData libData,      mint Argc, MArgument *Args, MArgument Res) {      MTensor T0;      mint I0;      double R0;      T0 = MArgument_getMTensor(Args[0]);      I0 = MArgument_getInteger(Args[1]);      R0 = libData->MTensorVector_getReal(T0, I0);      MArgument_setReal(Res, R0);     return LIBRARY_NO_ERROR;     }      I am trying to figure out what the command MTensorVector_getReal does. This looks like it is undocumented. Similarly, in the following example from the documentation, it is not clear what funStruct is, and where it is coming from. Should it be libData instead?               DLLEXPORT int demo1_TI_R(WolframLibraryData libData,      mint Argc, MArgument *Args, MArgument Res) {      MTensor T0;      mint I0;      double R0;      T0 = MArgument_getMTensor(Args[0]);      I0 = MArgument_getInteger(Args[1]);      R0 = funStruct->MTensorVector_getReal( T0, I0);      libData->MTensor_free(T0);     MArgument_setReal(Res, R0);     return LIBRARY_NO_ERROR;     }


Crank-Nicolson with NDSolve?

As far as I understand, the Crank-Nicolson method (a.k.a. trapezoidal method) can be expressed as a second order implicit Runge-Kutta method. It's Butcher tableau is:                0 |  0    0      1 | 1/2  1/2     ---|----------        | 1/2  1/2      And yes these coefficients can be found in:               NDSolve`ImplicitRungeKuttaLobattoIIIACoefficients[2, Infinity]     {{{0, 0}, {1/2, 1/2}}, {1/2, 1/2}, {0, 1}}      But when I try:               NDSolve[{y'[x] == Cos[x], y[0] == 0}, y, {x, 0, 1},       Method -> {"FixedStep", Method -> {"ImplicitRungeKutta", "DifferenceOrder" -> 2,                   "Coefficients" -> ImplicitRungeKuttaLobattoIIIACoefficients}},       StartingStepSize -> 0.1]      I get an ~~error~~ warning:               NDSolve`ImplicitRungeKutta::cmsing:       Singular coefficient matrix encountered for       NDSolve`ImplicitRungeKuttaLobattoIIIACoefficients, which is not suitable for stiff systems.      **Question:** Why this? (I have Mathematica 8. Also tested on Mathematica 9, same behavior.)


Need better font control

Generally many programs have a menu item to raise/lower current font size. This is much more convenient than trying to root around in in internal mathematica options. I need to change ALL default fonts not just particular ones. For instance the help system font is itself too small on my laptop. I hope there is a way to do what I want without having to know about a lot of different settings. I am not interested in how uber flexible internal settings are but in having a product that is comfortably readable and useable without a lot of fooling around.


How do I change my font size to 18 points globally?

The default font is WAY too small. I can't read it on my jumbo-size laptop monitor, and my professors can't read my papers when I turn them in. Can somebody please provide DETAILED instructions on how to change the GLOBAL default font size to 18 points?


How to set default magnification for all windows

This is certainly a newbie question but I could not find the answer by searching. I am using Mathematica 8 under Windows 7. I want to use default magnification of 150% for all notebooks and help files which I open in Mathematica. At present I have to do it through Windows->Magnification for every single document I open which is of course tedious. I assume there is a way of setting some options which is saved across different sessions as well. Would appreciate any help.


How do I get output size to stick?

I have increased size of text to something I can read comfortable. When I delete output and evaluate notebook again with any changes made, the output text size returns to eyestrain inducing size.


Keeping Text Size the Same Throughout Entire Notebook File

Is there a way in which when you choose to format the size of the font within your notebook, for a particular cell, when you go into another cell, the default size font (12pt) will not be re-activated. I want the font size to stay constant throughout the entire notebook, until I go back and need to manually change it by hand. Example: > Format -> Size -> 16 Point


How to set up the font size permanently (i.e. for all notebooks, all future sessions?)

The default input / output font size in Mathematica's notebooks are too small for my screen. I would like to set up _permanently_ a conveniently larger font size so that in any future session I get always the size I want. Can you please help me?


Constrain movement of a locator inside Manipulate

Once again a big thank you for the great help in my earlier post: Plotting function with Dynamic parameter. It totally worked out. I now have a new coding problem               Manipulate[       Plot[Norm @ p2*t + Norm @ p1, {t, 0, 1}, PlotRange -> {0, 5}],        {{p1, {0, 0}}, Locator},        {{p2, {0, 0}}, Locator}]      Given this `Manipulate` object, how would it be possible to add a new locator that has its movement constrained to a given parametric curve? I've tried the code given on the user manual of `Locator` and of `LocatorPane`, but without success.


Horizontal Tree Layout?

I need to display arbitrary _Expressions_ in `TreeForm,` but the standard vertical layout produces too many horizontally overlapping boxes. Am I doomed to rewriting expressions as graphs and using `TreePlot` and `GraphPlot` and going down this road http://www.wolfram.com/technology/guide/FullyAutomatedGraphLayout/ or is there something I can do in a hurry to make `TreeForm` look better? Docs say               TreeForm takes the same options as TreePlot.       so I pop over to `TreePlot` and see               TreePlot[{1 -> 4, 1 -> 6, 1 -> 8, 2 -> 6, {3 -> 8, "3\[Rule]8"},        4 -> 5, 7 -> 8}, Left]      go back to `TreeForm` and try               TreeForm[a + b^2 + c^3 + d, Left]      but oops:               TreeForm::tlev: Warning: level specification Left is not a non-negative integer or     Infinity; ignored. >>


How to export data to a file?

Do[{T[i] = 2 Cos[(2*π*i)/60],        B[i] = 2 Cos[(2*π*i)/60 + π/3],        A[i] = 2 Cos[(2*π*i)/60 + (2 π)/3],        H[i] = 2 Cos[(2*π*i)/60 + (3 π)/3],        F[i] = 2 Cos[(2*π*i)/60 + (4 π)/3],        G[i] = 2 Cos[(2*π*i)/60 + (5 π)/3], Matt = ( {          {T[i], 1, 0, 0, 0, 1},          {1, B[i], 1, 0, 0, 0},          {0, 1, A[i], 1, 0, 0},          {0, 0, 1, H[i], 1, 0},          {0, 0, 0, 1, F[i], 1},          {1, 0, 0, 0, 1, G[i]}         } ), data[i] == Print[N[Eigenvalues[Matt]]]}, {i, 0, 9}]      I am getting $10\times 6$ values i.e. a total of 60. I want to store them in a matrix form. Result: > {-3.09557,3.09557,-1.41421,1.41421,-0.646084,0.646084} > > {-3.09468,3.09468,-1.42525,1.42525,-0.625768,0.625768} > > {-3.09234,3.09234,-1.45234,1.45234,-0.572806,0.572806} > > {-3.08943,3.08943,-1.48291,1.48291,-0.506382,0.506382} > > {-3.08704,3.08704,-1.50577,1.50577,-0.450331,0.450331} > > {-3.08613,3.08613,-1.51414,1.51414,-0.428007,0.428007} > > {-3.08704,3.08704,-1.50577,1.50577,-0.450331,0.450331} > > {-3.08943,3.08943,-1.48291,1.48291,-0.506382,0.506382} > > {-3.09234,3.09234,-1.45234,1.45234,-0.572806,0.572806} > > {-3.09468,3.09468,-1.42525,1.42525,-0.625768,0.625768}


Replace elements in a list

Suppose that I have a list:               G = {{{a, c}, {a, c, x}}, {{c, e}, {c, e, x}}, {{e, f}, {a, e, f}},           {{f, g}, {a, f, g}}, {{g, a}, {a, f, g}}, {{a, c, x}, {a, c}},           {{a, c, x}, {a, e, x}}, {{a, c, x}, {c, e, x}}, {{a, e, f}, {e, f}},           {{a, e, f}, {a, e, x}}, {{a, e, f}, {a, f, g}}, {{a, e, x}, {a, c, x}},           {{a, e, x}, {a, e, f}}, {{a, e, x}, {c, e, x}}, {{a, f, g}, {f, g}},           {{a, f, g}, {g, a}}, {{a, f, g}, {a, e, f}}, {{c, e, x}, {c, e}},           {{c, e, x}, {a, c, x}}, {{c, e, x}, {a, e, x}}}      in which each element of `G` is an ordered pair `{A,B}`, where `A` and `B` are sets. I would like to convert the elements `A` and `B` into the numbers such as `{a, c} -> 1`, `{c, e} -> 2`, ..., `{a, c, x} -> 10`. I also need to change all of `{c, e}` in `G` into `2`. How can I do this? I try to use `Replace` but it doesn't work.


How do I plot Numerical Range of two hermitian matrices

Let $A_1$ and $A_2$ be two $3\times 3$ hermitian matrices. Then their numerical range is defined as two-dimensional set \begin{align} \mathbb{S}=\\{\left[u^HA_1u,u^HA_2u\right]\in \mathbb{R}^2,u^Hu=1\\} \end{align} where $u$ is a unit-norm vector. Each of the $u^HA_iu,~i=1,2$ is a real number. Thus for a given $u$, I calculate the first co-ordinate as $u^HA_1u$ and second co-ordinate as $u^HA_2u$, then I have to vary $u$ through all possible unit-norm vectors. Thus $\mathbb{S}$ becomes a 2-D set. **EDIT** If it is possible to find a solution for the real case, that is fine. But then the matrices $A_1$ and $A_2$ will be of size $6 \times 6$. The reason is you can convert the above set of equations in terms of real variables and real matrices in higher dimensions (twice the dimension to be exact).


n-fold symbolic integral in Mathematica

I am trying to compute symbolically a n-fold integral (n is a parameter of a function) over, say, the cube [0,a]^n. My code looks like this               intCube[n_, a_] := Module[{xvars, range, expression},     xvars = Table[Symbol["x" <> ToString[i]], {i, 1, n}];     range = Table[{xvars[[i]], 0, a}, {i, 1, n}];     range = Row[Riffle[range, ","]];     Print[range];     expression = Product[xvars[[i]], {i, 1, n}];     Print[expression];     Integrate[expression, range]     ];      The range and the expression to integrate look both ok, however, I get an awkward result. Any ideas why ?               intCube[2, a]          {x1,0,a},{x2,0,a}     x1 x2     x1 x2 Row[{{x1, 0, a}, ",", {x2, 0, a}}]      Thanks, Ion


Boosting the performance of expensive NIntegrate by feeding in a cheap approximation of the integrand

I need to integrate an expensive likelihood `L[x]` over its n-dimensional domain. I know that `L[x]` is decently approximated by a gaussian likelihood `G[x]`, which is very cheap to evaluate. In particular, `L` and `G` share the same maximum. The approximation, however, is not good for the integral I need. I've already got a good performance boost by restricting the integration to the 4-sigma Ellipsoid predicted by `G`, as discussed in NIntegrating within an Ellipsoid. I would like to ask now if it is possible to feed NIntegrate with the information that `G` is a decent approximation for `L` so that the sampling in NIntegrate is done in a more efficient way.


How to execute JavaScipt on a webpage and then import the result on OSX?

I would like to import data from this page through Mathematica, http://www.oddsportal.com/soccer/netherlands/eredivisie/ . I tried importing through the default Import function               d = Import["http://www.oddsportal.com/soccer/netherlands/eredivisie/","Data"[[3, 1, 1, 2]];     Select[d, ! StringFreeQ[#[[1]], " - "] &] // Quiet // TableForm      I got a simular table like this where all the interessting data is replaced by a '-'.               Heracles - Cambuur      -   -   -     Willem II - AZ Alkmaar  -   -   -     Heerenveen - Excelsior  -   -   -     G.A. Eagles - Dordrecht -   -   -     Zwolle - Vitesse        -   -   -     Breda - Twente          -   -   -     Den Haag - Groningen    -   -   -     Feyenoord - Utrecht     -   -   -     Ajax - PSV              -   -   -      I've been told this is because the webpage updates the data through a JavaScript, that fetches the information form a database. So is there a way of letting the webpage load it's data before importing it? Futhermore, I found a solution for Windows users, where the webpage is loaded with Internet Explorer by NETLink. But since I mostly use a OSX machine, this won't work for me.               Needs["NETLink`"];     InstallNET[];     ie = CreateCOMObject["InternetExplorer.Application"];     ie@Navigate[     "http://www.oddsportal.com/soccer/netherlands/eredivisie/"];     Pause[3];     doc = ie@Document;     html = doc@body@innerHTML;      This made able to construct a table with all the data, after combing through the html code.               AZ Alkmaar - Ajax       2.96    3.47    2.26     Excelsior - G.A. Eagles 2.38    3.37    2.86     Utrecht - Willem II     2.19    3.4     3.16     Groningen - Heracles    1.7     4.      4.41      So again, is there a way of executing the JavaScript on a page before importing the data? Maybe through a JLink equivalent of the code above?


Is it possible to generate a Hasse Diagram for a defined relation?

I'm looking for a way to create a Hasse Diagram from a given partial order binary relation. The relation will be given explicitly, for example: `Hasse[{{1,2},{2,3},{1,3}}]`, and the output will be the corresponding graph. I've googled for a solution, and I did find some solution, but I didn't get how to use it.. here's what I found. If there is a way to generate a Hasse diagram for a conditional partial order set, and for a non-finite relation (of course, for this case I'm only interested in an approximate diagram), I would be happy to hear about it too.


Create Euler equation

I've tried to make some research, but without any luck. How do I setup the Euler equation for this in Mathematica?: $ \text{Min} \int_0^1\left(2x^2+ \left(4t-5 e^{r \, t} \right) x \, \dot{x} + 12e^{r \, t} \,\dot{x}^2 \right) dt,\; \; \text{for} \; x(0)=1, \; \text{and} \; x(1)=e^{\frac{1}{6}}$ Thanks a lot guys, and happy friday.


Saving notebook, excluding output cells, without losing "working notebook" output cells

In order to discuss this, I think it's easiest to start with two definitions. (If there's a standard terminology, please comment.)   1. **Working notebook** : a notebook that is open and in memory.   2. **Disk notebook** : a notebook that is saved to the disk. Typically, whenever we are editing a notebook `foo.nb`, it is a working notebook. When we save the notebook, the entirety of `foo.nb` is copied to the disk, making it a disk notebook. Previously, it has been noted that, for various reasons, it is desirable to save everything in a notebook except the output cells, which increase the file-size (especially with graphics). The answer gives a method of deleting output cells upon closing the window in which the notebook is being viewed. Note that means that the working notebook may have been saved to the disk notebook (hopefully) many times throughout a session _with all output cells_. Upon closing the window and saving, all output cells are deleted and the working notebook is saved (now sans output cells) to the disk notebook. Primarily for purposes of version control, I would like to avoid the disk notebook ever containing output cells. In the comments to the answer, the following solution was suggested:               SetOptions[       EvaluationNotebook[],       NotebookEventActions ->          {           {"MenuCommand", "Save"} :>                         FrontEndExecute[FrontEndToken["DeleteGeneratedCells"]]         }     ];      This works, except that the working notebook deletes all its output cells whenever it is saved to the disk notebook. This is undesirable. **Is there any way to save the working notebook sans output to the disk notebook?** Note that it would be best if the answer avoided using separate disk notebooks (unless they were temporary and cleaned-up), which I think is easier, but missing the point, to some extent.


How to suppress a warning message

If I change `$MinPrecision` before running `ListPlot[{{1, 2}}]`, there will be a warning in _Mathematica_ 10\. But there is no warning in _Mathematica_ 9\. Is there a way to avoid this warning?               $MinPrecision = 30;     ListPlot[{{1, 2}}]      > N::precsm: "Requested precision 16 is smaller than \$MinPrecision. Using > \$MinPrecision instead." Added: What I wanted to ask is not how to suppress a warning message in general. In fact, I think it is unreasonable for _Mathematica_ 10 to have this warning, because (1) _Mathematica_ 9 does not have it; (2) it is not useful. `Off[N::"precsm"]` does solve the problem, but some useful warnings may also be suppressed as well.


How to get a list of all expressions in a notebook matching a certain pattern?

Suppose I have a _Mathematica_ notebook saved to a certain location on disk. Given a pattern I need to get the list of all expressions matching this pattern that appear in input, output or print cells in the notebook, every expression being wrapped in `Hold` to prevent its evaluation. Ideally, I also want to extract expressions from cells with erroneous/incomplete input, if the expression itself is complete, but that is not strictly necessary. How can I do this?


Breaking a sorted list into bins of a specified size

Can somebody please explain me the following: If I try to split data every increase in 0.5:               list = Range[1.2, 3.2, 0.15]          {1.2, 1.35, 1.5, 1.65, 1.8, 1.95, 2.1, 2.25, 2.4, 2.55, 2.7, 2.85, 3., 3.15}      I would like to get the following:               {{1.2, 1.35, 1.5, 1.65}, { 1.8, 1.95, 2.1}, {2.25, 2.4, 2.55, 2.7}, {2.85,3., 3.15}      If I use the example given I here: Splitting a list using SplitBy, by comparing adjacent elements I can split either not at all               splittedlist = Split[list, (#1 < ( #2 - 0.1)) &]           {{1.2, 1.35, 1.5, 1.65, 1.8, 1.95, 2.1, 2.25, 2.4, 2.55, 2.7, 2.85, 3., 3.15}}      or I can split each of them               splittedlist = Split[list, (#1 < ( #2 - 0.5)) &]          {{1.2}, {1.35}, {1.5}, {1.65}, {1.8}, {1.95}, {2.1}, {2.25}, {2.4}, {2.55}, {2.7}, {2.85}, {3.}, {3.15}}      I found this package, http : // www.theophys.kth.se/~phl/Mathematica/ which uses exactly this method (on 2D data, but still), why does it work in their method? Obviously, I am missing something. I found this way of doing it, Calculate mean of values in bins but is this really the simplest way to split into intervals? I could of course write a loop, but I tried to not use a loop.


How to speed up my Project Euler code

The evaluation speed of _Mathematica_ often depresses me. It did it again when I wrote a code to solve a Project Euler problem. https://projecteuler.net/problem=206 Here's my code:               ClearAll[a];     a =       Compile[{},        NestWhile[# + 1 &, 10^9, ! MatchQ[           IntegerDigits[#^2], {1, _, 2, _, 3, _, 4, _, 5, _, 6, _, 7, _,8, _, 9, _, 0}] &],     CompilationTarget -> "C"]      I think it is the simplest solution. I can't find other solutions which are simpler. But my _Mathematica_ runs a long time before getting the answer. How can I speed this up? I've run into similar problems while I was solving other problems.


FindFit and Integration errors

First off, appologies for what may sound like a newbie question, as I am very new to using _Mathematica_. I am trying to find a way to get _Mathematica_ to give me an expression that would describe the data I get from my code, but I'm not sure how. I've played around with `FindFit` and can't seem to get it to work. Also, I have an integral whose integrand relies on two variables, but I'd only like to integrate with respect to one and keep the other constant. I can do this at the "defining a function" stage but am unsure as to how to display the information thereafter. Any help would be much appreciated! Here is my code               a := 3.24077*10^-20 (* km \[Rule] Mpc *)     b := 3.16888*10^-14 (* s \[Rule] MYear *)     c := a/b*(2.99792*10^5) (*Mpc/ MYear*)     H0 := a/b*71 (*1/MYear*)     G := a^3/b^2*6.67398*10^-20 (*Mpc^3/(Kg*MYear^2)*)     \[CapitalOmega]M := 0.27     \[CapitalOmega]\[Gamma] := 8.24*10^-4     \[CapitalOmega]\[CapitalLambda] := 0.73     f := 1*10^-4     y := 100     \[Lambda] := (1/(a^2)) 1*(10^-58)(*1/Mpc^2*)     H[z_] := H0 Sqrt[\[CapitalOmega]M (1 +            z)^3 + \[CapitalOmega]\[Gamma] (1 +            z)^4 + \[CapitalOmega]\[CapitalLambda]]     \[Rho]crit := 3/(8 \[Pi]*G)*(H0)^2      \[Rho]Pert[r_] := \[CapitalOmega]M*\[Rho]crit*(1 + f*Exp[-(r/y)^2])     M1[r_] := 4 \[Pi] Integrate[\[Rho]Pert[r]*r^2, r]     E1[r_] :=       1/2*((H[999]*r)/(c*(1000)))^2 - ((G*M1[r]*(1000))/(        c^2*(r))) - (\[Lambda]*r^2)/(3 (1000)^2)     ScaleFactor =        NDSolveValue[        SetPrecision[{(Sqrt[R[r, t]] (D[R[r, t], t])) == Sqrt[           2*G*M1[r] + 2*c^2*E1[r]*R[r, t] + (2 c^2 \[Lambda]*R[r, t]^3)/            3], R[r, 0] == r/1000}, 200], R, {r, 1, 20000}, {t, 1, 15000}];     Plot3D[Re[ScaleFactor[r, t]], {r, 1, 20000}, {t, 1, 15000},       PlotRange -> Automatic, Axes -> True,       AxesLabel -> {"Comoving Radius (Mpc)", "Time (MegaYears)"},       LabelStyle -> Directive[Bold, Black]]     FindFit[ScaleFactor[r,        t], \[Alpha]*r^n + \[Beta]*t^m, {\[Alpha], \[Beta], n, m}, {r, t}]     ParticleHorizon[r_, t_] :=       c*Integrate[Sqrt[1 + 2*E1[r]]/D[ScaleFactor[r, t], r], t]


How to check empty tables using SQL Select or Execute?

If[SQLExecute[con, "Select * from TABLE"] == "{}", Print["TRUE"], Print["FALSE"]]      I need to know the way, if the TABLE is empty or not


Solving a system of equations where two variables can only be one of several discrete values

I want to solve a three-equation system, but I need to constrain two of the variables so that they can only take one of several discrete values that I would specify (this is a circuit design problem where I need to find a resistor that can have a continuous range of values and two standard capacitors). I attempted to use Solve[] using the logical OR operator || to constrain the two variables, but Mathematica tells me that the system is not a quantified system of equations and inequalities. Does anybody know of a solution to this? Here's the code:               Solve[{       (10*^3 == 1/(2*Pi*Sqrt[10000*r2*c1*c2])),       (20 == 3*Sqrt [r2*c2]/Sqrt[10000*c1]),       (3 == Sqrt[r2/10000]*Sqrt [c1*c2]/(c1 + c2)),       (r2 > 5000),       (c1 == (10*^-12) || (100*^-12) || (22*^-12) || (0.001*^-6) || \         (0.01*^-6) || (0.1*^-6)),       (c2 == (10*^-12) || (100*^-12) || (22*^-12) || (0.001*^-6) || \         (0.01*^-6) || (0.1*^-6))},      {r2, c1, c2}]


Extracting matrix rows when one of its elements is part of a list (without a loop)

I have a matrix whose rows I want to extract based on whether the elements of one of its columns is a member of another vector (calling it the "comparison vector"). I would like to get better at using functional programming, and so I want to avoid using a loop, if it´s possible. I believe I have the right functions: `Select`and `MemberQ`. But I can´t coerce MemberQ to compare the element of the matrix to each element of the comparison vector. If there´s a duplicate answer, I´m willing to be lead to it (I´ve searched though)... Addition to my question:                mymatrix={{1, 1, -56}, {1, 2, 3.06}, {2, 0, -30.02}, {3, 1, -7.291}, {3, 2,1.93}, {4, 0, 0}, {5, 0, 0}, {5, 1, -356.4}, {6, 1, 9.945}, {7,0, -7.512}};           compvector={1,2,6,7,11,12,16,17};      I would like to extract the rows of ´mymatrix´ based on whether the values of the first column of ´mymatrix´ are in ´compvector´.


Pattern matching on Orderless functions inside Hold

MatchQ[Hold[1 + 2], Hold[2 + 1]]      returns `False`. But in the presence of a `Blank[]` in the matching pattern as in the example below               MatchQ[Hold[1 + 2], Hold[2 + _]]      which returns `True`, apparently the fact that `Plus` is `Orderless` is being respected. Apart from doing something like removing the `Orderless` attribute from `Plus`, how can I make the order matter when pattern-matching in a case like this? Where can I read more about this in the documentation?


DSOLVE for tenth order boundary value problem

I am currently using _Mathematica_ 9 to find solutions for higher order ordinary differential equations. The following was my input for a tenth order boundary value problem (BVP):               DSolve[{y''''''''''[x] == (E^-x)*(y[x])^2, y[0] == 1, y''[0] == 1,       y''''[0] == 1, y''''''[0] == 1, y''''''''[0] == 1, y[1] == E,       y''[1] == E, y''''[1] == E, y''''''[1] == E, y''''''''[1] == E},       y[x], x]      `DSolve` returned unevaluated. So, I tried for a numerical solution with slight modification by giving the range for `x`:               NDSolve[{y''''''''''[x] == (E^-x)*(y[x])^2, y[0] == 1, y''[0] == 1,       y''''[0] == 1, y''''''[0] == 1, y''''''''[0] == 1, y[1] == E,       y''[1] == E, y''''[1] == E, y''''''[1] == E, y''''''''[1] == E},       y[x], {x, 0, 1}]      But, it gave me the result in terms of an interpolating function, so fine until here. The third time I used the last input but this time with `DSolve` that is :               DSolve[{y''''''''''[x] == (E^-x)*(y[x])^2, y[0] == 1, y''[0] == 1,       y''''[0] == 1, y''''''[0] == 1, y''''''''[0] == 1, y[1] == E,       y''[1] == E, y''''[1] == E, y''''''[1] == E, y''''''''[1] == E},       y[x], {x,0,1}]      However, I get the error               DSolve::dsvar: 0 cannot be used as a variable. and the output was same as input.      I know the exact solution for the BVP which is $y(x)=e^x$, But, how do I obtain it using _Mathematica_? What am I doing wrong in the first and the third case when I am using `DSolve` for getting exact solution instead of a numeric one. Is there some error or there is some limitation in the software? * * * Again let me clarify, i.e. it is possible to find a numerical solution using `NDSolve[]` for this example. So it's true that equation has an approximate solution which can be given in form of some interpolating function. You can check this by simply putting in my `NDSolve` input in _Mathematica_. The point is, this equation has a solution which is $y(x)=e^x$. Here is a link to the research paper where this is mentioned (please check example 3.1. Note that in the paper, there is a small mistake: boundary condition should be $y(8)(1)=e$ instead of $y(8)(0)=e$ since it has already been mentioned earlier that $y(8)(0)=1$. So there cannot be two different values at one point. Rest of it is fine and one can see that it is clearly written that the exact solution is $y(x)=e^x$.). My question is simple   1. If there is an exact solution to the problem above (which I've already told that there is an exact analytic solution) then how to get it through _Mathematica_.   2. Or there is some limitation of the software due to which we can have numerical solutions to say, problems of tenth or higher order BVPs and no analytic solutions. Please, be specific and, yes, I have a fair understanding that if an equation has a general solution that same one can be evaluated given boundary conditions.


Checking if an Expression Falls within a Range

Is there a simple way in Mathematica to check under what conditions an expression (involving multiple variables) falls within a given range? For example, say I had a real-valued function f(x,y,z), where x,y,z are real numbers. I want to find the set S such that f(x,y,z) > 0 whenever (x,y,z) are contained in S. Is there a way to do this?


Support for pro font families?

While researching this question, I encountered an issue with Mathematica’s font selection mechanism when rich families of pro fonts are used. I can plot text in a given font with:               Graphics[Style[Text["iPhone"], FontFamily -> "Myriad Pro", 50]]      However, while I can use `FontFamily` to select various weight ("Light", "Semibold", "Bold" and "Black"), I cannot use it to select condensed fonts: for example, while `Myriad Pro Semibold Semicondensed` is a valid combination, Mathematica refuses to use it and simply fall back to its default font.   1. Is this a known limitation? Is it OS-specific? (I'm on Mac OS 10.7)   2. Also, how can I get Mathematica to issue an error when it cannot pick up the font requested, instead of falling back to a default font?


Problem with Select and Pick

I want to filter a data file choosing those elements that match a condition and then plot them. Here is the corresponding code I use:               data = Import["data.out", "Table"];     pick[m_List, i_Integer] := Module[{s = m[[i, 8]]}, Pick[m, s, s != 0]];     dataP = Table[{PointSize[0.005], Red, pick[data, i],        Point[{data[[i, 3]], data[[i, 4]], data[[i, 5]]}]}, {i, 1, Length[data]}]      The module `pick` is supposed to choose those elements from the list `m` for which $s\neq 0$. However, it does not work and therefore all the elements of the list are plotted. I used also `Select[m, s !=0]` but with no success. What am I doing wrong? This is a small sample of the data file               data1={{-4.05, -0.48, -1.4648, -1.36804, -1.7282, 648.01, 1.03023*10^-13, 7},     {-4.05, -0.41, -1.2762, 1.7369, 1.55982, 278.54, 1.99574*10^-14, 0},     {-4.05, -0.34, -1.54191, 1.42069, 1.59888, 178.32, 9.0609*10^-14, 5}}


Is it possible to calculate with declarations only?

simple Example: maximize $u(x), x$ solution would show constraints: $\frac{\partial u(x)}{\partial x} = 0$ $\frac{\partial^2 u(x)}{\partial x} < 0$ etc... or do I always have to explicitly define functions?


Procedure to find direction of triangle

I'm trying to write a procedure or function to find the direction in which a 2D triangle points. The triangle is assumed to be isosceles. While I can see the basic outline of what I want to do, making this into a procedure/function is proving harder. This is very basic Mathematica programming, I think... :( Suppose that points _p_ , _q_ , and _r_ are three arbitrary 2D points assumed to form an isosceles triangle: ![a triangle](http://i.stack.imgur.com/9sNF5.png)               triangles =      {       {{30.07, 11.04}, {20.07, 35.905}, {40.905, 19.095}},        {{82.918, 26.9417}, {77.5077, 43.5925}, {88.3281, 43.5925}}}          aTriangle =  First[triangles];       {p, q, r} = aTriangle          (*      {{30.07, 11.04}, {20.07, 35.905}, {40.905, 19.095}}     *)      The side lengths are found easily enough:               {EuclideanDistance[p, q],      EuclideanDistance[p, r],      EuclideanDistance[q, r]}          (*      {26.8005, 13.5011, 26.7708}     *)      and clearly in this case `pr` is the different side that helps define the direction:               midPoint = {(p[[1]] + r[[1]])/2 , (p[[2]] + r[[2]])/2}          (*      {35.4875, 15.0675}     *)      Then all that's left is to find the angle of the line `Line[{midPoint, q}]`, which is probably something like this:               ArcTan[q[[1]] - midPoint[[1]], q[[2]] - midPoint[[2]]] / Degree          (*      126.497     *)      But I want this to be automated, and I can't see how to do this.


How to find the most compact form of an equation

I would like to know whether there is any general approach to obtain the most compact form of an equation with Mathematica. I used to believe that the `FullSimplify` command would do that for me, but I recently found out that it will not necessarily give the most compact form. I found out with the following equation, which has been FullSimplified: $$\left[\sec (\alpha ) \left(\coth \left(L \sqrt{\text{Bo} \cos (\alpha )}\right)+\text{csch}\left(L \sqrt{\text{Bo} \cos (\alpha )}\right) (\text{Bo} L R \sin (\alpha )-1)-R \sin (\alpha ) \sqrt{\text{Bo} \sec (\alpha )}\right)\right]\left(R \sqrt{\text{Bo} \sec (\alpha )}\right)^{-1}$$ Or, in inputform for your convenience:               eq1 = (Sec[α] (Coth[L Sqrt[Bo Cos[α]]] - R Sqrt[Bo Sec[α]] Sin[α] +            Csch[L Sqrt[Bo Cos[α]]] (-1 + Bo L R Sin[α])))/(R Sqrt[Bo Sec[α]])      However, if I now run the following:               Collect[eq1,Bo] //FullSimplify      I get a much more compact form, namely: $$ -\tan (\alpha )+L \sin (\alpha ) \sqrt{\text{Bo} \sec (\alpha )} \text{csch}\left(L \sqrt{\text{Bo} \cos (\alpha )}\right)+\frac{\tanh \left(\frac{1}{2} L \sqrt{\text{Bo} \cos (\alpha )}\right)}{R \sqrt{\text{Bo} \cos (\alpha )}}$$ Can someone explain why I get a more compact solution when I first collect the equation for a certain parameter and then run `FullSimplify` and whether there is a general 'recipe' to get the most compact form of an equation? P.S. sorry for the long equation, but it seems that most of the smaller equations do not have this behaviour which makes sort of intuitive sense


Function input assistance not working in Mathematica 8?

I'm sorry if this not allowed here. On one computer (maybe with a newer version of Mathematica?) the autocomplete/input assistance for functions works perfectly: when I start typing one like ComplexExpand[], it displays a list of functions that start with that word so I can just hit tab. Also, if I make my own functions it learns about them and will autocomplete them. But on my other computer with Mathematica (Version 8.0.4.0), no list shows up. I've checked in Edit->Preferences->Interface, and there is nothing to turn it on -- strangely though, there is a check box that says "Match case in command completion", which suggests to me that the feature _does_ exist in this version. Does anyone know how I can get it to work? Thanks!


Debug OpenCL installation issues and beignet

I am trying to make Mathematica recognize my OpenCL installation, which is beignet. It is experimental software, so I know that it probably won't work (even `clinfo` terminates with an error after displaying some info), yet I would like to know exactly why `OpenCLQ[]` returns `False`.


How to extract connected bipartite graph from incidence matrix

I'm trying to extract a connected bipartite graph Bconn from the a given incidence matrix B- I have a matrix representing a bipartite graph - the incidence matrix B (weighted or not is unimportant). I want to extract the incidence matrix Bconn of the corresponding connected bipartite sub-graph. The incidence matrix may be rectangular. ù One can transform the incidence matrix B into a squared adjacency matrix A, where the off-diagonal blocks are the incidence matrices (one the transpose of the other if the bi-partite graph is undirected and thus A is symmetric) - standard basic graph theory. I would like to find a method for both directed and undirected graphs, and I do NOT want to transform the incidence into an adjacency matrix and in turn A into a graph, and then use ConnectedComponent or SubGraph, and then re- transform the graph object into a matrix: this method is not very efficient. I think that just working with matrices is faster. I have been able to find a method for undirected NON-bipartite graph, but probably there is a even more efficient way to solve the problem and especially to find a way so to operate directly with the incidence matrix B. My code is the following:               Sx = Dimensions[B][[1]]; Sy = Dimensions[B][[2]];          A = Join[Join[Table[0, {i, 1, Sx}, {j, 1, Sx}], B, 2],Join[B // Transpose, Table[0, {i, 1, Sy}, {j, 1, Sy}], 2]];          isnode = Position[Total[A], 0] // Reverse;          Aconn = Transpose[Delete[Transpose[Delete[A, isnode]], isnode]];          Bconn = A[[1 ;; Sx, Sy + 1, Sx + Sy]];      Of course I can do a function doing all these operations, but the point is that I'm not convinced of this algorithm, as I'm looking to something faster and that I can use directly to B. Thanks for any suggestion/solution!!


About an infinite product

I have a curiosity as regards the infinite product below. I wonder why Mathematica v.8.0. says   the limit is $1$. This is not true.               Limit[(Product[(1 - a/n^2), {n, 1, Infinity}])^(1/Sqrt[a]),  a -> Infinity]


Substitute complex functions into complicated polynomials

Mathematica has some strange way of sorting terms. It seems that it is using a canonical sort on expressions, e.g. $\mathbb{i} \sin[x] \cos[y] \cos[z]$ is returned as $\mathbb{i} \cos[y] \cos[z] \sin[x]$. I interpret this behaviour that the function names ($\cos$ and $\sin$) have precedence over their arguments in the output sequence. This behaviour makes output sometimes difficult to interpret complicated terms involving sums and products of transcendent functions. These terms are sorted according to the transcendent function names and not according to their arguments as I'm used to. However, the core of my question is related to the problem of simplifying a given complex function e.g. $\frac{1}{3} (V_{xx}-V_{xy}) \left(\cos \left(\frac{\pi k_1}{2}\right) \sin \left(\frac{\pi k_2}{2}\right) \sin \left(\frac{\pi k_3}{2}\right)+i \sin \left(\frac{\pi k_1}{2}\right) \cos \left(\frac{\pi k_2}{2}\right) \cos \left(\frac{\pi k_3}{2}\right)\right)-\frac{4}{3} \left(\frac{V_{xx}}{4}+\frac{V_{xy}}{2}\right) \left(\cos \left(\frac{\pi k_1}{2}\right) \sin \left(\frac{\pi k_2}{2}\right) \sin \left(\frac{\pi k_3}{2}\right)+i \sin \left(\frac{\pi k_1}{2}\right) \cos \left(\frac{\pi k_2}{2}\right) \cos \left(\frac{\pi k_3}{2}\right)\right)$ by substituting the definition of another complex function $g_2=-\cos \left(\frac{\pi k_1}{2}\right) \sin \left(\frac{\pi k_2}{2}\right) \sin \left(\frac{\pi k_3}{2}\right)+i \sin \left(\frac{\pi k_1}{2}\right) \cos \left(\frac{\pi k_2}{2}\right) \cos \left(\frac{\pi k_3}{2}\right)$ "As one readily can see" (I love these textbook statements!), the resulting function is $V_{xy} g_2^*$. However the use of complex functions is complicating the substitution task in Mathematica. A simple substitution using patterns like               -Cos[x_] Sin[y_] Sin[z_] + I Sin[x_] Cos[y_] Cos[z_] -> g      does not work for two reasons:   1. The sequence of trigonometric functions is not preserved as expected in the canonical sorting of expressions. Thus the patterns x_, y_ and z_ are matching different arguments. This is in this case not a problem because I'm not using the named patterns in the substitution, but I can think of multiple issues where this would be one.   2. The second, more severe problem is the case of conjugate, and negated functions as shown in the above example. There is of course one solution, which is defining 4 patterns covering all possible complex cases of the function definition $g_2$ as               {      -Cos[x_] Sin[y_] Sin[z_] + I Sin[x_] Cos[y_] Cos[z_] -> g2,      +Cos[x_] Sin[y_] Sin[z_] - I Sin[x_] Cos[y_] Cos[z_] -> -g2,      -Cos[x_] Sin[y_] Sin[z_] - I Sin[x_] Cos[y_] Cos[z_] -> Conjugate[g2],      +Cos[x_] Sin[y_] Sin[z_] + I Sin[x_] Cos[y_] Cos[z_] -> -Conjugate[g2]     }      but I'm looking for a less cumbersome approach, since in my problem I have 12 different complex functions to substitute which multiplies up to 48 substitution lines with the above approach. Any idea how to implement this in a more elegant way?


How to find the phase difference of two sampled sine waves?

I'm trying to measure a phase difference between two Sine functions I've acquired with a computer. I'm uploading one of the .txt files with the data I'm working with here: txt file. To remove the units of every row I'm using the function that @R.M posted here. The first two columns of each file make a Sin function, the other columns make a different one. Here's a plot of those functions togheter: ![Two Sin functions with different pahses.](http://i.stack.imgur.com/sgkgj.jpg) I'm looking for a way to find all rows that have a maximum value on the second coordinate (that is, second and fourth column) and then be able to manipulate those lists in order to get the difference between the other two coordinates. For example, if this are the two lists with the maximums:               max1={{1.1,6},{2.2,6},{3.3,6},{4.4,6}{5.5,6}}     max2={{1.3,10},{2.4,10}{3.5,},{4.6,10},{5.7,10}}      Then I could easily get the difference between the first coordinates of each pair (1.3-1.1, 2.4-2.2, etc.), which is what I need. I have tried doing the proposed methods in this question but none of them worked for me. Furthermore, I got a lot of files like this to analyze, so I'm importing all of them with a For loop and putting them all on the same list with `Table`. It would be nice if I could get the maximums of all my files at the same time. I'll apreciate any ideas, thank you. Ps.: By the way, by asking and reading the contents of this page I realized Mathematica is a much more powerful tool than I thought, and I would like to learn more about how to properly use it. I know the Mathematica documentation is really good, but I would like to get a good book about Mathematica. Do you know one to reccommend?


How to match expressions with a repeating pattern

The expression I want to match obey a simple pattern that repeats it self a number of times.               f[a]@f[b]@f[c]@...@f[X]      How would you match all expressions of this form?


How do I remove this awkward plane?

Using `Plot3D`, I tried to plot $x^3 + y^3+3xy=z$                Plot3D[x^3 + y^3 + 3 x y, {x, -5, 5}, {y, -5, 5}, PlotRange -> {-10, 20},          PlotStyle -> Directive[Yellow, Specularity[White, 20], Opacity[0.8]]]      Now for some reason _Mathematica_ generates this awkward blue plane out of nowhere and I cannot find a way to remove it since I do not even know what it is ![enter image description here](http://i.stack.imgur.com/G7lmF.jpg) I am on _Mathematica_ 8.0.4


Upload CDF to Blogspot

I am trying to upload my CDF files to Blogspot. I tried the follow script:               <script src="http://www.wolfram.com/cdf-player/plugin/v2.1/cdfplugin.js" type="text/javascript"></script> <script type="text/javascript"> var cdf = new cdfplugin(); cdf.embed('https://www.dropbox.com/s/erpdi1rqwk5d3vm/Spe%20Para%20Dat.cdf', 500, 500); </script>      But when I try to acess it, I receive the message "File could not be loaded". I thought that maybe it was because I am using an `Import[]`, but even if I try to use a CDF Example I have the same problem. For me it seems that the problem is with the link of the file I updated. Do you know how to solve this? Thanks in advance.


How to plot a log log plot of the error

Suppose I have a function $$ f(x) = \frac{1}{1+e^x}$$ I can use the function `Series[]` to generate a series expansion of $f$ as follows               x0 = 0;     f[x_] = 1/(1 + E^x);     poly[n_] := Normal[Series[f[x], {x, x0, n}]]     poly[3]      which yields $$ f(x) \approx \frac{1}{2}-\frac{x}{4}+\frac{x^3}{48} $$ Denote by $f_n(x)$ the series truncated after the nth term. I want to generate a plot of the error $|f(x)-f_n(x)|$ versus $|x|$ on log scales. I think I can do this with `LogLogPlot[]` as follows               Clear[error]     error[n_] := error[n] = Abs[f[x] - poly[n]]     LogLogPlot[error[3], {x, 10^-10, 1}]       This generates the plot ![error](http://i.stack.imgur.com/xKnpK.png) Which I think looks correct, the error curve is a straight line as expected. But now suppose I change the point of expansion to $x_0 = 1$. Now I want to plot $|f(x)-f_n(x)|$ versus $|x-x_0|$ on log scales. How can I do this? I have tried               ParametricPlot[{Log[error[2]], Log[Abs[x - x0]]}, {x, x0, x0 + 1}]      but I don't know how I can label the ticks correctly as above. ![error plot using ParametricPlot](http://i.stack.imgur.com/Wi37t.png) I think maybe I need to use `ListLogLogPlot[]` but I'm not sure how to generate the points for the x range. What i'm looking to do is plot something similar to ![I want to generate something like this](http://i.stack.imgur.com/8dXyb.png) the matlab code to do this is available here


Fast Simulations with Compile

this post relates to another post that I didn't follow up propely. If I wanted to simulate a system of stochastic proesses like the following, and loop over this run many many times would writing the processes as 'compiled' pure functions speed up the run time? Or, is Nestlist already trying to do this for me?               norTheta[mu_, sigma_] := Random[NormalDistribution[mu, sigma]];     norPi[mu_, sigma_] := Random[NormalDistribution[mu, sigma]];          thetaNext[thetaNow_] :=      thetaNow + (-lambdaTheta*(thetaNow - thetaBar)*deltaT      + sigmaTheta*norTheta[0, 1]*Sqrt[deltaT]);     piNext[piNow_, thetaNow_] := piNow + (-lambdaPi*(piNow - thetaNow)*deltaT +      sigmaPi*norPi[0, 1]*Sqrt[deltaT]);          lambdaTheta = 0.07; sigmaTheta = 1.2; thetaBar = 2; lambdaPi = 1.0;      sigmaPi = 1.25; deltaT = 1/12;     steps = 252;     T = 5;      deltaT = 1/steps; // N      Maturity = T*steps;          simulateRun = Transpose[NestList[{piNext[#[[1]], #[[2]]],                             thetaNext[#[[2]]]} &, {2, 2}, Maturity]];


convert long string to integer list

at first, i would like to thank all the people here. i'm working with mathematica for half a year now and always found great advice and tricks. now, i came up with a problem i couldn't find a solution for. from a file, i import a string with around 23 mio. characters which is reasonably fast (it acutually is a dna sequence). i then want to split this string into its characters and convert each of them to an integer number. my first, naive approach was the following:               MaxMemoryUsed[]/1024^2//N     AbsoluteTiming[list=Characters[a]/.{"A"->1,"T"->2,"G"->3,"C"->4};]     ByteCount[list]/1024^2//N     MaxMemoryUsed[]/1024^2//N      which creates the following output:               134.286     {13.301206,Null}     702.261     1976.42      as you can see, the timing is quite good but the memory usage during the process is horrible. my next approach was reading from a stream and convert each character to an integer instantly:               MaxMemoryUsed[]/1024^2//N     string=StringReplace[string,{"A"->"1","T"->"2","G"->"3","C"->"4"}];     str=StringToStream[string];     AbsoluteTiming[list=Table[ToExpression[Read[str,Character]],{i,1,StringLength[string]}];]     Close[str];     ByteCount[list]/1024^2//N     MaxMemoryUsed[]/1024^2//N      which results in               134.281     {176.502736,Null}     702.252     813.208      as yo can see, this approach needs way less memory but takes considerably longer. my question now is, if there is another memory efficient way to do this which is faster than my second try? thanks a lot!


Calling blank arguments using enclosing functions

Is there a way to call a function and have that function use an argument defined in an enclosing function? e.g.,               set = Table@Range@50;          posE[set_] := Select[set, EvenQ]          tform1[mult_,set_] := (#*mult) & /@ set[[posE]];          t1set = tform1[10, set]      which leads to the following message/error, > Part::pspec: Part specification posE is neither an integer nor a list of > integers. >> I would like `posE` to get its argument `set_` from the second argument in `tform1` (also named `set_`). Is this possible? is there a better way to do this? (Note that I do not want to combine the two functions into a single function).


Why do all plots open in new windows when I use JavaGraphics?

I want to open only one plot in new window. When I use `<<JavaGraphics`` all plots open in new windows. I put `<<JavaGraphics`` before one last plot but it works for all plots. How can I do this?


Robust function for manipulation of nested lists

I have a nested list of the form:               test = {{"sample1", {"elema", "ppm", 238}, {"elemb", "ppm", 57},                          {"elemc", "w%", 14.23}, {"elemd", "w%", 0.112}},              {"sample2", {"elema", "ppm", 215}, {"elemb", "ppm", 13},                          {"elemc", "w%", 12.13}, {"elemd", "w%", 0.095}},              {"sample3", {"elema", "ppm", 219}, {"elemb", "ppm", 28},                          {"elemc", "w%", 19.11}, {"elemd", "w%", 0.55}}};      I want to be able to select and order rows from this list based on another list:               samples = {"sample3", "sample1"};      and reorder elements based on their label,               order =  {"elemd","elemc","elemb","elema"};      to end up with something like: > {{0.55, 19.11, 28, 219}, {0.112, 14.23, 57, 238}} The main aim is to have a robust re-ordering function of the form               trchem[data_, order_, sample_] := ...      I have played around with the following:               Intersection[sample, #] & /@ test      > {{"sample1"}, {}, {"sample3"}}               Position[#, test[[All, 1]]] & /@ sample      > {{}, {}} Neither of which are quite right.. I'm sure this is really easy but I can't figure it out at the moment. Any suggestions? Thanks.


Minimizing a functional takes forever

I need help with minimizing a functional in Mathematica. I have a function $V(\xi)=\sum_{i=1}^\infty C_{3_i}J_0(\xi/C_i)+C_{4_i}Y_0(\xi/C_i),~~~\Sigma\leq\xi\leq\xi_1$, and want to find such $\\{C_{3_i}\\}$ and $\\{C_{4_i}\\}$ that $V(\xi)\equiv-1$. Here $\\{C_i\\}$ are known (see below), $J_0(x)$ and $Y_0(x)$ are Bessel functions. To do that, I take $\int\limits_\Sigma^{\xi_1}|V(\xi)+1|d\xi$ and minimize it whit respect to parameters $\\{C_{3_i}\\}$ and $\\{C_{4_i}\\}$. I don't know why, but it takes forever for Mathematica to minimize that functional (at least more than 14 hours). Probably that's because integration increases the number of summands adding some with $C_{3_i}C_{4_i}$ coefficients. Am I doing something wrong or is there a method for getting the $\\{C_{3_i}\\}$ and $\\{C_{4_i}\\}$ faster? **Important note:** I take $V(\xi)\approx\sum_{i=1}^N C_{3_i}J_0(\xi/C_i)+C_{4_i}Y_0(\xi/C_i)$, where $N$ is length of $\\{C_i\\}$, and $\\{C_i\\}$ are eigenvalues of Sturm-Liouville problem (see the code for detailed information). $V(\xi)\equiv-1$ is actually obtained from initial condition for the initial function $F(\xi,\tau)=V(\xi)U(\tau)$.               xi1 = 10;     Sigma = 1;     nn = 1;     f3[z_] = BesselJ[1, nn*xi1/z]*BesselY[0, nn*Sigma/z] -      BesselJ[0, nn*Sigma/z]*BesselY[1, nn*xi1/z];     Plot[f3[z], {z, 0, 10*nn}]     NumberOfRoots = 0;     Timing[roots3 =      Reap[First[       NDSolve[{x'[z] == f3'[z], x[1] == f3[1]}, {x}, {z, 1000, 0.1},         Method -> {"EventLocator", "Event" -> x[z],           "EventAction" :> {Sow[y /. FindRoot[f3[y], {y, z}]],             NumberOfRoots++}}, MaxStepSize -> 0.1,         MaxSteps -> 1000000]]][[2, 1]]];     NumberOfRoots     Min[Abs[f3 /@ roots3]]     Max[Abs[f3 /@ roots3]]     roots3 = Sort[roots3];      The code above finds $\\{C_i\\}$ - roots of equation given by boundary conditions $V(\Sigma)=0$ and $\frac{dV}{d\xi}(\xi_1)=0$ $$J_1(\xi_1/C)Y_0(\Sigma/C)-J_0(\Sigma/C)Y_1(\xi_1/C)=0.$$ I use the function $$f_3(C)=J_1(n\xi_1/C)Y_0(n\Sigma/C)-J_0(n\Sigma/C)Y_1(n\xi_1/C),$$ where $n$ is a scale parameter. Bigger $n$ gives more roots. Thus, for $n=1$ we get 29 roots, $n=5$ - 143, $n=10$ - 286, etc. Then I print maximum and minimum values of $f_3(\\{C_i\\})$ to check if I really get zeros. For $n=1$ $\min f_3(\\{C_i\\})\sim2*10^{-19}$, $\max f_3(\\{C_i\\})\sim 2*10^{-15}$, which is really satisfactory.               Array[CCNew, NumberOfRoots]; (*CCNew=C*)     Array[C3, NumberOfRoots];     Array[C4, NumberOfRoots];     For[i = 0, i < NumberOfRoots, CCNew[i] = roots3[[i]]/nn, i++] (*here we take the scale into account*)     Clear[xi];     InitFunction[xi_] =      Sum[C3[i]*BesselJ[0, xi/CCNew[i]] +      C4[i]*BesselY[0, xi/CCNew[i]], {i, 1, NumberOfRoots}]; (*InitFunction=V*)     C5 = Join[Array[C3, NumberOfRoots], Array[C4, NumberOfRoots]];     Timing[Minimize[Integrate[Abs[InitFunction[xi] + 1], {xi, Sigma, xi1}], C5]]      And here it takes forever to find $\\{C_5\\}=\\{C_3\\}\cup\\{C_4\\}$. Any help with this?


Check Specific Connections within Graph

Say you have the skeleton of a graph:               fullSkele = PolyhedronData["GreatRhombicosidodecahedron", "SkeletonRules"]      and you've an arbitrary list of some fraction of those nodes, say `extantNodes = {1, 5, 8, 72, 101}`, which you want to turn into the list of all nodes **_connected_** directly to those `extantNodes` (along with the number of `extantNodes` each is connected to). With,               connCheckTool[node1_, node2_] := Count[fullSkele, (node1 -> node2)] + Count[fullSkele,(node2 -> node1)]      The following function achieves this:               DeleteCases[        DeleteCases[         Transpose@{Range[120],             Total /@          Table[connCheckTool[i, extantNodes[[z]]], {i, 1, 120, 1}, {z,            1, Length@extantNodes}]} /. {x_Integer, 0} -> delete, delete], {x_, y_} /;      MemberQ[extantNodes, x] == True];      However, the inner `connCheckTool` is not very efficient, especially with larger graphs. Can anyone think of a way to accomplish this in a better way? I suspect it will involve the `AdjacencyMatrix` of the original, whole graph, as opposed to the list-search mechanism, but can't quite get it...


Keyboard issues with Mathematica 9.0.1 for Linux

After working for a while with `Manipulate` function and increasing the number of variables to be manipulated, keyboard stops working properly in the Notebook. It gets really crazy, mainly the keys `Backspace`, `Space`, `Delete`, `Ctrl`, `Alt`, `Left`, `Right`, `Up` and `Down`. For example, some times `Backspace` starts behaving as the `Left` Key, some times as `Right`, etc. all this randomly. I am running _Mathematica_ for Linux, and I have had this issue with Ubuntu 13.04 and recently with Ubuntu 13.10 as well. This is not an issue related to my computer since outside _Mathematica_ the keyboard works as usual.


Shading area in graphics

I want to shade the area between the formula               eqn=(a (Sqrt[a] (-40 + 37 a + 10 a^2 - 3 a^3) + (-1 + a)^2 (32 +        a) ArcTanh[Sqrt[a]]))/(2 (-Sqrt[a] (1 + a) + (-1 + a)^2 ArcTanh[      Sqrt[a]]))      and `-3/2`. To be clearer: `-3/2 < region to be shaded < eqn` I tried with:               Show[{{Plot[{eqn, -3/2}, {a, -2, 1.5}]},        Plot[{eqn, -3/2}, {a, -1.2, 1},         Filling -> {1 -> {-3/2, Automatic}}]}, PlotRange -> {-2, 4}]      but I don't get what I want: it shades also               eqn < region < -3/2      Any ideas? I am sorry but I don't understand how to link a figures, I hope I explained myself... Oh, I am using Mathematica 8.


Asynchronous evaluation on EventHandler

How can I make this progress bar appears when I press `Enter`? The `Button` Evaluate works just fine, but when `Enter` is pressed it jumps the progress bar. It would be easy if EventHandler could have `Method-> "Queued"`, but is't not the case. Here is my code:               DynamicModule[{output="",slowReport,progress,str,btnEval,enterAction,number,enterEval},              progress=ProgressIndicator[Dynamic[Clock[Infinity]],Indeterminate,ImageSize->280];              enterEval=EventHandler[#,{"ReturnKeyDown":>(output=progress;output=slowReport[])}]&;             btnEval=Button["Evaluate",(output=progress;output=slowReport[]),Method->"Queued"];              Dynamic@Panel@Column[{Row[{InputField[Dynamic[number], String]//enterEval,btnEval}]," ",output," "},Alignment->Center]              ,Initialization:>        (            SetOptions[$FrontEndSession,DynamicEvaluationTimeout->10];            slowReport[]:=(Pause[1];ToExpression@number^2)         )     ]      Here is what happens when Evaluate is pressed: ![enter image description here](http://i.stack.imgur.com/TUPVd.png) ![enter image description here](http://i.stack.imgur.com/F6Dia.png)


How can I generate a variable-length list of options in PieChart?

I would like to allow a user to manipulate the segments of a pie-chart, which is to be generated from a list of a specific format. The code looks something like the following:               pieChartList = {         {category1, 1},         {category2, 2}     };          generatePieChart[dataList_List, plotLabel_String] :=         Manipulate[             PieChart[                 {category1, category2},                 PlotLabel -> plotLabel             ],             {{category1, 1}, 0, 10}, {{category2, 2}, 0, 10}         ];          generatePieChart[pieChartList, "Test pie chart"]      As you can see, the lists are being written "manually," even though `pieChartList` contains all the information to generate the necessary structures. Is there an elegant way to generate the manipulation list automatically? In other words, if I were to add `{category3, 3}` to `pieChartList`, the function `generatePieChart` should pick up the new value automatically. Thanks in advance for your help.


Evaluating terms in series

I'm trying to evaluate a simple expression:               Subscript[λ, n] = (2 n - 1) π/(2 L);      And then sum it up:               Sum[Subscript[λ, n], {n, 1, 3}]      The result is: > >     π/(2 L) + Subscript[λ, 2] + Subscript[λ, 3] >   How can i get _Mathematica_ to write the second and third term in the same way as the first?


Add Brackets to a string list

Hello stackexchange community! I have a stringlist with a value and his error for eg:               {{"12","1"},{"13","2"}}      Now i want to output this as something like this (for a lab-report):               {"12(1)","13(2)"}      Unfortunately I have no idea how to get this working... Thanks in advance   Cx


Extracting values from nested rules in JSON data

I have been using Mathematica to analyse some data from the StackExchange API. It is conveniently available in JSON form, which Mathematica interprets as replacement rules. However, some of the rules are nested as the right-hand side of an outer rule, as you can see in the case of `badge_counts` here:               Import["http://api.stackexchange.com/2.0/users?page=1&order=desc&sort=reputation&site=mathematica",        "JSON"][[2, 2, 10]]          (* Out[1]=      {"accept_rate" -> 75, "account_id" -> 395497, "age" -> 41,       "badge_counts" -> {"bronze" -> 35, "gold" -> 0, "silver" -> 11},       "creation_date" -> 1326833982, "display_name" -> "Verbeia",       "is_employee" -> False, "last_access_date" -> 1331949804,       "last_modified_date" -> 1330990001,       "link" -> "http://mathematica.stackexchange.com/users/8/verbeia",       "location" -> "Sydney, Australia",       "profile_image" -> "http://www.gravatar.com/avatar/3df2379fc0221bb0281c0d608542bd84?d=\identicon&r=PG",       "reputation" -> 3571, "reputation_change_day" -> 0,       "reputation_change_month" -> 857,       "reputation_change_quarter" -> 3475, "reputation_change_week" -> 605,      "reputation_change_year" -> 3475, "user_id" -> 8,       "user_type" -> "registered",       "website_url" -> "http://www.verbeia.com/mathematica"}     *)      Users without any badges don't have this nested rule. To handle both cases I am doing something like this to get the badge counts in a flattened list, so each row of the final list corresponds to a user of the site:               getUserData[page_Integer] := Module[{ad},       ad = Import[          "http://api.stackexchange.com/2.0/users?page=" <>            IntegerString[page] <>            "&order=desc&sort=reputation&site=mathematica", "JSON"][[2,2]];       If[Length[ad] > 0,        Join[Most[#], {"bronze", "silver", "gold"} /.             Last[#]] & /@ (({"display_name", "creation_date", "reputation",               "reputation_change_week", "is_employee", "last_access_date",               "user_type", "badge_counts"} /. ad) /.            "badge_counts" -> {"bronze" -> 0, "silver" -> 0,              "gold" -> 0}), {}]       ]      Which I can then build up into a list of all users and their stats like this:               Monitor[      pageM = 0;      resultM =        FixedPoint[Join[#, getUserData[++pageM]] &, {}];,       StringForm["Loading page `` ...", pageM]      ]      The final output is list of vectors that look like this:               resultM[[10]]     (*Out[2]= {"Verbeia", 1326833982, 3571, 605, False, 1331949804, "registered", 35, 11, 0} *)      My question is: is there a more concise or elegant way to write the `getUserData` function, without need a `Join` _and_ three separate `ReplaceAll` (`/.`) constructions?


Counting radial ridges on an image

After happily using the v9 image assistant to crop elliptically an image, and then the drawing tools to put a white disk in the middle, I turned this image: ![](http://i.stack.imgur.com/QDGVy.png) into the following one: ![Mathematica graphics](http://i.stack.imgur.com/NNzNM.png) that can be imported with               im=Import["http://i.stack.imgur.com/NNzNM.png"]      The overall objective is to programatically count the number of those radial lines. Due to the lighting, there are parts of the image in which those lines are darker than its surroundings and others where it is lighter. So far I haven't found a good way worth posting, so any pointer to a good solution would be appreciated. I have the feeling the image processing people will see better ways of dealing with this and I will be grateful to learn something. Thanks a lot **EDIT** A first approach with @RahulNarain's suggestion would be               int = ListInterpolation[        ImageData[ColorConvert[im, "GrayLevel"]], {{-1, 1}, {-1, 1}}];     polInt = Function[t, int[0.95 Cos[2 \[Pi] t], 0.95 Sin[2 \[Pi] t]]];          Plot[polInt[t], {t, 0, 1}, AspectRatio -> 0.2, ImageSize -> Large,       PlotRange -> Full]      ![Mathematica graphics](http://i.stack.imgur.com/sH3mT.png) Now,               ListLinePlot[Abs@Fourier[polInt@Range[0, 1 - 0.001, 0.001]],       PlotRange -> {{0, 500}, {0, 50}}]      ![Mathematica graphics](http://i.stack.imgur.com/07ovO.png) A better zoom shows the maximum at 98 However, manual counting (could be wrong) gave me 96, and nikie's approach is suggesting 97. 1 or 2 off count could be due to the light changes making the real ridge be the local minimum at some places and local maximum at others