Write a function that returns the logarithmic derivative

How can we write a function that if we input an expression f, it returns the log derivative $\frac{1}{f} \frac{df}{dx}$. We have to use a conditional or pattern test so that the function accepts any symbols as input except for lists. I will show all my attempts and I have some questions about why certain ways are wrong and why are they wrong. I am new to Mathematica and still not very familiar about how it works. Here are all my attempts:   1).   In: $f = x^{2};$   In: func[f_] = $\frac{1}{f} f'$   Out: $\frac{(x^{2})'}{x^{2}}$   This attempt is wrong because first we are not using conditional or pattern test. Also, Why by using ' sign cannot differentiate the function? 2).   In: $f = x^{2};$   In: func[f_] := $\frac{1}{f} f'$   Out: No output   Why by using delayed assignment, there is no output? 3).   In: $f = x^{2};$   In: func[f_,x_] = $\frac{1}{f} f'$   Out: $\frac{(x^{2})'}{x^{2}}$   Does adding another argument x_ redundant or does it make any difference? 4).   In: $f = x^{2};$   In: func[f_] = Module[{f}, Switch[f, _Symbol, $\frac{1}{f} f'$]]   Output: $\frac{f$8344'}{f$8344}$   The syntax might not make any sense, but I am struggling to find ways to fix it. And I might have used to _Symbol incorrectly, what is _Symbol after all? Now I am trying to write the function in a less general way.   5).   Now In: $f = x^{2};$   In: func[f_] = $\frac{1}{f} D[f,x]$   Output: $\frac{2}{x}$   This method of course works but if I change the input to f = $y^{2}$, the function will return 0 as output.   One way to solve this is by changing to func[f_] = $\frac{1}{f} D[f,y]$, but I think this is considered as cheating, since we are not really answering the question and meeting the requirements set by the question. What really makes me struggle is to compute the derivative, how can we compute the derivative of the input function with respect to its independent variable. Also, I don't fully understand the Switch condition:   It is mentioned in Mathematica Help, that Switch evaluates $expr_i$, then compares it with each of the $form_i$ in turn, evaluating and returning the $value_i$. What is form and what is value?   Suppose I write the function:   In: f[x_] := Switch[x, x>0, 1, x<=0, 0]   In: {f[5], f[-5], f[x]}   Out: {0,0,0}   Am I using the wrong form? Any detailed helps are greatly appreciated. Thanks!


How to get confidence bands of parameters from a fitting procedure?

I have done fitting of data points with a given model that has two parameters (A and B), using `NonlinearModelFit`. The result of the fit is the maximum of the likelihood function, aka the best fit, and the best values for parameters A and B, say (A0, B0). On the A-B plot this would be a single point. There is also a standard deviation given for both parameters separately σA and σB. However, the likelihood function should also give a region on A-B diagram, therefore possible values for A and B that give a good fit - the one that is under a certain confidence level, like 68%. This region is not exactly {A-σA, A+σA} × {B-σB, B+σB}. Instead, {A-σA, A+σA} is probably projection of this region on A-axis. How to get the region of A-B dependence with a specified confidence level (.68, .95, .99) coming from the fit?


Why doesn't Mathematica plot $n(-1)^n$ with Plot?

I was in doubt if this question should be asked in Mathematics.SE or _Mathematica.SE_ , but I've decided this site would be more appropriate, because I think those who read my question here will know about both mathematics and _Mathematica_. I tried to plot $n(-1)^n$ with `Plot`, but it showed nothing. When I tried to plot it with `DiscretePlot`, it worked. Why did that happen?


Method used by FindFit

Using `FindFit`, _Mathematica_ selects an optimal algorithm when `Automatic` is selected. I'd like to know the name of the method applied to the `FindFit` computation. Is there any option to explain that?


How to get Cases to wrap results in an arbitrary head?

A number of functions provide for results to be wrapped in an arbitrary head. This is very important in cases where the results should not be evaluated. Take `Level` as an example:               expr = Hold[{2/2, g[8/4], 1/0}];          Level[expr, {-2}, Hold]      > >     Hold[1/2, 1/4, 1/0] >   `Cases` however provides no such parameter, causing undesired evaluation:               Cases[expr, _Times, 3]      > Power::infy: Infinite expression 1/0 encountered. >> >   >   >     {1, 2, ComplexInfinity}  (* failure *) >   How can this behavior be attained?


Not FullDefinition for Save. MachineID not Protected?

Is there a way to set what symbols's definitions I do not want to store? Consider the following code:               f := $MachineID;     SetDirectory[NotebookDirectory[]];     Save["testm.m", f];          ClearAll@f          << "testm.m"     f      > >     Set::specset: Cannot change the value of special symbol $MachineID. >> >     0000-00000-00001 (*id of storing machine*) >     0000-00000-00002 (*id of getting machine*) >   This happens bacause `testm.m` contains: > >     f := $MachineID >     $MachineID = "0000-00000-00001" >   **Questions:**   * Is there nicer way to avoid this than my approach:              f:= Symbol["MachineID"]       ?   * Is it `Protected` attribute which decides what is going to be stored? Because there is no problem if `f:=SystemID` but:              Attributes[{$SystemID, $MachineID}]      > >     {{Locked, Protected}, {}} >   **Edit** :   * Why `MachineID` is not protected? - **The bounty is founded for this question.**


On the order of rules specification

I wanted to understand how Mathematica parses function definitions in rules- based programming, so I started with the simple code:               Clear[f];     f[x /; MatchQ[x, {_?NumericQ, _?NumericQ}]] := Total@x;     f[x_] := -1;     f[{1, 2.3}]     f[{4}]      As expected, the output is:               3.3     -1      Then I added another line:               Clear[f];     f[x /; MatchQ[x, {_?NumericQ, _?NumericQ}]] := Total@x;     f[x ;/ MatchQ[x, {_?NumericQ, 0}]] := (2 * x)[[1]];     f[x_] := -1;     f[{1, 2.3}]     f[{1, 0}]     f[{4}]      Interestingly, the output is now:               3.3     1     -1      So the second rule specification did not really override the first rule. But now, if I put that second rule `before` the first rule, like so:               Clear[f];     f[x ;/ MatchQ[x, {_?NumericQ, 0}]] := (2 * x)[[1]];     f[x /; MatchQ[x, {_?NumericQ, _?NumericQ}]] := Total@x;     f[x_] := -1;     f[{1, 2.3}]     f[{1, 0}]     f[{4}]      I get the expected output:               3.3     2     -1      So, I am guessing if I want multiple rules, I should put the more restrictive ones before the general ones. This way, Mathematica will be able to use the first match to execute the appropriate function. But now consider this:               Clear[f];     f[x_] := -1;     f[x /; MatchQ[x, {_?NumericQ, _?NumericQ}]] := Total@x;     f[x ;/ MatchQ[x, {_?NumericQ, 0}]] := (2 * x)[[1]];     f[{1, 2.3}]     f[{1, 0}]     f[{4}]      The most general rule is at the top, yet the output is:               3.3     2     -1      Can someone please explain why Mathematica didn't just see every input as matching `f[x_]` and simply return `-1`? Thanks in advance.


Multiple down-values with exactly the same lefthand side

I was working on an answer to this question, when I was sidetracked by what I bring up here. I wanted a function, which when given a string representing a binary number, would convert the string to a list of digits. I wanted to reject any invalid strings and to return the function expression unevaluated an invalid string was rejected. I had a lot of trouble debugging the function. My edits to the function body didn't seem have any effect. Finally, in desperation, I got to performing `Clear[bitsToDigits]` before making an edit. This allowed to complete my debugging, but left me very puzzled because I have come to expect edits which don't effect the first argument of a `SetDelayed` not to require clearing the function's identifier. In such cases, I have come to expect evaluating `SetDelayed` to replace the old down-value with the new one. I decided to look at the down-values after making a second definition of now working function, but not to clear before evaluating it.               bitsToDigits[bitstr_String] :=       With[{result =         Module[{valid, bits = Characters[bitstr]},           valid = StringFreeQ[bitstr, Except["0" | "1"]];           If[valid, bits, False, False]]},         result /; result =!= False]          bitsToDigits[bitstr_String] :=       With[{result =                If[StringFreeQ[bitstr, Except["0" | "1"]],                   Module[{bits = Characters[bitstr]}, bits], False, False]},         result /; result =!= False]      I now looked at the down-values               DownValues[bitsToDigits]      To my horror, the result was > >     { >        HoldPattern[bitsToDigits[bitstr_String]] :> >          With[{result = >            Module[{valid, bits = Characters[bitstr]}, >              valid = StringFreeQ[bitstr, Except["0" | "1"]]; >              If[valid, bits, False, False]]}, >            result /; result =!= False], >        HoldPattern[bitsToDigits[bitstr_String]] :> >          With[{result = >                  If[StringFreeQ[bitstr, Except["0" | "1"]], >                    Module[{bits = Characters[bitstr]}, bits], False, > False]}, >            result /; result =!= False] >      } >   The new version of my function will never be executed because the older definition will always match first. This was totally unexpected. Should I have expected this? Is there something wrong with my definitions of `bitsToDigits`? If so, how should I fix them? Or have I found a bug? I have verified that my problem occurs in both V9 and V10 running on OS X. ### update Mr.Wizard has answered my question as originally posted, but I would be keen to learn if there is a way to implement the behavior I want without the distressing side effect, which interferes with my ingrained code development habits.


Faster Eigenvalues with lower precision goal

I compute all eigenvalues of a large matrix, and I decide that the speed is more important than the precision. Then the question is, can I speed up `Eigenvalues[]` by setting a lower precision goal? For example, consider a real symmetric random $100\times 100$ matrix:                In[1]:=  A = # + Transpose[#] &@RandomReal[{-1, 1}, {100, 100}];      and compute                In[2]:=  Do[Eigenvalues[A], {10}]; // AbsoluteTiming      Out[2]=  {0.019001,Null}      In real computation I may use a matrix much larger than $100\times 100$, and the computation would take much longer time than $0.019$ seconds. I want to speed up the computation. Can I set a lower precision goal, say `3`, so that `Eigenvalues[]` runs fuster? So I tried                In[3]:=  Do[Eigenvalues[SetPrecision[A, 3]], {10}]; // AbsoluteTiming      Out[3]=  {12.358707,Null}      The precision of the results is `3`, but the computation took `12.36` seconds. This is not what I want. Is there a clever way to speed up `Eigenvalues[]` by setting precision goal to be `3`?


Quadratic Equations mod p^k

As part of a larger program, I need to solve $A x^2+B x+C \equiv 0 \mod p^k$ for prime $p$. Right now I'm doing this by calling `Reduce[A*x^2+B*x+C==M*p^k,{x,M},Integers]` and then parsing this to find what I need (i.e. usually just assigning `C[1]->0` and ignoring `M` results). But when $A$, $B$, $C$, and especially $p^k$ start to get large (e.g. $A,B,C \approx 10^{30}$ and $p^k \approx 10^{70}$), there is quite a lag. Is there a faster way to find solutions for $x \mod p^k$? Thanks!


check if the expression is a equation

I need to check if the expression is a correct equation with only 1 variable x and without functions, that are not build into Mathematica. For example               Sin[x]==0       is correct equation. And expressions               Sin[x*a]==0, Sin[[x]==0, f[x]==0, Exp[x]=9       are not correct equations.


Differential curve geometry Frenet Formula

I am using Mathematica for differential geometry studies using Frenet Formulae. The problem is that I need to graph the solution curve r[t]. Suppose the curvature of a curve is k(s) = |s|and the torsion of a curve t(s)(s) = .3. Starting with the initial conditions with T,N, B being i, j, k,I have to graph the solution curve r(t) that has this data. Can anyone suggest me how to go ahead with this? T'(s) = k(s) N(s), N'(s) = - k(s) T(s) + t(s) B(s), B'(s) = - t(s)N(s). Here T, N, B are the unit tangent and unit normal and B is the unit binormal B = T * N


Is there a "precedence table" for the canonical Sort ordering?

This answer in which I wrote about the Operator Precedence Table was unexpectedly popular.   That got me thinking about similar things, and I am wondering: **Does an "ordering table" exist for the canonical order used by`Sort` and similar functions?**   (`Ordering`, `Order`, `OrderedQ`) It's easy enough to test the ordering of various expressions, but just as the precedence table contains some surprises even for experienced users I'm wondering if the canonical ordering does too? It seems odd if this isn't spelled out clearly somewhere, yet I don't recall seeing such a list. The documentation for `Order` tantalizingly says: > Order uses canonical order as described in the notes for Sort. Yet the documentation for `Sort` is quite basic, as far as I can find, saying only:   * Sort by default orders integers, rational, and approximate real numbers by their numerical values.   * Sort orders complex numbers by their real parts, and in the event of a tie, by the absolute values of their imaginary parts.   * Sort orders symbols by their names, and in the event of a tie, by their contexts.   * Sort usually orders expressions by putting shorter ones first, and then comparing parts in a depth-first manner.   * Sort treats powers and products specially, ordering them to correspond to terms in a polynomial.   * Sort orders strings as in a dictionary, with uppercase versions of letters coming after lowercase ones. Sort places ordinary letters first, followed in order by script, Gothic, double-struck, Greek, and Hebrew. Mathematical operators appear in order of decreasing precedence. This describes how `Sort` treats certain classes of expressions but it doesn't describe the relative ordering of these classes or attempt in any way to be exhaustive.


Finding the location of the last day of the month in a list of dates

My question differs from earlier questions about getting the eom dates from a list; I want to get the position of those dates so I can get the corresponding values from other lists. My problem seems to boil down to one about how to use `Position` where _pattern_ is a list. It's an ordinary list of about 5000 dates.               dates[[1 ;; 5]]     {{1995, 1, 31}, {1995, 2, 1}, {1995, 2, 2}, {1995, 2, 3}, {1995, 2, 6}}      As I said, I know how to get the eom dates (there are 229), but I can't seem to make `Position` work with a list.               Map[Last, GatherBy[dates, {#[[1]], #[[2]]} &]][[1 ;; 5]]     {{1995, 1, 31}, {1995, 2, 28}, {1995, 3, 31}, {1995, 4, 28}, {1995, 5,31}}      So, here's the kluge. Partition the dates into pairs. Map a function over the list of pairs that returns 1 if the day of the second member is less than the day of the first member, and zero otherwise. Finally, get the position of the members of this list that equal 1.               p = Flatten[Position[If[#[[2,3]]-#[[1, 3]]<0,1,0]&/@ Partition[dates,2,1],1]]     {1, 21, 44, 64, 87, 109, 130, 153, 174, 196, 218, 239,...}      And here is the list of values:               csh[[p]]     {114.141, 115.698, 116.331, 117.328, 119.333, 119.983,...}      It works, but it seems kind of clumsy.


Inconsistent results for equivalent converging symbolic integrals

I have looked at previous questions and I'm aware that this seems to be a known bug: _Mathematica_ giving inconsistent results for symbolic integrals done in different ways. The origins for the bugs seem to be varied. I'm having a hard time tracking down _where_ Mathematica is going wrong with this particular one, especially since I am explicitly assuming that all my variables ($L$ and $\rho$) are positive. I've played around with the assumptions without any luck. Here's my code:               $Assumptions = {ρ > 0, L > 0};          limits = Sequence[{ux, 0, L}, {vx, 0, L}, {uy, 0, ux}, {vy, 0, vx}]          N1 = Integrate[a1 = Exp[-ρ (ux - uy) (vx - vy)], limits];     N2 = Integrate[a2 = Exp[-ρ (ux - uy) (vx - vy)] (ρ (ux - uy) (vx - vy)), limits];     N3 = Integrate[a3 = Exp[-ρ (ux - uy) (vx - vy)] (ρ (ux - uy) (vx - vy))^2, limits];     N4 = Integrate[a4 = Exp[-ρ (ux - uy) (vx - vy)] (ρ (ux - uy) (vx - vy))^3, limits];          int1 = Integrate[4 ρ (a1 - 7/2 a2 + 2 a3 - 1/4 a4), limits]          int2 =  Simplify[4 ρ (N1 - 7/2 N2 + 2 N3 - 1/4 N4)] // Expand      Apologies for the large expressions but the particular simplifcations only happen when all four integrands are included with the correct factors. By comparing integrands it's easy to see that `int1` and `int2` are the same integrals. But for `int1` I get               (1 - E^(-L^2 ρ)) L^2      whereas for `int2` I get               L^2 - E^(-L^2 ρ) L^2 - (7 L^4 ρ)/4 + 7/2 L^4 ρ Log[L]      I know that the outcome for `int1` is correct whereas that for `int2` is incorrect. Any thoughts would be very welcome.


Simplify rearranges equations?

I've been using `Simplify/FullSimplify` to simplify some nasty equations, and by and large it does well but sometimes it rearranges equations in an unhelpful way. Here's a simple example. Say `x` is a positive number (standing in for some generally much more complicated factors),               $Assumptions=x>0      I have an equation like               eq = x^2 (a + b - 2 c^2 b) == 0     eq // Simplify      > >     a + b == 2 b c^2 >   But I don't want it to move terms from the `LHS` to the `RHS`, splitting up terms proportional to `b`. I want them grouped together. I can use `Collect` to keep these terms together, but then I have no way of dividing out the `x^2`. I could use `Collect` then divide out the `x^2` manually, but the terms I'm using `x^2` to stand in for are quite unwieldy, and it would be quite laborious to do this case-by-case, especially when `Simplif`y does it right away. **My question** : Is there any simple way to take `eq` and output > >     a + b - 2c^2 b == 0 >     (* or *) >     a + (1-2c^2)b ==0 >   without explicitly specifying that I want to divide out `x^2` (since `Simplify` divides this out automatically)?


Digital Elevation Maps (DEM) are Warped yet ReliefPlot renders as a rectangle - how do i join?

I downloaded several USGS Digital Elevation Maps (DEM files) corresponding to 12 adjacent areas. Each file Imports[] into _Mathematica_ and I can render the individual `ReliefPlot`s easily. The intent was, however, to create a mosaic by joining the individual images. Unfortunately, each DEM is warped and when I render using `ImageAssemble` there are triangular gaps between each `ReliefPlot`. Does anyone know if there is a simple way of using _Mathematica_ to orthogonalise the tiles so they can be assembled without gaps? It seems like `Import` pads the gaps using a number corresponding to a corner thereby creating an array that can be processed by `ReliefPlot`. I gather the issue stems from fact each tile is a quadrangle defined using UMT coordinates so I'm hoping the Geodesy package will help effect the transformation. However, having looked at the Geodesy functions I can't see the wood for the trees! Is there a simple fix. And is there a tutorial or book for the package?


How to create a writable and clearable symbol?

I'm trying to create several symbols and assign values to them. Here's what currently appears to work:               Evaluate[Symbol["fdds" <> ToString[10]]] = 1      But there's then another problem: I can't clear it without explicitly saying `fdds10`, i.e. this code               Evaluate[Symbol["fdds" <> ToString[10]]] =.      as well as this               Clear[Evaluate[Symbol["fdds" <> ToString[10]]]]      give errors: the former gives > Unset::usraw: Cannot unset raw object 1. >> and the latter results in > Clear::ssym: 1 is not a symbol or a string. >> How do I create good easily manageable symbols? PS: I know I could use something like `fdds[[10]]` here, but I'm interested in symbol-based solution.


Solving a Trigonometric parameter

I have a similar case as given before : Solving a Trigonometric function with one parameter Let:               m = 1;     Dx = 100;     ν = 0.25;     b = 1;      and,               λ1 = Sqrt[(((m^2)*(π^2))/a^2) + Sqrt[(n*(m^2)*(π^2))/(Dx*(a^2))]];     λ2 = Sqrt[(-(((m^2)*(π^2))/a^2)) + Sqrt[(n*(m^2)*(π^2))/(Dx*(a^2))]];     ω1 = ((λ1^2) - ν*((m^2) + (π^2))/a^2);     ω2 = ((λ1^2) - ν*((m^2) + (π^2))/a^2);      Now I have the following equation,               2*ω1*ω2 + ((ω1^2) + (ω2^2))*Cosh[λ1*b]*Cos[λ2*b] -        1/(λ1*λ2)*(((λ1^2)*(ω2^2)) - ((λ2^2)*(ω1^2)))*Sinh[λ1*b]*Sin[λ2*b] ==       0      Which is needed to be solved for the smallest Value of `n` as a function of ratio `a/b` Taking a similar solution given previously in the link I try:               solutions =       Table[{a,         Min[n /.           NSolve[2*ω1*ω2 + ((ω1^2) + (ω2^2))*Cosh[λ1*b]*Cos[λ2*b] -               1/(λ1*λ2)*(((λ1^2)*(ω2^2)) - ((λ2^2)*(ω1^2)))*Sinh[λ1*b]*               Sin[λ2*b] == 0 && 0 < n < 10, n]]}, {a, 0.1, 1, 0.1}]          ListLinePlot[solutions]      Which gives me errors               is neither a list of replacement rules nor a valid dispatch table, \     and so cannot be used for replacing. >>      I am stuck with this one, can anyone see why?


How do I export a text file with strings on different lines?

I would like to `Export` a text file, and use paragraph / ENTER commands to place different strings on different lines. Say we have three strings - str1, str2, and str3. How can we place them on separate lines of a text file? This command -               Export["test.txt", StringJoin[str1, str2, str3]];      Places str1, str2, and str3 on a single line.


Custom BoxWhisker Plot

I’d like to figure out how I can show my entire dataset overlaid on a box whisker plot.               data = {{0.763983, -1.11426, 1.05153, -0.0369066, 1.1571, 0.834856, 0.146695,     0.100646, 2.69399, 0.425281}, {0.506237, 1.05127, 1.58117,      0.976295, 1.62204, 1.39005, 1.62387, 1.36098, 1.83858,      0.709489}, {-1.62786, 0.947744, 4.50628, 0.444416, 1.30947, 0.60594,     0.890642, 4.04505, 4.57667, 0.781394}}      The following allows me to show Outliers overlaid on the plot. How would I go about overlaying all of the datapoint on the plot?               BoxWhiskerChart[data, {"Notched", {"MedianMarker", Blue}, {"Outliers",      "\[EmptySmallCircle]", Red}},ChartLabels -> {"X", "Y", "Z"}]


Testing Credit Usage in Wolfram Programming Cloud

I currently have a free WPC account, which I am using for testing purposes. Amongst other things, I want to find out more about how the credit system works, in particular how many credits are used, based on various different operations. However, whenever I try to access the Usage Summary Report in my WPC account I receive the following, unhelpful error message: "Sorry you do not have permission to access this item. Try using a different account." Are free WPC accounts not provisioned with access to usage reports? How does one budget credit usage without such information?


Matrix Plot – Little Exercise

Hi there, mathematicians. I'm not very good at coding plots in _Mathematica_ , so I was hoping that one of you could help me solve a problem I'm having. I have the following matrix plot:               Z = {Subscript[x, 0], Subscript[x, 1], Subscript[x, 2]}     X = {{0, 8, 12}, {.1, 0, 0}, {0, .2, 0}}      Then I put it in a function as follows:               P[x_] := X^x.Z      I would like _Mathematica_ to display plots such that, whenever x iterates from 1 to 10 in the function, the x1, x2, and x3 from the matrix are respectively plotted in three plots. Can anyone help me? * * * **EDIT: Trying to be more clear** I have the matrix (mat) and the vector (v):               mat = {{0, 8, 12}, {.1, 0, 0}, {0, .2, 0}}     v = {x0, x1, x2}      Then later I define the function for population development, `pD`, taking `t` (for time in days) as its only parameter.               pD[t] = mat^t.v      Now I would like to show the development of the variables $x_1$,$x_2$, and $x_3$ assuming the values 30, 60, 30, respectively. I would do so by making plots of the three functions over the range 1 to 10 days. For each the first plot should display the values of $\{t,pD[t_{x_1}]\}$, the second the values of $\{t,pD[t_{x_2}]\}$, and the third the values of $\{t,pD[t_{x_3}]\}$. I hope this clarifies my question. Sorry for being so unconventional in the first place. However, having worked my eyes blind for quite some time, I presumed that it was anything but difficult to understand. Thanks for your patience! * * * Best regards, Brinck10


How can I plot the real and imaginary parts of a complex function given by an implicit equation?

My equation is               I e2 s2 w (m1^2 m2 q1 s1^2 s2 + m1 m2^2 q2 s1^2 s2 + m1^2 q1 s1^2 s2 ζ -        m2^2 q2 s1^2 s2 ζ - 2 m1 q1 s1^2 s2 ζ^2 - m2 q1 s1^2 s2 ζ^2 + m1 q2 s1^2 s2 ζ^2 +        q1 s1^2 s2 ζ^3 - q2 s1^2 s2 ζ^3) +      1/w s1 γ ζ^3 (2 I m2^2 q2 s1 s2^2 ζ + 2 I m2 q1 s1 s2^2 ζ^2 -        2 I m2 q2 s1 s2^2 ζ^2 - 2 I q1 s1 s2^2 ζ^3) -      I (m1^2 m2 q1 s1 s2^2 + m1 m2^2 q2 s1 s2^2 - m1^2 q1 s1 s2^2 ζ + m2^2 q2 s1 s2^2 ζ +        m2 q1 s1 s2^2 ζ^2 - m1 q2 s1 s2^2 ζ^2 - 2 m2 q2 s1 s2^2 ζ^2 - q1 s1 s2^2 ζ^3 +        q2 s1 s2^2 ζ^3) (-e1 s1 w + (s1 γ ζ^3)/w) == 0      and               m1 = Sqrt[ζ^2 - I*w/s1]; m2 = Sqrt[ζ^2 - I*w/s2];      The independent variable is `w`. All the other variables are constant except `ζ` (complex number).               q1 = 1; q2 = 0.5; e1 = 1; e2 = 0.8; s1 = 1; s2 = 0.6; γ =1000;      I used `FindRoot` and solved this problem. `FindRoot` gives the solution only for one case of `w`, but I want to plot the graph of `w` and `ζ`. How do I plot `Re[ζ]` vs.`w` and `Im[ζ]` vs. `w`?


Obtaining Size Of Graphical Objects

I have created a panel, say `Panel[""]`. I want to know its size/dimensions. Is there any built-in function for doing that?


Fit text to a path

> **Possible Duplicate:**   >  Movable text on a curve This is a common feature among vector-based graphics suites (e.g. Illustrator), so I was wondering how it could be done in Mathematica. Here's an example: ![enter image description here](http://i.stack.imgur.com/vcg4z.png) I'm pretty sure one has to "vectorize the font" first, as demonstrated here under "neat examples," but beyond that, I'm stuck. In Illustrator, one can choose to align the text to the path using the baseline, ascenders, descenders, and also choose various methods of fitting the path to the curve ("rainbow," "skew," "3D ribbon," "stair step," "gravity"), but I would be satisfied with a solution that uses the lowest point in a string of text (i.e. the descender), and uses the "rainbow" style of Illustrator, as is shown in the above example. For simplicity, let's just align the above string ("The quick brown fox jumped over the lazy dog") with the Sin function.


Automatic substitution of fractions

I have several equations with many variables, and here and there I would like to do a variable substitution. For example, in the equation:               a (b + 42 c / d)      I might want to remap variables _a * b --> p_ and _a * c / d --> q_ in order to get:               p + 42 q       Can _Mathematica_ do this? I tried to play with the `With[]` and `Rule[]` function and the like, but that doesn't seem to produce anything. I can imagine that _Mathematica_ is not capable of doing such a thing, but I thought it would be worth asking. **And the pro question:** And then very much related to this: is there a way to use `With[]` not to set a single variable but to set variable relations, e.g. the sum or product of two variables. So that this:               With[{a * b = 5},  a (b + 42 c / d)] (* This doesn't work*)      would reduce to:               5 + 42 a * c / d


Nested Map and Apply

There are some other questions on this topic but I could not get an answer from reading them. What I want to do is use `Apply` on some of the arguments of a function, `h`, and then `Map` on another argument. Here is what I attempted:               Map[Apply[{h[#, ##]} &, {a, b}] &, {1, 2}]     (* ===>{{h[a, a, b]}, {h[a, a, b]}} *)      The elements I want to `Map` over never get used. But this is not what I want. I want just               {h[1,a,b],h[2,a,b]}      I could use Table instead of Map but it's slow (slower than just using `Apply` twice) and I was hoping `Map` would be faster. I understand that `Apply` is using both `#` and `##` but I'm not sure what syntax is correct to force the first `Slot` to be used by `Map` instead of `Apply`. EDIT: This is more like what I actually want to do:               Map[Apply[{h1[#, ##],h2[#, ##]} &, {RandomReal[], RandomReal[]}] &, {1, 2}]      So I want output as               {{h1[1, a1,b1], h2[1, a1,b1]},{h1[2, a2,b2], h2[2, a2,b2]}}      where I `a`'s and `b`'s are the random numbers. So to get this, I think the order of `Apply` and `Map` is important.


PlotLegends doesn't work on Plot3D-V8.0.0

I am trying to plot in 3D and I need to use `PlotLegend`. My code is               Needs["PlotLegends`"]     Evaluate[PlotLegends]     Plot3D[Tanh[H/T], {T, 0, 300}, {H, 0.001, 1},      PlotLabel ->        Style[Framed[         "Energy Dependance on Magnetic Field H and Absolute Temperature \     T"], 13, Red, Background -> Lighter[LightYellow]],       Background -> LightGray,       ColorFunction -> Function[{x, y, z}, Hue[.65 (1 - z)]],       AxesLabel -> {T[kelvin], H[tesla]}, BoundaryStyle -> Thick,       ClippingStyle -> Opacity[0.5], Mesh -> Full,       PlotLegends -> Automatic]      While I use `Needs["PlotLegends`"]` I don't seem to be able to plot a legend. I get an error saying _Plot3D::optx: Unknown option PlotLegends in Plot3D[...]_ How can this be fixed?


Programming- cryptography

I have defined the following function in _Mathematica_ to get a SET OF `m` SETS (these sets are the codes `{p,q,d,e,n}` for the encryption system `RSA`.):               RSA[m_] :=        Table[          Module[{prime, p, q, k, factors, d, e, n,ans},                 prime = RandomPrime[{2, 10^2}, 2]; p = prime[[1]]; q = prime[[2]];                k = (p - 1)*(q - 1) + 1; factors = FactorInteger[k];                 d = RandomChoice[factors][[1]]; e = k/d; n = p*q;                 ans = {p, q, d, e, n}; ans],         {i, 1, m}];      The problem is that although it is not very probable, these sets can be repeated, and I would like to avoid this case, but I have no idea. I have tried using the _Mathematica_ function `Union`, in which reapeted sets wouldn't be included, but I don't know how to add more in order to get just m elements (sets).


A* algorithm for finding shortest path in a graph

FindShortestPath finds the shortest path between two vertices in an edge- weighted graph, allowing a choice between the Dijkstra and Bellman-Ford algorithms. In my (limited) understanding, both of these algorithms fall into the breadth-first category. My question is if there are accessible implementations of depth-first shortest path algorithms like A* for edge-weighted graphs in Mathematica. I am aware of the question How to display each step of an A star algorithm?, but before delving into modifying that code so as to work with weighted graphs I wanted to make sure that I don't re-invent the wheel. In fact, I haven't been able to locate an efficient implementation (using fancy data structures etc.) of A* for edge-weighted graphs in _any_ programming language, but that would probably be a question for another site.


How to construct a coordinate system that owns detailed calibration in the 3D enviroment?

**_Recently,I write a program to demonstrate the forward kinematics of the SCARA robot.The code showed as below:_** **Using this function to construct the`BigArm` and `SmallArm` of SCARA robot.**               KeywayGeometry[color_List, coordinate_List, length_, height_, radius_,                    rotation_List] := Block[     {KeywayGeometryResult},      KeywayGeometryResult =      {       Rotate[         {color[[1]], Dashed, Thick,          Line[{coordinate - {0, 0, 2}, coordinate + {0, 0, height + 2}}],          Line[{coordinate + {length, 0, -2}, coordinate + {length, 0, height + 2}}],          color[[2]],          Cylinder[{coordinate, coordinate + {0, 0, height}}, radius],          Cuboid[coordinate - {0, radius, 0}, coordinate + {length, radius, height}],          Cylinder[{coordinate + {length, 0, 0}, coordinate + {length, 0, height}}, radius]},         Sequence @@ rotation       ]      }     ]      **Main program**                Manipulate[      Block[           {CoodinateSystem, ModelCoodinateSystem, Base, BaseHeight = 14,            BigArm, BigArmLength = 35, BigArmHeight = 4, BigArmRadius = 2,            SmallArm, SmallArmLength = 20, SmallArmHeight = 4, SmallArmRadius = 2,            LiftMechanism, LiftMechanismHeight = 18, Wrist,px, py},         px = BigArmLength Cos[θ1] + SmallArmLength Cos[θ1 + θ2];         py = BigArmLength Sin[θ1] + SmallArmLength Sin[θ1 + θ2];       CoodinateSystem =          {           Sequence @@ Flatten@           ({#1, Arrowheads[.02], Arrow[Tube[#2]]} &@@@           {            {Lighter@Red, {{0, 0, 0}, {10, 0, 0}}},            {Lighter@Green, {{0, 0, 0}, {0, 10, 0}}},            {Blue, {{0, 0, 0}, {0, 0, 10}}}           }),           Lighter@Red,           Sequence @@            (Text[Style[#1, Bold, 12, FontFamily -> Times, Italic], #2] & @@@           {            {"x", {12, 0, 0}}, {"y", {0, 12, 0}}, {"z", {0, 0, 12}}           })          };       ModelCoodinateSystem =          {           Sequence @@ Flatten@           ({#1, Arrowheads[.02], Arrow[Tube[#2]]} &@@@           {            {Lighter@Red, {{0, 0, BaseHeight + BigArmHeight},             {10, 0,BaseHeight + BigArmHeight}}},            {Lighter@Green, {{0, 0, BaseHeight + BigArmHeight},             {0, 10, BaseHeight +BigArmHeight}}},            {Blue, {{0, 0, BaseHeight + BigArmHeight},             {0, 0, 10 + BaseHeight + BigArmHeight}}}           }),          };      Base =       {        RGBColor[1, .5, .5, .6],        Cylinder[{{0, 0, 0}, {0, 0, 2}}, 3],        Cylinder[{{0, 0, 2}, {0, 0, BaseHeight}}, 2]       };      BigArm =        KeywayGeometry[          {Red, Blue}, {0, 0, BaseHeight}, BigArmLength, BigArmHeight, BigArmRadius,                     {θ1, {0, 0, 1}, {0, 0, 0}}];      SmallArm =        KeywayGeometry[          {Green, Purple},{BigArmLength Cos[θ1], BigArmLength Sin[θ1],           BaseHeight + BigArmHeight}, SmallArmLength, SmallArmHeight, SmallArmRadius,          {θ1 + θ2, {0, 0, 1}, {BigArmLength Cos[θ1],            BigArmLength Sin[θ1], 0}}];       LiftMechanism =       {        Rotate[         Cylinder[         {{px, py, BaseHeight + BigArmHeight - d3},         {px, py, BaseHeight + LiftMechanismHeight + BigArmHeight - d3}}, 1],         θ1 + θ2, {0, 0, 1}, {px, py, 0}]       };      Wrist =       Flatten@({#1, Cylinder[#2, #3]} & @@@       {        {Green, {{px, py, BaseHeight + BigArmHeight - d3}, {px, py,            BaseHeight + BigArmHeight - d3 - .5}}, 2.5},        {Red, {{px + 2 Cos[θ1 +θ2 - θ4],py + 2 Sin[θ1 +θ2 - θ4],            BaseHeight + BigArmHeight - d3 - .5},          {px + 2 Cos[θ1 + θ2 - θ4], py + 2 Sin[θ1 + θ2 - θ4],            BaseHeight + BigArmHeight - d3 - 2}}, .5},        {Orange,          {{px + 2 Cos[θ1 + θ2 - θ4 + π], py + 2 Sin[θ1 + θ2 - θ4 + π],            BaseHeight + BigArmHeight - .5 - d3},          {px + 2 Cos[θ1 + θ2 - θ4 + π], py + 2 Sin[θ1 + θ2 -θ4 + π],            BaseHeight + BigArmHeight - 2 - d3}}, .5}       });      Panel[         Graphics3D[           Sequence @@ # & /@        {CoodinateSystem, ModelCoodinateSystem, Base, BigArm, SmallArm, LiftMechanism, Wrist},      BoxRatios -> Automatic, ImageSize -> 550, ViewPoint -> {80, -60, 15},       PlotRange -> {{-60, 60}, {-60, 60}, {0, 45}}],       Style["SCARA Model Demostration", FontFamily -> "SketchFlowPrint",Red, 15]]     ],      {{θ1, 20 \[Degree], "θ1"}, -100 \[Degree], 100 \[Degree]},      {{θ2, 50 \[Degree], "θ2"}, -150 \[Degree], 150 \[Degree]},      {{d3, 5, "d3"}, 0, 10},      {{θ4, 20 \[Degree], "θ4"}, -180 \[Degree], 180 \[Degree]},      ControlPlacement -> Bottom,       FrameLabel -> Style[" The Kinematics of SCARA Robot " , FontFamily -> Times, 15,Purple]      ]      **_It generrate the picture as below:_** ![SCARA Model](http://i.stack.imgur.com/6YIQS.jpg) **_However,I want add a`module` that can show `the position of the endeffector of SCARA robot.` or help the user to read the coordinate of the endeffector._** **I have a method that construct a coordinate system that owns detailed calibration.Unfortunately,`I don't know how to write the code`**


Can I use a custom (Frame)Ticks specification to define the PlotRange?

The documentation for `Ticks` and `FrameTicks` shows how one can define a function for custom ticks or frame ticks, for example:               niceTicks[min_, max_, n_: 7] := FindDivisions[{min, max}, n]      After creating some example data               fakedata1 = FoldList[0.99 #1 + #2 &, 1.,         RandomVariate[NormalDistribution[0, 1], {100}]];      We can see that `FrameTicks` specifications will allow for functions, and will automatically pass the minimum and maximum of the data set as arguments.               ListLinePlot[fakedata1, Frame -> True, PlotRange -> All, PlotRangePadding -> 0,       FrameTicks -> {{niceTicks, None}, {Automatic, None}}]      ![enter image description here](http://i.stack.imgur.com/jvylT.png) Similarly one could use:               ListLinePlot[fakedata1, Frame -> True, PlotRange -> All, PlotRangePadding -> 0,       FrameTicks -> {{niceTicks[##, 10] &, None}, {Automatic, None}}]      ![enter image description here](http://i.stack.imgur.com/EajtH.png) As an aside, when using data points specified in terms of ${x,y}$ coordinates, as in `DateListPlot` and related functions, the `FrameTicks` specification will correctly pass the minimum and maximum _of the x or y coordinates as appropriate_ , which is pretty cool. My question is how one can link the `PlotRange` of the plot to the ticks determined by such a custom function. In this particular instance, the `FindDivisions` function called by `niceTicks` ranges from -2 to 10, but the plot only takes up as much space as the data require, plus any `PlotRangePadding`.               niceTicks[Min@fakedata1, Max@fakedata1]     (* {-2, 0, 2, 4, 6, 8, 10}  *)      If I want the plot to have ticks effectively at the very top and bottom of the frame like this, using all the ticks output by my `niceTicks` function, I need to specify the PlotRange explicitly using the same `niceTicks` function:               ListLinePlot[fakedata1, Frame -> True,       PlotRange -> niceTicks[Min@fakedata1, Max@fakedata1][[{1, -1}]],       PlotRangePadding -> 0,  FrameTicks -> {{niceTicks, None}, {Automatic, None}}]      ![enter image description here](http://i.stack.imgur.com/prKyB.png) I'm sure that calling an auxiliary function twice like this doesn't add a lot of overhead, but it does require getting explicit minima and maxima from the data, which is a bit clunky when you consider multiple series, dated data for `DateListPlots` etc. **Is there a way to pass the maximum and minimum tick values determined in the`Ticks` or `FrameTicks` option expression to the `PlotRange` option automatically?** It would be more elegant code with fewer special cases to code for. I'm building this into a suite of custom plotting functions, where a tick specification like the last picture shown is a requirement. It would also be nice to pass the same tickmarks to `GridLines` somehow, so that `Automatic` gridlines automatically matched up with the specified ticks.


Mathematica quine

A quine is a computer program which takes no input and produces a copy of its own source code as its only output. There are many trivial quines in Mathematica:               In[1]:= "Hello world"     Out[1]= "Hello world"          In[2]:= 3.14     Out[2]= 3.14          In[3]:= f[x]     Out[3]= f[x]      where `f` and `x` are undefined symbols; and some more               In[4]:= Hold[N[\[Pi]]]     Out[4]= Hold[N[\[Pi]]]      These are all trivial. I was thinking that perhaps a more interesting challenge for Mathematica was a multiquine. This is a program A that outputs another program B, _distinct_ from A, such that when B is exectued, the output is A. Multiple levels of depth are also allowed: Thus one might have a program that when executed outputs a distinct program that when executed outputs another program distinct from the first two ... that when executed outputs the original program. There are also multiquines that output a distinct program _in a different language_ , such that when this program is executed, the output is the original program. **QUESTION** (Though more of a challenge): Can you come up with a multiquine for Mathematica?


Using Thread or MapThread over multi-level, ragged lists

This may be a rather strange question. I will try to create a sort of minimal working example. Suppose that I have two lists, `list1` and `list2`. Both `list1` and `list2` are ragged, and they both have multiple levels. However, `list1` and `list2` have the same number of elements, and their level distributions/arrangements are the same. For example:               list1 = {{{a, b, c}, {d, e, f, g, h}, {i, j}}, {{AA, BB}, {CC, DD, EE}}};     list2 = {{{1, 2, 3}, {4, 5, 6, 7, 8}, {9, 10}}, {{11, 12}, {13, 14, 15}}};      I would like to "thread" or "transpose" `list1` and `list2` to obtain `list3`, which has the same basic structure but with corresponding elements paired:               list3 =      {{{{a, 1}, {b, 2}, {c, 3}}, {{d, 4}, {e, 5}, {f, 6}, {g, 7}, {h, 8}}, {{i, 9}, {j, 10}}},         {{{AA, 11}, {BB, 12}}, {{CC, 13}, {DD, 14}, {EE, 15}}}}      Is there a relatively simple way to obtain `list3` from `list1` and `list2`, apart from using a complicated nesting of `Table` commands? `Transpose`, `Thread`, and `MapThread` all seem potentially useful, but not entirely straightforward for such "deep," ragged lists. Do you have any suggestions? Thanks for your time.


Elementwise join

I have two tensors of arbitrary but equal rank n (and equal dimensions): `A` and `B`, and I want to get a third tensor of rank n + 1, `C`. I want to do a element by element `Join`, so the element in `A` and the corresponding element in `B` are contracted into a list in `C`. For example, with n = 2:               A = {{a[0,0],a[1,0]},{a[0,1],a[1,1]}};     B = {{b[0,0],b[1,0]},{b[0,1],b[1,1]}};      then:               C = {{ {a[0,0],b[0,0]} , {a[1,0],b[1,0]} },{ {a[0,1],b[0,1]} , {a[1,1],b[1,1]} }}      I think it might be doable with some combination of `Inner` and `List`, but I'm not sure.


How to show legend in a combined plot of many lists,

I am having trouble with adding a legend to a plot. The example I discuss here is simpler than my real problem, but describes it well. I have a vector, called X with dimensions (100 x 6). I use the command `ListPlot` to plot one row of X at a time:               plotX={};     Do[     p1=ListPlot[X[[i]]];     AppendTo[plotX,p1],     {i,1,Length[X]}];      Therefore, the list `plotX` contains six list plots with 100 points each. To show all the plots, I use the command `Show`               Show[plotX]      Now I want to create a legend for this graph, for example `{"x1","x2","x3","x4","x5","x6"}`. How can I do this? Thanks


Auto line breaks in workbench

I have been using Mathematica for a while and thought of using Worbench to structure my project better. However, moving my code from .nb-files to .m-files in a Workbench project does not really work, since unlike the Mathematica frontend Workbench does no line breaks. Is there a way to enable auto line breaks in Wolfram Workbench? If not, how is one supposed to work with long expressions in Workbench?


Probability of xy point on bivariate normal distribution

I have a bivariate normal distribution and I am trying to calculate the probability of finding a point at a certain distance from the mean, so far with limited success. My approach has been to build the two normal distributions, and then form a product distribution:               px = NormalDistribution[-3.89764, 0.08369444426];     py = NormalDistribution[1.29137, 0.0175124];     pxy = ProductDistribution[px, py];      I can plot this and things look fine, but I can't seem to get the syntax correct for the probability calculation. I want to calculate the probability of finding x between -3.98529 and -3.80999, and y between 1.27792 and 1.30482. I can do this in 1D if I take just one of the normal distributions and do:               prob = Probability[x > -3.98529  && x < -3.80999, x \[Distributed] NormalDistribution[-3.89764, 0.08369444426]];      although so far I haven't been able to extend the syntax to the 2D case. I'm still reasonably new to Mathematica and any help will be much appreciated!


Formatting Fortran complex number output for use in Mathematica

Here is a list that was orignially output from Fortran.               {{"(0.277336296055697, 0.120000000000000E+000)"},       {"(-1.489297392708939E-002, 0.340000000000000E+000)"}}      which is to be interpreted as a list of two complex numbers. Of course, _Mathematica_ does not understand this, so, I would like to convert it into something like               {{0.277336296055697 + 0.12I}, {-0.01489297392708939 + 0.34I}}      Can I do this programmatically in _Mathematica_?


How to organize and run functions?

I am very new to Mathematica. I thought I would try it out for my first assignment in my computer science class. Until now I have only used C-base languages including C#, Java, Objective-C, and Python. This assignment is to implement RSA encryption and I thought Mathematica would be perfect for this. My code works when it is run outside of functions, but for some reason I can not figure out how to make functions and run them properly. Can someone please explain what is wrong with how I have my document set up right now? Thank you. My Document (after attempting to run)![enter image description here](http://i.stack.imgur.com/nlRe1.png) It seems like Mathematica is trying to run the document even though I have not called any of the functions.


Finding real roots of negative numbers (for example, $\sqrt[3]{-8}$)

Say I want to quickly calculate $\sqrt[3]{-8}$, to which the most obvious solution is $-2$. When I input $\sqrt[3]{-8}$ or `Power[-8, 3^-1]`, Mathematica gives the result "$2 (-1)^{1/3}$". Not what I want. When I input `Power[-8, 3^-1] // N` or `Power[-8., 3^-1]`, Mathematica gives the result "$1. + 1.73205i$". While technically correct, this is messy and not always useful. **How can I get the _real_ cube root of a negative number?** Or more generally, how can I get a list of _all_ valid roots?


obtaining real roots of negative numbers in a long expression

I have a complicated symbolic expression which contains many terms like $(a/(a-2))^{1/m}$, where $a/(a-2)$ could be positive or negative after replacement. I only need the real root after replacement, but `Power[]` function in _Mathematica_ most of the time gives me a complex number instead. I found something that almost suits my need here (the `realPower` function by Peter Breitfeld), but I have a hard time get it working in the way I want. For example:               ((a/(-2 + a))^(1/3) /. {x_^y_ :> realPower[x, y]}) /. {a -> 0.5}      still gives me a complex number. (it seems that `realPower` only work with numerical values) What should I do to get only the real root after replacement?


Plot cubic root which includes the negative graph

> **Possible Duplicate:**   >  Finding real roots of negative numbers (for example, $\sqrt\[3\]{-8}$) Yes, I know there are other Threads which have similar questions and yes I read them but I am just not able to solve the problem. Please help me I am totally at the limit with this :( How do I plot a cubic root in Mathematica, where also the negative graph is shown? ![cubic root in plot without negative graph](http://i.stack.imgur.com/6Yne2.png) NOTE: Threads I have found and not understood How to plot imaginary part of a function Finding real roots of negative numbers (for example, $\sqrt[3]{-8}$) Plotting Complex Quantity Functions


How to tell Mathematica to use Real Only Mode

How do I tell Mathematica to use real only mode. For example if I want to graph $(x-1)^{1/3}$ for $-3<x<3$, I need to use Real Only mode to get the right graph.


Reduce an equation by putting a new variable

I have the following equation given: $$ (26-x)\cdot\sqrt{5x-1} -(13x+14)\cdot\sqrt{5-2x} + 12\sqrt{(5x-1)\cdot(5-2x) }= 18x+32. $$ In order to solve it, I want to substitute $t = \sqrt{5x - 1}-\sqrt{5-2x}$. This cannot be done directly but with this step the equation could be transformed in the form $(t-2)^3 = 0$, which can be solved easily. Is it possible to make this substitution with Mathematica? The only thing I have achieved is to solve it directly with               Solve[(26 - x)*Sqrt[5*x - 1] - (13*x + 14)*Sqrt[5 - 2*x] +            12*Sqrt[(5*x - 1)*(5 - 2*x)] == 18*x + 32]


Mean squared error of two matrices

I want to compare two matrices. For this I use the mean squared error between them with the following code               mse[mat1_, mat2_] :=(mat1 - mat2)^2 // Flatten // Mean       Is this code correct? Are there other methods to compare two matrices? **update** Thank you all for your answers! Actually, I want to determine an unknown parmeter by comparing model and data. The matrix 1 contains empirical data, whereas matrix 2 is calculated from a model which has an unknown parmeter. My idea was to calculate a set of theoretical matrices with different values of the parameter $\Theta$ and compute the mean squared difference between empirical and theoretical matrices for each $\Theta$. The best $\Theta$ is the one for each the mean squared difference is minimum. Does this make sense? Are there better ways to do that?


Functional-Style Fixed-Length Queue Object?

Following up on question Side-effecting an array in an association? and @Mr.Wizard's answer in there, I'm modernizing and tweaking Daniel Lichtblau's efficient queues and ran into a little roadblock. First, I came up with the following API, stripped-down for brevity. The queue I want is fixed-length and lossy. Make a new queue with `newQ[capacity]`. Push values to the back with `pushQ[aQueue, aValue]`; pop values from the front with `popQ[aQueue]`, just like a queue of humans. If the queue is full, just pop the value at the front, losing it (on purpose) I want `pushQ` to return the queue it receives, so that I can fold it and chain it as follows:               Fold[pushQ, newQ[4], Range[10]]      Here's what I came up with, with the functional mojo highlighted:               ClearAll[newQ, emptyQQ, fullQQ, pushQ, popQ, peekQ, bumpQ];      newQ[cap_Integer] /; cap > 0 :=       <|"storage" -> ConstantArray[Null, cap],        "len"    -> 0, "cap"   -> cap,        "iFront" -> 1, "iBack" -> 1|>;     emptyQQ[Q_] := Q[["len"]] === 0;     fullQQ[Q_]  := Q[["len"]] === Q[["cap"]];     peekQ[Q_]   := Q[["storage", Q[["iFront"]]]];     SetAttributes[bumpQ, HoldFirst];     bumpQ[Q_, index_] := Q[[index]] = Mod[Q[[index]] + 1, Q[["cap"]], 1];     SetAttributes[pushQ, HoldFirst];     pushQ[Q_, item_] :=       (Q[["storage", Q[["iBack"]]]] = item;        bumpQ[Q, "iBack"];        If[fullQQ[Q],         (*then*)bumpQ[Q, "iFront"],         (*else*)Q[["len"]]++];        Q); (* <<<<<<< HERE IS THE FUNCTIONAL MOJO <<<<<<<< *)     SetAttributes[popQ, HoldFirst];     popQ[Q_] /; emptyQQ[Q] := Null;     popQ[Q_] :=      (Q[["len"]]--;       With[ {result = Q[["storage", Q[["iFront"]]]]},        Q[["storage", Q[["iFront"]]]] = Null;        bumpQ[Q, "iFront"];        result ])      This passes a bunch of unit tests:               $q = newQ[4];     pushQ[$q, 1]; $q["storage"]      > >     {1, Null, Null, Null} >                 pushQ[$q, 2]; $q["storage"]      > >     {1, 2, Null, Null} >                 pushQ[$q, 3]; $q["storage"]      > >     {1, 2, 3, Null} >                 popQ[$q]      > >     1 >                 $q["storage"]      > >     {Null, 2, 3, Null} >                 popQ[$q]; $q["storage"]      > >     {Null, Null, 3, Null} >                 pushQ[$q, 4]; $q["storage"]      > >     {Null, Null, 3, 4} >                 pushQ[$q, 5]; $q["storage"]      > >     {5, Null, 3, 4} >                 popQ[$q]      > >     3 >                 $q["storage"]      > >     {5, Null, Null, 4} >                 pushQ[$q, 6]; pushQ[$q, 7]; pushQ[$q, 8]; pushQ[$q, 9]; pushQ[$q, 10];         $q["storage"]      > >     {9, 10, 7, 8} >                 popQ[$q]      > >     7 >   and so on. Now, when I try the obvious generalization to folding, I'm back where I started with the `... in the part assignment is not a symbol.`               Fold[pushQ, newQ[4], Range[1]]      > >     During evaluation of In[49]:= Set::setps: > <|storage->{Null,Null,Null,Null},len->0,cap->4,iFront->1,iBack->1|> in the > part assignment is not a symbol. >> >     During evaluation of In[49]:= Set::setps: > <|storage->{Null,Null,Null,Null},len->0,cap->4,iFront->1,iBack->1|> in the > part assignment is not a symbol. >> >     During evaluation of In[49]:= General::stop: Further output of > Set::setps will be suppressed during this calculation. >> >     <|"storage" -> {Null, Null, Null, Null}, "len" -> 0, "cap" -> 4, > "iFront" -> 1, "iBack" -> 1|> >   Ok, I need some kind of symbol for `Set` to work. A couple more attempts as follows produce the same results, and I did a bunch of tracing and printing, and couldn't see a good way through this:               Module[{$q = newQ[4]}, Fold[pushQ, $q, Range[1]]]      > >     During evaluation of In[48]:= Set::setps: > <|storage->{Null,Null,Null,Null},len->0,cap->4,iFront->1,iBack->1|> in the > part assignment is not a symbol. >> >                 Module[{$q = newQ[4]}, Fold[($q = pushQ[#1, #2]) &, $q, Range[1]]]      > >     During evaluation of In[44]:= Set::setps: > <|storage->{Null,Null,Null,Null},len->0,cap->4,iFront->1,iBack->1|> in the > part assignment is not a symbol. >> >   **EDIT** : This question is really about elegance because I _can_ get meaningful, useful side effects with `Map` and `Scan`, as follows:               Module[{q = newQ[4]}, pushQ[q, #] & /@ Range[10]]      > >     {<|"storage" -> {1, Null, Null, Null}, "len" -> 1, "cap" -> 4, "iFront" > -> 1, "iBack" -> 2|>, >        <|"storage" -> {1, 2, Null, Null}, "len" -> 2, "cap" -> 4, "iFront" > -> 1, "iBack" -> 3|>, >        <|"storage" -> {1, 2, 3, Null}, "len" -> 3, "cap" -> 4, "iFront" -> > 1, "iBack" -> 4|>, >        <|"storage" -> {1, 2, 3, 4}, "len" -> 4, "cap" -> 4, "iFront" -> 1, > "iBack" -> 1|>, >        <|"storage" -> {5, 2, 3, 4}, "len" -> 4, "cap" -> 4, "iFront" -> 2, > "iBack" -> 2|>, >        <|"storage" -> {5, 6, 3, 4}, "len" -> 4, "cap" -> 4, "iFront" -> 3, > "iBack" -> 3|>, >        <|"storage" -> {5, 6, 7, 4}, "len" -> 4, "cap" -> 4, "iFront" -> 4, > "iBack" -> 4|>, >        <|"storage" -> {5, 6, 7, 8}, "len" -> 4, "cap" -> 4, "iFront" -> 1, > "iBack" -> 1|>, >        <|"storage" -> {9, 6, 7, 8}, "len" -> 4, "cap" -> 4, "iFront" -> 2, > "iBack" -> 2|>, >        <|"storage" -> {9, 10, 7, 8}, "len" -> 4, "cap" -> 4, "iFront" -> 3, > "iBack" -> 3|>} >


Is it necessary to introduce ImplicitRegion and ParametricRegion in version 10?

In version 10.0, _Mathematica_ introduced a new function about region plotting: ImplicitRegion. But I'm wondered that haven't this function been already existed in the older version? That is, RegionPlot. I truly can't see the difference. Another question is, in version 10, _Mathematica_ also introduced a function called `ParametricRegion`, my question is the same again: isn't it equivalent to the third usage of `ParametricPlot`? PS: I found a little bit difference is that `ParametricRegion`(new function in ver. 10) have the ability to constrain the parameters in more specific way(not just required to be `{u,u_min,u_max}, {v,v_min,v_max}`, but also `{1 <= u <= 5, 3 <= v <= 10, u+v < 7.5}`), but it can seemingly be done by option `RegionFunction` in the older version!


How do I insert a piece of code in Mathematica?

In Fortran, I can use `include "file"` to insert a piece of code. Is there a similar method in Mathematica?


Non-geometric transformation of Graphics3D primitives

I want to apply non-geometric transformations to polygons etc, the goal is to have a `Manipulate` objects that behaves like that famous möbius transform video. Since I was unable to apply non-geometric transformation to a polygon I went ahead and created a bunch of points in the plane and did appropriate transforms to them               (* plane region *)     region = {-1, 1};     d = 0.07;     (* Some points in plane *)     pts = Flatten[Table[{xi, yi, 0},         {xi, First@region, Last@region, d},         {yi, First@region, Last@region, d}]        , 1];     col = ColorData["Rainbow"] /@ Rescale[pts[[All, 1]], region];     (** Projections from plane to sphere on line going through north pole \     of sphere centered at {0, 0, 1} **)          (* Plane to sphere *)     f[vec_] := With[{t = 4/(4 + vec[[1]]^2 + vec[[2]]^2)}, vec*t + (1 - t) {0, 0, 2}]     (* Sphere to plane *)     g[vec_] := With[{t = -(2/(-2 + Last@vec))}, vec*t + (1 - t) {0, 0, 2}]          rt = RotationTransform[2.1, {0, 1, 0}, {0, 0, 1}];     Graphics3D[{       {Black, Opacity[0.3], Sphere[{0, 0, 1}]},       Point[(rt@f@# &) /@ pts, VertexColors -> col],       Point[((g@rt@f@# &) /@ pts), VertexColors -> col]       },      PlotRange -> {{-10, 10}, {-10, 10}, {0, 2}}]      ![output](http://i.stack.imgur.com/DVADU.png) I wish that I could instead do something like:               Graphics3D[{      {Black, Opacity[0.3], Sphere[{0, 0, 1}]},      SomeTransformation[Polygon[{ {-1, -1, 0}, {-1, 1, 0}, {1, 1, 0}, {1, -1, 0}}], rt@f@#&],      SomeTransformation[Polygon[{ {-1, -1, 0}, {-1, 1, 0}, {1, 1, 0}, {1, -1, 0}}], g@rt@f@#&]      ]      And end up with a smooth output, not just a few points here and there. Is there already a function like this that I have missed? If not are there other ways to arrive at the same result? How about for more advanced transformations?


Remove image background of headshot in Mathematica?

For example, using `ExampleData[{"TestImage", "Girl2"}]`: ![Mathematica graphics](http://i.stack.imgur.com/wstxf.png) what's a general way to make the background transparent? I've tried various combinations of `EdgeDetect` and `Threshold` and ImageAdd but can't figure it out. Thank you.


What function can I use to evaluate $(x+y)^2$ to $x^2 + 2xy + y^2$? I want to evaluate It and I've tried to use the most obvious way: simply typing and evaluating $(x+y)^2$, But it gives me only $(x+y)^2$ as output. I've been searching for it in the last minutes but I still got no clue, can you help me?


Performance tuning - Explicitly set Mathematica use Nvidia GPU for rendering

I feel hesitated to ask this question, but I cannot figure out a way to increase the performance. ![enter image description here](http://i.stack.imgur.com/rOAt9.gif) The problem is about running this featured example on a computer with both Intel HD GPU and Nvidia GPU. If the computer only has a Nvidia GPU, everything is smooth and fine. However, if both GPUs are installed on the computer, the performance will be very poor due to the transparent rendering and the fact that Mathematica always use the Intel GPU for rendering. Even if I set Nvidia GPU as the default one to use for all programs and explicitly run Mathematica with Nvidia GPU, this example is still run with the Intel GPU... I wonder if there is a way to fix this? Furthermore, can we explicitly tell Mathematica which GPU it should try to use by using a `Style`-like statement similar to this answer? I am running on a windows 7 laptop with following configurations, ![enter image description here](http://i.stack.imgur.com/Y3L37.png) ![enter image description here](http://i.stack.imgur.com/HYTij.png) * * * **Edit** I have reported this problem to Wolfram.


Fast method to select matrix elements based on a vector of positions

There is an operation for which I have long wanted to find a better solution. Let:   * `a` be a matrix of dimensions $m\times n$   * `v` be an integer vector of length $n$ with elements drawn from $[1, m]$ For every element $x$ at position $p$ in `v` I wish to select the element at row $x$, column $p$ in `a`. Example:               SeedRandom[0]          a = Array[Range[7] 10^# &, 3, 0]          v = RandomInteger[{1,3}, 7]      > $\left( \begin{array}{ccccccc} 1 & 2 & 3 & 4 & 5 & 6 & 7 \\ 10 & 20 & 30 & > 40 & 50 & 60 & 70 \\ 100 & 200 & 300 & 400 & 500 & 600 & 700 \\ \end{array} > \right)$ >   >   >     {3, 3, 2, 1, 1, 3, 1} >   Desired output:               {100, 200, 30, 4, 5, 600, 7}      * * * ### Details:   * Although a compiled function is likely to be the fastest approach for packed arrays I want something more general, allowing arrays of mixed types, and ideally optimized for arrays in which each row is a packed array (list) of a different type, e.g. $\left( \begin{array}{ccccccc} 1 & 2 & 3 & 4 & 5 & 6 & 7 \\ 0.1 & 0.2 & 0.3 & 0.4 & 0.5 & 0.6 & 0.7 \\ \text{a} & \text{b} & \text{c} & \text{d} & \text{e} & \text{f} & \text{g} \\ \end{array} \right)$   * I am still interested in seeing the fastest possible compiled function as it may serve as the basis for a general solution as well.   * I seek a solution that works well for any shape of array `a`, from $n\gg m$ to square to $m\gg n$, though if compromise is necessary I would optimize for $n > m$.


Trying to generate a function from InterpolatingFunction with FunctionInterpolation

Here is the code (I'm sorry to give you such a complex code sample but I failed to reproduce the error with a simpler InterpolatingFunction):               (*constants*)     R0 = 8.314; M = 28.8 10^(-3); R = R0/M;     te0 = 298; pa0 = 101325; \[Rho]g0 = Pi 25 10^-4 pa0/(R te0);     \[Rho]s0 = 0.17; t0 = 0.005; x1 = 0.01; x2 = -10^-3;     Q = 3000000; A = 10^15; ea = 9 10^4; cg = (5/2) R; cs = 1.46 10^3;     kg = 2.61 10^-2; ks = 0.36; ac = 4/0.01; hc = 1500;               c1 = NDSolve[{((ArcTan[-10^5 x]/Pi) + 1/2) (\[Rho]s0 cs D[te[t, x], t] -              (0.005^2 Pi) ks D[te[t, x], x, x] - \[Rho]s0 Q A Exp[-ea/(R0 te[t, x])])           + ((ArcTan[1000000 x]/Pi) + 1/2) (\[Rho]g0) cg D[te[t, x], t]              (+\[Rho]g0) (A \[Rho]s0/\[Rho]g0 Exp[-ea/(R0 te0)] x2 -               A \[Rho]s0/\[Rho]g0 Exp[-ea/(R0 te0)] x2/x1 x) (1 - Exp[-10^4 t])                cg D[te[t, x], x] (+\[Rho]g0) R te[t, x] (1 - Exp[-10^4 t])              (-A \[Rho]s0/\[Rho]g0 Exp[-ea/(R0 te0)] x2/x1) -              ((0.005^2 Pi) kg D[te[t, x], x, x]) + (0.005^2 Pi) ac hc (te[t, x] - te0) == 0,             te[0, x] == te0, te[t, x2] == te0, te[t, x1] == te0},           {te[t, x]}, {t, 0, t0}, {x, x2, x1}, PrecisionGoal -> 3];          f[t_, x_] = te[t, x] /. c1; teb1[t_] = f[t, 0];     Plot[teb1[t], {t, 0, t0}]     Subscript[teb, i] =       FunctionInterpolation[       If[(D[(te[t, x] /. c1), x] /. x -> 0) < 100, ((te[t, x] /. c1) /. x -> 0) + 0.01,                                                     ((te[t, x] /. c1) /. x -> 0)],       {t, 0, t0}]      After I ran the code, the warning message generated…"The function did not evaluate to a real number", why? Who can tell me what is wrong?


How can I create Arguments Maps with Mathematica's graph functions?

I am relatively new to _Mathematica_ , and I would like to know how I could use it to represent an Argument Map, such as those that you generate on online tools such as http://debategraph.org. The goal is to test an algorithm on a Argument-Map-like data structure. I think this should not be too difficult as they are nothing else but simple graphs with vertex/edge labeling.


Can $\it{every}$ usage of While be changed into NestWhile?

Ok, I think this problem is more close to philosophy. :P I've some idea now. But I'm not sure whether it's correct. For the purpose of convenience, I will use some C-like code instead of MMA's. A `While` loop is something like:               i=0; // some initialize of variable i     While(test of variable i)   // such like i<10 or i^3<90, etc.     {        // involving doing something which has nothing to do with i (e.g. Print["*"])        // or involving taking i as an argument of another function, such like Sin[i]        // or involving re-assign some value to i, such like i=i+7     }     Print[i] // after doing such evaluations, we want to get the final value of i      The first and second line surrounded in while is not really a problem for `NestWhile`. It is just because `NestWhile` is `NestWhile[f,expr,test]`, one can write `(Print["*"];Sin[#]+1&)` in the place of `f`, doing the same thing you want when you're dealing with `While`. However, when you want to re-assign `expr` in `NestWhile`, No, you cannot. `i=0;NestWhile[#=#+1&,i,#<70&]` is not what you want. (The `i` is immediately change into 0 before you would want to do `i=i+1`) And just because of this simple difference between `While` and `NestWhile`, I doubt that EVERY `While`-code can change into `NestWhile`-code.


DownValue "associative array" to list?

I have a "sparse array" like this               arr[1.5]=0.4, arr[3.5]=0.7, arr[7]=0.3      which is not really a sparse array since the keys are not all integers. This is like a hash table or associative array. How can I convert `arr` into a list? I tried `Normal[arr]`, but it won't work. I would like to be able to compute `Total@arr`, but first it needs to be converted to a normal list.


Implementing Kane's Subset Sum Algorithm

In the following paper, D. Kane describes an algorithm for subset sum that runs in logspace: http://arxiv.org/pdf/1012.1336v2.pdf. I am trying to implement it               subsetsum[sum0_, set0_] := Module[{sum = sum0, set = set0},     c = 0;     csum = Abs[sum] + Total[set] + 1;     p = NextPrime[csum];     n = Length[set];     check = False;     While[c <= n,     Print["c=" <> ToString[c] <> "p=" <> ToString[p]];     If[IntegerQ[Sum[x^(-sum)*Product[(1 + x^(set[[i]])), {i, 1, n}], {x, 1, p - 1}]/p],     check = True; Break[];];     c = c + Floor[Log[2, p]]; p = NextPrime[p];     ];     check     ];      This initial value $C$ which seems to be the $C$th prime or the next prime after $C$ is given as: $ C = \lvert B \rvert + \sum_{i=1}^n \lvert m_i \rvert +1 $ $B$ is the sum to which a subset of some set $\{m_1,m_2,m_3,\ldots,m_n\}$ sum to. Furthermore, on a simple instance such as:                   set = {2, 3, 5, 7, 8, 9};         sum = 9;         subsetsum[sum, set]       the program seems to stop after 2 loops returning False... which is wrong. It should be returning true... Anyone has any ideas on this?


Autocomplete of non-global functions

In Mathematica 9 and 10 they added autocompletion. Out of the box this works great, but when I set the CellContext to "Notebook" instead of the default "Global" (following this) it no longer autocompletes the functions I define in my notebook. If I specify that the function is global, then the autocomplete mechanism works as you can see in the example below: ![enter image description here](http://i.stack.imgur.com/PoRBh.png) Is there a way of making Mathematica's autocompletion work with functions just defined within the notebook, and not just with global functions?


FindRoot - Speed and errors

I am using `FindRoot[]` to solve a complicated equation. It seems I get the correct answer even though I get errors about an `NIntegrate[]` inside the `FindRoot[]` and the number of evaluatons is just one. Moreover is there any possibility of speeding up the process? In the following example I calculate the function `ABar` from the functions `bf` and `cf` and then recover `bf` from `ABar` and `cf`. This is done in the function `bn`. `bnVerbose` and `bn` are identical except for the `EvaluationMonitor`.                   n = 5;         a0 = 1;         bmax = 0;         For[i = 1, i <= n,           Subscript[b, i, 1] = 1/i^2;           Subscript[b, i, 2] = 1/i^2;           a0 = a0 + Subscript[b, i, 1] + Subscript[b, i, 2];            bmax = a0 + Subscript[b, i, 1] + Subscript[b, i, 2]; i++;];         For[i = 1, i <= n,           Subscript[c, i, 1] = 1/i^2;           Subscript[c, i, 2] = 1/i^2;           a0 = a0 + Subscript[c, i, 1] + Subscript[c, i, 2]; i++;];              bf[x_] :=            Sum[Subscript[b, i, 1]*Sin[2 \[Pi] i x] +              Subscript[b, i, 2]*Cos[2 \[Pi] i x], {i, 1, n}];         cf[x_] :=            Sum[Subscript[c, i, 1]*Sin[2 \[Pi] i x] +              Subscript[c, i, 2]*Cos[2 \[Pi] i x], {i, 1, n}];         ABar[x_] := 1/NIntegrate[1/(a0 + bf[x] + cf[y]), {y, 0, 1}];         ABarB[b_?NumericQ] := 1/NIntegrate[1/(a0 + b + cf[y]), {y, 0, 1}];         ABarBJ[b_?             NumericQ] := {{NIntegrate[               1/(a0 + b + cf[y])^2, {y, 0,                 1}]/(NIntegrate[1/(a0 + b + cf[y]), {y, 0, 1}])^2}};              bn[x_] :=            b /. FindRoot[ABarB[b] - ABar[x], {b, 0, -bmax, bmax},              Jacobian -> ABarBJ[b]];              bnVerbose[x_] :=            Module[{e, b}, e = 0;             sol = FindRoot[ABarB[b] - ABar[x], {b, 0, -bmax, bmax},               Jacobian -> ABarBJ[b], EvaluationMonitor -> e++];            Print["Number of evaluuations:", e, "\n"];            b /. sol            ];         bnVerbose[0.5]         Plot[{bn[x], bf[x]}, {x, 0, 1}, PlotStyle -> {Green, Red}]      In each evaluation `bn` I get several errors of the form:                   NIntegrate::inumr: The integrand 1/(6169/900+b$2526673+Cos[2 \[Pi] y]+<<6>>+1/9 Sin[6 \[Pi] y]+1/16 Sin[8 \[Pi] y]+1/25 Sin[10 \[Pi] y])^2 has evaluated to non-numerical values for all sampling points in the region with boundaries {{0,1}}. >>      Edit: Error Screenshot: ![error](http://vollmer.ms/error.png)


Are Mathematica 9 units really slow?

This generates 75 unitized pairs for a plot that displays physical units:               x = UnitConvert@Quantity["PlanckConstant" "SpeedOfLight" / "BoltzmannConstant"]     x1 = UnitConvert@Quantity[2,"PlanckConstant" ("SpeedOfLight")^2]     B[L_,T_]:= (L^-5) /(Exp[x/(L T)]-1)     p = Table[{Quantity[ll, "Micrometers"], UnitConvert[      x1 B[Quantity[ll, "Micrometers"], Quantity[1000, "Kelvins"]],       "Watts"/("Meters")^3]}, {ll, 0.1, 15, 0.2}]; //Timing      Then plot it               ListLinePlot[p, AxesLabel -> Automatic]      to get nice unitized labels. However, this naive coding to generate "p" takes 27 seconds on my core-duo 2.4 GHz laptop under windows 7 32-bit, ridiculously slow for 75 pairs! Can anyone accelerate this, say tenfold? Not too tricky please because I need transparency for Mathematica beginners.


Reduction of repetitive calculations in Table

If I generate two tables inside a function which are               function[n_, x_, y_]:=(      table1 = Table[i* x/n^x, {i,1,n}];      table2 = Table[i* y/n^y, {i,1,n}];     )      where `y - x = z`. So I can notice that I am making very similar evaluations and generate two almost identical tables. Can I do it faster, I mean: after generating of `table1` can I generate table2 based on values from table1? Of course I am looking for some solution which is faster than generating `table1` and `table2` as above. I was trying to use ParallelTable but it was wrong direction I think. I will be grateful if someone can suggest something.


How to reduce the InterpolatingFunction building overhead?

I want a linear interpolation from the following example list:               list={{0.0005023, 22.24}, {0.01457, 21.47}, {0.04922, 19.79},            {0.07484, 18.7}, {0.104, 17.55}, {0.1331, 16.52}, {0.1632, 15.49},           {0.1888, 14.52}, {0.2215, 13.31}, {0.2506, 12.16}, {0.3024, 10.01},            {0.3435, 8.304}, {0.3943, 6.036}, {0.4098, 5.329}, {0.4726, 2.384}};      The easiest way is to use:               Interpolation[list, InterpolationOrder -> 1]      but my `list` will be changing a lot, and the `InterpolatingFunction` takes a lot of time to build:               Timing[        Table[Interpolation[list, InterpolationOrder -> 1][q], {q,           0.0006, 0.4, 0.00001}];]      is 10x slower than:               test=Interpolation[list, InterpolationOrder -> 1];     Timing[Table[test[q], {q,0.0006, 0.4, 0.00001}];]      How can I remove the overhead? **EDIT** (following JxB comment) This compiled version is 5 times faster than the original version, but I don't think Partition is compiling (it appears between all the `List`s when I use `FullForm`); and there's also a `CopyTensor` that _doesn't look good_ :               Compile[{{list, _Real, 2}, {value, _Real, 0}},      Module[{temp},       temp = Select[          Partition[list, 2, 1], #[[1, 1]] <= value && #[[2, 1]] > value &][[1]        ];       temp[[1, 2]] +        (value - temp[[1, 1]])/(temp[[2, 1]] - temp[[1, 1]])*(temp[[2, 2]] - temp[[1, 2]])       ]      ]      Any suggestions? (I don't want to compile to C)


Is there an $n^{\text{th}}$ root function in Mathematica?

Is there a way to find $\sqrt[n]{x}$ with _Mathematica_ beside of `x^(1/n)` as this is something different, because this is not always the same $$(-1)^{\frac{2}{4}}=i \neq 1= \sqrt[4]{(-1)^2}$$ In the help I only found `Sqrt[x]` which is the squareroot and `CubeRoot[x]` for the cubic root.   Is there a reason that there aren't $n$-th roots implemented? (Assuming they really don't exist and I am not to stupid to find them). I am using _Mathematica_ 9.0.1 Student Edition.


Select positive value from a vector

I am wondering how to pick out the positive `Omega` value from `soln`, and make these positive values into a row vector. I know how to do it if elements in `soln` are numerical. But here all the elements are in the symbolic form.               Remove["Global`*"]          Nmax = 4;          T = 1/2 Sum[m[i] x[i]'[t]^2, {i, 1, Nmax}];     U = 1/2 Sum[k[i] (x[i][t] - x[i - 1][t])^2, {i, 1, Nmax + 1}];     L = T - U;          EL[q_] := D[L, q] - D[D[L, D[q, t]], t]          eigen = Table[EL[x[i][t]], {i, 1, Nmax}];          x[i_][t_] = a[i] E^(I \[Omega] t);          sim = eigen /. t -> 0;     x[0][t] = 0;     x[Nmax + 1][t] = 0;          For[i = 1, i < Nmax + 1, i++, m[i] = m]     For[i = 1, i < Nmax + 2, i++, k[i] = k]          matrix = D[sim, {Array[a, Nmax]}];          Print["The reduced eigenmatrix looks like ", matrix // MatrixForm]          soln = \[Omega] /. Solve[Det[matrix] == 0, \[Omega]]      ![enter image description here](http://i.stack.imgur.com/iFonl.png)


Using PatternSequence on its own in ReplaceAll?

Say I have this list:               list = {0, 1, 2, 0, 1, 3, 0, 1, 4}      and say I want to remove consecutive sequences of 0 and 1. I'd normally go for this:               list //. {before___, 0, 1, after___} :> {before, after}      > >     {2,3,4} >   But a more concise way would be the following:               list /. PatternSequence[0, 1] -> Sequence[]      Alas, this doesn't do anything. The examples in the `PatternSequence` documentation are all of the form               list //. {before___, PatternSequence[0, 1], after___} :> {before, after}      which kind of defeat the purpose. (It's pretty useful if you want to _name_ the `PatternSequence` on the LHS of the rule, but that's not my aim). So the question is, is there a way to use constructs like `PatternSequence[0, 1] -> Sequence[]` in `ReplaceAll`?


How to tweak the following purely numerical code

I am using the following numerical function in my program and I would like to speed it up.               calculate[mm_, nn_, pp_, ff_, quiet_] :=        Module[{n, y, m, z, f, k, p, l, \[Tau]},        h[0, 0, 0] = 1;        h[n_, 0, y_] := If[Mod[n, 2] == 0,          n!*y^(n/2)/((n/2)!),          0];             If[quiet != 1,          If[Simplify[h[4, 0, -1] - HermiteH[4, 0]] === 0, ,           Print["Bogus definition of h[n_,0,y_]"]]];        If[quiet != 1,          If[Simplify[h[3, 0, -1] - HermiteH[3, 0]] === 0, ,           Print["Bogus definition of h[n_,0,y_]"]]];             hh[m_, n_, 0, y_, 0, z_, \[Tau]_] :=          Sum[m!*n!/((m - k)!*(n - k)!*k!)*(\[Tau])^k*h[m - k, 0, y]*           h[n - k, 0, z], {k, 0, Min[m, n]}];             r[m_, n_, k_, f_] := (1/f)^k*          Sum[Binomial[k, l]* m!*n!/((m - l)!*(n - k + l)!)*            hh[m - l, n - k + l, 0, -1 + 1/f, 0, -1 + 1/f, 2/f], {l, 0, k}];             integral[m_, n_, p_, f_] :=          Sqrt[N[Pi]/f]*          Sum[Binomial[p, k]*h[p - k, 0, 1/(4*f)]*r[m, n, k, f], {k, 0, p}];             Return[integral[mm, nn, pp, ff]];        ];      Performance isn't too bad at the moment,               Timing[Table[calculate[n, n, 0, f, 0], {n, 0, 100}]]     {0.096000, {....}}      but the function is called millions of times. All the input to the function will be solemnly numeric. I don't need any symbolic evaluation and machine precision would be just fine. So I figured that there would be plenty of room for improvement, but I am fairly new to Mathematica and especially to its numerical capabilities. I would greatly appreciate any suggestions on speeding up that code. Thanks so much. **Note:** after taking into account the comments, this is my current code:               h[0., 0., 0.] = 1;     h[n_, 0., y_] := If[Mod[n, 2] == 0, n!*y^(n/2)/((n/2)!), 0];          hh[m_, n_, 0, y_, 0, z_, \[Tau]_] :=        Sum[m!*n!/((m - k)!*(n - k)!*k!)*(\[Tau])^k*h[m - k, 0., y]*         h[n - k, 0., z], {k, 0., Min[m, n]}];          r[m_, n_, k_, f_] := (1/f)^k*        Sum[Binomial[k, l]*m!*n!/((m - l)!*(n - k + l)!)*          hh[m - l, n - k + l, 0, -1 + 1/f, 0, -1 + 1/f, 2/f], {l, 0.,           k}];          calculate[m_, n_, p_, f_] :=        Sqrt[N[Pi]/f]*        Sum[Binomial[p, k]*h[p - k, 0., 1/(4*f)]*r[m, n, k, f], {k, 0.,           p}];      and the performance is               f = 1.;     Timing[Table[integrateGaussAndTwoHermite[n, n, 0, f], {n, 0, 100}]]     {0.080000, {...}}      **Note:** After taking into account even more comments, my code is               h[0., 0., 0.] = 1;     h[n_, 0., y_] :=        If[Mod[n, 2] == 0, Gamma[n + 1.]*y^(n/2.)/((n/2.)!), 0];          hh[m_, n_, 0., y_, 0., z_, \[Tau]_] :=        Sum[Binomial[m, k]*Gamma[n + 1.]/(Gamma[n - k + 1.])*(\[Tau])^k*         h[m - k, 0., y]*h[n - k, 0., z], {k, 0., Min[m, n]}];          r[m_, n_, k_, f_] := (1./f)^k*        Sum[Binomial[k, l]*Gamma[m + 1.]*          Gamma[n + 1.]/(Gamma[m - l + 1.]*Gamma[n - k + l + 1.])*          hh[m - l, n - k + l, 0., -1. + 1./f, 0., -1. + 1./f, 2./f], {l,           0., k}];          integrateGaussAndTwoHermite[m_, n_, p_, f_] :=        Sqrt[N[Pi]/f]*        Sum[Binomial[p, k]*h[p - k, 0., 1./(4.*f)]*r[m, n, k, f], {k, 0.,           p}];      and the execution time is               {0.0720000, {...}}


A derivative encountered in matrix factorization using gradient descent

I want to factorize a matrix $a_{ij}$ as $$ a_{ij} = \sum_k u_{ik} v_{jk} $$ using variational method for some reason. That is, I want to minimize the cost function $$ F = \sum_{ij} b_{ij}^2 $$ with respect to $u_{ik}$ and $v_{jk}$ where $$ b_{ij} = \sum_k u_{ik} v_{jk} - a_{ij} $$ I use gradient descent to find the minimum, therefore I need to calculate the derivative of $F$ with respect to $u_{ik}$ and $v_{jk}$. These can be calculated very easily with hand for example $$ \frac{\partial F}{\partial u_{ik}} = 2 \sum_j b_{ij} v_{jk} $$ However, I want to see how Mathematica solves this quite typical problem so that I don't need to use hand to calculate a much more complex version of the problem. The code I wrote is               KD[x_, y_] := KroneckerDelta[x, y]     u /: D[u[a_, b_], u[c_, d_], NonConstants -> {u}] := KD[a, c] KD[b, d]     v /: D[v[a_, b_], v[c_, d_], NonConstants -> {v}] := KD[a, c] KD[b, d]     b[i_, j_] := Sum[u[i, k] v[j, k], {k, Infinity}] - a[i, j]     F = Sum[b[i, j]^2, {i, Infinity}, {j, Infinity}];     $Assumptions = {i, j, k, i1, k1} \[Element] Integers && i > 0 && j > 0 && k > 0 && i1 > 0 && k1 > 0;     D[F, u[i1, k1], NonConstants -> {u}]      after a few minutes I got the result $$ \sum _i^{\infty } \sum _j^{\infty } 2 \left( \begin{array}{ll} \{ & \begin{array}{ll} v[j,\text{k1}] & i==\text{i1} \\ 0 & \text{True} \\ \end{array} \\ \end{array} \right) \left(-a[i,j]+\sum _k^{\infty } u[i,k] v[j,k]\right) $$ Is there an elegant way to evaluate the simple derivative $\frac{\partial F}{\partial u_{ik}}$ with Mathematica?


What is wrong with triangle PlotMarkers in v.10.0.0?

In _Mathematica_ 10.0.0 we have built-in graphical triangle `PlotMarkers`. Let us look closer on them:               ListLinePlot[{{Missing[]}, {{0, 0}}}, PlotTheme -> "Monochrome",       ImageSize -> 20, Ticks -> False, AxesOrigin -> {0, 0},       BaseStyle -> {Magnification -> 10, Thickness -> Tiny}]          ListLinePlot[{{Missing[]}, {{0, 0}}},       PlotTheme -> {"OpenMarkersThick", "LargeLabels"}, ImageSize -> 20,       Ticks -> False, AxesOrigin -> {0, 0},       BaseStyle -> {Magnification -> 10, Thickness -> Tiny}]      > ![plot1](http://i.stack.imgur.com/pZDW8.png) > > ![plot2](http://i.stack.imgur.com/f9mXH.png) It is clear that there is something wrong with the triangles. Is this functionality implemented correctly?


How can I style a TabView?

I have been trying to style a `TabView` like in the examples on the Wolfram CDF site, where they have custom sizes and backgrounds with images or gradients, but I am struggling to find documentation on how to style `TabViews` Is there a way in _Mathematica_ I can list all the properties of a control like `TabView` or just those controls which can be modified by the user? Edit: Link to an example of styling done by Wolfram


Clipboard with transparency

After reading this question I have determined that               Rasterize[Graphics[Circle[]], "Image", Background -> None]      allows you to do `Save As` on the Image and the keep the transparency. But if you use the the menus `Edit->Copy As->Bitmap` or `Edit->Copy As->Metafile` I have noticed that graphics fail to keep their transparency when pasting into other applications. Now I can `Export` an image and copy and paste it back into Mathematica(or another application) and everything works just fine, therefore the clipboard can hold references to transparent images. Doing some further investigation, here is an image of ClipSpy showing how `CF_HDROP` and `FileNameW`(FileName doesn't seem to contain the entire piece of text) contain the location of the png file, allowing you to paste it into other applications. ![enter image description here](http://i.stack.imgur.com/4UyTZ.png) When working with lots of images, exporting every image becomes quite tedious. It seems like their should be some way to automatically have Mathematica export the file and store a reference of it in the clipboard to retain the image transparency. **So how do I patch or extend Mathematica's clipboard functionality to work with transparent images?** Possible useful links for myself and others 1 2 3 4 **EDIT:** It appears a handful of applications like Inkscape and Powerpoint don't allow you to paste with only a `CF_DROP` reference. Instead it seems to be better to store the actual image as a `PNG` on the clipboard.


Solving a Volterra integral equation numerically

I would like to solve for $P(t)$, in Mathematica, a Volterra integral equation of the 2nd kind. It is: $$P(t) = R_0(t) + \int_0^t P(t') R_0(t-t')dt'$$ I know the function $R_0$ and would like to find a general way to solve for $P(t)$ given any $R_0$. I am aware that it is a convolution and can be solved in Laplace domain but I do not want to do it that way since inverting the transform brings about a whole other set of problems for me.


Converting Mathematica to $\LaTeX$

Is there a _Mathematica_ -to-$\LaTeX$ converter, so that I can place _Mathematica_ code, including things like `A // MatrixForm`, just as they are in the console straight into a $\LaTeX$ document?


How to solve this system of equations?

I want to solve the following system of equations: $$\begin{cases} 1+\sqrt{2 x+y+1}=4 (2 x+y)^2+\sqrt{6 x+3 y},\\ (x+1) \sqrt{2 x^2-x+4}+8 x^2+4 x y=4. \end{cases}$$ I tried               Reduce[{    1 + Sqrt[2 x + y + 1] == 4 (2 x + y)^2 + Sqrt[6 x + 3 y],             (x + 1) Sqrt[2 x^2 - x + 4] + 8 x^2 + 4 x  y == 4 },                 {x, y}, Reals]      I also tried with `Solve` and `NSolve`, but the evaluation exhausted my patience. I know the given system has $\left(\frac{1}{2};-\frac{1}{2}\right)$ as the only real solution. How do I tell _Mathematica_ to get that solution ?


Problem with Raster and custom ColorTable

**Context** Let me define two colour tables: (which come from brewer and xmedcom respectively)                  GoldColor = Blend[{{0, Black},         {1/9, RGBColor[32/97, 1/62, 0]},         {2/5, RGBColor[44/59, 23/78, 1/32]},         {3/5, RGBColor[84/85, 1/2, 4/51]},         {2/3, RGBColor[84/85, 53/87, 1/10]},         {4/5, RGBColor[84/85, 4/5, 11/32]},         {9/10, RGBColor[84/85, 68/75, 46/75]},         {1, White}}, #1] &       and               GalColor = Blend[{          {0, RGBColor[7/11, 0, 1/7]},           {1/17, RGBColor[10/13, 1/9, 1/7]},           {31/255, RGBColor[7/8, 1/4, 1/6]},           {47/255, RGBColor[13/14, 5/13, 1/4]},           {21/85,RGBColor[31/32, 5/9, 4/13]},           {79/255,RGBColor[46/47, 7/10, 2/5]},           {19/51, RGBColor[46/47, 5/6, 9/17]},           {37/85, RGBColor[1, 10/11, 5/8]},           {127/255, RGBColor[1, 1, 3/4]},          {143/255, RGBColor[10/11, 22/23, 7/8]},           {53/85, RGBColor[5/6, 11/12, 17/18]},           {35/51, RGBColor[7/10, 6/7, 10/11]},           {191/255, RGBColor[4/7, 10/13, 6/7]},           {69/85, RGBColor[3/7, 21/32, 4/5]},           {223/255, RGBColor[1/3, 8/15, 11/15]},           {239/255,RGBColor[1/4, 5/13, 2/3]},           {1, RGBColor[1/5, 3/13, 3/5]}}, #1] &       which looks like this:               GraphicsRow[{ContourPlot[x y , {x, -1, 1}, {y, -1, 1},         ColorFunction -> GalColor],       ContourPlot[x y , {x, -1, 1}, {y, -1, 1},         ColorFunction -> GoldColor]}]      ![Mathematica graphics](http://i.stack.imgur.com/bu9cg.png) But if I use it on large data sets, the first one works fine                dat = RandomReal[{0, 1}, {512, 512}];      Graphics[Raster[dat, ColorFunction -> GoldColor]]      ![Mathematica graphics](http://i.stack.imgur.com/Cuhej.png) whereas the second one fails with `Raster`                Graphics[Raster[dat, ColorFunction -> GalColor]]           (* void plot *)      while it works fine with `MatrixPlot` ![Mathematica graphics](http://i.stack.imgur.com/H91IL.png) Note that the problem depends on the size of `dat`; e.g. it works fine with `256^2`. **Question** How come `Raster` fails on this color table?


Half-delayed evaluation

In a certain wider context, I need to make some delayed definitions, such as `x := a + b + c`, but within these definitions I want `a` and `b` to be evaluated to their current values, not their later values. Here's a bit of code that does the trick:               a = 1; b = 2; c = 5;     With[{a = a, b = b}, x := a + b + c; y := b + c];     a = 10; b = 20; c = 50;      If `x` is printed at the end, it comes out to be `53` and if its definition is inspected with `?x`, it comes out to be `x := 1 + 2 + c`. Likewise at the end `y` is `y := 2 + c`. This is precisely the behaviour I want, but within my wider context, I care about elegance and this is inelegant. So I'd like to be able to define a command (really, a "macro") `WithCurrent`, so that `WithCurrent[{a, b}, delayeddefs]` would be equivalent to `With[{a = a, b = b}, delayeddefs]`. Any ideas?


Add options to upvalues

I have some objects that I want to present in TeXForm. Thus, it is easily to do as follows:               YoungTableau/:TeXForm[YoungTableau[diagram_]]      However, what if I want to extend the functionality of TeXForm, but only when working with this particular object? Say that I wish to be able to specify if I want line breaks or not in the output. I can do it like this,               YoungTableau/:TeXForm[YoungTableau[diagram_],OptionsPattern[]]      but then `OptionValue[LineBreaks]` will not work, since I have not added this as a possible option. It IS possible to do it as follows:               Unprotect[TeXForm];     Options[TeXForm] = {LineBreaks->True};     Protect[TeXForm];      but this feels too intrusive. Should I just give up, and invent my own version of TeXForm which can take options? What alternatives are there that does something similar to what I want?


Using a given colour table with Image?

**Context** I would like to represent large images with a given colour table. Now, if I use `Image`               dat = RandomReal[{0, 1}, {1024, 1024}];     dat // Image; // Timing          (* ==> {0.000027, Null} *)      its fast, but in grayscales; on the other hand if I use, say `MatrixPlot`               dat // MatrixPlot[#, ColorFunction -> "Temperature"] &     dat // MatrixPlot[#, ColorFunction -> "Temperature"] &; // Timing          (* ==> {1.5748, Null} *)      ![Mathematica graphics](http://i.stack.imgur.com/BS1jb.png) its in colour, but its slow. **Question** Is there a method to get the best of both worlds? (i.e. Speed and chosen colour table). Thank you for your help.


Fast principal component analysis

I'd like to speed up a principal value value analysis. The data contains a large set of vectors with a large dimension. Both are in the range of 1000. I want to obtain the loadings matrix for further calculations. The "Eigenvectors" part takes most of the computation time.               lMat = Table[RandomReal[], {i, 1000}, {j, 2000}];      mwVec = Mean[lMat];      lVerMat = (# - mwVec) & /@ lMat (* translation to the mean *);      covarMat = Covariance[lVerMat];      loadMat = Eigenvectors[covarMat] (* loadings matrix *); //AbsoluteTiming      lHKMat = lVerMat.Transpose[loadMat];      Thanks in advance.


Can I tell Simplify to prefer nested polynomials?

I need to export expressions for numerical evaluations in a C codebase. Simplify often does a good job for this, and polynomial factorisation goes a long way. However, occasionally I would come across things like               8 + 13 r^2 + 11 r^4 + 5 r^6 + r^8      as a subexpression. Obviously for floating point evaluation it is preferable to write this as               8 + r^2 (13 + r^2 (11 + r^2 (5 + r^2)))      Given a polynomial it is easy enough to write a function to do this conversion. The question is: how do I tell Mathematica that, after Simplify is done with its default rules, it should find all (sufficiently complicated by some metric) polynomial subexpression and turn each of them into the above "nested form"? EDIT: I wrote this question up in a hurry and perhaps didn't quite make the point clear. I'll admit I wasn't aware of `HornerForm`, but that sort of really isn't the issue. As mentioned before I've quickly cooked up a bit of code to perform the same basic function already so I perhaps neglected to check if there's a built-in one. The real issue here is that `HornerForm` would undo any factorisation, that is, `Simplify` may well have produced a factor of               (1 + 3 r^3 + r^7)^2      which `HornerForm` would expand into               1 + r^3 (6 + r^3 (9 + r (2 + r^3 (6 + r^4))))      whereas I would rather prefer               (1 + 3 r^3 + r^7)^2 -> (HornerForm[1 + 3 r^3 + r^7, r])^2      which gives `(1 + r^3 (3 + r^4))^2`. Similarly,               HornerForm[Sqrt[1 + 3 r^3 + r^7], r]      would just fail completely, where my desired output is `Sqrt[1 + r^3 (3 + r^4)]`. I suppose what I'm really looking for is to put each _unfactorisable_ polynomial in the expression, on which `Simplify` was previously applied, through `HornerForm`. Apologies for any confusion.


Filling between two 3D surfaces

I know it is possible to create a filling in between two curves on a 2D plot, but is it possible to do the same in 3D? My attempt like this:               Z1 := E^(-x^2) Cos[x^2 + y^2]     Z2 := 2 - x^2 - y^2          Plot3D[{Z1, Z2}, {x, -1, 1}, {y, -1, 1}, AspectRatio -> 1,      ViewPoint -> {4, 1, 1}, Filling -> Top, FillingStyle -> Opacity[0.9]]      yields the graph below: ![enter image description here](http://i.stack.imgur.com/FcHgF.png) Is there a way I can fill the graph between the two aforementioned 3D surfaces? Thank you for your time.


Plot Piecewise-Smooth Vector Field.

I want to plot a piecewise-smooth vector field. For instance: $F_1(x,y) = (x^2 + y^2, y^2)$, $F_2 (x,y) = (2xy,2xy-x^2)$ and $H(x,y) = x-y$ $F(x,y) = \begin{cases} F_1(x,y) \text{ if } H(x,y) >0 \\ F_2(x,y) \text{ if } H(x,y)<0 \end{cases}$ How can I plot $F(x,y)$ in Mathematica?


How do I write a ValueQ function that only returns True if there exists an OwnValue?

Reading the comments in this answer has motivated me to request a full solution to part of this problem. What I'd like is an efficient solution that returns `True` if there exist an `OwnValue` and `False` in _all_ other cases. This narrow behavior mirrors what folks coming from other programming languages expect of asking if something has a value or not. A solution needs to be able to handle symbols with any number of `OwnValue`, `UpValues`, `DownValues`, `SubValues`, `NValues`, and `FormatValues`. The only evalution that should occur is that required to get the value of the symbol's `OwnValue`. ## Motivation My motivation for this request is twofold.   1. There have been many queries on this topic, but none that appear to be specific enough to narrow down to one correct interpretation. I hope this question solves that.   2. The behavior requested mirrors the behavior of most programming languages that folks are familiar with. That is, when we think of a symbol/"variable" having a value, we really mean to ask if the symbol has some `OwnValues` or not. Yes there are other interpretations of what it means to have a `ValueQ` that does not do extra evaluations, but this question does not cover them.


How can I connect database(MSSQL Server) with Mathematica?

Newly I started working with database(MSSQL Server 2012). by google help, I created `Table` name as `EmployeesList` and also `Inserted`values into the table. know I want to connect database with `Mathematica`.for that I seen documentation and founded `OpenSQLConnection`function.but still not connected.                databaseInstalizationLink="C:\\Program Files\\Microsoft SQL Server";        Needs["DatabaseLink`"];      OpenSQLConnection[databaseInstalizationLink]      I seen `JDBC`function also but I didn't get it. I tried `OpenSqlConnection[]`wizard also.like if you evaluate the below one line code we get the wizard that screenshots I posted below                  OpenSQLConnection[]      Step 1: ![enter image description here](http://i.stack.imgur.com/4Nu8c.jpg) I click on `New` Button Step 2: ![enter image description here](http://i.stack.imgur.com/ongm0.jpg) I click on `Next` button. Step 3: ![enter image description here](http://i.stack.imgur.com/Mmd5C.jpg) Step 4: ![enter image description here](http://i.stack.imgur.com/ig8F7.jpg) here,I changed to `SystemLevel`. Step 5: ![enter image description here](http://i.stack.imgur.com/HRTn2.jpg) but,I installed 2012 version . Step 6: ![enter image description here](http://i.stack.imgur.com/nIObA.jpg) Step 7: ![enter image description here](http://i.stack.imgur.com/5Ys9v.jpg) here,I didn't add any properties because,I didn't understood. Step 8: ![enter image description here](http://i.stack.imgur.com/iDRSh.jpg) Finally,I click on `Connect` button but,it shows `$Failed`. I hope,everyone understood what my problem. can anyone help me? Fell free,If you want to edit my question.


Splitting a list using SplitBy, by comparing adjacent elements

Suppose that I have the following list called `mylist`:               mylist = {80.2, 80.3, 80.4, 327.6, 327.7, 327.8};      I would like to split `mylist` so that "runs of consecutive elements" are placed in the same sublist. Here, I will define two "consecutive elements" as real numbers that differ by 0.1. The second element can be either 0.1 greater than or 0.1 less than the first element, although in reality it makes more sense if the second element can only be 0.1 greater than the first element. (In my actual application, `mylist` is a list of times [i.e., elapsed time], in seconds, for example. My system is sampled every 0.1 seconds. Time never moves backwards, at least in my world!) So the result I would like is:               {{80.2, 80.3, 80.4}, {327.6, 327.7, 327.8}}      I am thinking that `SplitBy` would be appropriate for this application: > `SplitBy[list, f]` splits _list_ into sublists consisting of runs of > successive elements that give the same value when _f_ is applied. However, in looking in the documentation, it is not clear to me how "adjacent elements" are defined. In Mathematica 7, "More Information" says: > `SplitBy` performs comparisons only on adjacent pairs elements. Thus, what `f` do I use? I have tried:               SplitBy[mylist, #[[2]] - #[[1]] == 0.1 &]      and               SplitBy[mylist, #2 - #1 == 0.1 &]      but neither work. Does `SplitBy` define separate "slots" for the first and second element of a pair? Thanks for your time.


Is there any way to force Mathematica to collect a symbol in a polynomial?

Let's say that I have a polynomial like this:               a + b + c      Is there any way that I can get _Mathematica_ to transform it to:               a*(1 + b/a + c/a)      I found such a manipulation on polynomials very common when deducing equations by hand; however, I have been trying all day and still can not figure out how to make _Mathematica_ do this automatically.


Plotting the open ball for the post office metric space

The post office metric space, $P$ has the distance function defined as follows: $$ d_P (\mathbf{x},\mathbf{y}) := \begin{cases} 0 & \mathbf{x} = \mathbf{y}\\ \Vert \mathbf{x}\Vert_2+\Vert \mathbf{y}\Vert_2 & \mathbf{x}\neq \mathbf{y} \end{cases} $$ where $\Vert \mathbf{x}\Vert_2 = \sqrt{x_1^2+x_2^2}$ is the Euclidean distance from $\mathbf{x}=(x1,x2) \in \mathbb{R}^2$ to the origin. I am interested in drawing the balls of this metric centered at point $\mathbf{p}$, having a radius $r$: $$B_r(\mathbf{p}) \triangleq \{\mathbf{x} \in P\vert\ d(\mathbf{x},\mathbf{p})<r \}$$ Does anyone have any tips on how to do this?