UnitStep in Mathematica when t varies differently

How can I use the `UnitStep` command when I have a piecewise function $f(t)$, where $f(t)= 0$, when $|t|>4$, and $f(t)=1$, when $|t|<4$? I tried with `UnitStep[t-4]` but didn't work like I want it to work.


Asymptotic expansion

I wanted to expand a function of $x$ about $x=\infty$ and see its coefficients as a function of the parameters $m,n,q,y$ and I wrote this - but it didn't work! It gave me back a very complicated expression with powers of $x$ scattered everywhere - but I want a Laurent series expansion of it! Can someone kindly help with this?               Assuming [ y ∈ Reals &&  m ∈ Reals && q > 0 &&  n ∈ Integers    && x > 0 , Series [   ((         Gamma [ I x + (1 + y)/2]   Gamma [ -I x + (1 + y)/2]    )/(        Gamma [I  x] Gamma [ -I  x] ) )* (1/(        x^2  + m^2 + (n/q)^2)), {x, Infinity, 3}] ]      To write it readably - the function is, $\frac{ \Gamma (ix + (1+y)/2) \Gamma( -ix + (1+y)/2)}{\Gamma (- i x) \Gamma (i x) } \frac{1}{x^2 + m^2 + (n/q)^2 }$ * * * On some computers and Mathematica versions - the answer to the above comes out as -               (1/x)^-y (1/x+(2 π (-m^2/(2 π)-n^2/(2 π q^2))+1/24 (-y +y^3)) (1/x)^3+O[1/x]^4)      but I don't know why on my computer and Mathematica it doesn'! * * * Some simple examples do work like Series [ x/(x^2 + 3) , {x, Infinity, 2}]


solution of differential equation

I have the following code that gives you a phase portrait of a 2d system and I can't understand what means the 3rd and 4th line (sol1 and sol2).               sys = {x'[t] == 3 x[t], y'[t] == -y[t]};          ss = DSolve[sys, {x[t], y[t]}, t];          sol1 = ss[[1, 1, 2]];          sol2 = ss[[1, 2, 2]];          toplot = Flatten[       Table[{sol1, sol2} /. {C[1] -> i, C[2] -> j},          {i, -0.5, 0.5, 0.25}, {j, -0.5, 0.5, 0.25}], 1]          graphs = ParametricPlot[Evaluate[toplot], {t, -3, 3}]      I searched the documentation but I couldn't figure it out. Thank you. @J.M. @belisarius I try to extend it in non linear eqiations. I tried another example with a non linear diff eq. What I wanted to find was the phase space. When I put μ>0 then it plots a solution, but it does not show the other fixed point that is non stable. For everything else μ it does not do anything. `sol = NDSolve[{x'[t] == μ - x[t]^2, y'[t] == -y[t], x[0] == x0, y[0] == y0}, {x[t], y[t]}, {t, 0, 100}]` `toplot = Table[{x@t, y@t} /. sol, {x0, -.5, 2, .25}, {y0, -.5, .5, .25}];` `ParametricPlot[Evaluate[toplot], {t, 0, 100}, PlotRange -> All]` I now the dynamics of the above, I do not want you to explain that to me. I want your help because I am trying to learn mathematica.


Manipulate which creates and deletes Manipulators dynamically

I want to plot a function in a `Manipulate` in which the number of terms varies and a `Manipulator` for the coefficient of each term is created or deleted as the terms increase and decrease. For example, when I have three terms, I should get the equivalent of               Manipulate[       Plot[a0 + a1 x + a2 x^2, {x, 0, 10}],        {a0, 1, 10},        {a1, 1, 10},        {a2, 1, 10}]      I want to let the number of terms vary and but still control each coefficient with a `Manipulator`. I tried to do it in the following way:               Manipulate[       Plot[Total[ToExpression["a" <> ToString[#]] x^# & /@ Range[0, n]], {x, 0, 10}],       {n, 1, 10, 1},       Dynamic[Sequence @@ ({ToExpression["a" <> ToString[#]], 1, 10} & /@ Range[1, n])]]      It did not work. Can anybody suggest what I should do to make it work?


How to read image files in Analyze 7.5 format?

I am using GATE/Geant4 for simulating photon beams interacting with matter. For 3D dose distributions, GATE outputs the data into an Analyze 7.5 format [1]. I was wondering whether there exists a function in _Mathematica_ that could read files in this format and display the data. For what is worth, Matlab has `analyze75read` [2] for this purpose. [1] http://eeg.sourceforge.net/ANALYZE75.pdf [2] http://www.mathworks.com/help/images/ref/analyze75read.html ( This comment will soon be deleted: I don't have access at the moment to my Mathematica installation, but here is a file in case anyone would like to play with it: http://leaf.dragonflybsd.org/~beket/geant4/Config-gamma-Dose.hdr and http://leaf.dragonflybsd.org/~beket/geant4/Config-gamma-Dose.img ).


Keep order of mulciplication in Matrix production

{{λ E, B}, {λ A1, λ E}}.{{E, 0}, {-A1, E}}      \begin{align*}\left(\begin{array}{cc} E^2 \lambda -A1 B & B E \\\ 0 & E^2 \lambda \\\\\end{array}\right)\end{align*} The result is not quit true, since $A1 B$ may not equal to $B A1$ when $A1$ and $B$ are block matrix.


Using LinkSnooper for monitoring the communication with an installable MathLink program

How can I monitor the communication between an installable MathLink program and the kernel? Can LinkSnooper do this?


Find area of polygon on a sphere from a set of latitude-longitude points

Given a list of latitude and longitudes say               {{32.6123, -117.041}, {40.6973, -111.9}, {34.0276, -118.046},       {40.8231, -111.986}, {34.0446, -117.94}, {33.7389, -118.024}}      how can I find the area enclosed by the polygon formed by these points. In other words, how can I implement the 3D convex hull (surface area) on a set of lat-long pairs?


Want to label vertices of a graph and manually move them around

I would like to plot a graph in such a way that   1. The vertices are labeled using labels that I've given them, rather than just their number,    2. I can manually move the vertices around. In the code below, `A` is my 4 x 4 adjacency matrix, and `People` specifies the labels that I'd like for the 4 vertices. `AG` gives me a graph that accomplishes (1) but not (2). `GP` gives me a graph that satisfies (2) but not (1) -- it only labels the vertices by their number. How can I accomplish both (1) and (2) simultaneously? `GraphPLot` does not seem to allow for `VertexLabels` as an option, so I'm at a loss here.               A = {{0, 1, 1, 1}, {1, 0, 0, 0}, {1, 0, 0, 1}, {1, 0, 1, 0}}     People = {Bob, Eric, Lucy, Liz}     AG = AdjacencyGraph[A, VertexLabels -> Table[i -> People[[i]], {i, 1, Length[People]}]]     GP = GraphPlot[AG, VertexLabeling -> True]


Eigenvectors inside a maniupulate function

I am trying to make a physics application and it requires that the eigenvectors be taken for a 3x3 matrix. It is my intention that Mathematica never have to deal with the matrices symbolically. Therefore, because the element I am plotting by is in the matrices, I have used set delay in my code to make sure that when the functions are called all parameters have numerical values. Nonetheless, Mathematica continuous to return the error that not all the eigenvectors can be found though I have `SynchronousUpdating -> False`, and what I also find strange is that having a set delay inside the manipulate function causes the application to continuously update even when nothing is changing. The code below is a simplified case of how the code runs. Does anyone have ideas to how to make this code run so that it is not continuously updating and athematica never has to deal with things symbolically.                Manipulate[      g[e_] := ( {     {e, ρ, 11},     {1, e, ρ},     {1, 1, e}} );          U[e_] := (Transpose[Eigenvectors[g[e]]]).( {      {0, 0, 1},      {0, 1, 0},      {1, 0, 0}     } );      LogLinearPlot[(\!\(     \*UnderoverscriptBox[\(\[Sum]\), \(l = 1\), \(3\)]\(\(U[e]\)[\([1,        l]\)]\)\)), {e, .01, 50},        AxesLabel -> {"Disrance (Km)", "Probability"},        PlotRange -> All], {{ρ, 9.6,         "\!\(\*FractionBox[\(g\), SuperscriptBox[\(cm\), \(3\)]]\)"}, 0.,        120.}, ControlPlacement -> Left, SynchronousUpdating -> False,       ContinuousAction -> False]


How to transform equation

Is there any possible way to write this equation of 4th order as a system of two diff equations of second order with two new variables and to do that automatically? statespace command is transforming it into first order                 eq=a1*X1[x] + a2*Derivative[2][X1][x]-Derivative[4][X1][x];


will the same result be evaluated twice per evaluation?

here is the silly question of mine, if `mathematica` takes `3` seconds to evaluate the function `f[3]` then I plug the this value `f[3]` into a new function `g[f[3],f[3]]`, Let's ignore the evaluation time for the new function `g`, how long does it take for `g[f[3],f[3]]`, 3 seconds or 6 seconds? if it is 6 seconds, how can I make `mathematica` temporarily to remember the value of `f[3]` thanks


HSB -> HSL Converter

Starting from an image I would like to apply a custom filter to an image. I have thought and implemented this filter in HSL space and it goes like this :   * Boost the saturation of the pixels that have a S value > .5    * Decrease the ones where S < .5. Would I have the HSL Values instead of the HSB the code would go like this :               img = Import["ExampleData/lena.tif"];     ImageColorSpace[img]     img = ImageResize[img, 128];     img = ColorConvert[img, "HSB"];     imgd = ImageData[img];     newimg = ({#[[1]], 1/(1 + E^(10*#[[2]]*(#[[2]] - .5))), #[[3]]} & /@        imgd[[#]]) & /@ Range[Length[imgd]];     newimg = Image[newimg]      **My Problem :** I cannot figure out how to convert HSB (only hue based space in M9 to my knowledge) to HSL.


Exporting 3D plotted figure complete with legend ready for Word

I have one more problem, still with exporting full quality 3d figure into Word. I want perfect quality in a Word document of a 3d figure prepared with legend (traditional form of text). Extremes of the function in figure is nice to be yellow and rest of the function feature red. Example,                 Plot3D[Sin[4 x]*Cos[4 y], {x, -2, 2}, {y, -2, 2}]      I need this figure to import in Word with full prepared legend and combination of color (red-yellow).


TensorContract of inverse matrix

### Matrix inverse in mathematica If $A$ is an invertible $n \times n$ matrix, then $A\cdot A^{-1} = I$. To get this statement in Mathematica, you need the assumption   `MatrixPower[A, 0] = IdentityMatrix[n]`               $Assumptions = {Element[A, Matrices[{n, n}]],                      Det[A] != 0, ForAll[{A}, MatrixPower[A, 0] == IdentityMatrix[n]]}     TensorExpand[Inverse[A].A] // Simplify      `Out[1]= IdentityMatrix[n]`. ### Matrix as a tensor A matrix can also be seen as a tensor of rank 2; i.e. a list with two levels, on for the columns and one for the rows. The tensor product $A \otimes A^{-1}$ corresponds in Mathematica with the outer product of the two lists. In this case it is a list with four levels, a four-tensor. When matrices are viewed as tensors, the dot product is the same as a tensor product followed by a contraction. In Mathematica the matrix product $A\cdot A^{-1}$ can also be written as               TensorContract[Inverse[A]\[TensorProduct]A, {2, 3}]       **Question 1** How can I let Mathematica evaluate the above expression to IdentityMatrix[n]? ### Involving more tensors Suppose there is a second $n \times n$ matrix $B$. In that case one can think of more complex tensor products, for example $B \otimes A \otimes A^{-a}$. This is a rank 6 tensor. Contracting slots 3 and 4 of the 6-tensor gives 4-tensor $B \otimes I$, where $I$ is the identity matrix. In Mathematica, this contraction can be written as               TensorContract[B\[TensorProduct]A\[TensorProduct]Inverse[A], {3, 4}]       **Question 2**   Also for the above contraction, I would like Mathematica to use the idenity $A\cdot A^{-1} = I$. It should evaluate to               B\[TensorProduct]A\[TensorProduct]Inverse[A], {3, 4}]       More over, I want Mathematica to use the same identity in more complicated tensor products, like $ B \otimes A \otimes B \otimes A^{-1} $. The last example should evaluate to               TensorTranspose[B \otimes I \otimes B, {{4, 5}]      How can this be realized with Mathematica 9? ### Generalizations Ihe above, there was allays only one invertible matrix which was called $A$.   **Question 3**   Can you take identity relations are into account for any invertible matrix, irrespectively of the names or number of invertible matrices?


Problem with Integrate

Integrate[(c*al*be)/Beta[a, b]*x^ -          (be + 1)*Exp[t*x]*Exp[-al*a*c*x^-be]*(1 - Exp[-al*c*x^-be])^(b - 1),        {x, 0, ∞},        Assumptions -> {a > 0 ,  b > 0, c > 0, al > 0, be > 0, t > 0}]      When I evaluate the above expression in _Mathematica_ , I do not get a solution.   What's the problem? For `t = 0`, the above expression is a proper "pdf". With a simple transformation we can prove the value of the integral is 1. But Mathematica not get solution. For manual solution, I get the following: > $$\frac{c^* al^* be}{B(a,b)} \int_0^\infty x^{-be-1} e^{-al^* a^* c^* > x^{-be}} (1-e^{-al^* c^* x^{-be}})^{b-1}\,\mathrm{d}x$$ Write $z=e^{-al^* > c^* x^{-be}}$, whence $$\mathrm{d}z = e^{-al^* c^* x^{-be}} (al^* be^* c^* > x^{-be-1})\,\mathrm{d}x$$ and $$\frac{\mathrm{d}z}{z} = (al^* be^* c^* > x^{-be-1})\,\mathrm{d}x$$ By substitution, $$\frac{1}{B(a,b)} \int_0^1 > z^{a-1} \left(1-z\right)^{b-1} \,\mathrm{d}z = 1.$$


Interfacing with a LabJack

I have a LabJack U3-HV and I wanted to use it with _Mathematica_ to interface some hardware. I cannot find any information on the Internet; if I have to use Python, I will, but I would rather use _Mathematica_. Does anyone have any advice on this? Specifically, I can't figure out how to read "AIN0" (the LabJack's first analog input) using _Mathematica_.


Calculating difference ratios (Δβ/Δρ) from a data set

I am little bit confused about how to calculate `δβ/δρ` value if I have set of values like this. I have the values of β and ρ like this.               β          ρ          0,324     0,687     0,322     0,695     0,319     0,721     0,317     0,759     0,316     0,798      aka:               β={0.324, 0.322, 0.319, 0.317, 0.316};     ρ={0.687, 0.695, 0.721, 0.759, 0.798};      from the above set of values I would need to calculate `δβ/δρ`. Can anyone explain me how to do it with _Mathematica_?


How can I set the kernel for CreatePalette?

I have written some code that requests some calculations from an SQL server every N seconds and uses a palette:               CreatePalette[Dynamic[DateListPlot[...]]]      I create many copies of this notebook, each with different parameters, and launch as many independent kernels. But there is a problem. Frist, I launch the 1st palette on kernel1. Next, I start a 2nd palette on kernel2, (Evaluation->Notebook Kernel), but when I do that, the first palette thinks that its kernel is kernel2. How can I set the kernel for `CreatePalette` ?


Passing optional parameters to functions

Assume I want to write a function which has to have an argument structure like               myFunction[variable_,parameters_]      for compatibility reasons. Where parameters should contain a variable number of parameters (myFunction has just two parameters however). I have been using rules lists to functions to solve this:               variable=0     parameters={param1->1,param2->2}     myFunction[variable,parameters]      which I accessed inside the `Module` as `param1 /. parameters`, etc. Now I am reading that this kind of substitution is disfavored for efficiency reasons and that it is better to use `With` or `Block` to insert values. So what is the recommended way to pass to and substitute in functions with given argument number multiple parameters? As an extra: Is there a way to do it which is compatible with `Compile`?


LinearModelFit with millions of rows

I'd like to do a simple regression with millions of rows of (x,y) data. It seems to be too long for Mathematica. Is there a way to speed it up? It shouldn't be that hard to do, I am not sure what Mathematica is doing. For example here's how the timing grows with the size of the input:                   First@Timing[LinearModelFit[RandomReal[NormalDistribution[], {#, 2}], x, x];] &              /@ {10, 100, 1000, 10000, 100000}      generating on my machine:                   {0., 0.015600, 0.046800, 0.670804, 26.722971}      It doesn't seem like it should be taking so much longer for longer data, and yet it does.


How to generally match, unify and merge patterns?

This question was split from this one. While that question is now about how to match two _particular_ patterns (mostly using `Verbatim` or `HoldPattern`), this question is about **how to match _any_ pattern with another one**, in other words: "How can I test if a given pattern intersects with, or is a subset of another pattern?" (borrowed from Mr.Wizard). Consider the following examples where one can see that the left pattern should "match" the right one, but which all return `False`:               MatchQ[a|b, b|a]     MatchQ[{a..}, {a..}]     MatchQ[{a..}, {a...}]      Of course one trivial way to deal with `Alternatives` would be to simply `Sort` its arguments:               MatchQ[a | b | c, Verbatim[Sort[b | c | a]]]  --->  True      but things get complicated if the pattern involves more than `Alternatives`.      ## Problem specification:    Therefore I am looking for a predicate function that **compares any pattern with another pattern** and decides whether the first one matches the second one. For this, one needs a general way of matching two expressions that may contain any of these operators: `{|, .., ..., _, __, ___}` and possibly anything else that is specific for patterns. The predicate should have the following behaviour:               PatternMatchQ::usage="PatternMatchQ[e1, e2] returns True     if the set of expressions matched by pattern e1 is the same     or is a subset of the expressions matched by pattern e2, False otherwise."      i.e. the first pattern should cover the same (or smaller) domain as the second does. Now of course if any of the arguments is a non-pattern, `PatternMatchQ` can fall back to `MatchQ`.      ## Examples:      * `a|b` agrees with `b|a`   * `a|b` agrees with `c|b|a` (as `a|b` covers a domain that is covered by `a|b|c` as well)   * `a|b|c` does not agree with `b|a` (as `a|b|c` covers a domain that is larger than the domain covered by `b|a` **unless** `c == a` or `c == b`, in which case the pattern simplifies to `a|b`)   * `{a..}` agrees with `{a..}`   * `{a..}` agrees with `{a...}`   * `{a...}` does not agree with `{a..}`    ## Extension:    Now the concept of matching can be extended in the following way. So far we were only concerned about whether it is true that $domain(e_1) \subseteq domain(e_2)$, and if not, return `False`. But even if the test gives false, it is possible to define the smallest (most simple) domain that both patterns cover. Also, a full pattern-set-algebra emerges, if one thinks it further. Accordingly, for example `PatternUnion` could work on any number of arguments, and should return the most general unifier of all the argument patterns. The union of patterns would be equivalent to the merging of patterns. Now, of course, " _The thing that hath been, it is that which shall be; and that which is done is that which shall be done: and there is no new thing under the sun_ "... in certain fields (e.g. in logic or in linguistics and especially in construction grammar), this method is called unification: > Two expressions $e_1$ and $e_2$ are said to unify iff there exists a > substitution $s$ such that $s(e_1) = s(e_2)$ where a substitution is a **binding** of variables (i.e. implicit, hidden variables introduced by _Mathematica_ to deal with e.g. `_`, `__`) in patterns $e_1$ and $e_2$ with actual fitting values. Note that the substituted value of a pattern-variable can be any atom, even symbols, it does not matter. Thus what the code should look for is the equality of variables (i.e. implicit pattern variables). If such an $s$ exists, it is called a **unifier**. It is known that if two expressions $e_1$ and $e_2$ unify, then there always is only one most general unifier (up to a renaming of variables). Now this general unifier of two pattern expressions can be called (or used to describe) the intersection of $e_1$ and $e_2$.


Mathematica performance on Mac

I recently got a trial version of both Mathematica 9 and MATLAB 13a for Windows. I was stunned by the performance difference in the Windows and the Mac version. It was a simple test in matrix multiplication. Here's the code:               a = RandomReal[{0,1},{1000,2000}];     b = RandomReal[{0,1},{2000,3000}];     Timing[a.b;]      On Windows, **running on VMWare Fusion** , the above code takes 0.17 second to complete, more or less same as MATLAB. But on the Mac, it takes 1.8 seconds, or 10 times longer to complete the calculation. Something is terribly wrong here. What can be the explanation for this discrepancy? (I have 12GB free RAM on my 2012 Mac Mini so we can rule out memory shortage). **Edit:** here some benchmarking information. Windows is running in Bootcamp in the benchmark, not from VMWare Fusion:                                               Mac        Windows                                     -------    -------     Data Fitting                    0.666      0.468     Digits of Pi                    0.711      0.733     Discrete Fourier Transform      1.082      0.874     Eigenvalues of a Matrix         0.737      0.608     Elementary Function             1.072      0.780     Gamma Function                  0.532      0.655     Large Integer Multiplication    0.518      0.608     Matrix Arithmetic               1.         1.108     Matrix Multiplication           0.841      0.562     Matrix Transpose                0.889      0.842     Numerical Integration           1.083      0.764     Polynomial Expansion            0.118      0.094     Random Number Sort              1.459      1.061     Singular Value Decomposition    0.751      0.671     Solving a Linear System         0.767      0.655     ------------------------------------------------     Total Time                     12.226     10.483     Benchmark Result                1.132      1.320      Mathematica on Mac seems to be a good 20% slower than on Windows.


Print numbers in the terminal

I am trying to run a parallelized version of my Mathematica code on a cluster and i want to display some information on the terminal. When i try to display the time taken for the calculation, using AbsoluteTiming[], i get a number displayed on the terminal that does not represent the time taken for the calculation. I assume it has to do with the data format that i am trying to print and how bash interprets it, but i could not find a solution. Here is some of the code:               Print[ $ProcessorCount, $MachineType, $System]          output = AbsoluteTiming[Parallelize[Table[Table[MyExpression[..],{iterator1,...}],{iterator2,...}]]];          Print[N[output[[1]],3]]      Feel free to comment on my use of Parallelize[]. There is probably a more intelligent way to do this but i found that ParallelTable[] is slower in my case (evaluating the expression using two iterators).


Add Piecewise functions expanding domains

I want to reproduce these plots for further development in Mathematica: ![enter image description here](http://i.stack.imgur.com/Ad9VZ.jpg) To do so I defined the functions A and B as following `A[x_ /; 0 < x < 200] := Piecewise[{{65, 0 < x < 100}, {110, 100 < x < 200}}]` `B[x_ /; 0 < x < 200] := Piecewise[{{40, 0 < x < 100}, {90 , 100 < x < 200}}]` Now when I plot their sum the domain is fixed and the ranges are added together. In the graph above the domains of A and B are added. Then in a try in each step of the new domain the minimum of A or B or A+b is returned. How one can make this graph below from A and B? EDIT: The domain of the functions are not necessarily unique. Take this example: `A[x_ /; 0 < x < 200] := Piecewise[{{65, 0 < x < 100}, {110, 100 < x < 200}}]` `B[x_ /; 0 < x < 300] := Piecewise[{{40, 0 < x < 170}, {90 , 170< x < 300}}]`


Having SetOptions[] affect CDF styling

Instead of writing a package and importing it, at the beginning of many of my .nb files I have a string of SetOptions commands which govern things like plot styling. However, when I subsequently make a CDF based on elements using those options, the CDF doesn't incorporate them. Is there an easy way to fix that?               SetOptions[Plot,       AxesStyle -> Directive[25, Thickness[.005]],        PlotStyle -> {Thickness[.005]},       ImageSize -> 550     ];     Manipulate[       Plot[x^e, {x, 0, 1}, PlotRange -> {{0, 1}, {0, 1}}, AxesOrigin -> {0, 0}],       {e, 0, 5}     ]      Thanks!


Call Functions From File Without Modifying Context (Sandbox)

Let's say I have file named `test.m` containing               test[arg1_] := ( Print[arg1];)      What is the best technique for calling test like `test["value"]` while preventing test from being added to the `$ContextPath`? The following almost works except you must know function values ahead of time               Block[{$ContextPath,test}, Needs["test`"];test["test"]];      My question is: **How do I generalize the call above to work with any number of functions without the user needing to input definitions manually?**


Set default font for Output

Is it possible to set the font family to Arial for axes, legends and labels globally? I found out about               SetOptions[       Legending`GridLegend,        Legending`LegendContainer -> (Framed@ Append[#, FontFamily -> "Arial"] &)     ];      for legends, but now I am trying to set the axis labels.


Count the number of sqrt and 4th powers in a function

This is a simple and short question. I have a function which contains a certain number of square roots and 4th powers, lets take this one:               f=Sqrt[x] Sqrt[y] Sqrt[z + 2] b^4 + c^3 + d^4      I want to be able to count the number of occurrences of the square roots (3) and the number of occurences of the 4th power (2). I think it should be possible to use `Count` for this, but I can't figure out how. I have tried               Count[f,_Sqrt,Infinity]      and               Count[f, Power[4, _], {0, Infinity}]      but both don't seem to work. Can someone tell me how to achieve this?


Find dy/dx given an equation

Here's a homework problem from the Coursera course Calculus: Single Variable by Robert Ghrist > Find the derivative $\frac{dy}{dx}$ from the equation $x \tan y - y^2 \ln > x=4$ I wanted to check my work using Mathematica so I tried this:               Dt[x Tan[y] - y^2 Log[x] == 4];     % /. {Dt[y] -> dy, Dt[x] -> dx};     Reduce[{%, dy/dx == z}, z]      On my system (Mathematica 9, Windows 7), this computation seems to hang. Does anyone have a suggestion on how to solve this? **Edit:** I'm also interested in why `Reduce` doesn't handle the problem well when used as above whereas `Solve` handles it just fine (see answers).


How to trash files / directories?

Both `DeleteFile` and `DeleteDirectory` can only delete files / directories, and lack the option to move them to the trash. Is there an elegant (and OS- independent) way to trash items?


What is the difference between NotebookEvaluate and FrontEndToken

I am wondering what exactly are the differences in using `NotebookEvaluate[filename]` **vs** `FrontEndExecute[FrontEndToken[nb, "EvaluateInitialization"]]`; to evaluate cells in a given notebook. In particular, I am referring to the discussion: Evaluate Initialization Cells of another notebook. Given my new status here, I couldn't see how I could continue with that conversation directly, so I decided to post a new queston. The comments in the referenced question proposed these two solutions to the problem:   * method 1.              filename = SystemDialogInput["FileOpen"];     NotebookEvaluate[filename, EvaluationElements -> "InitializationCell"]        * method 2.              filename = SystemDialogInput["FileOpen"];     nb = NotebookOpen[filename];     FrontEndExecute[FrontEndToken[nb, "EvaluateInitialization"]];     NotebookClose[nb]      I am trying to solve the same problem. Taken at face value, it seems both approaches are valid. Are there any subtleties that make one preferred to the other, issues of scope/context, etc.?


Drawing Zonotopes from Adjacency Matrix

This is crossposted in cs.stackexchange.com, but I have been trying to use Mathematica do this and figured it might be more appropriate to ask here. Define a " **simple zonotope** " to be a regular $2n$-gon which is tiled by the following rule: all tiles are rhombi. They key point here is that rhombuses have equal side lengths (say equal to 1), but their shapes are allowed to vary arbitrarly. Here's an example of a 12-gon zonotope: ![Zonotope](http://i.stack.imgur.com/YATPS.png) There are many characterizations and properties of these objects. For example, one can encode a zonotope using $2n$ vectors (one for each outer edge) since we can just translate copies of each vector. **What I would like to do is the following:** I have the adjacency matrix of a graph that I believe to be a simple zonotope. Specifically, you can assume that we are starting with a _planer geometric graph_ , in that I have an adjacency matrix, in addition to having (x,y) coordinates of each point. In other words, it's fairly straightforward to identify which vertices go to the outer vertices of the $2n$-polygon.Here's an example of a geometric graph that I could have: ![enter image description here](http://i.stack.imgur.com/TFPlL.png) In the above picture, the two red vertices indicate the north/south poles of the zonotope they are mapped to (which happens to be the zonotope in the first picture). > Question: What is the most painless way of drawing the simple zonotope from > a given adjacency matrix plus geometric graph coordinates? Some observations: part of the algorithm is somewhat clear to me: one should work from the outside in. Once a specific rhombus side has been identified, all sides below it must be the same until we run into the opposite side of the zonotope. However this all seems very computationally expensive. I am honestly not preferential to any specific solution. I would even accept something akin to attaching springs to vertices and then running the algorithm until the graph converges to a zonotope. What I have tried in Mathematica 8.0: I've been trying to use               GraphPlot[A, VertexCoordinateRules -> VertexCycleCoordTag, VertexLabeling -> True,         Method -> {"SpringElectricalEmbedding", "RepulsiveForcePower" -> -2}]      Here 'A' is the adjacency matrix (in this case a 22x22 matrix). 'VertexCycleCoordTag' fixes what I know to be the outer vertices of this particular adjacency matrix. Here is the output: ![enter image description here](http://i.stack.imgur.com/OHBaI.jpg) Not too shabby! The repulsive force helped organize things here a bit. However, I would _ideally_ like to fix the edge lengths to all be equal and to start seeing rhombi. I've had trouble doing this, even after consulting a post talking about EdgeWeight. It doesn't seem like GraphPlot has the EdgeWeight option (is this amended in Mathematica 9.0?). Here's the full code, where 'VertexCycle' denotes the vertices which run around the edge of the 2-n gon in counterclockwise order:               A={{0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,      1}, {0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,      1}, {0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,      1}, {1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,      0}, {1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,      0}, {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,      0}, {0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,      0}, {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0,      0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,      0}, {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0,      0}, {0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,      0}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0,      0}, {0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,      0}, {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,      0}, {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,      0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0,      0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0,      0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1,      0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1,      0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1,      0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0,      0}, {1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,      0}};          VertexCycle={21, 18, 15, 9, 4, 1, 22, 3, 8, 14, 17, 20};          n = Length[VertexCycle]/2;     VertexAngles[{x_, y_}] := {x*Cos[Pi/n] - y*Sin[Pi/n],      x*Sin[Pi/n] + y*Cos[Pi/n]}          VertexCycleCoordTag = {};     For[i = 1, i < 2*n + 1, i++,          VertexCycleCoordTag =          Append[VertexCycleCoordTag,          VertexCycle[[i]] -> VertexCycleCoord[[i]]]];          GraphPlot[A, VertexCoordinateRules -> VertexCycleCoordTag,          VertexLabeling -> True,          Method -> {"SpringElectricalEmbedding", "RepulsiveForcePower" -> -2}]


Matching a list of sequences with common form

I am trying to find a pattern that matches a list of sequences that share a common form. The sequence form is: 1 followed by zero or more nonzero integers, followed by 0. An example list is:               {1,3,2,0,1,0,1,2,0,1,1,4,0}      The closest thing I've struck on so far is this:               MatchQ[{1, 2, 0, 1, 2, 0}, {PatternSequence[1, s___ /; FreeQ[{s}, 0], 0] ..}]      which yields `True` in this case because the sequences are both the same. Is there a way to get the `s___` to apply uniquely to each instance in the `Repeated`? This would solve the problem. Other suggestions are most welcome.


Cleaning up a List of HTML Data to Render Usable Information

I am using Mathematica to scrape information from webpages. To get file information, I am gathering plain text that is enclosed by `<tr>` and `</tr>` tags. I have made a list, of which each element is the entire data. I want to somehow scrape the plaintext readable element out of this. By way of example, here are two elements from my list:                  "
              1.	              1841-1869 (Province of \         Canada), number 195, 21 June 1845, page 15	         GIF | PDF
", "
              2.	              1841-1869 (Province of \         Canada), number 402, Extra, 16 May 1849, page 4	         GIF | PDF
"      I've been playing around with `Shorten[]` and `StringCases[]` to try to find a way, but would there be a way to quickly map a function on this list that would result in the following:               "1841-1869 (Province of Canada), number 195, 21 June 1845, page 15",     "1841-1869 (Province of Canada), number 402, Extra, 16 May 1849, page 4."      The actual text changes, i.e. it doesn't always say 1841-1869 etc., but the general format of the `<tr>` portion remains consistent. I don't mind if the GIF | PDF part remains either. Would there be a quick way to just render the actually visible part of the HTML file in this list? * * * If somebody wants to reproduce the list I am using, here is my code (I include this only to make things simpler, but this is probably more of a theoretical question):               baseurl =        "http://www.collectionscanada.gc.ca/databases/canada-gazette/001060-\     110.01-e.php?q1=youth&q3=&interval=199&sk=";     pagelist =        Import[baseurl <> ToString[#], "Source"] & /@ Range[1, 1889, 199];     pagetext = Apply[StringJoin, pagelist];     trlist = StringCases[pagetext, Shortest["
" ~~ ___ ~~ "
"]];


Can the position of Tooltips be changed?

Is it possible to change the position of tool tips, which currently always appear to the lower right of the mouse position. In the screen grab below the mouse is over 10000000 and the tooltip appears to the bottom right (8.0.4 on Mac). ![enter image description here](http://i.stack.imgur.com/8B9Y8.png) By way of an example how would you go about making the tooltip appear to the bottom left (courtesy of photo editing): ![enter image description here](http://i.stack.imgur.com/U9ijy.png) (This was originally asked on StackOverflow, but it did not draw any answers.)


NullSpace[_, Method->"OneStepRowReduction"] is sometimes wrong; how can I work out when this happens?

(This is on MMA 7.0.1.0 on OS X) I've just found a large matrix `m` for which `NullSpace[m]` and `NullSpace[m, Method->"OneStepRowReduction"]` give different answers (the first one is the correct answer). I put the matrix up at pastebin as won't fit here! What's going on? How might I guess ahead of time which arguments are going to break `Method->"OneStepRowReduction"`? (Update; it seems the bug has got _worse_ in 8, rather than better.)


Generate a new output using Manipulate

Thanks to methods found in the below, I was able to assemble those elements : Tile image on specific location without space between them How to combine images with the same dimensions in a grid? ![enter image description here](http://i.stack.imgur.com/SepuA.jpg) Now, I would like to use Manipulate [] to have a button that, when pressed generate a new composition, "re-run" the code.


Why don't I get the graphics output I'm expecting?

**Today,I want to use a point generate a circle,the main picture as below:** ![enter image description here](http://i.stack.imgur.com/qlnEv.jpg) Given that I know the equation of circle, and the value of $L_1$,$L_2$.The coordinate of point $A$ is $(p_x,p_y)$. I use the equations: $$p_x=L_1 cos(\theta_1)+L_2cos(\theta_1+\theta_2) \\\ p_y=L_1 sin(\theta_1)+L_2sin(\theta_1+\theta_2)$$ to solve the results of $\theta_1,\theta_2$ as below:$$cos(\theta_2)=\frac{-L_1^2-L_2^2+p_x^2+p_y^2}{2 L_1 L_2} \\\sin(\theta_2)=\pm \sqrt{1-cos^2(\theta_2)}$$ $$sin(\theta_1) =-\frac{sin(\theta_2) L_2 p_x-L_1 p_y - cos(\theta_2) L_2 p_y}{p_x^2+p_y^2}\\\ cos(\theta_1) =-\frac{-L_1 p_y - cos(\theta_2) L_2 p_x - sin(\theta_2) L_2 p_y}{p_x^2+p_y^2} $$ My trial as below:               Manipulate[       Module[{L1, L2, θ1, θ2, A, B, C1, D1, px, py},         L1 = 35; L2 = 20;       A = (-L1^2 - L2^2 + px^2 + py^2)/(2 L1 L2);       B = Sqrt[1 - A^2 ];       C1 = -((-L1 px - A L2 px -        B L2 py)/(px^2 + py^2));       D1 = -((B L2 px - L1 py - A L2 py)/(       px^2 + py^2));       px = 50 + 15 Cos[20 ° t];       py = 50 + 15 Sin[20 ° t];       θ2 = ArcTan[B, A] // Simplify;       θ1 = ArcTan[D1, C1] // Simplify;      Graphics[              {Line[{0, 0}, {L1 Cos[θ1],          L1 Sin[θ1]}, {L1 Cos[θ1] +          L2 Cos[θ1 + θ2],          L1 Sin[θ1] + L2 Sin[θ1 + θ2]}], Red,         Point[{L1 Cos[θ1] + L2 Cos[θ1 + θ2],          L1 Sin[θ1] + L2 Sin[θ1 + θ2]}]},        Axes -> True]     ], {t, 0, 18}     ]      ### Edit Thanks for Mr.Wizard's help.               Manipulate[       Module[{L1, L2, θ1, θ2, c2, s2, c1, s1, px, py},     L1 = 35; L2 = 20;     c2 = (-L1^2 - L2^2 + px^2 + py^2)/(2 L1 L2);     s2 = Sqrt[1 - (c2^2) ];     c1 = -((-L1 px - c2 L2 px - s2 L2 py)/(px^2 + py^2));     s1 = -((s2 L2 px - L1 py - c2 L2 py)/(px^2 + py^2));     px = 50 + 15 Cos[20 ° t];     py = 50 + 15 Sin[20 ° t];     θ2 = ArcTan[c2, s2] // Simplify;     θ1 = ArcTan[c1, s1] // Simplify;     Graphics[     {Circle[{50, 50}, 15],       Line[{{0, 0}, {L1 Cos[θ1],          L1 Sin[θ1]}, {L1 Cos[θ1] +           L2 Cos[θ1 + θ2],          L1 Sin[θ1] + L2 Sin[θ1 + θ2]}}],       Blue, PointSize[Large],       Point[{L1 Cos[θ1], L1 Sin[θ1]}],       Red, PointSize[Large],        Point[{L1 Cos[θ1] + L2 Cos[θ1 +θ2],         L1 Sin[θ1] + L2 Sin[θ1 + θ2]}]},       Axes -> True, PlotRange -> {{-20, 80}, {-20, 80}},       AspectRatio -> Automatic] /. z_Complex :> Re[z]],      {t, 0, 18}]      It generates: ![enter image description here](http://i.stack.imgur.com/xINw7.jpg) **By manipulating the value of`t`,I found the length of shaft `L1` and shaft `L2` vary. This is contradictory because the length of `L1` and `L2` are constants. I don't know why.**


Using a function name instead of its definition in AxesLabel

I seek to use a token as an axis label, but this token, having other meanings, is expanded by Mathematica. If I enclose the token in quotes, it is not expanded, but it is also no longer italicized. Using `LabelStyle->{Italics}` results in italicization of all fonts in the figure (axis labels and axis tick labels). How do I circumvent token expansion (or equivalently, in effect, italicize only the axis labels and not the axis tick labels)? Two examples: (1) I may wish to plot a function `f` (say `f=x^2`) and want the axis label to be simply `f` (in italics), but it is expanded to `x^2` by the command `Plot[f, {x, -2, 2}, AxesLabel -> {x, f}]`. Changing to `Plot[f, {x, -2, 2}, AxesLabel -> {x, "f"}]` results in italic `x` and roman `f`. (2) I may wish to label an axis with `E`, but it is changed by Mathematica to `e` (the irrational constant). Again, I can use `"E"`, but this has the undesired effect of altering the font face.


Efficient ways to create matrices and solve matrix equations

I am attempting, for the first time, to use Mathematica to do some serious linear algebra. I would like to solve systems of equations of the form $$U_{n n'} f_{n'} = b_n.$$ I have an expression for $U_{n n'}$ that is of the general form $U_{n n'} = f_1(n) \delta_{n n'} + f_2(n,n')$. Is using 2 nested Table commands the easiest/most efficient way to build this matrix in Mathematica? I am not entirely sure how large I will need to make the matrix (it results from discretizing an integral equation, so the number of rows/columns will be as many as I need to get an accurate solution). I guess that it could be as large as 10,000 x 10,000, maybe. Is LinearSolve efficient enough to handle these sized systems on a standard desktop PC? Is parallelization for this automatic or do I need to do something manually? After I have found the solution, I am going to need to feed the solution to another equation to find the quantity that I am actually interested in. Is there anything I should do at the outset to make my life easier later? I apologize for the general nature of my question, but this is all new ground for me, so I am not sure what general guidelines and practices are best.


Mapping higher dimensions to color, opacity, point size, etc

I have a set of points of dimension >3, and I'd like to modify ListPointPlot3D so that the higher dimensions are mapped to different variables, such as color, opacity, point size, etc. so for example               a = Table[RandomVariate[NormalDistribution[3], 4], {5000}];     ListPointPlot3D[a] +some options...


Tutorial for basic numerical methods for PDEs

I'm afraid this is probably not going to be a "good" question, but I'd like to use _Mathematica_ to learn about basic numerical schemes for solving pdes. For example, I'd like to compute the solution of a 2D heat equation initial value problem using finite differences and Euler timestepping, and then look at how big errors are or stability (not interested in using `NDSolve` directly). My question is, are there any resources that already do this the "right" way? I'm just getting acquainted with _Mathematica_ and don't know the language well, but I do know I want to use packed arrays and avoid loops. There's lots of language-agnostic references for the numerical methods themselves, but I can't find good clean examples of _Mathematica_ implementations of these methods. Edit: One of the books recommended in the answers suggest doing stuff like (1d heat equation IVP):               Clear["Global`*"];     gridX = 10; (* num interior points *)     dx = 1./gridX;     dt = .005; (*cfl: dt/dx^2 <= .5 *)          T[i_, j_] := T[i, j] = T[i, j - 1] +                        (dt/dx^2) (T[i + 1, j - 1] - 2 T[i, j - 1] + T[i - 1, j - 1]);          T[i_, 0] := 1. (* initial value *)          T[0,         j_] := 0.; (* boundaries *)     T[gridX + 1, j_] := 0.;           TFinal[t_] := Table[T[i, IntegerPart[t/ dt]], {i, 1, gridX}];     ListLinePlot[TFinal[1]]      But I suspect that it's not the best way, because as soon as I crank up the grid size and shrink down the time step, I get a recursion limit error. The code above is storing the solution at all time steps, which I definitely don't want. I'm sure there are clean, non-recursive sample implementations of this method out there, just can't seem to find.


Find the domain in which a sequence converges

I seem to have a lot of problems in the format of: > Given the sequence $a_n=\frac{n^\alpha+1}{2n^8+5}$, for $\alpha > 0$, find > the values of $\alpha$ such that the sequence converges. However, I can never seem to get _Mathematica_ to solve for a variable in a limit. I have tried               Solve[Limit[(1 + n^a)/(5 + 2 n^8), n -> Infinity, Assumptions :> a > 0] == 0, a]          Reduce[Limit[(1 + n^a)/(5 + 2 n^8), n -> Infinity, Assumptions :> a > 0] == 0, a]      `Solve` gave me no solutions, with a warning about inverse function. `Reduce` gave me the solution is `C[1] ∈ Integers && α == 0`, which also violates the initial assumption ($\alpha > 0$). However, I tried particular cases manually, such as               Limit[(1 + n^3)/(5 + 2 n^8), n -> Infinity, Assumptions :> a > 0] == 0        which gave `True`. Am I going about this in the wrong way?


Find roots of a function involving Bessel functions

I'm trying to find the roots of a function involving Bessel functions. Here is my code               Clear[f, eta, chi, omega, alpha, beta, h, M, T, v, rho, phi, a, n, k, Zeros, z];     eta = Sqrt[beta^2 (Sqrt[4 alpha^2 omega^2/beta^4 + 1] - 1)/(2 alpha^2)];     chi = Sqrt[beta^2 (Sqrt[4 alpha^2 omega^2/beta^4 + 1] + 1)/(2 alpha^2)];     beta = Sqrt[alpha^2*(14.682 phi)/a^2];     alpha = a^2*omega/k;     a = .5;     f[n_, k_, phi_] = eta*(BesselJ[n - 1, eta*a] - BesselJ[n + 1, eta*a]) -         chi*((BesselI[n - 1, chi*a] + BesselI[n + 1, chi*a])*(BesselJ[n,eta*a]))/BesselI[n, chi*a];      Plotting the functions for different values of $n$ and $\phi$               Manipulate[Plot[f[n, k, phi], {k, 1, 300}, PlotRange -> {-10^1.5, 10^1.5}],           {n,0, 5, 1}, {phi, .25, 3, .25}]      ![enter image description here](http://i.stack.imgur.com/3ny7R.png) Now, based on this post FindRoot giving false roots with Bessel Functions , I tried to obtain a list of the roots just by renaming my function and manually introduce the values of $n$ and $\phi$ as follows               n = 0;     phi = .25;     k = z;     Zeros[z_] = f[n, k, phi];     (zeros = First@     Last@Reap@       Quiet@NDSolve[{y'[x] == Zeros'[x], y[0] == Zeros[0],           WhenEvent[y[x] == 0, Sow[FindRoot[Zeros[z], {z, x}]]]},          y, {x, 0, 40}, AccuracyGoal -> 1,          PrecisionGoal -> 1]) // AbsoluteTiming      But it is not working!!! Mathematica gives the following error               First::first: {} has a length of zero and no first element. >>     {0.044039, First[{}]}      Any support that you can give me is highly appreciated.


Finding all paths of certain length between vertices in path graph, non-simple ones too

First I will tell you what my ultimate goal is, because maybe there's another way of doing it other than what I am trying. I need a list of all $(a_1, a_2, \ldots, a_N)$ tuples that satisfy certain conditions.   * $a_i$ can take integer values between $1$ and $s$, that is, from the set $\\{1, \ldots, s\\}$.   * Neighbouring entries differ by $1$, that is, $|a_i - a_{i+1}| = 1$   * A "periodic boundary condition" holds. That means that $a_N$ and $a_1$ also differ by $1$ (we effectively have a ring).   * $N$ can be assumed to be even, because otherwise it's not possible to satisfy the previous two conditions at the same time. For $N=6, s=5$, I've put $a_1$ at the back of the list in parentheses for clarity. $2,3,4,5,4,3(,2)$ works.   $2,3,4,5,4,5(,2)$ doesn't, because $5$ and $2$ don't differ by one.   $2,4,3,4,3,3(,2)$ obviously doesn't work, because some pairs of neighbouring entries don't differ by $1$.   OK, I've been thinking that I could take `PathGraph[Range[1,s]]`, which is a builtin Graph with 1 being adjacent to 2, 2 being adjacent to 3 (and 1), 3 being adjacent to 4 (and 2), ..., s-1 being adjacent to s (and s-2). Now I can easily get _the number_ of tuples with the above properties by calculating the Nth `MatrixPower` of the `AdjacencyMatrix` and taking the Trace of that matrix, because the entries on the diagonal are Paths of length N, starting at 1, ending at 1, (plus the ones starting at 2 ending at 2, plus ...) possibly going back and forth between vertices. However, I need to have the tuples to work with them, so I wanted to get a list of paths of length N between two vertices of that simple path graph. But I can't seem to get that with the builtin functions. `FindPath[PathGraph[Range[1, 7]], 1, 3, {2}]` will give the path `1 -> 2 ->3` which has length 2. However, `FindPath[PathGraph[Range[1, 7]], 1, 3, {4}]` will give an empty set. It won't give me the path `1 -> 2 -> 3 -> 4 -> 3`, which visits nodes twice and goes back and forth along the same edge. Is there some way to get all of these? (the mentioned one and, say `1 -> 2 -> 3 -> 2 -> 3`). Of course I've read numerous posts on paths on these forums and a couple of entries about functions concerning graphs in the Mathematica documentation, but I couldn't seem to find what I need. I'd expect `FindPath[PathGraph[Range[1, 7]], 2, 2, {2}]` (same starting and ending point) to give me `2 -> 3 -> 2` and `2 -> 1 -> 2`. Which would get me the tuples $2,3(,2)$ and $2,1(,2)$, speaking the language from the beginning of the post.


k-means clustering using squared correlation in Mathematica

I am trying to cluster data using the squared correlation coefficient since in the case of my data, -1 correlation is equivalent to 1 correlation (polarities do not matter). How can this be done in Mathematica using the k-means algorithm?


Join decimal part

I have a list of mesures that each vector is like `{0,1,-2,259}` but it should be like `{0.1,-2.259}` So I did a rule, like `list/. {a_,b_,c_,d_}->{a.b,c.d}` but for the positives number it works fine! but for vector like this one I get `{0.1,(-2).239}` how can I fix this?


How to generate a blank crossword sheet?

I attempted to generate a blank crossword sheet. My method is by combining the rows and columns as shown on the graph below. However, some of the `across` and `down` numbers then appeared out of place after combining. What is the better way to obtain a blank crossword sheet? ![enter image description here](http://i.stack.imgur.com/WVSaf.gif)               fillRow[i_] := (        startPos = RandomInteger[{1, randomStartPos}] ;        randomWordLen = RandomInteger[{minWordLen, dimX - startPos}];        endPos = startPos + randomWordLen - 1;        Do[cwSheet[[i, n]] = 0, {n, startPos, endPos}];        AppendTo[ hintNumPad, { counter++, {startPos, dimX - i}}]         If[endPos <= dimX/2,          randomWordLen = RandomInteger[{minWordLen, dimX - endPos - 1}];          Do[cwSheet[[i, n]] = 0, {n, dimX, dimX - randomWordLen + 1, -1}];          AppendTo[            hintNumPad, { counter++, {dimX - randomWordLen + 1, dimX - i}}];          ]        );               fillCol[j_] := (        startPos = RandomInteger[{1, randomStartPos}] ;        randomWordLen = RandomInteger[{minWordLen, dimY - startPos}];        endPos = startPos + randomWordLen - 1;        Do[cwSheet[[   n , j]] = 0, {n, startPos, endPos}];        AppendTo[ hintNumPad, { counter++, { j, dimY - startPos  }}]          If[endPos <= dimX/2,          randomWordLen = RandomInteger[{minWordLen, dimX - endPos - 1}];          Do[cwSheet[[n, j]] = 0, {n, dimY, dimY - randomWordLen + 1, -1}];          AppendTo[ hintNumPad, { counter++, {j, randomWordLen - 1  }}];          ]         );          minWordLen = 3;     hintNumPad = {};     {dimX, dimY} = {9, 9};     randomStartPos = 4;     Clear[cwSheet];          cwSheet = ConstantArray[1, {dimX, dimY}];           counter = 1;      Do[fillRow[k], {k, 1, dimY, 2}];            counter = 1;      Do[fillCol[k], {k, 1, dimX, 2}];                g = MatrixPlot[cwSheet , Mesh -> All,       Frame -> False,       ColorFunction -> "Monochrome",        Epilog -> {Text[Style[#[[1]], 9], #[[2]] + {-0.9, 0.8}] & /@           hintNumPad}]      The correct positions of the hint numbers should look like this: ![enter image description here](http://i.stack.imgur.com/TBgkg.gif)


Why is Mathematica not able to calculate more digits

When I want a numerical value with a precision of 50 digits...               N[1.15/(1 - E^-0.2)^2, 50]      Why is Mathematica not able to provide the desired solution? ![enter image description here](http://i.stack.imgur.com/TnBIo.jpg) And I know that this is irrational and the given solution is not precise and besides Mathematica would provide more digits even if the solution is already precise in other cases. ![enter image description here](http://i.stack.imgur.com/PIGUS.jpg) So what is the problem here and how can I get more digits?


Why is evaluation Enter for Mac and shift+Enter for Windows?

Per the title, why is evaluation done using just the Enter key for Macintosh and shift+Enter for Windows? UPDATE Okay, I see the Mac keyboard's "Enter" key is actually labeled "Return", so by Enter we mean the numeric keypad Enter.


BVP - shooting method

I really don't know how to realize this method. The examples in internet and the reference aren't helpful for me. 1) I have the values for today:                x[0] == 0, y[0] == 0.84, r1[0] == 0.39, r2[0] == 0.39, z[0] == 0      Now I need the initial conditions at t=-20 that reproduces the values today.               alpha = 0.5     beta = 1          sol = First@NDSolve[{           x'[t] == -x[t]*a[t] - 3*x[t] + alpha*y[t]^2 +         1/2*beta*(r1[t]^2 - r2[t]^2),      y'[t] == -y[t]*a[t] - alpha*x[t]*y[t],       r1'[t] == -r1[t]*a[t] - 3/2*r1[t] + beta*x[t]*r1[t],       r2'[t] == -r2[t]*a[t] - 3/2*r2[t] - beta*x[t]*r2[t],      z'[t] == -z[t]*a[t] - 2*z[t],      x[0] == 0, y[0] == 0.84, r1[0] == 0.39, r2[0] == 0.39, z[0] == 0},      {x, y, r1, r2, z},     {t, 0, -20}];     a[t_] = -1/2*(3 - 3*y[t]^2 + 3*x[t]^2 + z[t]^2)      Most of the examples are integrated in a plot. First I don't want that. 2)Is it maybe also possible to say that I have the conditions at the present as follows:                 x[t]^2 + y[t]^2==0.5       r1[t]^2 + r2[t]^2==0.5      PS: This topic can be deleted: boundary problem


How to debug Mathematica crash?

If i have some program which crash Mathematica every time it's run. What are the steps to make a more informative report and/or how do i go about debugging it? EDIT: I guess essentially my question is how even professionals such as Wolfram support will go about doing the initial diagnosis.


k-means clustering in parallel

How can the k-means algorithm for some given distance function be implemented using ParallelMap or other parallel processing program constructs in Mathematica?


ImageDifference. Is there an ImageSame, or how would one do that?

Is there an inverse to ImageDifference? What in two images are the same?


How Manipulating a matrix and a graphic in only one Manipulate?

I have to manipulate a matrix and graphics in one big Manipulate-Block. This way:               Manipulate[Matrixform[mat],Graphics3D[]]      How can I achieve that? Ok, here my Code:               Manipulate[      Graphics3D[       {        Switch[x,          "Streckung", {GraphicsComplex[streckung[a, b, c], Polygon[i]]},          "Verschiebung", {GraphicsComplex[           wuerfel[a, b, c, verschiebung, k], Polygon[i]]},          "Parallelprojektion", {GraphicsComplex[           wuerfel[a, b, c, verschiebung, k], Polygon[i]], Green, Polygon[           Transpose [             ReplacePart[              Transpose[               wuerfel[a, b, c, verschiebung,                  k].{{1, 0, 0}, {0, 1, 0}, {0, 0, 0}}], {{_, 2}, {_,                  4}, {_, 6}, {_, 8}} :> Sequence[]]][[{1, 2, 4, 3}, All]]],           Blue, Polygon[           Transpose [             ReplacePart[              Transpose[               wuerfel[a, b, c, verschiebung,                  k].{{1, 0, 0}, {0, 0, 0}, {0, 0, 1}}], {{_, 3}, {_,                  4}, {_, 7}, {_, 8}} :> Sequence[]]][[{1, 2, 4, 3},              All]]], Red, Polygon[           Transpose [             ReplacePart[              Transpose[               wuerfel[a, b, c, verschiebung,                  k].{{0, 0, 0}, {0, 1, 0}, {0, 0, 1}}], {{_, 5}, {_,                  6}, {_, 7}, {_, 8}} :> Sequence[]]][[{1, 2, 4, 3},              All]]]},          "x-Drehung", {GraphicsComplex[wdrehungx[w], Polygon[i]]},         "y-Drehung", {GraphicsComplex[wdrehungy[w], Polygon[i]]},         "z-Drehung", {GraphicsComplex[wdrehungz[w], Polygon[i]]}]},       Axes -> True, Boxed -> True,        Switch[x, "Verschiebung", PlotRange -> {{0, 5}, {0, 5}, {0, 5}},         "Parallelprojektion", PlotRange -> {{0, 5}, {0, 5}, {0, 5}}, _,         PlotRange -> {{-2, 2}, {-2, 2}, {-2, 2}}]], {{a, 1, "x-Richtung"},        Switch[x, "Verschiebung", 0, "Streckung", 0, "Parallelprojektion",         0, _, -3], 3},      {{b, 1, "y-Richtung"},        Switch[x, "Verschiebung", 0, "Streckung", 0, "Parallelprojektion",         0, _, -3], 3},      {{c, 1, "z-Richtung"},        Switch[x, "Verschiebung", 0, "Streckung", 0, "Parallelprojektion",         0, _, -3], 3},      {{w, 0, "Winkel (in \[Degree])"}, 0, 360},      Button["Reset", a = 1; b = 1; c = 1; w = 0],      {x, {"Streckung", "Verschiebung", "Parallelprojektion", "x-Drehung",         "y-Drehung", "z-Drehung"}, ControlType -> PopupMenu},      Initialization :>        (verschiebung := {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {a, b,            c, 1}};        k := PolyhedronData["Cube", "VertexCoordinates"];        Short[i = PolyhedronData["Cube", "FaceIndices"]];        streckung[a_, b_, c_] := k.{{a, 0, 0}, {0, b, 0}, {0, 0, c}};        wuerfel[a_, b_, c_, M_, l_] :=          ReplacePart[          Transpose[            Insert[Transpose[l],              ConstantArray[1,               Map[Part[Dimensions[l], Sequence @@ #] &, {1}]],              Map[Part[Dimensions[l], Sequence @@ #] &, {2}] + 1]].M, {{_,              4}} :> Sequence[]];        wdrehungx[a_] :=          k.{{1, 0, 0}, {0, Cos[a Degree], -Sin[a Degree]}, {0,             Sin[ a Degree], Cos[a Degree]}};        wdrehungz[a_] :=          k.{{Cos[a Degree], -Sin[a Degree], 0}, {Sin[a Degree],             Cos[a Degree], 0}, {0, 0, 1}};        wdrehungy[a_] :=          k.{{Cos[a Degree], 0, -Sin[a Degree]}, {0, 1, 0}, {Sin[a Degree],             0, Cos[a Degree]}};        )      ]      ![Mathematica graphics](http://i.stack.imgur.com/8emx6.png) I have to show each transformmatrix. when you choose "streckung" for example, you should see the transformmatrix streckung with the manipulated variables a,b and c.


Java Heap Space Error on data insertion over SQL Server

I'm trying to insert 2-milliion lines into a SQL Database, and get this error: > JDBC::error: Java heap space The insert is a standart _Mathematica_ SQL statement:               conn = myConn[ip]     columns = {"Col1", "Col2", "Col3", "Col4"}     SQLInsert[conn, "MyTable", columns,data]     CloseSQLConnection[conn]      Where data is a `List`of 2-million elements (rows). The command works just fine for a smaller number of rows. I know I could break data into small chunks, but I would like to know how to solve it increasing the Java heap space.


Weird behaviour from ListSurfacePlot3D

Looking at Documentation for `ListSurfacePlot3D`, I follow the basic example presented there.               data = ExampleData[{"Geometry3D", "StanfordBunny"}, "VertexData"];     ListSurfacePlot3D[data, MaxPlotPoints -> 50, Mesh -> 30, Axes -> None,       MeshFunctions -> (#1 - #2 + #3 &), MeshShading -> {None, Yellow}]      What happens is that, first of all the vertex data from Stanford Bunny is read and stored in `data`, but then running `ListSurfacePlot3D` returns no output (I was expecting a graphic object as shown in documentation). In fact after running the line with `ListSurfacePlot3D` I see that `data` is cleared from workspace (it doesn't contain any data, in fact it is not even defined anymore - changing color from black to blue). It seems that `MeshShading` is causing this problem, so the following works:               data = ExampleData[{"Geometry3D", "StanfordBunny"}, "VertexData"];     ListSurfacePlot3D[data, MaxPlotPoints -> 50, Mesh -> 30, Axes -> None,       MeshFunctions -> (#1 - #2 + #3 &)]      ![enter image description here](http://i.stack.imgur.com/V2ZEm.jpg) I face the same problem when trying other examples from documentation; ListSurfacePlot3D/Options/MeshShading So, is this a bug or am I missing something? I am using OS X 10.8.4 64 bit, and _Mathematica_ version 9.0 for Mac OS X x86 (64-bit) (January 24, 2013).


finding roots of an equation involving infinite series

Tc[κ_] := t /. Chop[       FindRoot[         1 == (4 κ^4 NSum[ 2/3 Hypergeometric1F1[3/2, 5/2, -((2 κ^2 l)/t)], {l, 1, Infinity}]                 + 2 κ^2 t (PolyLog[1, Exp[(-2 κ^2)/t]])                 + 2 t^2 (PolyLog[2, Exp[(-2 κ^2)/t]]                 + (2 κ^2)/t PolyLog[1, Exp[(-2 κ^2)/t]])),       {t, tstart}, AccuracyGoal -> 8, PrecisionGoal -> 8]      ]          tstart = 0.5; ni = 100; κmin = 0; κmax = 1;      dκ := (κmax - κmin)/(ni - 1);     dat = Chop[ Table[{κ = κmax - (i - 1) dκ, Tc[κ]}, {i, ni}] ];      ListLinePlot[dat]      _Mathematica_ cannot plot for `ni=100` points. It just keeps on running for hours, but it does produce a plot for a very small number of points, e.g. `ni=5`. How could I tackle this problem?


Guidelines on giving readable names to variables

I know that one cannot use `underscore` to a variable name, like `degree_of_The_First_Polynomial`. But for a long variable name, it is difficult to read something like `degreeOfTheFirstPolynomial`. What do you do when you need a **clear, self-explained, easy-to-read** variable name?


How can I use Dynamic to run a script when a new file is added to a directory?

I have an external program saving files to some directory on my hard disc. I'd like to run a script that imports and runs a script on each file as it is added to the directory. Is there a simple way to do this using `Dynamic`? Is it necessary to use `Refresh`? For example, I'd like to be able to save a series of text files to a directory (with arbitrary names) and then print the contents in near real-time.


Time ColorFunction

I have the following data               data = {{0, 0}, {-0.0385, 0.0667}, {-0.0566, 0.1283}, {0.0966,          0.0441}, {-0.1166,          0.0038}, {-0.2046, -0.0673}, {-0.2536, -0.21}, {-0.5485, \     -0.2643}, {-0.3702, -0.1148}, {-0.4201, -0.2319}, {-0.5558, -0.2748}, \     {-0.693, -0.3272}, {-0.6276, -0.3844}, {-0.6305, -0.3448}, {-0.671, \     -0.4833}, {-0.6809, -0.3441}, {-0.7082, -0.2548}, {-0.5978, -0.3126}, \     {-0.4337, -0.3588}, {-0.2542, -0.4139}, {-0.3318, -0.3318}, {-0.4991, \     -0.2123}, {-0.4195, -0.1966}, {-0.4797, 0.0285}, {-0.2198,          0.0965}, {-0.1914, 0.1604}, {-0.0854, 0.1668}, {0.0715,          0.3025}, {0.0847, 0.3116}, {0.175, 0.3152}, {0.0123,          0.4577}, {0.0941, 0.4445}, {0.083, 0.3729}, {0.1251,          0.1414}, {0.0239, 0.3119}, {-0.0665, 0.3748}, {-0.0171,          0.4261}, {0.0781, 0.4031}, {-0.0945, 0.315}, {-0.2497,          0.3892}, {-0.285, 0.3823}, {-0.2873, 0.4343}, {-0.196,          0.4628}, {-0.2812, 0.5166}, {-0.186, 0.2917}, {-0.3101,          0.3047}, {-0.4103, 0.2439}, {-0.4335, 0.2251}, {-0.5113,          0.4149}, {-0.6487, 0.4662}, {-0.5045, 0.1807}}; which represents movement of some particle in time 0,...,50. Using `ColorFunction` is possible to get rainbow color according to axis $y$ as               ListLinePlot[data,ColorFunction->Function[{x,y},ColorData["Rainbow"][y]],PlotStyle->Thick] or axis $x$ as               ListLinePlot[data,ColorFunction->Function[{x,y},ColorData["Rainbow"][x]],PlotStyle->Thick] Is it possible to use `ColorFunction` according to time 0,...,50 and to get rainbow according to its movement in this time?


Equivalent of __FILE__?

Many languages define a special identifier whose value is the path to the source file currently being processed. (For example, in C, this is done through the `__FILE__` preprocessor macro.) Does Mathematica have anything like this (at least for `*.m` files)? (I could not find a tag that adequately represents the topic of this question (namely, something like "source file processing"); suggestions welcome.)


Inverse of a complicated function

Mathematica is struggling to find the inverse of this function f(r): `f[r_]:=ArcCos[(-1 + 4.20278 r (0.008712/r^2 + 0.475876/r - 1/(1 + r)))/Sqrt[ 1 - 10.598 r^2 (0.008712/r^2 + 0.475876/r - 1/(1 + r))]]` If I attempt to use Solve or NSolve `(N)Solve[s==f[r],r]` mathematica just hangs up. The same is true for InverseFunction[]. I was wondering if there were any strategies to find the inverse of this function, even perhaps a numerical approximation. I have many functions like this and need to find their inverses. Many thanks.


How to resolve a Unix symlink?

Does Mathematica have any function to resolve a Unix symlink (recursively, if necessary) to its real path?


Whether NIntegrate evaluation is multithreaded or not?

About MultiThread evaluation I am talking about here, see this post I am NIntegrate the function `grarm[e, 3, dimension, 1, 1, 0.005]`. There is matrix operation in function `grarm`, the `dimension` set the dim of the matrix. I give the code of `gram` in the end.( **take notice that you will have to manually change the dimension to get different`gram` with different dimension variable before integration**) OK, First I set `dimension` equals 7, and integrate the following               In:=NIntegrate[Im[grarm[e, 3, 7, 1, 1, 0.005]^2], {e, -0.3, 0},        MaxRecursion -> 200] // AbsoluteTiming          Out:={7.454151, 0.0581345}      and If I use linux command `top` to monitor the cpu situation, I see it is single threaded. See ![enter image description here](http://i.stack.imgur.com/Rjgea.png) now, I set `dimension` to 9, and integrate the following               In[55]:= NIntegrate[Im[grarm[e, 3, 9, 1, 1, 0.005]^2], {e, -0.3, 0},        MaxRecursion -> 200] // AbsoluteTiming          Out[55]= {83.592780, 0.0271489}      and If I use linux command `top` to monitor the cpu situation, I see it is multi-threaded. See ![enter image description here](http://i.stack.imgur.com/E33kD.png) And Now I force the same integration to use one thread only, integrate the following               In[56]:=      ParallelMap[       NIntegrate[         Im[grarm[e, #[[1]], 9, #[[2]], 1, 0.005]^2], {e, -0.3, 0},          MaxRecursion -> 200] &,        Tuples[{Range[3, 3], Range[1, 1]}]] // AbsoluteTiming          Out[56]= {16.575363, {0.0271489}}      Notice it is much faster, that is odd. In summary, There are two peculiar things waited to be explained   1. why dimension=7 is single thread while dimension=9 is multi-thread? Can `NIntegrate` actually naturally multi-threaded or not? Or the multi-thread is actually due to the matrix operation in the integrand(well, I personally think this is not likely)?   2. why multi-thread evaluation is much slower than single thread evaluation in the case of dimension 9? * * * In the end, the code for `grarm`.(don't forget to change the dimension, before integration)               dimension = 7;          Clear[armchairibbonmat]     armchairibbonmat[kx_, n_] :=      (       h = Table[0, {i, 1, 2 (n + 2)}, {j, 1, 2 (n + 2)}];       a[m_] := 2 m - 1;       b[m_] := 2 m;       t1 = 1;       aa = 1;       Do[        h[[b[i], a[i]]] = t1 E^(I kx aa);        h[[a[i], b[i]]] = t1 E^(-I kx aa);        h[[b[i + 1], a[i]]] = t1 E^(-I kx aa/2);        h[[b[i - 1], a[i]]] = t1 E^(-I kx aa/2);        h[[a[i - 1], b[i]]] = t1 E^(I kx aa/2);        h[[a[i + 1], b[i]]] = t1 E^(I kx aa/2);        , {i, 2, n + 1}];       h = ArrayPad[h, -2]       )          mat = Compile[{kx, n}, Evaluate@armchairibbonmat[kx, dimension]];     Clear[armchairibbonmat];     armchairibbonmat = mat;          Clear[gkarm]     gkarm[kx_?NumericQ, e_, xx_, width_, ii_, label_, \[Eta]_] :=       Inverse[(e - I \[Eta]) IdentityMatrix[2*width] -          armchairibbonmat[kx, width]][[2*(ii - 1) + label,         2*(ii - 1) + label]]          Clear[fkx]     fkx[kx_?NumericQ, xx_] := E^(I kx xx)          Clear[grarm]     grarm[e_?NumericQ, xx_, width_, ii_, label_, \[Eta]_] :=       NIntegrate[       gkarm[kx, e, xx, width, ii, label, \[Eta]]*        fkx[kx, xx], {kx, -\[Pi]/3, \[Pi]/3}, MaxRecursion -> 200]


List-manipulation Interpolation

For example, I have the following list:               AA={{0, 20000.}, {26.6, 19950.}, {53.2, 19950.}, {79.8,        19950.}, {97.1198, 18644.1}, {102.681, 16452.3}}      Another calculation results in an arbitrary value intended for the first part of the list, let's say 21.3. By interpolating linearly, this results in a value of 19960 for the second part of the list. How can I import this in Mathematica?


Problems with Simultaneous Equation Solving

Let me first explain what I am doing and then I will explain the problem that I can't figure out. I am basically trying to solve 2 equations for 2 unknowns (`a1` and `a2`) with some given definitions such as `GL1` `GL2` `GC1` and `GC2`. With the given code below, I solved the unknowns in terms of some parameters and (`C1` and `C2`). However, I want to substitute the equations of `C1` and `C2` in the solutions. I tried to put the equations first like given `GL1` `GL2` `GC1`... But I didn't get any answers then I tried to solve it without putting `C1` and `C2` and I got an answer. I now try to substitute those by using `Simplify`, but I don't get any answers again. I need some help to solve these equations. Please check my code below.               GL1 = fd a1 t Y1;     GL2 = fd a2 t Y2;     GC1 = (Y1 + Y2) (1 - fd) t p;     GC2 = (Y1 + Y2) (1 - fd) t q;          FullSimplify[       Solve[((GC1 - GL1) q / (GC2 - GL2) p) (a2/a1) - (C2/Y1)/(C2/Y2) == 0 &&          a ((GC1/(1 -    fd) - GL1/fd)/C1 + (GC2/(1 - fd) - GL2/fd)/C2) +          2 b (1 - 2 fd)/fd (1 - fd) == 0,        {a1, a2}] ]           (*     Solutions: (2 roots for a1 and a2)     {{a1 -> 1/(2 a C2 fd^2 t Y1 (p q Y1^2 - ...,       a2 -> 1/(2 a C1 fd^2 t Y2 (-p q Y1^2 + ...      },       {a1 -> 1/(2 a C2 fd^2 t Y1 (p q Y1^2 - ...,        a2 -> 1/(2 a C1 fd^2 t Y2 (-p q Y1^2 + ..}}     *)      Now as we see solutions are in terms of `C1` and `C2`, I want to substitute these two equations:                  C1 =  (1 - t (fd a1 + (1 - fd))) Y1;        C2 =  (1 - t (fd a2 + (1 - fd))) Y2;      When I substitute these equations and try to Simplify I don't get any answers, I think the kernel goes into a infinite loop. Any suggestions.


Use only exponents (no radicals) in output expressions

Radical symbols ($\sqrt{\,\,\,\,}$) are the devil. Is there any way to get mathematica to never use them, and instead express everything as an exponential? i.e. I want               In[1]:= Sqrt[x]      to give $x^{1/2}$ instead of $\sqrt{x}$.


How to parallelize this code

Here I obtained one code which should tests some zeros of the poly for various g, but sometimes I have to many cycles because of step and I need to parallelize the running on all cores. Classical ParallelDo instead the Do doesn't work. What to do further                poly=g*x^3+21*x^2-1.23*x+7.3247*g*I*x^2;                LM = {};      Do[      Lroots = x /. NSolve[(poly /. {g -> G}) == 0, x];           res = 0;      Do[      root = Lroots[[i]];      If[Im[root] >= 0,      L1 = Drop[Lroots, {i}];      res = res + 1/(Times @@ (root - L1));      ];       , {i, 1, Length[Lroots]}        ];       M = 1/((4*G^2)*res);       AppendTo[LM, M];           , {G, 0.001, 15, 0.01}      ];


Reassign values to symbols

I've got a situation where I have, say 4 symbols, `a`, `b`, `c` and `d`. This is a simplification of the issue I've been working with. Let's say I assign numeric values to these symbols:`a=1; b=2; c=3; d=4`. I now create a list: `myList:={a,b,c,d}`. I'd like to be able to say: `( # = 5 ) & /@ myList` to assign the value 5 to `a`, `b`, `c` and `d`. The code works as long as `a`-`d` are unassigned. Is there a way to do this, or am I trying to abuse the language?


What's wrong with this stylesheet?

I edited this style sheet:               Cell[StyleData["Text"], FontSize -> 20, FontWeight -> "Bold",        FontColor -> RGBColor[255, 255, 255], FontFamily -> "Courier New"]      but nothing happens. Is there anything wrong with this piece of code?


Customizing AxesStyle->Arrowheads

How do I call `AxesStyle->Arrowheads[ ]` in order to control whether or not an arrow appears on each of the four ends of the axes in a `Plot`, and if it does appear how to control the size of each one? Here's an example:               Plot[1/x^5, {x, -20, 20}, AxesStyle -> Arrowheads[{-.02, 0}],      ImagePadding -> None]      It seems `Axes->Arrowheads[.05]` makes all 4 of them appear and appear at the same size, while `Axes->Arrowheads[{-.05,.05}]` makes them appear in "pairs". But sometimes I just want the "north" and "west" axes to have arrows and nothing else.


How to cancel a common term from numerator and denominator?

What mathematica commands are needed to simplify $\frac{x+n x^m}{x(1+x)}$ to $\frac{1+n x^{m-1}}{(1+x)}$ ?               ClearAll[n , x, m];     num = n x^m + x;     den = x (x + 1);     s = num/den      ![Mathematica graphics](http://i.stack.imgur.com/pld6I.png) to verify               Reduce[s == (1 + n x^(m - 1))/(1 + x)]      ![Mathematica graphics](http://i.stack.imgur.com/bCIZv.png)


Can I get a trace of the complexity of a convergent sum?

_Motivation--- I have a glimmer of an idea that a convergent sum could be considered a self-referential number similar to a fractal. I would like to play with it for a while._ I have the following convergent sum:               NSum[((1/Pochhammer[m^2 + 1, m]) + (1/Pochhammer[m^2 + m + 1, 2 m])),       {m, 1, Infinity}, WorkingPrecision -> 50]        Is there a way to show the internals of about 4 or 5 steps?


Identifying the sign of an expression in an interval

My expression is the following: $$ \frac{(1-\alpha ) \alpha h^2 (h+2) \mu r}{(h+1) ((1-\alpha ) h+1) (\alpha h+1)}-\left(\frac{\alpha h \mu }{h+1}\right)^{\alpha } \left(\frac{(1-\alpha ) h \mu }{h+1}\right)^{1-\alpha }+\left(\frac{(1-\alpha ) h \mu }{(h+1) (\alpha h+1)}\right)^{1-\alpha } \left(\frac{\alpha h \mu }{\alpha h+1}\right)^{\alpha } $$ or given as _Mathematica_ input:               (((μ*h*α)/(1 + h*α))^α ((μ*h*(1 - α))/((1 + h*α)*(1 + h)))^(1 -α)) +      ((r*μ*h^2*α*(2 + h)*(1-α))/((1 + h*(1 - α))*(1 + h)*(1 +h*α))) -      (((μ*h*α)/(1 + h))^α ((μ*h*(1 - α))/(1 + h))^(1 -α))      and I would like to know the sign of this when : $1/2\leq α\leq 1$ and $h$,$r$ and $\mu$ are positive


Basic Dynamic Interface Programming that returns variables to nb functions

I have a dynamic module that contains some basic PopupMenu's and Buttons but also need to use the variables returned from these buttons and PopupMenu's in my nb functions outside of this DynamicModule. Here is the code:               DynamicModule[{var = 1, var2 = 3},      Dynamic[Column[Join[       {PopupMenu[pass2Fun1 = Dynamic[var], {1 -> "Return 1", 2 -> "Return 2",         3 -> "Return 3"}, ContinuousAction -> True]},       Switch[var, 1,        {Button["One", Module[{data = SystemDialogInput["FileOpen"]}, {}],         Method -> "Queued"]}, 2,         {Button["Two", Module[{data2 = SystemDialogInput["FileOpen"]}, {}],           Method -> "Queued"],           Button["Three",Module[{data3 = SystemDialogInput["FileOpen"]}, {}],           Method -> "Queued"]}, 3,         {Button["Four", Module[{data4 = SystemDialogInput["FileOpen"]}, {}],          Method -> "Queued"],       PopupMenu[pass2Fun2 = Dynamic[var2], {3 -> "choice 1", 4 -> "choice 2",          5 -> "choice 3"}, ContinuousAction -> True]}      ]]], TrackedSymbols :> {var, var2}]]      pass2Fun1 and pass2Fun2 are variables that are needed outside the Dynamic Module, and of course so are the SystemDialogInput variables. Take for example the If statement code where we can test to see if the variable pass2Fun1 ==1 To run this test place the above Dynamic Module code in a cell and check to see that the variable pass2Fun1 is filled as Global` Then run the If statement code in another cell to see if you get a good printed result.                If[pass2Fun1 == 1,      Print["This works", pass2Fun1],      Print["Broken", pass2Fun1]]      The If statement can not see the variable pass2Fun1==1 but If I print that variable it prints. If I check the context and the context path both are Global`. Now for the fun Part: In a separate cell evaluate:               pass2Fun1=1;       Then run the If statement again. Now the code runs fine. I thought we had a solution but further checking revealed this strange behavior. After trying Rojo's code below you will see that this If statement will still not complete. So in both the example code above and Rojo's solution below the result in the If statement test is the same. Rojo's code in the above function:               DynamicModule[{pass2Fun1 = 1, pass2Fun2 = 3},      Dynamic[Column[       Join[{PopupMenu[          Dynamic[pass2Fun1], {1 -> "Return 1", 2 -> "Return 2",            3 -> "Return 3"}, ContinuousAction -> True]},         Switch[pass2Fun1,          1, {Button["One",            Module[{data = SystemDialogInput["FileOpen"]}, {}],            Method -> "Queued"]},          2, {Button["Two",            Module[{data2 = SystemDialogInput["FileOpen"]}, {}],            Method -> "Queued"],           Button["Three",            Module[{data3 = SystemDialogInput["FileOpen"]}, {}],            Method -> "Queued"]},          3, {Button["Four",            Module[{data4 = SystemDialogInput["FileOpen"]}, {}],            Method -> "Queued"],           PopupMenu[           Dynamic[pass2Fun2], {3 -> "choice 1", 4 -> "choice 2",             5 -> "choice 3"}, ContinuousAction -> True]}]]],        TrackedSymbols :> {pass2Fun1, pass2Fun2}]]      My question: What is the best method to get the variable data from another nb a Button or PopupMenu to the functions in a different nb? These nb functions control the generation of results based on the input data and the variables pass2Fun1 & 2 and the SystemDialogInputs. Should all the functions be called inside the DynamicModule or made Global? Even if it's made Global as in the case above, how do I make sure the variable is filled in such a way as to be useful to other functions? Thanks in advance for the help!


Differential equations: Solving a singular/nonlinear ODE using NDSolve

I am trying to numerically solve a rather horrible looking singular/nonlinear ode: `A*(y''[x]/y[x])'' +y[x]^2==1` on the interval `[0,1]`, where `A` is a small parameter `(~10^(-4))`. The boundary conditions are :               y[0]=y[1]==1     y'[0]==0     y''[1]==0.       I expand the term in parentheses and use `NDSolve`:               s = NDSolve[{10^(-4)*(y''''[x]/y[x] - 2*y'''[x]*y'[x]/(y[x]*y[x]) - (y''[x]/y[x])*                  (y''[x]/y[x]) + 2*(y''[x]*y'[x]*y'[x])/(y[x]*y[x]*y[x])) + y[x]*y[x] == 1,                   y[0] == 0, y[1] == 0, y'[0] == 0, y''[1] == 0}, y, {x, 0, 1}]      And I get the following errors: > >     Power::infy: Infinite expression 1/0.^2 encountered. >> >       ∞::indet: Indeterminate expression 0. ComplexInfinity encountered. >> >       Power::infy: Infinite expression 1/0.^2 encountered. >> >       ∞::indet: Indeterminate expression 0. ComplexInfinity encountered. >> >       Power::infy: Infinite expression 1/0.^3 encountered. >> >       General::stop: Further output of Power::infy will be suppressed during >              this calculation. >> >       ∞::indet: Indeterminate expression 0. ComplexInfinity encountered. >> >       General::stop: Further output of ∞::indet will be suppressed during >              this calculation. >> >       NDSolve::ndnum: Encountered non-numerical value for a derivative at x > == 0.`. >   I realize the solution to this function is very ill behaved near $x=0$. I was wondering whether there is a way to over come this problem? I know that, in the interior, `y[x] = -1`. Thanks a lot!


How to convert a system of parametric equations to a normal equation?

For example, I have a system of parametric equations (`R` is a constant number) :               { x == p +  R Cos[k],       y == Cos[p] +  R Sin[k],       k == ArcTan[ 1/Sin[p] ]   }      Now I am going to find the normal equation of $\; y = f(x)\;$ without other variables. (Theoretically it is possible because there are totally 4 variables and 3 equations.) How can I do this in Mathematica?


How to perform DialogInput operation within Button

Can someone clarify how to perform a `DialogInput` operation within a `Button`? I wrote some code for that but it's not working.               Button["Enter value",       DialogInput[{name = ""},        Column[{InputField[Dynamic[name], String],          Button["Hi", Dynamic[name]]}]]]      My problem is this — when I run the above code, the given text is displayed but when I click on the button, the actual operation is not being carried out.


K-means clustering

In MATLAB, there is a command `kmeans()` that divides an array into $k$ clusters and calculates the centroid of each cluster. Is there any command in _Mathematica_ to perform the same action? For example:               x = {{1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15}, {16,17,18,19,20}, {21,22,23,24,25}}      The MATLAB `kmeans` command does this:               [b, c] = kmeans(x, 2)      It divides `x` into two clusters and calculates the centroids of these two clusters, and indicates for each element in the array which cluster it is a member of               b = {1,1,2,2,2}      and               c={{3.5000,4.5000,5.5000,6.5000,7.5000},{16.0000,17.0000,18.0000,19.0000,20.0000}}


What is the fastest way to maintain a large set of expressions?

In my algorithm I need to maintain a set (an unordered list of distinct elements) of expressions supporting two operations:   * Test an expression for membership in the set   * Adding a new expression to the set Expressions are to be compared using `SameQ`. The set can have hundreds of thousands of elements and I want it to work as fast as possible. In most programming languages I would use a hash-table or a balanced tree to implement such a set. Is there any better data structure in _Mathematica_ for this purpose than a plain `List`? Is it worth trying to manually implement a better structure?


Morphological Components with periodic boundary conditions

I would like to find the connected(with periodic boundary conditions) components in a large binary matrix. What I've tried, and it does a fair job is:               MorphologicalComponents[RandomInteger[{0, 1}, {100, 100}],CornerNeighbors -> False]      For instance:               ArrayPlot[MorphologicalComponents[RandomInteger[{0, 1}, {20, 20}], CornerNeighbors -> False], ColorFunction -> "Rainbow", ImageSize -> Large]      ![enter image description here](http://i.stack.imgur.com/edcNT.png) The only option missing here is the periodic boundary condition. `MorphologicalComponents` doesn't have a `DistanceFunction` to impose periodic boundary conditions there. The other idea I had was to give up on `MorphologicalComponents` and use `ClusteringComponents` with a complicated `DistanceFunction`, but that is just a pain in the neck. * * * ## Example: Let me give an example of what I mean by periodic boundary condition. For instance given the input:               {{1, 0, 0, 1, 1}, {0, 0, 1, 0, 0}, {1, 1, 1, 0, 1}, {0, 1, 0, 0, 0}, {1, 0, 0, 1, 0}}      I would expect to get something like:               {{1, 0, 0, 1, 1}, {0, 0, 2, 0, 0}, {2, 2, 2, 0, 2}, {0, 2, 0, 0, 0}, {1, 0, 0, 1, 0}}      As an output. The arrayplots for these two matrices are: ![enter image description here](http://i.stack.imgur.com/0Xmpq.png) ![enter image description here](http://i.stack.imgur.com/zc5Wj.png)


Filtering the elements of an array to split them into two categories

So, I am new to _Mathematica_ , and I am trying to write something that involves taking values from one array and separating them into two different arrays. My code for doing this is:               For[i = 1, i < (TruncationOrder + 1), i++,         (If[(Abs[Im[evalueb1[[1, i]]]] < 10^-14),             (If[Re[evalueb1[[1, i]]] > 0,                 ρplus[[i, i]] = evalueb1[[1, i]],                 ρminus[[i, i]] = evalueb1[[1, i]]]),              If[Im[evalueb1[[1, i]]] > 0,                 ρplus[[i, i]] = evalueb1[[1, i]],                 ρminus[[i, i]] = evalueb1[[1, i]]]])];      However, this does not give the desired results. I randomly have '1' several times in my new array. The actual values are given below: Original:                {-0.651301 - 2.44576*10^-16 I, 0.651301 + 3.73803*10^-17 I, 0.671298 - 6.68417*10^-16 I,       -0.671305 + 1.17248*10^-17 I, -0.000107956 + 0.735512 I, -0.000107956 -        0.735512 I,       9.93642*10^-6 + 0.764605 I, 9.93642*10^-6 - 0.764605 I, -0.965926 + 5.29506*10^-16 I,       0.965926 + 3.76737*10^-16 I, 0.97048 + 4.33453*10^-16 I, -0.97048 + 5.39299*10^-16 I,       0.0344992 - 1.4214 I, 0.0344992 + 1.4214 I, 0.0028631 + 1.4505 I, 0.0028631 - 1.4505 I,       -0.0626803 + 1.78014 I, -0.0626803 - 1.78014 I, -0.12443 + 1.98252 I, -0.12443 - 1.98252 I,       0.167724 - 2.24691 I, 0.167724 + 2.24691 I}      New incorrect ones: `ρplus`:                   {1, 0.651301 + 3.73803*10^-17 I, 0.671298 - 6.68417*10^-16 I, 1, -0.000107956 + 0.735512 I,          1, 9.93642*10^-6 + 0.764605 I, 1, 1, 0.965926 + 3.76737*10^-16 I,          0.97048 + 4.33453*10^-16 I}      `ρminus`:                   {-0.651301 - 2.44576*10^-16 I, 1, 1, -0.671305 + 1.17248*10^-17 I,          1, -0.000107956 - 0.735512 I, 1, 9.93642*10^-6 - 0.764605 I,          -0.965926 + 5.29506*10^-16 I, 1, 1}


Numerical integration involving Inverse Normal CDF

I'd like to evaluate the following numerical integration using _Mathematica_ $$ \ \int_0^T\int_0^\infty xe^{-0.04 s}g(x,s) dxds\ $$ where g(x,s) is a Gaussian copula function with say, marginal exponential distributions with parameter A and parameter B (i.e. X~exp(A) and S~exp(B)). In the following MMA attempt, the g(x,s) is defined by GE[Theta,A,B]. This is what I've tried so far:               GE[Theta_, A_, B_] := CopulaDistribution[{"Binormal", Theta}, {ExponentialDistribution[A],ExponentialDistribution[B]}];          Delta = 0.04; A = 0.10; B = 10; Theta = 0.9; T=5;     GExpExp[x_,s_] := PDF[GE[Theta, A, B], {x, s}]          NIntegrate[Exp[-Delta*s]*x GExpExp, {x, 0, Infinity}, {s, 0, T}]       and the following is the error I obtain: * _NIntegrate::inumr: The integrand 1.1547 E^(-10 s-0.1 x-s [Delta]+2 InverseErfc[2 \ Plus[ <<2>>]]^2-1.33333 (0.707107 InverseErfc[<<1>>]-Power[<<2>>] \ InverseErfc[<<1>>])^2)_ x has evaluated to non-numerical values for all sampling points in the region with boundaries {{0.05`,36},{0.5`,1}}. >>* I then try to integrate the expression with respect to only one variable, in this case I chose variable x, so that I'd end up with a univariate expression (and hence I might be able to work on a simpler problem from then on)                 Integrate[Exp[-Delta*s]*GExpExp1[x, s], {x, 0, Infinity}]            (* 11.547 E^(-10.04 s + 1.33333 InverseErfc[4 - 4 E^(-10 s)]^2) *)      It seems that eventually I still have to deal with the Inverse[NormalDistribution] function, which I think is the source of this issue. I then continued with the following:                 T = 5;        Assuming[s > 0, LaplaceTransform[NIntegrate[11.547005383792516` E^(-10.04` s + 1.3333333333333337` InverseErfc[4 - 4 E^(-10 s)]^2), {s, 0, T}], s, T]]            (* NIntegrate::inumr: The integrand 11.547 E^(-10.04 s+1.33333 InverseErfc[4+Times[<<2>>]]^2) has evaluated to non-numerical values for all sampling points in the region with boundaries {{1.,2}}. >>  *)      It could be because the function does not converge, but even after reducing the limit interval from [0,T] to [2,3] (and of course changing T to 5 instead of 2) I still can't obtain a number. Does anyone know the correct syntax that I should use so that I can obtain a numerical answer eventually? Your assistance is much appreciated.


DateListPlot FillingStyle problem

In the following query, If the option `PlotStyle->{Red,Blue}` is inserted it works but `FillingStyle->{Red,Blue}` does not: The filling turns all Blue. Is this a known issue? I tried basic `ColorFunction` but could only get rainbows. Any other options? It's desirable to alternate the segments using only 2 colors (though not Red and Blue, that's just for example).               Labeled[DateListPlot[#, Joined -> True, ImageSize -> 1000,          AspectRatio -> 1/5,          Epilog -> {Inset[            Text[Style[">statigrafix<", Blue, Opacity[0.1],               FontFamily -> "Consolas", FontSize -> 14]],             Scaled[{0.15, 0.75}]]}, Frame -> {True, True, False, False},          Filling -> Bottom, GridLines -> None] &@       Split[FinancialData["^DJI", "Close", "Jan 1 1980"],         Not@(#[[2]] > 10000 && #2[[2]] <= 10000) &],      Style["Dow Jones Industial 1.1.80-6.22.12 segmented by 10k \     crossings", Gray, Opacity[0.3], FontFamily -> "Helvetica"], Bottom]


Accurately evaluating the hypergeometric function

As part of another problem, I am working to evaluate hypergeometric functions such as               Hypergeometric2F1[1, 1, n, -1]      for large $n$. I am hoping to obtain at least double-precision accuracy all the way through `n = 1600`. However, starting as low as `n = 200`, I obtain precision errors:               N[Hypergeometric2F1[1, 1, 200, -1], 17]     N::meprec: Internal precision limit      Are there ways to tell _Mathematica_ it can use as much time as it wants to compute this quantity? Or are there any other workarounds?


Overlapping ArrayPlot

I have two ArrayPlots, and I want to overlap them as it is done here. For clarity, suppose               Array1 = RandomReal[{0, 1}, {3, 2}];      Array2 = RandomReal[{0, 1}, {3, 2}];      and the first `ArrayPlot` uses `ColorFunction -> (Blend[{White,Yellow},#]&)`, and the second uses `ColorFunction -> (Blend[{White,Blue},#]&)`. I'd like to combine them in such a way I end up with an ArrayPlot with White, Yellow, Blue and Green shades. Thanks for your attention.


Can Mathematica propose an exact value based on an approximate one?

Sometimes, I use Mathematica to do some hypothesis on homeworks to make the question easier. For instance, when I have to compute big sums when $n\to\infty$ and Mathematica can't give the exact answer, I set $n$ to a very big number and I get an approached value. Is it possible with this value to get possible closed forms just like in Wolfram Alpha (which by the way runs Mathematica's kernel) ? **Example :** I have to find out the sum of all $\frac{1}{2p!}$ when $p$ goes from $0$ to $+\infty$ and let's say Mathematica doesn't directly say it's $\frac{e}{2}$, but it gives 1.66 for a big value of $n$. Is there a function which can figure out which constant is near this number ?


distance between each vertex of a graph and its output

I have a question regarding this Q&A. Let's call a vertex that is not the tail of any directed edge an _output_ of the graph. The graph below has only one output (at the far right). If I want the distance from each vertex to the output of the graph, what should I do? This one is on my graph:               matOP = {{0, 1, 0, 0, 1, 0, 1, 0}, {0, 1, 0, 0, 1, 0, 1, 0}, {0, 0, 1, 0, 1, 0, 1, 0},               {0, 0, 0, 1, 0, 0, 1, 0}, {0, 0, 0, 0, 1, 1, 0, 0}, {0, 0, 0, 0, 1, 0, 0, 0}};          pos = Position[matOP, 1];     edge = Subsets[Range@Length@pos, {2}];     dedge = DeleteDuplicates[        DirectedEdge @@@ (Extract[edge, #] & /@            With[{dist =               N@(EuclideanDistance[pos[[#]], pos[[#2]]] & @@@ edge)},             Flatten[Position[dist, #] & /@               DeleteDuplicates@N@Select[dist, # <= 1.5 &]]])];          Graph[dedge,        VertexCoordinates -> Rule @@@ Thread[{Range@Length@pos, pos}]]      ![enter image description here](http://i.stack.imgur.com/tOxbt.png)


How can you form a variable from a function and its arguments?

Is there a way to make the general replacement               foo[x,y,z]->fooxyz      so that I can treat the x_i as variables so that I will obtain foofgh from the following:               foo[f,g,h] /.{ foo[x,y,z]->fooxyz }      ?


DateListPlot input entry problem

I imported some data from Excel and got the following for my date and values:               {{{1986, 1, 2, 0, 0, 0.}, 25.56, ""}, {{1986, 1, 3, 0, 0, 0.}, 26., ""}      It seems that there is an extra space there. How can I remove that and make appropriate format for `DateListPlot`? Also important: what materials do I need to learn to overcome such difficulties?


Replace every Minus to Plus in Expression

Thought this is a rather simple thing, but I was not able to find a solution: I have a _polynomial_ expression like:                expr1=a^2-b+c*d      expr2=a-b      expr3=-a+b-c      and i want to replace every negative sign to Plus                expr1new=a^2+b+c*d      expr2new=a+b      expr3=a+b+c      The problem is that               FullForm[a-b]     (* Plus[a, Times[-1, b]] *)      thus I cannot use simple replacement. Do you know a simple way for that? **Update** This example does not work with simple replacements:               expr4 = (1 - I) a;     expr4 /. {-1 -> 1}     FullForm[expr4]          (* (1 - I) a     Times[Complex[1, -1], a] *)


Mathematica 10 fails to calculate integral that Mathematica 9 can handle

The following:               Mass/2  Integrate[(r^2 + Rotation^2 (2 - Cos[θ]^2))/(r^2 + Rotation^2       Cos[θ]^2)^2 Sin[θ], {r, r1, ∞}, {θ, 0, π},       Assumptions -> {r1 > 0 && Rotation >= 0}] // Simplify      returns > >     (1/(32 Rotation))Mass (-16 ArcTan[r1/Rotation] + 1/(2 r1^2)(16 π r1^2 + >     32 r1 Rotation + π Rotation^2 + 8 π r1^2 Log[r1] + >     4 ArcTan[Rotation/r1] (7 Rotation^2 - 8 r1^2 Log[r1]) - >     2 ArcTan[r1/(2 Rotation) - Rotation/(2 r1)] (Rotation^2 + 8 r1^2 > Log[r1]))) >   in _Mathematica 9.0.1_ , and > During evaluation of In[35]:= Simplify::time: Time spent on a transformation > exceeded 300.` seconds, and the transformation was aborted. Increasing the > value of TimeConstraint option may improve the result of simplification. >> > > Out[35]= 1/2 Mass Integrate[((r^2 - Rotation^2 (-2 + Cos[θ]^2)) Sin[θ])/(r^2 > + Rotation^2 Cos[θ]^2)^2, {r, r1, ∞}, {θ, 0, π}, Assumptions -> r1 > 0 && > Rotation >= 0] in _Mathematica 10.0.0_. In the latter case, it takes much longer to return, although it fails to produce the result. Is this a bug?


How to limit only two "0 and 1" strings for an xor implement?

I tried to implement some logic gates for a series of "0 & 1" strings, just like _and_ , _or_ , _nand_ , _nor_ and _not_ listed below. How could I limit _xor_ only accept a two strings list as its argument?               str2 = {"11000000", "10000001", "11111111"};          or[str : {__String}] :=        StringJoin[        MapThread[Or,           Characters[str] /. {"0" -> False, "1" -> True}] /. {False -> "0", True -> "1"}];          and[str : {__String}] :=        StringJoin[        MapThread[And,           Characters[str] /. {"0" -> False, "1" -> True}] /. {False -> "0", True -> "1"}];          nand[str : {__String}] :=        not[StringJoin[         MapThread[ And,            Characters[str] /. {"0" -> False, "1" -> True}] /. {False -> "0", True -> "1"}]];          nor[str : {__String}] :=        not[StringJoin[         MapThread[ Or,            Characters[str] /. {"0" -> False, "1" -> True}] /. {False -> "0", True -> "1"}]];          not[str : _String ] :=        StringJoin[         Characters[str] /. {"1" -> False, "0" -> True}  /. {False -> "0", True -> "1"}];          (* ????? *)     xor[str : {_String, _String}] :=        StringJoin[        MapThread[Xor,           Characters[str] /. {"0" -> False, "1" -> True}] /. {False -> "0", True -> "1"}];      ![enter image description here](http://i.stack.imgur.com/fSJx9.gif)


Collapsing summation

I am trying to write a command to collapse the sum of terms into an expression with summation. Something like               F_[1, j___] + F_[2, j___] + F_[3, j___] := Sum[F[i, j], {i, 1, 3}]      which is designed to to collapse the LHS, which is a function of 2 or more parameters (for example - F[i,j] or F[i,j,k] - this is the reason for the i___ in the definition) into a summation on the first variable. but I get the following error:               SetDelayed::write: "Tag Plus in F_[1,i___]+F_[2,i___]+F_[3,i___] is Protected"      It seems that I am overriding the _Plus_ definition. I don't know then how to define this properly. Thanks.