Is there any fast way to solve a quadratic matrix equation in Mathematica approximately?

Let the square nonsingular matrix $M$ is a given convergent matrix. What are the best scalar values for $\alpha$ and $\beta$ (in the real numbers domain), at which the following quadratic matrix equation _approximately_ holds: \begin{equation} M^2+\alpha M+\beta I\approx0. \end{equation} In fact, I would like to find the scalar values as closely as possible for the following matrix $M$ (as an example)               Clear["Global`*"]     SeedRandom[12345]     n = 1000; Id = SparseArray[{i_, i_} -> 1., {n, n}, 0.];     A = RandomReal[{-1, 1}, {n, n}];     X = 1/SingularValueList[A, 1][[1]]^2 ConjugateTranspose[A];     M = A.X;      Also I tried to use NMinimize or FindInstance, but I failed. Please note that a rapid approach is more better for me to find more accurate values for the scalar paramteres.


Using Piecewise in RevolutionPlot3D

The documentation for `RevolutionPlot3D` shows that you can specify a parametric curve like this:               RevolutionPlot3D[{u, u}, {u, 0, 1}]      ![Mathematica graphics](http://i.stack.imgur.com/Zppvk.png) I'd like to do this with a `Piecewise` function for `{fx,fz}`:               RevolutionPlot3D[Piecewise[{{{u, u}, u < 0.5}, {{u, 0.5}, u >= 0.5}}], {u, 0,        1}]      but I get messages and a blank plot: > Dot::rect: Nonrectangular tensor encountered. ![Mathematica graphics](http://i.stack.imgur.com/o57ob.png) whereas a `Piecewise` function for `{fx,fz}` works in `ParametricPlot`, for example:               ParametricPlot[Piecewise[{{{u, u}, u < 0.5}, {{u, 0.5}, u >= 0.5}}], {u, 0, 1}]      ![Mathematica graphics](http://i.stack.imgur.com/1pJqp.png) By writing `Piecewise` expressions for `fx` and `fz` separately, it works:               RevolutionPlot3D[{Piecewise[{{u, u < 0.5}, {u, u >= 0.5}}],          Piecewise[{{u, u < 0.5}, {0.5, u >= 0.5}}]}, {u, 0, 1}]      ![Mathematica graphics](http://i.stack.imgur.com/LtPbf.png) How is it possible to piece together a function for `{fx,fz}` in `RevolutionPlot3D`?


Two x-axis with different units connected by function using CustomTicks

I am trying to make a plot of some photoluminescence data, where wavelength is on the x-axis, and intensity is on the y-axis. Also, I would like to have the graph boxed, with the upper x-axis having units of energy in eV, connected to the wavelength through the function: energy=1240/wavelength. I have tried to use the `TickLabelFunction` in the LevelScheme package, and have only partly succeeded. I can't control the number of decimal points for the ticks on the energy scale. For some reason, `N[]` doesn't work. Also, the energy tickmarks seem to follow the wavelength ticks, i.e. one energy tick for each wavelength tick. I would like those ticks to be spaced nonlinearly and independently of the other axis, e.g. having them increase with steps of 0.2 eV. Here is a small code that I hope will illustrate my problem.               test = List[{500, 50}];     ListPlot[test, Frame -> True, ImageSize -> 600,      PlotRange -> {{400, 800}, {-10, 110}},      FrameLabel -> {"Wavelength (nm)", "Intensity (a.u.)", "Energy (eV)"},     FrameTicks -> {LinTicks[400, 800, 100, 5], LinTicks,      LinTicks[400, 800, 100, 5,      TickLabelFunction -> Function[x, N[1240/x, 2]]],      StripTickLabels[LinTicks]}]      Any input appreciated, either using the LevelScheme package or not. Thanks!


How to deal with WebServices error "any is not supported in sequence"?

I am trying to aquire data through Mathematica's WebServices and this example works just fine:               <<WebServices`     InstallService["http://www.webservicex.net/CurrencyConvertor.asmx?WSDL"]     ConversionRate["USD","RUB"]      However, when I try to install this service:               InstallService["http://cbr.ru/secinfo/secinfo.asmx?WSDL"]      Mathematica returns with error messages:               LoadSchema::unsupported: any is not supported in sequence.     LoadSchema::elementschema: The element schema cannot be found for {http://www.w3.org/2001/XMLSchema, schema}.      I'm not very well versed in XML however it seems that there's an "any" tag present in the code of the service, is that a provider's mistake?


Levels: how do they work?

I cannot understand how Mathematica manages levels, and so it's always a painful try-and-fail to use `Flatten`. Can someone please give me a very clear definition? If you feel like giving an example, please tell me how to turn this list `{{a, {a1}}, {b, {b1}}, {c, {c1}}, ...}` into `{{a, a1}, {b, b1}, {c, c1}, ...}` with `Flatten`, if possible.


Finding concave hull for separated small clusters

Data :                data3D = Import[file, "VertexData"];      Graphics3D[Point[data3D]]      ![enter image description here](http://i.stack.imgur.com/DKD0A.jpg) How to find concave polygon for separated small clusters.


Optimizing NIntegrate for higher PrecisionGoal

By default, `NIntegrate` works with `MachinePrecision` and its `PrecisionGoal` is set to `Automatic` which is effectively a value near 6:               In[1]:= Options[NIntegrate, {WorkingPrecision, PrecisionGoal}]          Out[1]= {WorkingPrecision -> MachinePrecision, PrecisionGoal -> Automatic}      I need sufficiently higher accuracy when computing the following integral:               dpdA[i_] := NIntegrate[       Cos[φ] Cos[i*φ] Exp[Sum[-Cos[j*φ], {j, 11}]], {φ, 0, Pi},        Method -> {Automatic, "SymbolicProcessing" -> None}]      The integral cannot be taken symbolically, so `"SymbolicProcessing"` is off. The problem is that when I increase `PrecisionGoal` to 15 and consequently `WorkingPrecision` to a value higher than `MachinePrecision` I get very low performance. Is it possible to compute this integral with at least 15 significant digits with high performance?


What's the main difference between FindClusters and ClusteringComponents?

In many cases, `FindClusters` and `ClusteringComponents` provide similar results. Options for hierarchical and agglomerative clustering are available for both of these functions. So, would you please help me to understand clearly the differences between them? Just to be clear,my main question concerns about choosing appropriate function for different research questions and anlysis. That is, it's not important if the two functions (or other similar functions) produce different outputs with the same meaning rather I want to know when to use which function and why. Also, please post any tutorial for cluster analysis in Mathematica if you aware of.


Is there any good way to find and/or plot numerical integrals of non-continuous functions like Tan[x]?

I believe that the answer to this may be obvious to some of you, but I just can't think of anything that works. NIntegrate, NDSolve, etc, all throw a temper tantrum when they have to divide by zero, and it's not really an issue that an InterpolatingFunction can deal with either. Is there any way to approach this? **EDIT** Example: If I just type               Plot[NIntegrate[Tan[u],{u,0,x}],{x,0,2Pi}]      I am going to get an error immediately, at least in the form of a graph that goes insane. I can kind of try to get around that by doing this:               ntan[x_] := FunctionInterpolation[Tan[x],{x,0,2Pi}]     Plot[NIntegrate[Tan[u], {u, 0, x}], {x, 0, 2 Pi}      This immediately throws some errors, and you get a plot that is certainly not right. The very large values ruin the calculation completely! This is definitely not right. I know with Tan[x] you can just easily integrate it and plot it and all is well, but I'm curious how to get a more general way of plotting integrals of functions with singularities that cannot be easily integrated.


How to make BSplineFunction pass each data point and naturally smooth?

( ** _Old package, works good_** )               Needs["Splines`"];          testData = {{10, 10}, {10, 20}, {10, 25}, {10, 27}, {10, 28}, {9,          26}, {8, 25}, {5, 20}, {3, 1}};          fFit = SplineFit[testData, Cubic];          ParametricPlot[fFit[n], {n, 0, Length[testData] - 1},                     Epilog -> Point[testData]]      ( ** _New spline package, how to make it work like the old one: passing each point exactly and naturally smooth_** )               fFit01 = BSplineFunction[testData];          ParametricPlot[fFit01[n], {n, 0, Length[testData] - 1},                     Epilog -> Point[testData]]      ( ***The fitting results are different: some points are not passed exactly, which is not what I need** )


finding poles of a function

Is there a command to find the poles of a function $f=f(z)$? example: let $$f(z) = \frac{1}{z^2-1}$$ then we know that the poles are at $z=\pm 1$ but is there a special command in mathematica to do this?


Locator following other locator in DynamicModule

I'm trying to create a dynamic environment where I specify, using two locators, the initial condition (position (x,y) and velocity angle (alpha)) of a 2D particle. To simplify, I'm assuming the initial position is restricted to a circle, and the velocity angle is always in respect to an angle _in relation to the normal_ vector, perpendicular to the tangent vector. This means that in the end, I would like to have 3 parameters: x,y initial position of the positional locator, and an initial angle, defined as the angle between the vector (positional locator - angle locator) and the normal vector. The main problem resides on the coupling between the positional locator, and the angle locator: when I move the positional locator, I would like to have the angle locator moved in such a way that the initial angle is preserved. To manipulate those, I'm using two Locators: one for position (initialPoint), one for initial angle (pt2)               DynamicModule[{initialPoint = {0, 0}, pt2 = {0, 0}},      Style[Graphics[{         Dashed,         Circle[{0, 0}, 1],         Locator[          Dynamic[pt2, (pt2 =               initialPoint + 0.5 Normalize[# - initialPoint]) &]],          Locator[Dynamic[initialPoint, (initialPoint = Normalize[#]) &]]},         PlotRange -> {{-3.3, 3.3}, {-3.3, 3.3}}, AspectRatio -> 1],        Selectable -> False]]      however, when I dynamically pick the initialPoint, the second locator does not follow it. What can I do it in order to keep pt2 always such that the initial angle is preserved?


Taking a percentage of data from a list or a table

I have a list of data and for the calculation I only need the a of portion of the data. I know that `Take[data, {1,100}]`, for example, is taking line 1 to 100 of the file. But what I need it for me is to take percentage of the data like, drop first 10% and drop last 10% of the data. So I'll only have 80% of the middle portion to work with. So that if I have multiple list with amount of data changing I would not have to keep counting the number of lines or length to calculate. Thanks.


Unwanted parentheses appearing in a notebook that is opened by a button

I am writing an interactive document and have an idea to make in-line buttons that on demand would create and bring up separate notebooks containing some explanations or a remindings. One example of the code of such a button is as follows:               Button["Show it",      CreateDocument[       Column[{         Spacer[30],         TextCell["some explanatory text:" , "Text", FontSize -> 20],         Spacer[10],         TextCell[           Row[{Spacer[50], Style["Φ=", 24, Italic],              Style[HoldForm[(ϕ*τ^2*ν^3*ω*θ[                 1 - ν*ω])/(τ^2*ν^2 +                  2*δ*ν*τ + ω^2)^2], Italic, 30]}],            TextAlignment -> Center] // TraditionalForm          }, Alignment -> Left],           WindowTitle -> "An expression", WindowSize -> {400, 300}],           ImageSize -> {70, 18}, Background -> Brown,           BaseStyle -> {"GenericButton", Bold}]       Upon its evaluation a button is created. This button one can copy-pasted into a necessary part of the text, say, into an in-line cell. It works, in principle. It works irreproachably, if there is only a text or a text and any graphics inside. With the formula it is more complex. If the button contains a formula such as the one in the code above, and if I press the button for the first (second and so on ) time I get the document open with the formula that looks as follows: If you see here no picture, try yourself, what I explained in words. And that is what I intended to. Now comes my "however". However, if I save/close the main document (the one containing the button code and the button itself, then open it once more and press the button, I get this: If you see here no picture, try yourself, what I explained in words. As you see there is a lot of unwanted patantheses appeared. The question is how can I get rid of these parasitic parantheses? Small addition: I have forgotten to write that there is an evident work around. The expression in question may be saved as an image and in that form passed into the button statement. Then the code is like this               Button["Show it",      CreateDocument[       Column[{         Spacer[30],         TextCell["some explanatory text:" , "Text", FontSize -> 20],         Spacer[10],         ExpressionCell[          Row[{Spacer[50],             Show["Paste here the image of a formula", ImageSize -> 250]}]]          }, Alignment -> Left],       WindowTitle -> "An expression", WindowSize -> {400, 300}],       ImageSize -> {70, 18}, Background -> Brown,       BaseStyle -> {"GenericButton", Bold}]      This is the way, of course, but I am not fond of it. The reason is that my document contains dozens of such buttons. If each of them will contain an image or two, the document size will rise too much. **To summarize** : after the very helpful answers made by bil s and bobknight I see two ways of coping with the problem. I first outline the problem below and then discuss the solutions. The problem consists in making a button to show a window with a formula as described. The difficulty is that the variables met in the formula may take part in calculations in the document and may have already been assigned to something. Even more, this assignment may be needed in some place of the document after the place where the button is used. I initially tried to cope with it by applying HoldForm. This is not the right way, however, since it is the HoldForm statement that is responsible for extra parentheses that show up when one closes the document, then opens it and then presses the button. I also tried to use the scoping constructs like Module, but with no success, as I explained in discussion with bil s (see comments). In the present form neither of the answers deal with this problem. However, on the basis of these answers I think I understand now how to deal with it. I see two ways. First, it is possible to clear the variables met in the formula. Then one should take care that the necessary variables should be defined before each calculations, or each calculation should use a scoping construct. Like this the bil s solutions works as follows:                Button["Show it",       Clear[Φ, τ, ϕ, ν, ω, θ, \     δ];       CreateDocument[       Column[{Spacer[30],          TextCell["some explanatory text:", "Text", FontSize -> 20],          Spacer[10],          TextCell[           Row[{Spacer[50], Style["Φ=", Italic, 30],              Style[(ϕ τ^2 ν^3 ω θ (1 - ν \     ω))/(τ^2 ν^2 +                 2 δ ν τ + ω^2)^2, Italic, 30]}],            TextAlignment -> Center] // TraditionalForm},         Alignment -> Left], WindowTitle -> "An expression",        WindowSize -> {400, 300}], ImageSize -> {70, 18},       Background -> Brown, BaseStyle -> {"GenericButton", Bold}]      Second, one may use the bobknight's solution, but write the formula as a string:                  Button["Show it", CreateDocument[       Notebook[{         Cell["some explanatory text:", "Text", FontSize -> 20], Cell[""],              Cell[BoxData[           ToBoxes[Row[{TraditionalForm[               Style["Φ", 30, Italic]],               TraditionalForm[Style[" = ", 30, Italic]],               TraditionalForm[               Style["\!\(\*FractionBox[\(ϕ\\\ \*SuperscriptBox[\(\     τ\), \(2\)]\\\ \*SuperscriptBox[\(ν\), \(3\)]\\\ ω\\\ \     θ \((1 - ν\\\ ω)\)\), \     SuperscriptBox[\((\*SuperscriptBox[\(τ\), \(2\)]\\\ \     \*SuperscriptBox[\(ν\), \(2\)] + 2\\\ δ\\\ ν\\\ τ \     + \*SuperscriptBox[\(ω\), \(2\)])\), \(2\)]]\)", Italic,                 30]]}]]], TextAlignment -> Center,           ShowStringCharacters -> False]                         },             WindowTitle -> "An expression", WindowSize -> {500, 300},         ShowCellBracket -> False                   ]                                                                ],           ImageSize -> Automatic, Background -> Brown,       BaseStyle -> {"GenericButton", Bold}]      I like this solution better, since it does not interact with the definitions of the parameters.


DateListPlot show all the dates in ticks

![enter image description here](http://i.stack.imgur.com/x79Do.jpg) The code below generates the plot above,               DateListPlot[{Drop[series[7], 1], Drop[series[16], 1]},Joined -> True,                    PlotMarkers -> {Automatic, Small}, Frame -> True,                   DateTicksFormat -> {"MonthNameShort", " ", "YearShort"} ] /.                   x : (FrameTicks -> _) :> (x /. s_String :> Rotate[s, 90 Degree])      I would like to show, on the x-axis, each and every one of the dates for which I have data. If that gets too cluttered then I would like to show a sampling of it that covers some of the staggered months. I will paste this into a pdf so tooltips won't be of use. Maybe for within year data, I can mention just the month, if it will improve readability. With non-date data, I know that I can enter ticknames and tick positions but I don't know how to do it with date data and also, I was wondering if this could be automated where I could tell it to show only the month for certain dates and month-year for others.


Measuring time complexity of a method

I use               NMinimize[someFunction, Method -> {"RandomSearch", Method ->{"InteriorPoint"},"SearchPoints" -> 2n, "RandomSeed" -> RandomInteger[{0, 100}], "PostProcess" -> {FindMinimum, Method -> "QuasiNewton"}}, MaxIterations -> 1000 n, PrecisionGoal -> 10, AccuracyGoal -> 10]`      where `someFunction` is a function of `n` variables. How could I measure the time complexity of this method?


I have a multidimensional array `A`. `Fourier[A]` finds the discrete Fourier transform over all dimensions. How to find discrete Fourier transform over a custom dimension like `fft(A,[],dim)` function in MATLAB? My current solution:               FourierDim[list_, dim_] :=       Module[{dims, ord, depth = ArrayDepth[list], tr, f},       dims = If[IntegerQ[dim], If[dim > 0, {dim}, {1 + depth + dim}], dim];       ord = Join[Complement[Range[depth], dims], dims];       tr = Transpose[list, Ordering[ord]];       f = ConstantArray[0.0 + 0.0 I, Dimensions[tr]];       With[{nn = Sequence @@ Table[Unique["n"], {depth - Length@dims}]},         With[{lim = Sequence @@ ({{nn}, Dimensions[tr][[1 ;; -1 - Length@dims]]}\[Transpose])},          Do[f[[nn]] = Fourier@tr[[nn]], lim]]];       Transpose[f, ord]       ];      It transposes the array, does Fourier transform in the loop, and transposes the array backward. Examples:               FourierDim[A,2]; (* Fourier over the second dimension *)     FourierDim[A,-1]; (* Fourier over the last dimension *)     FourierDim[A,{1,3}]; (* Fourier over the first and the third dimensions *)


probabiliy evaluation fails with equals condition

The following evaluation fails (the result is just the copy of the input) $$\text{Probability}[0<x\leq a | x-y=t,\\{x\ {ExponentialDistribution}[\lambda ],y\ {ExponentialDistribution}[\lambda ]\\}]$$ At the same time, the very exact expression evaluates correctly if I replace == with < $$\text{Probability}[0<x\leq a | x-y<t,\\{x\ {ExponentialDistribution}[\lambda ],y\ {ExponentialDistribution}[\lambda ]\\}]$$ Input:               Probability[0 < x <= a \[Conditioned] (x - y == t), {x \[Distributed]         ExponentialDistribution[\[Lambda]],        y \[Distributed] ExponentialDistribution[\[Lambda]]}]      Thank you!


Convoluting inverse square root with Gaussian

I would like to convolute the inverse square root on the interval `[0,inf]` with a Gaussian function, like so:               f[x_] := 1/Sqrt[x]     g[x_, sigma_] := Exp[-x^2/(2 sigma^2)]     conv[x_, sigma_] := Integrate[f[y] g[x - y, sigma], {y, 0, \[Infinity]}, Assumptions -> {sigma > 0}]     conv[x,sigma]      The result from Mathematica (9) reads               Exp[-x^2/(4 sigma^2)] Sqrt[-x] BesselK[1/4, x^2/(4 sigma^2)]/Sqrt[2]      which is purely imaginary for `x>0`. This is certainly not the answer to the question I had in mind, which should be a positive real-valued function for all real-valued x (correct?). Please tell me what is going wrong and (if possible) what I need to change to get the result I am looking for. P.S. Adding assumptions like `x>0` also doesn't seem to help (it simply will replace `Sqrt[-x]` by `I Sqrt[x]`).


Lie algebras packages (with E6, F4 & alii ... included)

I am looking for an add-on that deals seriously with computations inside exceptional Lie algebras (and obviously classical ones ...): I want at least all standard basic data concerning them & their representations to be included. I found some old ones but quite incomplete (no E6 or above). Do you have any recommendations or links to suggest . Thank you very much in advance.


Result of symbolic integration changed drastically by making assumptions

I would like to know the underlying reason for different outcomes for the two integration operation below. One of them includes a few assumptions, otherwise both have the same integrand:               Clear[a, b, c, d]     Integrate[(1/(a q^2 + b q Cos[θ] - c) - 1/(a q^2 + b q Cos[θ] + c)), {θ, 0, 2 π},        Assumptions -> {a, c, b} ∈ Reals]      > >     ConditionalExpression[-((2 Log[-((c - b q + a q^2)/Sqrt[-c^2 + b^2 q^2 - > 2 a c q^2 - a^2 q^4])])/ Sqrt[-c^2 + b^2 q^2 - 2 a c q^2 - a^2 q^4]) + (2 > Log[(c - b q + a q^2)/ Sqrt[-c^2 + b^2 q^2 - 2 a c q^2 - a^2 > q^4]])/Sqrt[-c^2 + b^2 q^2 - 2 a c q^2 - a^2 q^4] + (2 (-Log[-((c + q (b - a > q))/Sqrt[-c^2 + b^2 q^2 + 2 a c q^2 - a^2 q^4])] .... >                 Integrate[(1/(a q^2 + b q Cos[θ] - c) - 1/(a q^2 + b q Cos[θ] + c)), {θ, 0, 2 π}]      > >     -((2 π Sqrt[1 - (2 b q)/(-c + q (b + a q))])/( c + q (b - a q))) - >      (2 π)/((c + q (b + a q)) Sqrt[1 - (2 b q)/(c + q (b + a q))]) >


Plotting Laplace's equation on an infinite domain

I am trying to plot my solution to a Laplace equation on an infinite domain. However, when I try to plot it, _Mathematica_ just runs with nothing happening.               f[x_, y_] = Sinh[u*(5 - y)]/Sinh[u*5]*100/π*Cos[u*(ξ - x)];      DensityPlot[Integrate[f[x, y], {u, 1, 10}, {ξ, -5, 5}], {x, -5, 5}, {y, 0, 5}]      The code I have tried is above. The solution is $$ f(x, y) = \frac{100}{\pi}\int_0^{\infty}\int_{-\infty}^{\infty}\frac{\sinh(u(5-y))}{\sinh(5u)}\cos(u(\xi - x))d\xi du $$


How to change the variables Qi's to Ri's in one or two steps

I was wondering if there is a command in Mathematica to change all the following Qi's to Ri's? For example, change Q1 to R1, Q2 to R2, etc.                Q1 a1 + Q2 a2 + Q3 a3 + Q4 a4 + Q5 a5 + Q6 a6 + Q7 a7 + Q8 a8 +       Q9 a9 + Q10 a10 + Q11 a11 + Q12 a12 + Q13 a13 + Q14 a14 + Q15 a15 +       Q16 a16 + Q17 a17 + Q18 a18 + Q19 a19 + Q20 a20 + Q21 a21 + Q22 a22 +      Q23 a23 + Q24 a24 + Q25 a25 + Q26 a26 + Q27 a27 + Q28 a28 +       Q29 a29 + Q30 a30 + Q31 a31 + Q32 a32 + Q33 a33 + Q34 a34 + Q35 a35 +      Q36 a36 + Q37 a37 + Q38 a38 + Q39 a39 + Q40 a40 + Q41 a41 +       Q42 a42 + Q43 a43 + Q44 a44       I could go through and change the Qi's by hand, but I think there should be a more efficient way to do this. Thank you.


Mathematica + Numerical Recipes

the idea of combining Mathematica with the new routines in the 3rd edition of Numerical Recipes (NR) is very interesting. In fact, there is a NR library to Matlab which works very well because not only it allows one to create NR code (in C++) and install it as a function in Matlab, but it also cleverly handles the input and output of data. Does anyone know anything about this topic? I have asked the NR forum about this and received no answer. I know MathLink can be used to link C code to Mathematica, but seeing the coding level of it's Matlab counterpart, I wouldn't even dare to try and do this myself. In my view, the true power of scientific computing is in combining different libraries/platforms, efficiently exploiting their merits and deficits.


Flow in pipeline graph

I have pipeline directed graph which has one source and several sinks               getWeights = Function[{g},        res = {};        s = Flatten[{#1} & @@@ g, 1];        For[i = 1, i <= Length[s], i++,          AppendTo[res, 1/Count[Flatten[{#1} & @@@ g, 1], s[[i]]]];];        res        ];          egdes = {0 -> 1, 0 -> 2, 0 -> 3, 1 -> 4, 1 -> 5, 1 -> 6, 3 -> 6,        3 -> 7 , 2 -> 5, 2 -> 6, 4 -> 8, 5 -> 8, 5 -> 9, 6 -> 9, 7 -> 9,       5 -> 10, 7 -> 10};     wghts = getWeights[egdes]     Graph[egdes, EdgeWeight -> wghts,       VertexLabels -> Placed["Name", Center], VertexSize -> Medium,       EdgeLabels -> Table[egdes[[i]] -> wghts[[i]], {i, Length[egdes]}]]     sinks = Complement[DeleteDuplicates[Flatten[{#2} & @@@ egdes, 1]],        DeleteDuplicates[Flatten[{#1} & @@@ egdes, 1]]]     sources= Complement[DeleteDuplicates[Flatten[{#1} & @@@ egdes, 1]],        DeleteDuplicates[Flatten[{#2} & @@@ egdes, 1]]]      ![enter image description here](http://i.stack.imgur.com/iHSLa.png) Now I would like to calculate the the flow in sinks assuming the flow at source is equal to 1. I did it by finding all paths from source to sink and then summing the products of all edges weight in the path for all paths. My code is rather ugly and slow for large graphs so I do not put it here. I hope that someone could help me to find more elegant and fast decision. For the case in the figure there are three sinks {5,6,7} I found flows {3/8,1/4,3/8}


Any way to prevent Mac firewall from asking to allow connections all the time?

Whenever I start Mathematica 8 on my Mac the built-in Mac OS firewall asks if I want to allow JLink to accept incoming connections. Then, during running, I'll get the same question about Mathematica.app. Sometimes the requests occur several times during the day, though not always. It's a minor irritation but it'd be nice to know if there is a way to avoid it while keeping the firewall switched on. I already have the Mac firewall configured to allow connections permanently for Mathematica.app and JLink. Thanks


Random Matrix with integer coefficients and inverse also having integer coefficients

I'm trying to build a function that gives me matrices such that each:   1. Has integer coefficients.   2. Is non singular.   3. Has inverse which also has integer coefficients. I have some code that one of my teachers gave me, but it is code written in Derive. I have reproduced the code, but I'm not getting what a really need. The code for Derive requires a function that takes a column, multiplies it by a constant and adds it to another one, lest call this function `ColSum[M, i, j, α]`, which takes the i-th column multiplied by α and adds it to the j-th column. The code for the matrix in Derive is:               Matrix(n) ≔        \prod_{h=1}^{n-1}  \prod_{k=h+1}^{n} ColSum(IDENTITYMATRIX(n), h, k, (1 + RANDOM(2))·(-1)^h)*       \prod_{k=1}^{n-1}  \prod_{h=k+1}^{n} ColSum(IDENTITYMATRIX(n), k, h, (1 + RANDOM(2))·(-1)^k)*       VECTOR(VECTOR(IF(i_ < j_, 0, IF(i_ = j_, (-1), RANDOM(2) + 1)), i_, 1, n_), j_, 1, n_)       I think the problem is either in the `ColSum` function because it is where I've seen that things go wrong, or in the fact that `Product` does not perform an iterated `Dot`. I want to translate this function into _Mathematica_. My code so far is:               RowSum[v_,i_,j_,a_] := Table[If[m ==i , Part[v,i] + a*Part[v,j],Part[v,m]],{m,Dimensions[v][[1]]}]          ColSum[v_,i_,j_,a_]:=Transpose[RowSum[Transpose[v],i,j,a]]]               Matrix[n_] := Product[ColSum[IdentityMatrix[n], h, k, (1 + RandomInteger[2])*(-1)^h ], {h,1, n - 1}, {k, h + 1,n}].Product[ColSum[IdentityMatrix[n], k, h, (1 + RandomInteger[2])*(-1)^k ], {k, 1, n - 1}, {h, k + 1, n}].Table[Table[If[i < j, 0, If[i == j, (-1)^i,RandomInteger[2] + 1]], {i, n}], {j, n}]      I think the problem is either in the `ColSum` function because it is where I've seen that things go wrong, or in the fact that `Product` does not perform an iterated `Dot`. Thanks for helping.


Visualizing nested lists for easier human understanding

When interacting with Mathematica, I often find myself staring blankly at waves of curly braces, trying to understand how data is organized hierarchically. For example, the beginning of the result to               WolframAlpha["temperature in Toronto yesterday", "DataRules"]      looks like this: ![Waves of curly braces](http://i.stack.imgur.com/3Trq8.png) To visualize the hierarchy, I typically turn to TreeForm, but that's often unwieldy. There's no way to collapse parts of the tree you don't care about (as there would be in, say, a file system browser), so the visualization frequently spreads well off screen or is illegibly small. For example,               TreeForm[WolframAlpha["temperature in Toronto yesterday", "DataRules"]]      produces: ![TreeForm of a WolframAlpha query](http://i.stack.imgur.com/TmeJ4.png) Is there a better way?


Factoring a differential equation into an operator product

Following the fundamental theorem of algebra, I can (as stated here in Sec. 1.1.4) factor an $n$th-order linear ordinary differential equation $$ a_n \frac{d^n x}{dt^n} + a_{n-1} \frac{d^{n-1} x}{dt^{n-1}} +\cdots+a_1 \frac{dx}{dt}+a_0 = 0 $$ into $$ a_n \left( \frac{d}{dt} - r_1 \right) \left( \frac{d}{dt} - r_2 \right) \cdots \left( \frac{d}{dt} - r_n \right) x = 0 . $$ The Mathematica representation of the former is trivial, and I would represent the latter as               difOp[t, r] = (Dt[#, {t}] - r) &     an difOp[t, r1][ difOp[t, r2][x[t]] ] == 0      Is there any way to get the Mathematica kernel to connect the two, e.g. to compute the second from the first?


Harmonious graph labeling

Is it possible to harmoniously label a graph in _Mathematica_? I would like a function, that when given a graph, would return a harmonious labeling. If not, is there other software that can do it? A _Mathematica_ program that can do it for me would be great. Maybe use heruistics to do it. Consider all labelings and find one/several harmonious labelings? I dont think I have the programming chops to do it myself.


Finding simpler implied formulas while preserving contradiction

I have two Presburger formulas A and B such that A∧B≡False. From these I need to find "simpler" formula A′ (as simple as I can make it) such that A→A′ and A′∧B≡False. Is there any simple way to automate this for largish formulas in Mathematica? The formulas start off in sum of products form, with thousands of products and less than 20 variables. I'm already using FullSimplify to simplify A and B preserving equivalence, but I need to go even simpler, hence this weaker set of conditions.


Group list of lists by Total

I have some list which looks like               {{0,1},{4},{0,0,1},{2,0,1},{3,0,0},{3,1},{0,0,0,4}}      and I need to group lists with equal sum of elements in ascending order like               {{{0,1},{0,0,1}},{{2,0,1},{3,0,0}},{{4},{3,1},{0,0,0,4}}}      and for               {{0, 0, 0, 0, 0}, {1, 1, 0, 0, 0}, {1, 1, 1, 1, 0}, {1, 1, 0, 1, 1}, {0, 1, 1, 0, 0}, {0, 1, 1, 1, 1}, {0, 0, 1, 1, 0}, {0, 0, 0, 1, 1}}      I expected to see               {{{0, 0, 0, 0, 0}}, {{1, 1, 0, 0, 0}, {0, 1, 1, 0, 0}, {0, 0, 1, 1, 0}, {0, 0, 0, 1, 1}}, {{1, 1, 1, 1, 0}, {1, 1, 0, 1, 1}, {0, 1, 1, 1, 1}}}


Histogram For Non-Numerical Data

I have a non-numerical data, let say               data = Table[RandomChoice[{0.2, 0.3, 0.25, 0.15, 0.1} -> {"A", "B", "C", "D", "E"}], {500}];      and i want to make a histogram for this data. My solution so far               datanew = data;     label = Sort@DeleteDuplicates[data];     Do[datanew = ReplaceAll[datanew, label[[i]] -> i], {i, 1, Length[label]}]     Histogram[datanew, Ticks -> {None, Automatic}, ChartLabels -> {None, Placed[label, Below]}]      Is there any better way to do this? Thank you.


Generating and plotting hypocycloids

Hypocycloids are curves generated by following a fixed point on a smaller circle rolling around the inside of a larger circle. The following code is from the recent book of P. Wellin (with modified `PlotRange` by myself).               HypocycloidPlot[R_, r_, θ_] :=       Module[{Hypocycloid, center},        Hypocycloid[{a_, b_},          t_] := {(a - b) Cos[t] + b Cos[t (a - b)/b], (a - b) Sin[t] -           b Sin[t (a - b)/b]};        center[{a_, b_}, t_] := (a - b) {Cos[t], Sin[t]};        Show[{ParametricPlot[Hypocycloid[{R, r}, t], {t, 0, θ},           Axes -> None, PlotStyle -> Red],          Graphics[{{Blue, Thick, Circle[{0, 0}, R]},            Circle[center[{R, r}, θ]], {Thick,             Line[{center[{R, r}, θ], Hypocycloid[{R, r}, θ]}]}, {Orange,             PointSize[0.02], Point[center[{R, r}, θ]]}, {Red,             PointSize[0.03], Point[Hypocycloid[{R, r}, θ]]}}]},         PlotRange -> 1.5 (R + r), GridLines -> Automatic]]      For instance,               Table[HypocycloidPlot[R, 1,         θ], {R, {3, 7/2, Sqrt[7/2]}}, {θ, {Pi/3, 3 Pi/2, 2 Pi,          3 Pi}}] // TableForm      produces the following ![enter image description here](http://i.stack.imgur.com/MrnpI.jpg) (It can be verified that the curve only "closes up" when the ratio R/r is an integer or a rational number.) My first question. If we set `R = 3` and `r = 2`, for example, the inner circle loses the contact with the outer circle. (The author does not pose any restricition to r.) I think the problem arises due to the fixed center of the outer circle               Circle[{0, 0}, R]      Am I correct or am I missing something? And if I am indeed correct, how should the code be modified in order to circumvent the issue? My second question. Suppose that I have the following               Manipulate[      HypocycloidPlot[R, r, θ], {θ, 0.01,        2 π Denominator[(R - r)/r]}, {R, {3, 4, 5, 6, 7, 8, 5/3, 7/2},        Setter}, {r, Range[5], Setter}]      How can I make videos like the following one? http://en.wikipedia.org/wiki/Hypocycloid **Update** The thread is relating to Plotting an epicycloid There my second answer about animation is answered. So, it remains only the first one.


Any ideas on how to use the Region` context?

If you type               ?Region`*      you'll get: ![Mathematica graphics](http://i.stack.imgur.com/5a67H.png) which seems a bunch of interesting and not documented symbols. Any idea (or experience) on how to use them? **Edit** By using our "collective spelunking" **I was able to work outthis answer** \- Great! :) And Silvia used it to write another one!


How to enter and solve this equation in finite fields?

Is there a way in Mathematica 9 to enter and solve the following equation $p(x) = r^x$ where $p(x)$ is a polynomial whose coefficients are drawn from a finite field, and $r$ is a primitive root of the field modulus ? EDIT As an example, how to solve $x^3 + x^5 == 3^x$ mod 7


InterplationOrder, ListPlot3D and using AbsoluteOption to find value used. Slow using InterpolationOrder

What lead to this, is when I noticed that `ListPlot3D` was much slower when adding a specific `InterpolationOrder->n` vs. not and letting the default take care of it. To find out why it is so much slower (timing is below), I asked Mathematica to tell me what default `InterpolationOrder` it used for the current plot. So I used the command                     AbsoluteOptions[p, InterpolationOrder]      To do that, which supposed to return the value used in p. From the excellent book `Mathematica Navigator`: ![Mathematica graphics](http://i.stack.imgur.com/pAfvp.png) But Mathematica gave an error and said that `InterpolationOrder is not a known option for` this plot. But http://reference.wolfram.com/language/ref/ListPlot3D.html shows it there. ![Mathematica graphics](http://i.stack.imgur.com/2ed8a.png) So my question is, how does one find what `InterpolationOrder` is used for current plot of `ListPlot3D`? My sub question is actually (the reason why I wanted to find the above), is why ListPlot3D slows down so much when specifying this option vs. not? Here is the MWE               Clear[x, y, z];     nElem = 10; h = 1/(nElem - 1);     grid = N@Table[{i*h, j*h}, {i, -10, 10, h}, {j, -10, 10, h}];     f[x_, y_] := Sin[x*10 y] Exp[-x y];     force = Map[f[#[[1]], #[[2]]] &, grid, {2}];     p = ListPlot3D[force, InterpolationOrder -> 1, AxesLabel -> {x, y, z}]      ![Mathematica graphics](http://i.stack.imgur.com/tYbdD.png)                AbsoluteOptions[p, InterpolationOrder]      (*error*)           Timing[ListPlot3D[force, InterpolationOrder -> 1, AxesLabel -> {x, y, z}]]        (*5.647236*)           Timing[ListPlot3D[force, AxesLabel -> {x, y, z}]]          (* 0.624004 *)      And as an extra reward, if you can answer how can one use `InterpolationOrder -> 1` and still have fast plot, I will up-vote you 2 times if I can. Version 10.0 on windows 7.


Select elements of a Matrix that are the same (or have certain relationship) and return their position and the element itself

I have a matrix and I want to pick the elements that are the same and return their positions and their values. It seems easy to me, but all I know is how to pick elements that satisfy certain conditions, but not in relation to other elements.


BindEvent binding own function

I need to change property of window when button gets pressed. There are pretty enough examples on Wolfram's website, but all they bind predefined function "Print[]" and I have no problems with binding Print function. But I can't bind something different. I need call my own function and methods of Widgets.      This is a window whose property I want to change:               widget4 = Widget["TextPanel", {     "preferredSize" ->      Widget["Dimension", {"width" -> 800, "height" -> 660}],     "contentType" -> "text/html",     "editable" -> False, "path" -> html1path}, Name -> "MainOutput"]            functio[]:=(Print["fffff"]);      This is my button:               html2path="some text which I want to change";     butto = Widget["Button", {     "Text" -> "Update",     BindEvent["Action",     Script[    {SetPropertyValue[{"MainOutput", "path"}, html2path] ,        Print["fdfdf"], ref@InvokeMethod[{"Frame", "getX"}], functio[] } ]]     }]      I launch it all together so:               ref = GUIRun[ Widget["Frame", {widget4, butto}, Name -> "Frame" ]];      As result out of all my tries only function Print["fdfdf"] was called. ![enter image description here](http://i.stack.imgur.com/9psJb.png) I got stuck with it.   Thanks in advance.


Gram Schmidt inner and outer products

I know the Gram-Schmidt orthogonalization generates an orthonormal basis from an arbitrary basis. I need help with: > **Write a program that inputs a list $\\{b_1,\dotsc,b_n\\}$ of linearly > independent vectors and an inner proudct and outputs a list of orthonormal > vectors $\\{e_1,\dotsc,e_n\\}$ with the same span.**                           innerproduct1[f_,g_]:=Sum[(f/.t->i)(g/.t->i), {i,1,4}]                      gramschmidt2[innerproduct1_,list2_]:=                   Module[{k,u,v,e},                    k=Length[list2];                    Do[Subscript[v,i]=list2[[i]],{i,1,k}];                    Do[Subscript[u,i]=                      Subscript[v,i]-                       Sum[(innerproduct1[Subscript[v,i],Subscript[u,j]]/                           innerproduct1[Subscript[u,j], Subscript[u,j]]*Subscript[u,j],  {j,1 ,i-1}];                   Subscript[e,i]=                    Subscript[u,i]/Sqrt[innerproduct1[Subscript[u,i].Subscript[u,i]]],{i, 1,k}];                 Table[Subscript[e,i],{i,1,k}]                 ]      Sorry if the program is wrong. I might be going ahead of what I read which I probably am. I just learned somethings about the Gram-Schmidt process from reading an analysis text a couple days ago. I saw this question online and thought I would try to solve it with what I read. I came to some frustration and really wanted to know how to write a _Mathematica_ program for this.


How to obtain a Symplectic 4×4 matrix?

I have a problem in obtaining a $2n \times 2n$ Symplectic matrix $T$, with $n=2$. I couldn't find a direct command in _Mathematica_ to achieve this. Conditions:               Transpose[T].HH.T={{v1,0,0,0},{0,v2,0,0},{0,0,v1,0},{0,0,0,v2}     Transpose[T].JJ.T = JJ      where:               JJ={{0, 0, 1, 0}, {0, 0, 0, 1}, {-1, 0, 0, 0}, {0, -1, 0, 0}};     T={{T11,T12,T13,T14},{T21,T22,T23,T24},{T31,T32,T33,T34},{T41,T42,T43,T44}};     HH={{HH11,HH12,HH13,HH14},{HH21,HH22,HH23,HH24},{HH31,HH32,HH33,HH34},{HH41,HH42,HH43,HH44}};


Error while transponsing a tensor

I am trying to execute following:               TensorTranspose[Outer[D, metric, x], {2, 3}].       And _Mathematica_ says me > >     TensorTranspose::symmperm: "Invalid permutation or symmetry generator > {2,3}. >   While for permutation `{1,2}` there would not be an error. metric has dimentions `{5,5}`, `x` has `{5}`. Could anyone tell what is wrong with `{2,3}`?


How to get the boolean value of an inequality involving an InterpolatingFunction?

Here's the code:               yan = FunctionInterpolation[x^2, {x, -1, 1}];     FullSimplify[yan[x] > -1, -1 < x < 1]      Needless to say, what I expect to see in the output is "True", but `FullSimplify` doesn't seem to work. What function should I turn to? * * * @J.M. @belisarius @acl 囧…A very simple solution suddenly struck me, it is:               yan = FunctionInterpolation[x^2, {x, -1, 1}];     MinValue[{yan[x], -1 < x < 1},x]>-1


Strange NSum behavior for slightly larger number of terms

For some sums, NSum gives me the result nicely for some number of terms, but if I add one more term, it suddenly becomes much slower. I haven't found the minimum example for which this can be reproduced, but here is a problem I was just trying to compute:               NSum[Sin[x0*n*Pi]*Sin[d*n*Pi/2]*Exp[(n*Pi)^2 *t]*(2 - Cos[n*Pi] -      2*BesselJ[1, n*Pi/2]*Sin[n*Pi/2]), {n, 1, 24}]      Here t=-0.3, d=0.1 and x0=0.5. For 24 terms, this evaluates just fine (and gives me 0.015118), but for 25 terms, the calculation takes much longer. It seems to me that adding just one more term to the sum should not take much longer than the original calculation. What is going on here? I'm using Mathematica version 9.0.1.0.


Looking for mismatches between two lists

I'm able to do what I need, but it seems like there's always a better way. I have two lists, epiExcel and epiDB. Each has 3 columns and about 2,500 rows. I need to find out if the first 2 columns of each match, and when they don't where the mismatches are. I did the following:               z = Position[epiDB[[All, {1, 2}]], #] & /@ epiExcel[[All, {1, 2}]];     Position[z, {}]     z = Position[epiExcel[[All, {1, 2}]], #] & /@ epiDB[[All, {1, 2}]];     Position[z, {}]      This worked for the specific case I have at the moment. Is there a better way to do this?


Asking for input in an event handler

Why won't               EventHandler["text", {"MouseClicked" :> (output = Input[];)}]      work? When I click "text" the kernel hangs.


Why doesn't Mathematica pack Boolean arrays?

I've been wondering about this for a while now, so I'm going to ask. This is a question about the design of _Mathematica_ , which perhaps cannot be directly answered by anyone but the designers, however similar queries have been fruitful in the past. Simply: why aren't arrays of `True` and `False` values packed? `Compile` handles `True | False` so it seems _Mathematica_ has some understanding of optimizing for this type, yet:               boolean = Developer`ToPackedArray @ RandomChoice[{True, False}, 1*^6];          Developer`PackedArrayQ @ boolean      > False This is rather frustrating because packing would be particularly effective on binary data:               bigint = FromDigits[Boole@boolean, 2];          ByteCount[boolean]          ByteCount[bigint]      > 8000032 > > 125040 Yes, one can sometimes fall back to this storage format and use `Bit*` operations, but that is inconvenient and it doesn't always help; data must be converted for functions that expect `True` or `False` and the opportunity for internal optimizations may be lost. **Is there some reason I fail to comprehend that makes implementing packing of Boolean arrays a bad idea?**


Running Mathematica via JLink from a Servlet on Tomcat 7 Problem

I'm trying to make a java servlet running on Tomcat 7 for specilized mathematical calculations. So I want to link Wolfram Mathematica 8.0 mathkernel from my servlet via JLink (webMathmatica is not an option). I placed JLink.jar and JLinkNativeLibrary.dll into WebContent/WEB-INF/lib directory and wrote the following code:               String[] mlArgs = {"-linkmode", "launch", "-linkname", "\"path-to-mathkernel.exe\""};     mathKernelLink = MathLinkFactory.createKernelLink(mlArgs);      But, when I launch my servlet on Tomcat, it shows dilog box with title "Choose a MathLink programm to launch". If I choose mathkernel.exe from the Mathematica folder, further calculations run fine. I think that "path-to- mathkernel.exe" is incorrect to automaticaly run mathkernel.exe. I tried to use a global path c:\program files\wolfram research\mathematica\8.0\mathkernel.exe, but i didn't succeed. Witch path should I use? Or should I configure Tomcat to run external applications? Thanks.


Mathematica for Computer Scientists

## Background I've coded in C/Scheme for 10 years. I have a BS CS. I've recently become very interested in pattern-matching (lisp's match macro), and term rewriting systems, which brought me to Mathematica. I would like to read a book on Mathematica that will show me lots of cool term-rewriting as a programming style techniques. ## Question: What should I read?


Using MapIndexed only at certain elements of a list

`MapIndexed` is a very handy built-in function. Suppose that I have the following list, called `list`:               list = {10, 20, 30, 40};      I can use `MapIndexed` to map an arbitrary function `f` across `list`:               {f[10, {1}], f[20, {2}], f[30, {3}], f[40, {4}]}      where the second argument to `f` is the part specification of each element of the list. But, now, what if I would like to use `MapIndexed` only at certain elements? Suppose, for example, that I want to apply `MapIndexed` to only the second and third elements of `list`, obtaining the following:               {10, f[20, {2}], f[30, {3}], 40}      Unfortunately, there is no built-in "`MapAtIndexed`", as far as I can tell. What is a simple way to accomplish this? Thanks for your time.


Is SynchronousUpdating->False supposed to make this simple Dynamic example work?

x = 0; Dynamic[{x, Button["+1", Pause[6]; x++]}, SynchronousUpdating -> False]      The documentation states that Dynamic and Manipulate will abort synchronous computations that take longer than 5 seconds. The stated solution to this is to set SynchronousUpdating to False. That does not seem to work here. If I pause for 5 or fewer seconds it always works, but if I pause for 6 or more seconds, x always stays at 0 no matter the setting for SynchronousUpdating.


how to find iso-cost contours on a 2d plot efficiently

Consider a 2D plot in which dimension 1 and 2 represent quantity 1 and 2 respectively ranging over 0 to 100. Each point in the space corresponding to (x,y) represent cost of choosing quantity 1 as x and quantity 2 as y. Assume cost increases monotonically with increase in quantities. I want to find iso- cost lines(contours) in the space. Say all those points whose cost is equal to some K. How do I find it efficiently without checking cost of all the points in the space which is 100 cross 100.?


Strange result from evaluating a Limit expression

When I evaluate the limit of `(1-Cos[x]) Sin[1/x]` at `x = 0` in _Mathematica_ 9, I obtained `Interval[{-2, 2}]`. The problem is that this limit is 0. It is also 0 when I compute it by Maple and _Mathematica_ 7\. So, I wonder whether I've found a bug in _Mathematica_ 9?               Limit[(1 - Cos[x]) Sin[1/x], x -> 0]      > >     Interval[{2, 2}] >


Change size of a saved plot or image (post-processing)

I have many plots (that take a long time to run) and each is saved to a variable name. For simplicity, say one was:               m = Plot[Sin[x], {x, -1, 1}, ImageSize -> 600]        If I call for the plot               m        it will be presented as it should be, with ImageSize 600. I can click and drag the corners to change the size of the plot (instantaneously, so I know mathematica is not re-computing the plot, but simply adjusting the output image size continuously). Therefore, what I wish to accomplish must be possible to do, but I don't know how to instruct mathematica to do it. What I want is a command, something similar to, say               m/.ImageSize->200        etc. that can present m with a new, prescribed size, rather than manually sliding it to a new size, and certainly without having to re-compute the code that produced the saved plot. Help?


Area of the largest rectangle bounded by $y=x^2$ and the x-axis within the unit interval

I am trying to find the area of the largest rectangle (whose sides are parallel to the coordinate axes) contained in the region bounded by the graphs of $y = 0, y = x^2,$ and $x = 1$ using _Mathematica_. I am not sure where to begin other than that the area of a rectangle is $l w$. Any ideas?


Centrality measures and normalisation

Are centrality measures normalised in _Mathematica 9_? Only `ClosenessCentrality` is normalised. How I can normalise other centrality measures notably `DegreeCentrality` and `BetweennessCentrality`?               g = GridGraph[{5, 5}];     ClosenessCentrality[g] // Short     BetweennessCentrality[g] // Short     DegreeCentrality[g] // Short      > > {0.24,0.282353,0.3,0.282353,0.24,0.282353<14>>,0.24,0.282353,0.3,0.282353,0.24} > {2.6881,17.2071,21.5429,17.2071,<<18>>,21.5429,17.2071,2.6881} > {2,3,3,3,2,3,4,4,4,3,3,4,4,4,3,3,4,4,4,3,2,3,3,3,2}


Plotting multiple parametric functions with different intervals

I want to make a parametric plot like this:               ParametricPlot[{{2 t, -10 t^2}, {t, 2 t}}, {t, 0, 2}]      I have tried the following but it doesn't work:               ParametricPlot[{{2 t, -10 t^2}, {t, 2 t}}, {{t, 0, 2}, {t, 4, 7}}]


How to define a matrix with all elements 0?

A matrix can be defined as               M = Array[m, {3, 3}]      which gives               {{m[1, 1], m[1, 2], m[1, 3]}, {m[2, 1], m[2, 2], m[2, 3]}, {m[3, 1], m[3, 2], m[3, 3]}}      How to give all `m[i, j]` the value `0` (if `M` is a `NxN` matrix)?


Can I make V9 prompt witb "In[1]:=" before I enter an expression?

Using an older version of _Mathematica_ , I was used to the system automatically beginning each notebook line with `In[1]:=`. All I did was enter the expression and press enter on the keyboard to evaluate the expression. Now however, using the default _Mathematica_ Input (v.9), there is no initial `In[1]:=`. I enter the expression and press enter, and then the `In[1]:=` appears, followed by the value of the expression or the symbolic output. I would prefer to have each new line begin with a numbered `In[]:=`, I would like to know if it is possible to get back the old behavior that I was familiar with? If so, what preferences do I need to set?


Stop use of scientific notation when displaying FrameTicks

I have a dynamic graph which changes depending on the current selection from a drop down box. All selections from the drop down box give fine results except one. For the one selection it shows the `y` axis in scientific notation. I understand that this is due to the values being large but I don't want this to happen. I also can't specify the `y` axis values manually, I need to use the `FrameTicks->Automatic` functionality. Is there any way to stop the y-axis ticks from displaying in scientific notation? ![enter image description here](http://i.stack.imgur.com/rUbhw.jpg)


Compile: Putting integers into a list

The first part below is already answered, but I've got another question which I think is closely related to this one, so I edited my question. **First part:** I started compiling in Mathematica a few weeks ago. In the code below, I want to put the integer value 0 into the list "Pre". If I "Print" the list, it will look like {0,0,....,0}. But the output of the code is {0.,0.,0.,....,0.}. So, my question is, how can I manage it, that the output looks like the "Print", i.e. I want the list to have integer values and not real numbers.               In[1]:= CInit = Compile[{{v0, _Integer, 0}, {s0, _Integer, 0}},               Module[{s = s0, v = v0, d, Pre},               d = Table[$MaxMachineNumber, {v}];               Pre = Table[0, {v}];               Print[Pre];               d[[s]] = 0.;               {d, Pre}               ], CompilationTarget -> "C"];             CInit[5, 1]           During evaluation of In[1]:= {0,0,0,0,0}           Out[2]= {{0., 1.79769*10^308, 1.79769*10^308, 1.79769*10^308,               1.79769*10^308}, {0., 0., 0., 0., 0.}}      **Second part:** If I have an empty list and I want to put Integers into it, how can I let Mathematica know that it is a list of Integers and not Reals? I tried to manage this with the third argument in Compile, but that didn't work. For example:               In[22]:= CTest = Compile[{{s, _Integer}}, Module[{Perm = {s}},              Perm = {};              Append[Perm, 1]              ], {{Perm, _Integer, 1}}, CompilationTarget -> "C"]      > Compile::cset: Variable Perm of type {_Integer,1} encountered in assignment > of type >{_Real,1}. >> > > Compile::cset: Variable Perm of type {_Integer,1} encountered in assignment > of type >{_Real,1}. >> I can avoid this error by doing this rather unnecessary thing below:               In[25]:= CTest = Compile[{{s, _Integer}}, Module[{Perm = {s}},              Perm = Delete[Perm, 1];              Append[Perm, 1]              ], CompilationTarget -> "C"]      So, is there another way to tell Mathematica that Perm is a list of Integers without doing it like in the last example? Thanks in advance!


Solve a PDE on a domain $\Omega$ with given boundary conditions

I'm starting to study the behavior of some PDEs and I would like to run simulations in mathematica to help me visualize solutions. For example, a prime example that I would like to study is $$ \left\\{ \begin{array}{cc} -\Delta\phi + u\cdot\nabla\phi=1 & \text{in }\Omega\\\ \phi=0& \text{on }\partial\Omega \end{array}\right. $$ for a fixed (smooth enough) $u$ which is divergence free and flows tangentially to the boundary. For one dimensional problems, inputting boundary conditions is easy since there are typically only two bounary points at most. But I would like to study this PDE (in 2-d) with a variety of different $\Omega$'s. I can't find anything in the mathematica documentation about how to input arbitrary boundary conditions. To make things simpler, I will restrict myself to reasonably nice $\Omega$'s which have nice boundaries. Suppose that $\partial\Omega$ is given implicitly by $F(x,y)=0$, e.g. $x^2+y^2-1=0$. What would be the easiest/best/most efficient way to input the boundary condition $\phi(x,y)=0$ when $F(x,y)=0$? Edit: Feel free to use any reasonable discretization technique, or to assume that you have a function like `isInRegion[x,y]` if you need it.


Mathlink and Fortan: A list with more than 10 elements as result

I have a problem with Mathlink (Mathematica 9.0), form which I call a Fortran subroutine which should return a list of 13 numbers. I have written a C-wrapper to call the Fortran subroutine (called "hubclus") from C. The main part of this wrapper looks as follows:               void hubclusML P((int, int, int, double, double, double, int));          :Begin:     :Function:       hubclusML     :Pattern:        HubClus[ Nx_Integer, Ny_Integer, Ne_Integer, U_Real, t_Real, Temp_Real, fulldiag_Integer  ]     :Arguments:      { Nx, Ny, Ne , U, t, Temp, fulldiag }     :ArgumentTypes:  { Integer, Integer, Integer, Real, Real, Real, Integer }     :ReturnType:     Manual     :End:          #include "mathlink.h"     extern void hubclusML( int Nx, int Ny, int Ne, double U, double t, double Temp, int fulldiag );               void hubclusML( int Nx, int Ny, int Ne, double U, double t, double Temp, int fulldiag )     {            double results[12];            /* Call hubclus */       hubclus_(&Nx, &Ny, &Ne, &U, &t, &Temp, &fulldiag, &results);            /* Send the Results to Mathematica via MathLink */       MLPutReal64List(stdlink, results, 13);            return;     }      This wrapper calls the Fortran subroutine "hubclus" which in turn calculates a list with 13 elements as result and should pass it via Mathlink back to Mathematica. **Now here is the problem:** It always worked well as long as the list "results" contains not more than 10 elements. But if the list "results" contains more than 10 elements the Link to this function dies after the execution in Mathematica without giving any error message except "$Failed". I would be thankful for any help.


Save selection as PDF - non-image format

I am trying to save the following plot as a pdf, so that I can import it into LaTeX:               Grid[{{RegionPlot[{x<y,x>y},{x,-2-1/10,2+1/10},{y,-1/10,3+1/10},PlotPoints->20,PlotStyle->{Texture[Graphics[Table[Circle[{i,j},1/4],{i,20},{j,20}]]],Texture[Graphics[Table[Polygon[{{1+i,0+j},{0+i,Sqrt[3]+j},{-1+i,0+j}}],{i,2,80,4},{j,2,80,4}]]]},BoundaryStyle->Black,PlotRange->{{-2,2},{0,3}},ImageSize->350],Grid[{{Graphics[Table[Circle[{i,j},1/4],{i,3},{j,3}],ImageSize->30,Frame->True,FrameTicks->None],"(Min, Min) & (Mix, Max)"},{Graphics[Table[Polygon[{{1+i,0+j},{0+i,Sqrt[3]+j},{-1+i,0+j}}],{i,2,10,4},{j,2,10,4}],ImageSize->30,Frame->True,FrameTicks->None],"(Mix, Max)"}},Spacings->{1,1/2}]}},Spacings->{2,1}]      However, if I right-click on the output and click 'save selection as', the pdf I get changes the `RegionPlot` into a image (probably jpeg). However, it does manage to keep the `Graphics`, to the right of the `RegionPlot`, as a non- image pdf code. I believe this is due to the function `Texture`, which turns the `Graphics` inside `Texture` into an image. How can I get the full output into non-image pdf code?


Evaluation indicator for a notebook

I have a GUI with a number of `TabView` and other `Manipulate` controls. Sometimes clicking from one tab view to the other can take a while, and I would like to have a global "Please wait" indicator. So one way is to implement it for each button or slider, but I would essentially like to have a visual indicator that will show if any cell in my notebook is being evaluated. Any ideas or suggestions? (Have searched for answers here but I only found those related to progress bars for a specific calculation)


Determining which rule NIntegrate selects automatically

I need to numerically integrate a highly oscillatory function over the semi- infinite domain $(0,\infty)$: $$\int_0^\infty \frac{\sin^2(x) \sin^2(1000 x)}{x^{5/2}}\mathrm dx$$ Since the Levin rule (which was recently added to _Mathematica_ , starting in version 8) was developed specifically for oscillatory integrals such as this, I thought I'd try it:               ans = NIntegrate[Sin[x]^2 Sin[1000 x]^2/x^(5/2), {x, 0, Infinity},                       Method -> {"LevinRule"}, PrecisionGoal -> 8, MaxRecursion -> 30]      Using an exact solution for this integral, I can confirm the relative accuracy of the _Mathematica_ result is $1 \times 10^{-11}$, and moreover the calculation is very quick. At first, this led me to believe that Levin's method works great for this problem, but... It turns out that _Mathematica_ must be automatically switching to non- oscillatory rule behind the scenes, because forcing it not to do so gives a very poor result:               ans = NIntegrate[Sin[x]^2 Sin[1000 x]^2/x^(5/2), {x, 0, Infinity},                        Method -> {"LevinRule", "MethodSwitching" -> False},                      PrecisionGoal -> 8, MaxRecursion -> 30]      > NIntegrate::ncvb: NIntegrate failed to converge to prescribed accuracy after > 30 recursive bisections in x near {x} = {0.}. NIntegrate obtained -3497.5 > and 3510.0321785369356` for the integral and error estimates. >> Is there any way to find out which alternative non-oscillatory rule _Mathematica_ is automatically selecting? I've tried to guess which rule is being used by manually specifying few rules but the results I've obtained with other rules are inaccurate, slow, or both:               ans = NIntegrate[(Sin[x])^2 (Sin[1000 x])^2/x^(5/2), {x, 0, Infinity},                       Method -> "ClenshawCurtisRule", AccuracyGoal -> 8, MaxRecursion -> 30]      > NIntegrate::slwcon: Numerical integration converging too slowly; suspect one > of the following: singularity, value of the integration is 0, highly > oscillatory integrand, or WorkingPrecision too small. >> > > NIntegrate::eincr: The global error of the strategy GlobalAdaptive has > increased more than 400 times. The global error is expected to decrease > monotonically after a number of integrand evaluations. Suspect one of the > following: the working precision is insufficient for the specified precision > goal; the integrand is highly oscillatory or it is not a (piecewise) smooth > function; or the true value of the integral is 0. Increasing the value of > the GlobalAdaptive option MaxErrorIncreases might lead to a convergent > numerical integration. NIntegrate obtained 0.000013202052151832003` and > 1.0480362255168103`*^-6 for the integral and error estimates. >> I'd like to know what rule _Mathematica_ is using so that I can try adjusting options for the best performance possible. I need to calculate this integral several hundred thousand times, as the innermost integral of a nested double integration. Furthermore, when it comes to publishing my results, I would like to be able to state the integration strategy that was actually used, rather than " _Mathematica_ knew how to handle it".


Mathematica 9 link in OriginLab

Hi (I am an absolute newbie), I need to send Mathematica data to the program OriginLab to plot and change the graphs. Does anyone know if it is possible to send data from Mathematica 9 via Mathematica link to OriginLab? I have tried, but it was only possible to send data from OriginLab to the Kernel and use the programming power of Mathematica 9 to receive the results back in OriginLab.


How to initialize several elements per iteration with Table?

I would like to initialize this kind of vector : `{0,0,1,1,0,1,0,1,1,1,1,1}` with `Table`.   I tried `Table[{x, y, 1}, {y, 0, 1, 1}, {x, 0, 1, 1}]` but it outputs `{{0,0,1},{1,0,1},{0,1,1},{1,1,1}}`.   What is the right method to correctly initialize my vector without creating sub-lists ?


Most efficient way to sum over matrix products?

I have two lists. The first, `coefficientlist`, is dense and has dimension `{176,176}` elements. The second, `cubelist`, is a list of three-dimensional lists, i.e. `cubelist` has dimension `{176,65,65,65}`. I need to perform the following summation:                   sumlist=Table[0,{65},{65},{65}];         Do[         If[coefficientlist[[n,m]]!=0,           sumlist += coefficientlist[[n,m]] (cubelist[[n]]cubelist[[m]]) ];           ,{n,176},{m,176}];      Essentially I want to perform a sum like $S = \sum\limits_{i ,j} T_{ij} \phi_i \phi_j $ where the $T$ matrix is called `coefficientlist` in the code above and the $\phi_i$ are represented as grids over real space. I have to do this several times, so I want to find the most efficient way to do it. Thanks in advance.


How to return a string from LibraryLink?

I need to return a string from a LibraryLink function. The documentation states: > When a string is returned as a result, the Wolfram Language accesses the > memory to convert it to its own internal string format, but does not attempt > to free the memory. Thus, if your program allocates a string for a result, > it also needs to free that memory, but in a separate function from the one > setting the string result, since the Wolfram Language needs to access the > string memory after the library function has returned. Does this really mean that I need to have _two_ functions to be able to return the string, one to return it and one to free the memory? Is there really no simpler way? Based on my interpretation the _minimal_ work needed to return a dynamically allocated string is what's shown at the end of the post. Is this correct? This looks quite tedious. Is there a way to let Mathematica manage the memory for the string (including allocation and freeing, as with MTensors)? (To be fair: it can be expected that in many cases one would want to return a pre-defined string in which case there is no need to free it. Sometimes the string is dynamically allocated though, and it becomes necessary to free it.) * * * In this example use C++'s `std::string` to save some work, but using simple `char *` in C would be analogous, with some added tedium.               std::string *str = NULL; // ugly global variable          extern "C" DLLEXPORT int get_string(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res) {         str = new std::string("some string to return");         MArgument_setUTF8String(Res, const_cast<char *>(str->c_str()));         return LIBRARY_NO_ERROR     }          extern "C" DLLEXPORT int free_string(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res) {         delete str;         str = NULL;         return LIBRARY_NO_ERROR     }      Then in Mathematica:               iGetString = LibraryFunctionLoad["lib", "get_string", {}, "UTF8String"]     iFreeString = LibraryFunctionLoad["lib", "free_string", {}, "Void"]          getString[] :=        PreemptProtect@AbortProtect@Module[{str},         str = iGetString[];         iFreeString[];         str       ]


How can I change the MPS format in Linear Programming samples of Mathematica?

I am trying to play with some linear programming examples of _Mathematica_ as `ExampleData[{"LinearProgramming", "blend"}, "Equations"]`. It gives me the MPS format of the samples. How can I change them?


Display negative exponents always as fraction

I want _Mathematica_ to display negative exponents always as fractions. I already tried:               Needs["Notation`"]     (* Notation[1/a_^b_ <==> a_^-b_] *)     Notation[       ParsedBoxWrapper[RowBox[{"1", "/", RowBox[{"a_", "^", "b_"}]}]]       ⟺        ParsedBoxWrapper[RowBox[{"a_", "^", RowBox[{"-", "b_"}]}]]]      While I do have               x^-z      > >     1/x^z >   the following doesn't work:               x^-(2z)      > >     x^-2z >   Some hints ? Thank you very much !


How can I modify the interval of the function Image[]?

I think the default interval is [0,1]. when I have all positives I find it easy to rescale but when I included negative values it doesn't give me the results that I expect. for example how can I change the interval to [-1,1] ?? Thank you very much


How to find non zero elements of a list containing zeros and symbols

I have a list, obtained after differentiating a list of expressions, which contains zeros and symbols, say:               A = {x1^2, x2^2, x3^2, x4^2}     D[A,x3]      results in the list:               {0, 0, 2 x3, 0}      How do I get the position of the non-zero entry, mathematica cannot compare symbols to zero directly. I could convert the elements of the list to strings but is there a faster way?


Picking random items out of a list only once

I'm trying to create a function that randomly returns a value from a list but remembers the values that have been given before. At the end when the list is empty it should return an empty list. Basically like emptying a bucket full of eggs one at a time. Suppose I have two lists:               data1 = Range[10];     data2 = Range[20];      Assume a function               getRandomItem[l_List]      I tried playing with down-values but that doesn't work. Calling `getRandomItem[data1]` two times would give (e.g) `{1}` and `{3}`. Calling `getRandomItem[data2]` two times would give (e.g) `{15}` and `{20}` At the end as stated before when all items are chosen both `getRandomItem[data1]` and `getRandomItem[data2]` should return `{}`. I would like to do that without declaring `data1` and `data2` as global variables nor do I which to change/alter them. So, basically I presume the function itself should remember which data has been given to it and where it had left the previous time.


Why doesn't FullSimplify drop the Re function from an expression known to be real?

For some reason Mathematica does not properly simplify this expression:               In[7]:= FullSimplify[ArcTan[-Re[x + z], y], (x | y | z) \[Element] Reals]     Out[7]= ArcTan[-Re[x + z], y]      Obviously, if `x` and `z` are real, then so is `x+z`, so `Re[x + z]` should be replaced by `x + z`. Strangely enough, dropping any small part of the input fixes the problem, here are some examples.   No minus sign:               In[8]:= FullSimplify[ ArcTan[Re[x + z], y], (x | y | z) \[Element] Reals]     Out[8]= ArcTan[x + z, y]      No `z`:               In[9]:= FullSimplify[ArcTan[-Re[x], y], (x | y | z) \[Element] Reals]     Out[9]= ArcTan[-x, y]      No `y`:               In[10]:= FullSimplify[ArcTan[-Re[x + z]], (x | y | z) \[Element] Reals]     Out[10]= -ArcTan[x + z]      Of course I can just drop the `Re` function manually, but this is just a small fragment of the actual expression I'm trying to simplify, and I would like to avoid going though the whole expression looking for this specific pattern.   Anyone knows how to fix this? Is this a bug or what? (I'm using version 8.0.4.0)


Automatically evaluating related cells

I have the cells:               In[1]:= l = 2 + 2;          In[2]:= l >= 5      After evaluating them:               Out[2]:= False      Is there a way to evaluate all related cells, so if I change `In[1]` to `l = 2 + 5`, `Out[2]` would become `True` without evaluating the whole notebook?


inverse function not working -- but providing values for some arguments, a symbol otherwise?

Could you help me with what Mathematica is doing here, in the last lines? (The rest is here for context.) I removed the output to let you simply run this. Thanks.               k=10/3     u[c_,l_]:=Log[c]-Log[1+l^(1+k)/(1+k)]     T[z_]:=(1-0.84/1.3) * z     lType[n_]:=ArgMax[{u[n l-T[n l],l],l>=0},l]     zType[n_] := n lType[n]     Type := InverseFunction[zType]     Type[5345]     Type[2]     Type[4324424]      With a much longer version with some context, you can also switch to http://stackoverflow.com/questions/10641713/mathematica-define-inverse-only- where-it-exists Or please reconsider the same code with some output to see what my problem is with the inverse:               k=10/3     10/3     Utility function as in Saez 2001 allowing for income effects:     u[c_,l_]:=Log[c]-Log[1+l^(1+k)/(1+k)]     Actual tax schedule (approximate)     T[z_]:=(1-0.84/1.3) * z     Equation 14:     lType[n_]:=ArgMax[{u[n l-T[n l],l],l>=0},l]     zType[n_] := n lType[n]     Type := InverseFunction[zType] does not seem to work.     Type := InverseFunction[zType]     Type[5345]     5030.985810589009`     Type[2]     (zType^(-1))[2]     Type[4324424]     (zType^(-1))[4324424]


Infinite expression 1/0. encountered - caused by precision?

Planck's law dependent on frequency rho is as follows:                  B[T_, h_, rho_, k_, c_] := (2 h rho^3)/c^2 1/(Exp[h rho/(T k)] - 1)      As you can see, the denominator can only be zero for rho = 0. All the rest are nonzero constants. Curiously if we try to plot it               Plot[B[5800, 6.626 10^-34, rho, 1.38 10^-23, 299792458], {rho,        0.1 10^-6, 3 10^-6}]      It will return "Infinite expression 1/0. encountered" and the plot will be blank. In fact, substituting any value for rho appears to result in this error (out = ComplexInfinity). I have no experience with precision, but I don't see any other possible reason. Anyway to solve this?


Integrating with multiple indicator functions

I am trying to calculate an integral involving multiple indicator functions, such as: $$ h(u,v,w) = -\int_0^1 J^{\prime\prime}(s) (I_{(0,s]}(u) - s)(I_{(0,s]}(v) - s)(I_{(0,s]}(w) - s)\, dF^{-1}(s)$$ where $0 < u, v, w < 1$ and $$\begin{align} J(s) &= 6s(1-s)\\\ F(s) &= 1/[1 + \exp[-s]]\\\ F^{-1}(s) &= -\log[-1 + 1/s]\\\ \end{align} $$ Here is my code:               Js = 6 s (1 - s) (*weight function*)     FDJs = D[Js, s] (*first derivative of Js*)     SDJs = D[FDJs, s] (*second derivative of Js*)     Fs = 1/(1 + Exp[-(s)]) (*Fs*)     Finv = -Log[-1 + 1/s] (*F inverse*)     DFinv = D[Finv, s] (*derivative of F inverse*)     h = -Integrate[         SDJs*(Boole[u <= s] - s)*(Boole[v <= s] - s)*(Boole[w <= s] -          s) DFinv, {s, 0, 1},          Assumptions -> {0 < u < 1 , 0 < v < 1, 0 < w < 1}]      I get some output, but I am not sure if the syntax is correct especially for the indicator function.


Is it possible to construct a topological map of road network of Bangalore?

I saw this example wherein the `CityData` gives the map of a city. But this is available for a relatively small set of curated regions. Is it possible to extract such map, say the topologically connected roadmap (with edges representing edgelengths) of an arbitrary city?


ParallelEvaluate for function minimization

Is there a parallelized version of a minimization routine available in _Mathematica_? The objective function is non-linear and the gradients have to be numerically computed. Every function evaluation is compute-intensive and hence parallelization of numerical gradient computation will be beneficial. Simple attempts to wrap `Parallelize` around `FindMinimum` or `NMinimize` says it: > `cannot be parallelized; proceeding with sequential evaluation. >>` **Edit : 1** Here is an toy example               objFn[coeff_, xMin_, xMax_, n_] := (        Pause[5];         Total[(Cos[#] -               Sum[coeff[[i]] #^(i - 1), {i, 1, Length@coeff}]) & /@            Range[xMin, xMax, (xMax - xMin)/n]]^2);          NMinimize[      N@objFn[{x1, x2, x3, x4}, \[Pi]/3, 2 \[Pi]/3, 10], {x1, x2, x3, x4},       EvaluationMonitor -> Print[{x1, x2, x3, x4}]]      The `Pause[5]` is a placeholder for a long computation. This attempts to find a polynomial fit for the function using the coefficients list `{x1,x2,x3,x4}`. `Parallelize@Nminimize` resorts to sequential evaluation in this case. **Edit : 2** This question is inspired from an analogous possibility in Matlab as described here and here.


Numerical evaluation of ChebyshevT

When I evaluate the following Chebyshev series of the first kind in two different ways, I get two very different results:               N[ChebyshevT[100, Cos[Pi/7]], 8]     N[ChebyshevT[100, Cos[Pi/7]]]          Out[1] = 0.62348980     Out[2] = 3.71097*10^18      Clearly the first result is the correct one. Could someone please explain why the difference occurs e.g. is it perhaps because of a peculiar way that the long Chebyshev polynomial is numerically evaluated? The problem does not arise for shorter length Chebyshev polynomials.


Construct a function that can generate a geometry by extruding a section

Toady I want to construct a geometry shown as below: ![enter image description here](http://i.stack.imgur.com/qJio6.png) I know the Mathematica has the functions like `Cylinder`, `Sphere` and so on,but it lacks of a function to construct my geometry,so I have a trial as below: **_TengentLine_**                lineCofficient[x1_, y1_, r1_, x2_, y2_, r2_, style_] := Block[      {},        First@Solve[        {(k x1 - y1 + b)/Sqrt[1 + k^2] == r1  style,          (k x2 - y2 + b)/Sqrt[1 + k^2] == r2 style},        {k, b}]      ]      **tangentPoint**                tangentPoint[x1_, y1_, r1_, x2_, y2_, r2_, style_] := Block[       {k, b},      {        Solve[         {y == k x + b /.lineCofficient[x1, y1, r1, x2, y2, r2,style],         (x - x1)^2 + (y - y1)^2 == r1^2}, {x, y}],        Solve         [{y == k x + b /. lineCofficient[x1, y1, r1, x2, y2,r2,style],         (x - x2)^2 + (y - y2)^2 == r2^2}, {x, y}]      } // Flatten[#, 1] &     ]      **_My geometry_**                 FinalGeometry[x1_, y1_, z1_, r1_, x2_, y2_, z2_, r2_, h_] := Block[       {x, y, one, two, three, four},       Graphics3D[       {Cylinder[{{x1, y1, z1}, {x1, y1, h}}, r1],        Cylinder[{{x2, y2, z2}, {x2, y2, h}}, r2],            one = Flatten[         List[           Join[{x, y} /.tangentPoint[x1, y1, r1, x2, y2, r2, -1], {{z1}, {z1}}, 2],          Join[{x, y} /.tangentPoint[x1, y1, r1, x2, y2, r2, -1], {{h}, {h}}, 2]], 1];                     two = Flatten[          List[          Join[{x, y} /.tangentPoint[x1, y1, r1, x2, y2, r2, 1], {{z1}, {z1}}, 2],           Join[{x, y} /. tangentPoint[x1, y1, r1, x2, y2, r2, 1], {{h}, {h}}, 2]], 1];            three = Flatten[         List[          Join[{x, y} /.tangentPoint[x1, y1, r1, x2, y2, r2, -1], {{z1}, {z1}}, 2],          Join[{x, y} /.tangentPoint[x1, y1, r1, x2, y2, r2, 1], {{z1}, {z1}}, 2]], 1];            four = Flatten[         List[           Join[{x, y} /.tangentPoint[x1, y1, r1, x2, y2, r2, -1], {{h}, {h}}, 2],            Join[{x, y} /.tangentPoint[x1, y1, r1, x2, y2, r2, 1], {{h}, {h}}, 2]], 1];            Sequence @@         (Polygon /@            Flatten[{Partition[one, 3, 1], Partition[two, 3, 1],             Partition[three, 3, 1], Partition[four, 3, 1]}, 1])       },         BoxRatios -> Automatic       ]      ]      **Using my function:**                FinalGeometry[0, 0, 0, 3, 12, 0, 0, 2, 2]      ![enter image description here](http://i.stack.imgur.com/GyOUa.png) However, I feel my method is _tedious and ingeneral_ , well as owning surface intersection. In addition there many other geometry "by extruding a section" like in 3D software Autodesk Inventor. So my question is: Is there a good and easy method to realize my function `FinalGeometry`? Is there possible to construct a function that can generate **a geometry that can rotate freely** **(not a static image)** by extruding a section?


Plot groups based on unique tag

I have a .csv file that has 12 columns and 511 rows.               data = Import["C:\\Users\\Documents\\data\\AllResults\\result1.csv"];      The first two columns are id tags. I want to plot the last 10 columns of each row as a separate step function.               Do[Print[DiscretePlot[data[[i, k + 2]], {k, 1, 10}, AxesOrigin -> {0, 0}, ExtentSize -> All,     PlotRange -> {{0, 10}, {0, 10}}]], {i, 511}]      (Please feel free to make it prettier) Now I want to create multiple plots for each unique id in column 1. For example, The first 3 rows of the data have the same column 1 id ("1000_0.01"). I want 4 plots for this id, all in one row, side by side. The first 3 plots are the `DiscretePlot`s of each of the 3 rows in the data and the 4th plot is the summary plot that contains all the 3 plots earlier. **Note:** The data is sorted by the first column, so there is no need for searching.


First 10 digits of $\pi$ without rounding

I need to have $\pi$ with an accuracy of $10$ digits. My first guess would be               N[Pi, 10]       However, this rounds to the last digit instead of just chopping of any additional digits and hence the last digit is $4$ (and not $3$, as it actually is). I could do               N[FromDigits[RealDigits[Pi, 10, 10]], 10]      but I am pretty sure that there are nicer solutions.


Speeding Up Image Processing Functions

I am working with stacks of 1024x1024 timelapse microscopy images that I am performing a series of image processing functions on to help segment each image. These functions include `Sharpen`, `Erosion`, `Dilation`, `RidgeFilter`, `FillingTransform` and `WatershedComponents` (with hand- selected markers). After some trial and error it seems I need to at least use the following functions to arrive at a generally acceptable segmentation:               watershedLabelMatrix = WatershedComponents[RidgeFilter[image],markersForWatershed]      I would like to know if there is anyway to speed up these image processing steps (particularly the bit of code above). I have not had success with use of `Compile` or `Parallelize`. I am not sure if it is possible to Compile a function that takes an image as its argument. Here's one example of what failed for me:               watershedCompile1 = Compile[{{imageIn, _Real}, {markersIn, _Real}},                           WatershedComponents[imageIn, markersIn]]      I get this message after evaluating: > Compile::extscalar: "WatershedComponents[imageIn,markersIn] cannot be > compiled and will be evaluated externally. The result is assumed to be of > type Real." Similarly, when I try to `Parallelize` I am told `WatershedComponents` cannot be parallelized. When I try to use `WatershedComponents` "on the fly" within a little `DynamicModule` interactive notebook I have written that iterates through a stack of images and allows me to save acceptable `WatershedComponent` masks, I get a long (maybe 5 to 10 seconds) pause while I wait for the `WatershedComponents` result and usually see the dreaded _Progress: Formatting Notebook Contents_ dialog window popup. Any suggestions on improving the performance of these image processing functions or suggestions for how to improve performance within a `DynamicModule` (or alternatives to `DynamicModule`) would be greatly appreciated.


Plotting Voxel in mathematica

I am developping a 3D reconstruction application. I recuperate the voxels coordinates (the coordinate of each voxel) of the object that I need to reconstruct. Each voxel have a dimensions like this 5cm*5cm*5cm. I need to reconstruct this volume. I try to use `Image3D` function by put just a 3d binary table representing the voxels that belongs to volume but I could not change the size of each voxel. Any help please?


How do I represent a system dynamics feedback loop?

In System Dynamics, if I want represent the relationship between Speed and Distances, I create a Flow (Speed) and a Stock (Distance) as you can see in this Insight Maker Sample . Heres an Image of how it looks like: ![enter image description here](http://i.stack.imgur.com/dLHaq.png) Now, keeping a constant speed of 20 results in this nice Graph: ![enter image description here](http://i.stack.imgur.com/gPz7Z.png) I know how to represent that in Mathematica, it is easy:               speed = 20     distance = Integrate[speed, time]     Plot[distance, {time, 0, 20}]      That will get me this nice graph: ![enter image description here](http://i.stack.imgur.com/22paN.png) Now I want to do something more complex, I want to add a **feedback loop** , I have already done it in InsightMaker too, it looks like this: ![enter image description here](http://i.stack.imgur.com/aTvlB.png)   * The flow Reproduction is configured as: 20*[Reproduction Rate]   * The stock E. Coli Bacteria is configured as: Initial Value: 1    * The variable Reproductino Rate is configured as: [ E. Coli Bacteria] So I get exponential growth : ![enter image description here](http://i.stack.imgur.com/ge40N.png) My question is: how do I represent this kind of system dynamics model with a feedback loop in Mathematica? **UPDATE** : Here is a table with the values generated by InsightMaker   * Hour 0 E. Coli Bacteria: 1   * Hour 1 E. Coli Bacteria: 21   * Hour 2 E. Coli Bacteria: 441   * Hour 3 E. Coli Bacteria: 9,261   * Hour 4 E. Coli Bacteria: 194,481 Would you be so kind as to please configure your answers to match this results? ( _I am learning as a hobby system dynamics & mathematica and my goal with this question is to understand how to translate a system dynamics diagram to mathematica, so I want to be sure I correctly understad how each part of a system dynamics diagram matches an equivalent mathematica code_)


How create true reflect movement disk in the ellipse?

Help me please. Task: Disk movement inside the Ellipse so that naturally Disk reflected from the walls and continued to move. Thanks. My friend was able make a move on the square only:               x = 0.5;     y = 0.5;          vx = 1;     vy = Pi/2;          step = 0.01;     radius = 0.05;          Animate[           x = x + vx*step;      y = y + vy*step;                If[Abs[x - 1] <= radius || Abs[x] <= radius , vx = -vx];      If[Abs[y - 1] <= radius || Abs[y] <= radius, vy = -vy];           Graphics[       {        Cyan,        Rectangle[{0, 0}, {1, 1}],        Gray,        Disk[{x, y}, radius],         Point[{0.0, 0.0}],         Point[{1.0, 1.0}]        }       ],           {t, 0, Infinity}           ]      P.S. Sorry for my bad english =)


Rounding only coefficients

does Mathematica have built in functionality to round the coefficients of a polynomial to a certain accuracy. Say, we do               Print[0.2134320980x^2+0.0023432x]      Can we wrap a function around the expression in the print so that the output is > >     0.213x^2+0.002x >   I tried `NumberForm` but this rounds messes with the exponent. Thank you!


Button with for loop

How can I call a function that has a for loop inside a button? If I just write               button[{"name", function[]}]      nothing happens.


Interpolation of an upper-triangular list

I have 2d list which is upper triangular. I would like to interpolate it, but I cannot unless I set the interpolation order to 1. I tried making the list rectangular by filling the bottom half with `Null`. This does allow me to interpolate with higher order. However, the interpolation function ends too early; that is, it does not return values when the distance from the boundary (the diagonal elements of the list) is relatively small. I would like to have a full interpolation up to (or very close to) the boundary. any advice? Here is the list that I would like to interpolate.               {{0.103974, 0.103971, 0.103953, 0.103899, 0.103786, 0.103597,        0.103316, 0.102925, 0.102414, 0.10177, 0.100988, 0.100062,        0.0989872, 0.0977656, 0.0963984, 0.09489, 0.0932473, 0.0914792,        0.089597, 0.0876143, 0.0855483, 0.0834163, 0.0812392, 0.0790409,        0.0768409, 0.0746749, 0.0725479, 0.0703533, 0.068163,        0.0666494}, {0.10394, 0.103939, 0.103922, 0.103868, 0.103755,        0.103567, 0.103285, 0.102896, 0.102385, 0.101742, 0.10096, 0.100033,        0.0989584, 0.0977364, 0.0963682, 0.0948584, 0.093214, 0.0914444,        0.0895606, 0.087576, 0.0855068, 0.0833692, 0.0811831, 0.0789712,        0.0767541, 0.0745556, 0.0723645, 0.0701298, 0.0680141}, {0.10387,        0.103868, 0.10385, 0.103795, 0.103683, 0.103495, 0.103214, 0.102825,        0.102314, 0.10167, 0.100887, 0.0999592, 0.0988834, 0.0976591,        0.0962884, 0.0947757, 0.0931276, 0.091353, 0.0894624, 0.0874687,        0.0853863, 0.0832311, 0.0810217, 0.0787762, 0.076513, 0.0742205,        0.0718546, 0.0695221}, {0.103748, 0.103745, 0.103724, 0.103669,        0.103558, 0.103371, 0.10309, 0.102699, 0.102187, 0.101542, 0.100757,        0.0998263, 0.0987467, 0.0975176, 0.0961414, 0.0946217, 0.0929642,        0.0911773, 0.089271, 0.0872567, 0.0851463, 0.0829572, 0.0807012,        0.0783843, 0.0760088, 0.0734579, 0.0706321}, {0.103554, 0.103551,        0.103531, 0.103476, 0.103366, 0.103178, 0.102896, 0.102504,        0.101989, 0.101341, 0.100553, 0.099617, 0.0985308, 0.0972933,        0.0959062, 0.0943723, 0.0926975, 0.0908894, 0.0889562, 0.0869069,        0.0847519, 0.0825056, 0.0801589, 0.0777, 0.0750337,        0.0716811}, {0.103276, 0.103275, 0.103256, 0.103202, 0.10309,        0.102901, 0.102618, 0.102223, 0.101704, 0.101052, 0.100256,        0.0993117, 0.0982145, 0.0969632, 0.0955586, 0.0940032, 0.092303,        0.0904624, 0.0884869, 0.0863832, 0.0841579, 0.081807, 0.0792933,        0.0765284, 0.0728391}, {0.102903, 0.102902, 0.102884, 0.10283,        0.102718, 0.102528, 0.102241, 0.101843, 0.101318, 0.100658,        0.0998522, 0.0988945, 0.0977811, 0.0965098, 0.0950807, 0.0934955,        0.0917577, 0.0898677, 0.0878288, 0.0856427, 0.0832993, 0.0807647,        0.0779256, 0.0740117}, {0.102422, 0.102422, 0.102405, 0.10235,        0.102237, 0.102044, 0.101754, 0.101349, 0.100817, 0.100146,        0.0993255, 0.09835, 0.0972144, 0.0959158, 0.0944531, 0.0928257,        0.091033, 0.089073, 0.0869434, 0.0846283, 0.0820913, 0.0792068,        0.0751356}, {0.101822, 0.101823, 0.101806, 0.101752, 0.101637,        0.10144, 0.101144, 0.100732, 0.100188, 0.099502, 0.0986628,        0.097664, 0.0964989, 0.0951639, 0.0936555, 0.0919695, 0.090102,        0.0880447, 0.0857767, 0.083259, 0.0803534, 0.0761756}, {0.101097,        0.101098, 0.101081, 0.101026, 0.100909, 0.100708, 0.100405,        0.0999814, 0.0994228, 0.0987171, 0.0978542, 0.0968249, 0.0956215,        0.0942383, 0.0926684, 0.090904, 0.0889336, 0.0867302, 0.0842497,        0.0813519, 0.0771066}, {0.100239, 0.10024, 0.100224, 0.100167,        0.100048, 0.0998402, 0.0995268, 0.0990894, 0.0985123, 0.0977829,        0.0968891, 0.0958205, 0.0945678, 0.0931211, 0.0914701, 0.0895987,        0.0874762, 0.0850528, 0.0821852, 0.0779089}, {0.0992445, 0.0992461,        0.0992294, 0.0991719, 0.099048, 0.0988324, 0.0985062, 0.0980515,        0.0974514, 0.0966918, 0.0957588, 0.0946403, 0.0933235, 0.0917941,        0.0900337, 0.0880059, 0.0856582, 0.0828417, 0.0785649}, {0.0981125,        0.0981144, 0.0980973, 0.0980374, 0.0979076, 0.0976814, 0.09734,        0.096864, 0.0962348, 0.0954372, 0.0944552, 0.093273, 0.0918731,        0.0902326, 0.0883131, 0.0860581, 0.0833127, 0.0790662}, {0.0968426,        0.0968454, 0.096828, 0.0967645, 0.0966264, 0.0963876, 0.0960279,        0.0955252, 0.0948597, 0.0940148, 0.0929701, 0.0917054, 0.0901945,        0.0883946, 0.0862476, 0.0835918, 0.079405}, {0.0954383, 0.0954419,        0.095424, 0.0953556, 0.0952077, 0.0949537, 0.0945706, 0.0940344,        0.0933241, 0.0924188, 0.0912934, 0.0899197, 0.0882514, 0.0862242,        0.083675, 0.0795756}, {0.0939058, 0.0939098, 0.09389, 0.0938154,        0.0936557, 0.093382, 0.092969, 0.0923913, 0.0916245, 0.0906417,        0.0894103, 0.0878829, 0.0859885, 0.0835615, 0.0795752}, {0.0922516,        0.0922556, 0.0922334, 0.092151, 0.0919761, 0.0916776, 0.0912276,        0.0905977, 0.0897577, 0.088673, 0.0872931, 0.0855428, 0.0832538,        0.0794039}, {0.0904849, 0.0904886, 0.0904629, 0.0903703, 0.090176,        0.0898463, 0.0893496, 0.0886522, 0.0877159, 0.0864893, 0.0848929,        0.0827551, 0.0790643}, {0.0886172, 0.0886199, 0.0885891, 0.0884833,        0.0882643, 0.0878948, 0.0873377, 0.0865514, 0.0854815, 0.0840469,        0.0820716, 0.078562}, {0.08666, 0.086662, 0.0866252, 0.086502,        0.0862506, 0.0858294, 0.0851927, 0.0842826, 0.0830158, 0.0812123,        0.0779048}, {0.0846302, 0.0846316, 0.0845855, 0.0844381, 0.084145,        0.0836566, 0.0829073, 0.0818115, 0.0801893, 0.0771012}, {0.0825462,        0.0825452, 0.082486, 0.0823086, 0.0819616, 0.081374, 0.0804515,        0.0790206, 0.0761684}, {0.0804289, 0.0804223, 0.0803448, 0.0801253,        0.0796932, 0.0789504, 0.0777197, 0.0751256}, {0.0783023, 0.078285,        0.0781783, 0.0778938, 0.0773324, 0.0763055, 0.0739972}, {0.0761874,        0.0761545, 0.0760065, 0.0756224, 0.074797, 0.0728167}, {0.0741274,        0.0740638, 0.0738307, 0.0732125, 0.0716426}, {0.0721374, 0.0720111,        0.071612, 0.0705599}, {0.0701032, 0.0699286, 0.0694193}, {0.0680611,        0.0679384}, {0.0666374}}      and here is the code I am using               temp1 = ConstantArray[Null, {30, 30}];      Table[temp1[[ixa, ixb]] = data[[ixa, ixb]], {ixa, Range[1, 30]}, {ixb, 30 - ixa + 1}];      F = ListInterpolation[temp1, {{0, 1}, {0, 1}}]


Multiple Forms of Transportation Between Cities

I want to be able to show different connections between cities based on modes of transportation. For instance, you could walk to any city, but it would take a long time, you could take a train, but only to/from certain cities. Is it possible to display all of this on the same graph? Here is what I tried:               Coords = {{40.6642738`, -73.9385004`}, {34.0193936`, -118.4108248`},     {41.8375511`, -87.6818441`}, {29.7804724`, -95.3863425`}};           foot =     {{"NewYork", "NewYork", "UnitedStates"} -> {"LosAngeles",          "California", "UnitedStates"}, {"NewYork", "NewYork",          "UnitedStates"} -> {"Chicago", "Illinois",          "UnitedStates"}, {"NewYork", "NewYork",          "UnitedStates"} -> {"Houston", "Texas",          "UnitedStates"}, {"LosAngeles", "California",          "UnitedStates"} -> {"NewYork", "NewYork",          "UnitedStates"}, {"LosAngeles", "California",          "UnitedStates"} -> {"Chicago", "Illinois",          "UnitedStates"}, {"LosAngeles", "California",          "UnitedStates"} -> {"Houston", "Texas",          "UnitedStates"}, {"Chicago", "Illinois",          "UnitedStates"} -> {"NewYork", "NewYork",          "UnitedStates"}, {"Chicago", "Illinois",          "UnitedStates"} -> {"LosAngeles", "California",          "UnitedStates"}, {"Chicago", "Illinois",          "UnitedStates"} -> {"Houston", "Texas",          "UnitedStates"}, {"Houston", "Texas",          "UnitedStates"} -> {"NewYork", "NewYork",          "UnitedStates"}, {"Houston", "Texas",          "UnitedStates"} -> {"LosAngeles", "California",          "UnitedStates"}, {"Houston", "Texas",          "UnitedStates"} -> {"Chicago", "Illinois", "UnitedStates"}};          car = {{"NewYork", "NewYork", "UnitedStates"} -> {"Chicago",           "Illinois", "UnitedStates"}, {"Houston", "Texas",           "UnitedStates"} -> {"LosAngeles", "California",           "UnitedStates"}, {"LosAngeles", "California",           "UnitedStates"} -> {"Houston", "Texas",           "UnitedStates"}, {"Houston", "Texas",           "UnitedStates"} -> {"Chicago", "Illinois", "UnitedStates"}};          plane = {{"NewYork", "NewYork", "UnitedStates"} -> {"LosAngeles",           "California", "UnitedStates"}};     train = {{"LosAngeles", "California", "UnitedStates"} -> {"Chicago",           "Illinois", "UnitedStates"}, {"Chicago", "Illinois",           "UnitedStates"} -> {"Houston", "Texas",           "UnitedStates"}, {"Houston", "Texas",           "UnitedStates"} -> {"NewYork", "NewYork", "UnitedStates"}};          Graph[foot, VertexCoordinates -> Reverse[Coords, 2],       VertexStyle -> Red, VertexSize -> .1, ImageSize -> 650]      If it helps, the overall goal I'm working towards is not just to display the modes of transportation visually, but to run calculations based on the modes of transportation and routes you could take.


How to find out if invisible notebooks are still open

If I create a notebook `CreateDocument` and I set options such that `Visible -> False`, is there any way to tell if it's still open without setting it back to visible?               outputNotebook = CreateDocument[{}, Visible -> False]      Complication: The initial notebook object reference is reassigned, i.e. I create another document with the same notebook object reference symbol: `outputNotebook = CreateDocument[...]` and then later run the same code. How can I figure out if my first `outputNotebook` (which is invisible) is still open?


What is the proper way to verify that two expressions are equivalent?

First of all, it appears to me that $$\left|\frac{1}{x} + x^2\right| \Leftrightarrow \frac{|1 + x^3|}{|x|}$$ is true. I don't know why, but my attempt to verify it in _Mathematica_ failed.               In[1]:= Abs[1/x + x^2] === Abs[1 + x^3]/Abs[x]     Out[1]= False      It's weird because _Mathematica_ is unable to find a counterexample.               In[2]:= FindInstance[Abs[1/x + x^2] != Abs[1 + x^3]/Abs[x], x, Complexes]     Out[2]= {}


Image correlation

I have two images from motor scan, Image1 is shifted by MxN pixels from Image2. How can I find the shift between Image1 and Image2 ? Image -1 ![1](http://i.stack.imgur.com/laZeT.png) Image -2 ![2](http://i.stack.imgur.com/LAHyF.png) If we compare the shift between the images in terms of {X,Y} I will be able to tell how many steps of the motor scan corresponds to the pixel shift on the image array sensor.


StringForm and NotebookWrite

I'm trying to get my head around NotebookWrite for the last few days. I can't understand why               NotebookWrite[nb,       Cell[        StringForm["some text = ``", 3]       , "Text"        ]]      doesn't seem to produce what I would expect: some text = 3 in the newly defined notebook nb. Why is this? How can this be achieved? Thanks all, once again!


Is there a more Mathematica-y way to label these plots?

I am studying an infinite square well in the context of quantum mechanics.               ClearAll["Global`*"];          (* Length of the well *)     L = 1;          (* The eigenfunctions, n=1,2,3,... *)     u[n_, x_] := Sqrt[2/L] Sin[n π x / L]          (* Probability density function, ρ[x] = |u[n,x]|^2 *)     ρ[n_, x_] := Simplify[u[n, x]\[Conjugate] u[n, x], {n ∈ Integers, x ∈ Reals}]          (* Plots of ρ[n,x] for various values of n *)     Table[ Plot[ρ[n, x], {x, 0, L}, PlotLabel -> "ρ[" <> ToString@n <> ",x]"], {n, 1, 4}]      And here is the output: ![enter image description here](http://i.stack.imgur.com/LpGgM.png) **My questions is** : Can I use Mathematica pattern magic to rewrite `PlotLabel -> "ρ[" <> ToString@n <> ",x]"` ? For instance, I tried (although I knew it wouldn't work): `PlotLabel -> HoldForm@ρ[n,x]`, but that of course leaves `n` unevaluated as well, although I would like `n` to be evaluated and then the result to be held.


How does Mathematica find a series expansion of expressions containing logarithms when there is a singularity at the expansion point?

I am looking for a good approximation to a function containing logarithms, especially at values close to zero. When I used _Mathematica_ 's `Series` command I found something unexpected. _Mathematica_ seems to expand expressions containing a logarithm differently when there is a singularity at the expansion point. For example, the function $(a+\log[x^3+x^7])/(b+x)$ has a singularity at $x=0$. If I use `Series` with an expansion point greater than zero, I get the expected Taylor expansion. However, at the expansion point zero I get $$ \frac{a + 3 \log(x)}{b} + \frac{(-a - 3 \log(x)) x}{b^2} + O(x)^2. $$ It strikes me that the logarithm is retained as a function in $x$. And this result approximates the function much better than that of a simple Taylor series. _Mathematica_ somehow separates the logarithm from the expansion, which I find quite intelligent. I would like to know what technique _Mathematica_ uses and how it is called. I never came across such a thing and would be interested in learning more about it. I understand that `Series` can use several expansions and choses an appropriate one depending on the problem, so maybe this is a special procedure to treat expressions with logarithms. I also found (with some trial and error) that Mathematica's result equals the one I would get if I first did a Taylor expansion of the expression, but treating all logarithms as constants, and then reduced all logarithmic arguments to the lowest power of $x$. Why is this justified?