Apply StyleBox ConversionRule while using ExportString

The following:               ExportString[Cell[TextData[{StyleBox["BOLD", FontWeight -> "Bold"], " non bold"}],      "Text", FormatType -> "TextForm"], "HTML", "FullDocument" -> False]      gives me
      BOLD non bold
      So it seems that there has to be a way to find out whether a string is surrounded by a StyleBox and by applying ConversionRules I should be able to get something like this
      BOLD non bold
      So far all my attempts have failed. Moreover I've noticed that making the following ConversionRule `""->{}` I get no styling at all, that is:
      BOLD non bold


Symmetric FrameMargins problem

Such details are driving me crazy while creating GUIs with _Mathematica_ :               Panel[       Panel["", Background -> Yellow, ImageMargins -> 0, ImageSize -> {26, 26}]       , Background -> Black, Alignment -> Center]      ![enter image description here](http://i.stack.imgur.com/Izw2y.png) Margins above are symmetric in vertical and horizontal direction, let's say I want to take control and specify `FrameMargins`:               Panel[       Panel["", Background -> Yellow, ImageMargins -> 0, ImageSize -> {26, 26}]       , Background -> Black, Alignment -> Center, FrameMargins -> {{1, 1}, {1, 1}}]      ![enter image description here](http://i.stack.imgur.com/i2ewJ.png) Now clearly they are not. I used `1` because then it is easily seen but the value does not matter. Am I missing something? **Edit** With `Framed` it seems to be ok, but one have to add `FrameStyle->None`.


Equation of a line that is tangent to a curve at point

A common problem in the derivative section of calculus texts is "find the equation of the line that is tangent to the curve $y = \ldots$ at the point $P$." To find the line that is tangent to $y = 2 x \sin x$ at $(\pi/2,\pi)$, I'd do something like this in Mathematica:               y[x_] := 2 x Sin[x]     y[x] == y'[x] x + b /. x -> Pi/2;     bRule = Solve[%, b][[1]];     y == y'[a] x + b /. bRule /. a -> Pi/2      which outputs `y == 2 x`. Is this more or less idiomatic Mathematica code? Is there a better way?


How to correctly use PatternTest (?)

This works fine:               {3, -5, 2, 7, -6, 3} /. x_ /; x < 0 :> 0     (*{3, 0, 2, 7, 0, 3}*)      and this works fine:               {3, -5, 2, 7, -6, 3} /. _?Negative :> 0     (*{3, 0, 2, 7, 0, 3}*)      I am trying to use something like this:               {3, -5, 2, 7, -6, 3} /. _?(< 0) :> 0      but I am not able to form it correctly. any idea what is wrong?


How to evaluate the 0/0 type limit in Mathematica?

When I use `Limit` to evaluate the $k \to 0$ limit of               ((k + 2) (α^2 - Sqrt[α^4 + k]) + k)/(α^2 - Sqrt[α^4 + k] + 2 k)      If `α` and `k` are assumed to be real, `Limit` gives the answer: `2`. However, I believe the correct answer is               (2 (-1 + α^2))/(-1 + 4 α^2)      So, when should I trust the answer of `Limit`?


ScientificForm is not being applied

I am looking to compute the value of $\sum^{3249}_{n=58} 2^{n \choose 2}$, but when I try to execute `ScientificForm[Sum[2^Binomial[n, 2], {n, 58, 3249}]]`, I get a very large output. Why is `ScientificForm` not being applied?


Notation of partial derivative

I want to write partial derivatives of functions with many arguments. Why is it that when I type f[x,y] `ctrl`+`6` (0,1) it turns out to be bad syntax? The output of `D[f[x,y],y]` looks very much like f with a superscript (0,1).


Can this code be written in a more functional style

Referencing this question, I wonder if the following code can be written more concisely using a functional style, i.e. without `For` loops or `ReplacePart`?               Parti[A_, p_] := Module[{An, i = 1, j = 1},       An = Drop[A, Flatten[Position[A, p]]];       For [j = 1, j <= Length[An], j++,        If[An[[j]] < p,        An = ReplacePart[An, {j -> An[[i]], i -> An[[j]]}]; i++]; ];        Insert[An, p, i] ];       Where               A1 = {3, 5, 6, 2, 1};      Parti[A1, First[A1]]       has the expected output: `{2,1,3,5,6}`


JLink function not producing result

I have a simple JLink function as follows:               Needs["JLink`"]     sha256Signature[bytesList_] :=     JavaBlock[       Module[{sig, mdc, mdo},       InstallJava[];       mdc = LoadJavaClass["java.security.MessageDigest"];       mdo = mdc.getInstance["SHA-256"];       mdo[update[bytesList]];       sig = mdo[digest];       ReleaseJavaObject[mdo];       Return[sig]      ]     ];     sha256Signature[byteList]      It produces the following output               (JLink`JavaClass["java.security.MessageDigest", 0, {JLink`JVM["vm1"]}, 1,     java`security`MessageDigest`", False, True].getInstance["SHA-256"])[digest]      There is no error indication, but the code doesn't seem to do anything. I must be missing something simple. Making suggested modifications (see below)               Needs["JLink`"];     InstallJava[];     sha256Signature[bytesList_] :=       JavaBlock[        Module[{sig, mdc, mdo},         mdc = LoadJavaClass["java.security.MessageDigest"];         mdo = MessageDigest`getInstance["SHA-256"];         mdo[update[bytesList]];         sig = mdo[digest];         ReleaseJavaObject[mdo];         Return[sig]       ]     ];     sha256Signature[byteList]      Produces               Java::fldx: Attempting to set field named digest defined in class     java.security.MessageDigest$Delegate to an incorrect type of value:         JavaObject[java.security.MessageDigest$Delegate]».     $Failed


Adding controls for multiple functions in Manipulate

I am learning Mathematica and the Image Processing functions. I have the following `Manipulate` procedure which works fine:               helix = Import["/Users/dmcleod/imgs/helix_spitzer_720.jpg"];          Manipulate[      w = ImageAdjust[helix, {contrast, brightness, gamma}],      {{contrast, 0}, -1, 5, 0.01, Appearance -> "Labeled"},      {{brightness, 0}, -1, 5, 0.01, Appearance -> "Labeled"},      {{gamma, 1}, 1, 10, 1, Appearance -> "Labeled"},      Delimiter,      "Histogram",      Dynamic[ImageHistogram[w, Appearance -> "Separated",         ImageSize -> 250]],      ControlPlacement -> Left      ]      My question is: In addition to `ImageAdjust` how can I add a slider to perform `Sharpen[]`, and another slider to perform `GaussianFilter[]`. Both functions (i.e. `Sharpen`, and `GaussianFilter`) must update the image helix. Is this possible? Can someone provide a simple example how to do this? Sorry, I just don't see how to add the additional sliders that call separate functions.


Notification sound when simulation done?

> **Possible Duplicate:**   >  Customize front end to add notifications when evaluation finishes? How to setup sound alert notification when simulation is complete? I need to do something else while waiting for a long simulation to complete instead of sitting there watching the simulation to complete the whole 'Evaluate Notebook' process. Thank You


Splitting up delimited data in lists

One task that I frequently find myself doing in Mathematica is splitting lists into lists of sublists, using specific elements to define the break-points. This is particularly useful with imported files which often have a structure like this:               section 1     a     b     c     section 2      d     e      f      Upon import, this turns into               {"section 1", "a", "b", "c", "section 2", "d", "e", "f"}      I'd like to split this into sublists at the strings that mark sections, like so:               {{"a", "b", "c"}, {"d", "e", "f"}}      Doing this with Mathematica's library functions is pretty awkward. First, you want a predicate that tells you where the delimiting elements are:               delimiterQ[s_String] := StringMatchQ[s, "section "~~__]     delimiterQ[_]        := False      In cases like this, rule replacement seems like an elegant solution:               In[1]:= delimitingRule = {before___, _?delimiterQ,                Longest[run : Except[_?delimiterQ] ...],                after___} :> {before, {run}, after};             {"section 1", "a", "b", "c", "section 2", "d", "e", "f"} //. delimitingRule     Out[1]= {{"a", "b", "c"}, {"d", "e", "f"}}      However, the performance of this kind of solution is truly atrocious, as you might expect (I got bored of waiting with a test list of 1000 elements after a couple minutes). The alternative I usually use is:               In[2]:= splitAtDelimiters[l_List, test_] :=              With[{delimIndices = Flatten@Position[l, _?test, {1}],                len = Length@l},               With[{first = First@delimIndices, last = Last@delimIndices},                Take[l, #] & /@ Join[                  If[1 < first, {{1, first - 1}}, {}],                  # + {1, -1} & /@ Partition[delimIndices, 2, 1],                  If[last < len, {{last + 1, len}}, {}]]]];     In[3]:= splitAtDelimiters[              {"section 1", "a", "b", "c", "section 2", "d", "e", "f"},               delimiterQ]     Out[3]= {{"a", "b", "c"}, {"d", "e", "f"}}      This works OK, but I always think there must be a better way to do things whenever I generate a list of indices into a list just to immediately extract them all again. That sort of round trip is a Mathematica "code smell", IMO, and in this particular case there's a lot of extra work done to deal with corner cases involving delimiters at the begining or end of the list. Any other suggestions? I think that there must be a way to do it with `Split`, but after trying a few obvious things I'm not sure what it is. **EDIT** to add: My approach using `Position` has an annoying bug in cases where you are interested in splitting a list of lists (which is common when processing, say, Excel imports). The corrected version requires use of the `Heads -> False` option for `Position`:               splitAtDelimiters[l_List, test_] :=      With[{delimIndices =          Flatten@Position[l, _?test, {1}, Heads -> False], len = Length@l},        With[{first = First@delimIndices, last = Last@delimIndices},         Take[l, #] & /@ Join[          If[1 < first, {{1, first - 1}}, {}],          # + {1, -1} & /@ Partition[delimIndices, 2, 1],          If[last < len, {{last + 1, len}}, {}]]]]      Bugs like this make me think my unease with this approach is justified. **EDIT** the second: rcollyer suggested I move this from StackOverflow.


Using GRTensorM 1.2 in Mathematica 8.0

I am copying a post from 2009 that didn't get any reply on the Wolfram page, as I am experiencing a similar problem to this at the moment: * * * I was wondering if anyone here knows of a way to force 8.0 to behave like 3.x in the way it works with `iterb` in `Table` and `Do`. I'm currently trying to run grtensorm (grtensorii for Mathematica) from http://grtensor.phy.queensu.ca/software.html and am getting `iterb` errors left and right. A relatively benign example is loading a metric but the problems multiply as you try and do even moderately complicated calculations and the whole package rapidly becomes quite unusable. It seems to me that rewriting a 7.0 compliant version of this package would involve a fair amount of work so I'd prefer to find some way to set some sort of "regression" option. This is sort of a package specific problem but it would be nice if there was a global type solution. Examples: When loading a metric, I get:               qload[kerr]     Default metric = kerr     For the kerr metric.          Coordinates     Do::iterb: Iterator {grtG`a1,2,grtG`Ndim[metricName]} does not have     appropriate bounds. >>      xSuperscript[1] = grtG`xup[metricName,1]      For the kerr metric. Line element               ds Superscript[2] = ds[metricName]      instead of what the intro.nb file claims I should get:               qload[kerr]     Default metric = kerr     For the kerr metric.          Coordinates      x\[Null]^1 = r,  x\[Null]^2 = th,  x\[Null]^3 = ph,  x\[Null]^4 = t     For the kerr metric.      Line element               ds \[Null]^2 = dth^2 (r^2+a^2 Cos[th]^2)+(dr^2 (r^2+a^2 Cos[th]^2))/     (a^2-2 m r+r^2)+dt^2 (-1+(2 m r)/(r^2+a^2 Cos[th]^2))-(4 a dph dt m r     Sin[th]^2)/(r^2+a^2 Cos[th]^2)+dph^2 Sin[th]^2 (a^2+r^2+(2 a^2 m r Sin     [th]^2)/(r^2+a^2 Cos[th]^2))      Trying to calculate the Ricci tensor after loading the Kerr metric:               grcalc[R[dn,dn]]      For the kerr metric.               Table::iterb: Iterator {i$2045,grtG`Ndim[metricName]} does not have     appropriate bounds. >>     Table::iterb: Iterator {i$2045,grtG`Ndim[metricName]} does not have     appropriate bounds. >>     Do::iterb: Iterator {grtG`a1,grtG`Ndim[metricName]} does not have     appropriate bounds. >>     Calculated g[up,up]( 0. sec.)     Do::iterb: Iterator {grtG`a1,grtG`Ndim[metricName]} does not have     appropriate bounds. >>     Calculated g[dn,dn,pdn]( 0. sec.)     Do::iterb: Iterator {grtG`a1,grtG`Ndim[metricName]} does not have     appropriate bounds. >>     General::stop: Further output of Do::iterb will be suppressed during     this calculation. >>     Calculated Chr[dn,dn,dn]( 0. sec.)     Calculated Chr[dn,dn,up]( 0. sec.)     Calculated R[dn,dn]( 0. sec.)     CPU Time = 0. sec.


Efficient calculation of diagonal matrix elements

I have a matrix $V$ of size $M$ in which each row $i$ is a vector $v_i$. Now I have another matrix $H$ and I would like to calculate as efficiently as possible the list of values $v_i^\dagger\cdot H\cdot v_i$ for $i \in 1\ldots M$. I tried using Thread but I couldn't figure out how to do it. Thank you in advance for any insight.


Simplify matrix into an upper triangular matrix

I have a tridiagonal matrix that I am trying to simplify into an upper triangular matrix using Mathematica, so I can use back substitution and solve my linear system. I have found the command "RowReduce" but that simplifies the matrix to far and I get an identity matrix since the matrix I am trying to simplify is a square matrix. Is there a way in Mathematica to simplify a matrix into an upper triangular matrix? Note: I want to solve the linear system by hand. I just want Mathematica to simplify the matrix. Update: Specifically, I'd like to get an upper triangular matrix by using Gaussian elimination.


How to use Maximize correctly

I would like to Maximize this fairly simple expression               Maximize[{2^(-1-n)*(1+k)^(-1-n)*(1+2k)^(-1+n)*(-1 - 2 k + n)*(-2 k + n),k<=n/2, k>=1},              {n,k}, Integers]      However Mathematica just returns the query. What's the right way to do this?


Are there any cases when For[] loops are reasonable?

To my mind the only reason for the existence of `For[]` loops in Mathematica is to allow new users with some experience in procedural programming languages to write simple Mathematica programs. The real problem is that sometimes such a user do not dive deeper and as a consequence he has 1) ugly and unreliable code and 2) a belief that "Mathematica has a C-like syntax". It is hard for me to imagine a situation when `For[]` can not be effectively and more cleanly replaced by `Table`, `Map`, anything else or `Do` at least. Am I wrong? Should we really recommend beginners to avoid `For[]` loops? * * * SUMMARY There are actually two great answers. The first answer is the accepted one and the second answer is this question. I wish I could accept it as well.


Editing the Virtual Book?

It's my understanding that the Virtual Book (of mathematica 9) is in notebook (.nb) format. It appears to be a very polished style of documentation which I want to reuse (parts) of it to create my own documentation. However, I'm new to mathematica and the virtual book pages (notebooks?) aren't editable by merely highlighting text. Is there a way to get the notebook to be editable?


Replacing powers of $n$-th partial sums in the output of a function with $S[i]$ for $i = 1,\ldots,n$

I've written some simple code that, for various $N \geq 1$ and $k = 1,\ldots,N+1$ computes the $n$-th derivative of $\log S_N$ where $S_N(z) = \sum_{k=0}^N \frac{1}{k!}z^k$ as follows:               f[z_, N_] := Sum[z^k/k!, {k, 0, N}]     g[z_, N_] := Log[f[z, N]]     t = Table[Evaluate[D[g[z, 7], {z, n}]], {n, 8}]      Here I can vary $7$ and $8$ to be any $N$ and $N+1$ (resp.). For a shorter example, the output if $7$ and $8$ are replaced by $3$ and $4$ is $$ \left\\{\frac{\frac{z^2}{2}+z+1}{\frac{z^3}{6}+\frac{z^2}{2}+z+1},\frac{z+1}{\frac{z^3}{6}+\frac{z^2}{2}+z+1}-\frac{\left(\frac{z^2}{2}+z+1\right)^2}{\left(\frac{z^3}{6}+\frac{z^2}{2}+z+1\right)^2},\frac{2 \left(\frac{z^2}{2}+z+1\right)^3}{\left(\frac{z^3}{6}+\frac{z^2}{2}+z+1\right)^3}-\frac{3 (z+1) \left(\frac{z^2}{2}+z+1\right)}{\left(\frac{z^3}{6}+\frac{z^2}{2}+z+1\right)^2}+\frac{1}{\frac{z^3}{6}+\frac{z^2}{2}+z+1},-\frac{6 \left(\frac{z^2}{2}+z+1\right)^4}{\left(\frac{z^3}{6}+\frac{z^2}{2}+z+1\right)^4}+\frac{12 (z+1) \left(\frac{z^2}{2}+z+1\right)^2}{\left(\frac{z^3}{6}+\frac{z^2}{2}+z+1\right)^3}-\frac{4 \left(\frac{z^2}{2}+z+1\right)}{\left(\frac{z^3}{6}+\frac{z^2}{2}+z+1\right)^2}-\frac{3 (z+1)^2}{\left(\frac{z^3}{6}+\frac{z^2}{2}+z+1\right)^2}\right\\} $$ Since $S_m'(z) = S_{m-1}(z)$ for all $m \geq 1$, these expressions will always $\mathbb{Z}$-linear combinations of quotients of powers of $S_m$ for varying $m$, and I would like to find a way to tell Mathematica to replace each occurrence of $S_m(z)$ with the symbol `f[z,m]`. Is this possible? I've seen other questions on simple substitutions using `/.` but none where the replacement scheme seemed easily adapted to this problem. In particular, the replacement scheme would need to be greedy to avoid, _e.g._ , replacing instances of $S_m(z)$ with $`f[z,m-2] + (1/(m-1)!z^{m-1}) + (1/m!z^m)`. Is there a way to make this happen? **Edit:** This post seems quite relevant. (I had missed it when searching.) I will see if it can be applied here.


Given an equation with one parameter, how do I use NSolve to solve it for many values of the parameter?

I was wondering if there was a way to use the _Mathematica_ `NSolve` command to solve an equation that has a parameter with various values. An example of which is:               parameter = {1,2,3,4,5};          equation = x + parameter;          NSolve[equation == 0, {x}]      The output should be: > >     {-1,-2,-3,-4,-5} >   Obviously, my `NSolve` expression does not give the above output, but if it did, it would make my world MUCH easier. As my actual equations are much more complex and my parameter lists can sometimes contain a lot of values, copy and paste has been tedious, to say the least! Any help would be greatly appreciated.


How could I make visible the convex hull of 3 point inside this region?

Small version of the question How can I control the color and the Thickness of this graph??               a1 = 0.2;     a2 = 0.5;     a3 = 0.6;          p1 = {1, 1, 1};     p2 = {2, 2, 2};     p3 = {1, 2, 3};     chull = ConvexHullMesh[{p1, p2, p3}];     Show[HighlightMesh[chull, Labeled[1, "Index"]]]      * * * The question complete How can I control dthe color and the transparency of the triangle of 3 points in this code?               Manipulate[      segmento[a_] := {2, 5, 4} + a {3, -2, -1};      curva[a_] := {2 + 3 a, 5 - 2 a, 4 + 2 a - 3 a^2};      p1 = curva[a1];      p2 = curva[a2];      p3 = curva[a3];      chull = ConvexHullMesh[{p1, p2, p3}];           pp3 = ParametricPlot3D[        segmento[a] + h*(curva[a] - segmento[a]), {a, 0, 1}, {h, 0, 1},         PlotRange -> {{0, 5}, {0, 5}, {0, 5}},         PlotStyle -> Directive[Green, Opacity[0.75`], Specularity[White, 20]]];           pp2 = ParametricPlot3D[curva[a], {a, 0, 1},         PlotRange -> {{0, 5}, {0, 5}, {0, 5}},         PlotStyle -> Directive[Red, Opacity[0.85`], Specularity[White, 20]]];           pp1 = ParametricPlot3D[segmento[a], {a, 0, 1},         PlotRange -> {{0, 5}, {0, 5}, {0, 5}},         PlotStyle ->  Directive[Blue, Opacity[0.85`], Specularity[White, 20]]];           Show[pp1, pp2, pp3,        Graphics3D[{Red, Sphere[curva[accionpura], 0.1]}],        Graphics3D[{Blue, Sphere[segmento[alfa], 0.1]}],        HighlightMesh[chull, Labeled[1, "Index"]],        ViewPoint -> {4, 1, 0.75}],       {a1, 0, 1}, {a2, 0, 1}, {a3, 0, 1}]      to obtain any similar to this ![enter image description here](http://i.stack.imgur.com/Q7J18.jpg)


Collecting lists using Reap/Sow

I have a list like `{{a,x},{b,y},{c,x},{d,z},{e,y}}` and would like to produce from it a list formed by collecting all top-level elements whose second components are the same into a single list. For the list above, the desired output would be `{ {{a,c},x}, {{b,e},y}, {d, z}}`. Here `x`, `y`, and `z` could also be lists, if that matters. This seems like an application of `Reap` and `Sow`. But the on-line documentation of these functions is pretty poor, and the examples don't add much. Shifrin's book keeps referring to a discussion of Reap and Sow in Part II, but I can't actually find a part II. Is there a resource somewhere that I can look at to understand the ins and outs of these functions, and see some real examples of how to use them? The simple `Reap[Map[Sow[#, #[[2]]] &, r]]`, where `r` is the list above, produces almost what I want, but instead of `{{a,c},x}` above, it produces `{{a,x},{c,x}}`. (I'm sure that someone will post a solution to my programming problem; for that I would be grateful. But I really would like to understand these functions better.) EDIT: The code `Reap[Map[Sow[#[[1]], #[[2]]] &, r], _, {#2, #1} &] // Rest` does the trick. Perhaps there's a better way. In any case, my question about documentation still stands.


Nonlinear fit with piecewise functions

I have an ensemble of data points $(x_i,y_i)$ and I need to fit them according to $y=F(a,b,x)$ if $x \leq x_{ref}$ and $y=G(c,d,x)$ if $x \geq x_{ref}$. The parameters I need to adjust are then $a,b,c,d,x_{ref}$. Models $F$ and $G$ are nonlinear with respect to the parameters. For sure, if I select $x_{ref}$ among the $x_i$, I can run separate curve fits, add the sum of squares and change $i$ until I find a minimum. Is there any way   1. to automate this procedure with Mathematica (this would provide the best values of $a,b,c,d$ for the best $x_{ref}$ selected among the $x_i$)   2. perform in a second step the full regression Any help will be appreciated.


Is there a site where you can run mathematica without having to download anything?

I made a project in mathematica, and I have to present it in front of a couple of layman in two days, but I have to use school laptops and for some stupid reason I am not allowed to download anything on that laptop. So my question is: Is there a site which can run my code so I can show what I've made using mathematica?


Evaluating an If expression inside Dynamic

I was trying to display some value inside a `InputField`. Usually it looks like this:               DynamicModule[{a=1,b=20,fuc="1"},      Deploy[Style[Panel[      Grid[Transpose[{        {"Input Format","Value"},        {PopupMenu[Dynamic[fuc],{"1","2"}],         InputField[Dynamic[a],Number,Enabled->Dynamic[fuc=="1"]]}       }], Alignment->Right], ImageMargins->10]]]]      However I wanted to change what is displayed in `InputField` according to what `fuc` is. I was trying to put `If[]` inside `Dynamic`. But it failed:               DynamicModule[{a=1,b=20,fuc="1"},      Deploy[Style[Panel[       Grid[Transpose[{        {"Input Format","Value"},        {PopupMenu[Dynamic[fuc],{"1","2"}],          InputField[Dynamic[If[fuc=="1",a,b]],Number,Enabled->Dynamic[fuc=="1"]]}        }], Alignment->Right], ImageMargins->10]]]]      I can not change the value of a in the InputField even if fuc is chosen to be "1". The error message says: > >     Set::write: "Tag If in If[True,FE`a$$570,FE`b$$570] is Protected." >   Any idea how to solve this problem? I do need some `if` logic in `InputField`! Thanks


How to output (anything) if any error happens

I have long code which goes through iteration process. some times I get error messages. I want to get the iteration numbers (or any kind of output indications) when errors happen. for example, how can I print something when error happen in this simple example:                  Do[{i/i, 1/(i - 5)}, {i, -10, 10}]      here, there are two errors when i=0 & when i=5, how can I output the values of i when the errors happen. I have different kinds of errors so I want to get the output if any kind of error happen. thanks.


Is it possible to use the LevenbergMarquardt algorithm for fitting a black-box residual function?

I have a black-box multiargument multiparametric function of the type `SRD[dataPoint_List,params_List]` which accepts experimental data along with the parameters of the model and returns a vector with the first element being the squared relative deviation (SRD) between the computed model value and experimental value for the given data point and the rest of the elements being the gradient of the SRD in the given point with respect to `params`. I wish to minimize the sum `Sum[First[SRD[dataPoint, params]], {dataPoint, dataPoints}]` with respect to `params` using the Levenberg-Marquardt algorithm and the computed gradient of `SRD` with respect to `params` (equal to `Sum[Rest[SRD[dataPoint, params]], {dataPoint, dataPoints}]`). What is the best way to do this in _Mathematica_?


Regarding CompilationTarget->"C"

Recently I have read some interesting things about `CompilationTarget->"C"` on SE, e.g. in http://mathematica.stackexchange.com/a/54459/11116 where @MichaelE2 mentioned that " _compilation to C and Listable do not always get along_ ". In this regard, I want to pose three questions:   1. What are other things that are incompatible with `CompilationTarget->"C"`?   2. According to this http://mathematica.stackexchange.com/a/34070/11116 " _double inequalities is not yet implemented for`CompilationTarget -> "C".`_" What are some other functions that fall in that category? Is there a way to get the list of implemented functions?    3. Are there some guidelines on when `CompilationTarget -> "C"` performs better than `CompilationTarget -> "WVM"`?


Change dataset key name

Using the example in the documentation, how would I make a new dataset with the key "b" changed to key "h".               dataset = Dataset[{        <|"a" -> 1, "b" -> "x", "c" -> {1}|>,        <|"a" -> 2, "b" -> "y", "c" -> {2, 3}|>,        <|"a" -> 3, "b" -> "z", "c" -> {3}|>,        <|"a" -> 4, "b" -> "x", "c" -> {4, 5}|>,        <|"a" -> 5, "b" -> "y", "c" -> {5, 6, 7}|>,        <|"a" -> 6, "b" -> "z", "c" -> {}|>}]      I tried:               dataset /. "b"-> "h"      and also               Normal[dataset] /. "b"-> "h"      Which don't work. This comes up when I get sums using `GroupBy`. I'm using code from Szabolcs which results in my getting the sums, but they have the same name as the original key. I still don't really understand the code I'm using so I don't know how to handle it there, if possible. Eventually I have to use a `JoinAcross` to merge these totals with the original detail, and I need separate key names. Szabolcs code is:               sales[     GroupBy[#, KeyTake[{"Country", "Region", "BU", "Year"}] -> KeyTake["Sales"], Total] &     ][Normal     ][All, Apply[Join]]      Source of Szabolcs code


Graphics legend: How do I split tables into parts?

Using Jens's code:               data = Map[AccountingForm, gedreht , {-1}];     result = Framed@        Row[{end,           Grid[Transpose[{Range@Length@data,               Map[AccountingForm, data, {2}]}] /. {x_, {y__}} -> {x, y},            Frame -> All]}];     hdr = {{"Berechnete Koordinaten", SpanFromLeft, SpanFromLeft}, {"Nr.",          "x", "y"}};     legendmarkers = Range@Length@data;     legendlabels =        Map[Style[AccountingForm[#, 10], FontSize -> 20,           FontFamily -> "Calibri"] &, data, {-1}];     hdr[[2]] =        Style[#, Bold, FontSize -> 22, FontFamily -> "Calibri"] & /@         hdr[[2]];     hdr[[1, 1]] =        Style[hdr[[1, 1]], Bold, FontSize -> 26, FontFamily -> "Calibri"];     legendGrd =        Grid[hdr~Join~         Transpose[Join[{legendmarkers}, Transpose[legendlabels]]],         Frame -> All,         BaseStyle -> {FontSize -> 20, FontFamily -> "Calibri"},         FrameStyle -> GrayLevel[.9], Alignment -> {Center, Center},         Background -> {None, {GrayLevel[.5],            GrayLevel[.5], {GrayLevel[.8]}}}];     plan = Panel@Row[{end, legendGrd}, Spacer[5]]      I sometimes get pretty huge tables for the legend of a figure: ![Table](http://i.stack.imgur.com/M2ckg.jpg) How can I split this table in subtables of, say, 20 lines and to arrange them horizontally? Thanks a lot!!


How to avoid returning a Null if there is no "else" condition in an If contruct

I need to use `If` but with only one option that is if "a" then do "b", else do nothing. So I wrote `If[a,b]` but the problem is that if it is not `a` it returns `Null` in my output. How to avoid this? Here is the specific example I was working on. I am looking for the number of comparisons performed by the quick sort algorithm. Here is the code from Rosetta code with my additions               QuickSort[x_List] :=       Module[{pivot, aa = 0, bb = 0}, If[Length@x <= 1, Return[x]];       pivot = First[x];       aa = If [Length[Cases[x, j_ /; j < pivot]] > 1,          Length[Cases[x, j_ /; j < pivot]] - 1 , Sequence[]];       bb = If [Length[Cases[x, j_ /; j < pivot]] > 1,          Length[Cases[x, j_ /; j > pivot]] - 1 , Sequence[]];        count = count + aa + bb;       Flatten@{QuickSort[Cases[x, j_ /; j < pivot]],          Cases[x, j_ /; j == pivot],          QuickSort[Cases[x, j_ /; j > pivot]]} ; Return[count] ]      now if you run `QuickSort[{4, 3, 2, 1, 5}]` you will get `2+2 Null` instead of 4


Using If statements internal to Table

Is there a way to use `If` statements with `Table`? To give a kind of ridiculous example that captures to spirit of what I'm trying to do, and I'm aware there are much better ways to do this, let's say we want to make an array of even values from zero to ten:               Table[If[Mod[k,2]==0,k],{k,0,10}]      The output is:               {0, Null, 2, Null, 4, Null, 6, Null, 8, Null, 10}      We could then delete the NULL entries and have our list of even values from zero to ten. However, how is this actually properly so that we don't have any `NULL` statements in the output from `Table`?


If-statement does not evaluate if condition is true

> **Possible Duplicate:**   >  How to avoid returning a Null if there is no “else” condition in an If > contruct I know there are other ways to solve this problem. Just because I'm curious I tried:               Map[If[# == 1, , #] &, {2, 1, 3, 1, 4}]      This should return a list without the value 1, because when the statement is true it should do nothing. The solution should be:               {2,3,4}      and not               {2,Null,3,Null,4}      Why is it not working as I expect?


Eliminate some value from a matrix

I have a function that return a table consisting of a 2D points. These points are either {x,y} or {0,0}               function[]:=Module[{},(            If[condition,{x,y},{0,0}](*to avoid the Null as a return I inserted the default value {0,0}*)          )]      After this I want to delete the {0,0} points from the table and leave just the {x,y}. How can I do that?


Replace Missing[Unmatched] with zero

After a left `JoinAcross`, I have a number of `Missing["Unmatched"]` values in my list of associations. I'd like to set them all equal to zero. I tried the following:               q = JoinAcross[Normal[reported], Normal[estimates], Key["key"], "Left"];     q1 = q /. Missing["Unmatched"] -> 0;     q[[100]]     q1[[100]]      > >     <|"key" -> "2009-ABCDE", "ActuarialEPI" -> 26603.6, >       "ReportedEP" -> 28535., "ReportedLI" -> 0., "ELI" -> 25619.3, >       "DLI" -> 25619.3, "EstimatesEP" -> Missing["Unmatched"]|> >   >     <|"key" -> "2009-ABCDE", "ActuarialEPI" -> 26603.6, >       "ReportedEP" -> 28535., "ReportedLI" -> 0., "ELI" -> 25619.3, >       "DLI" -> 25619.3, "EstimatesEP" -> Missing["Unmatched"]|> >   ### Edit I neglected to mention that I need to do this to the entire list of associations. I used element 100 as an example.


How do I use a passed-in symbol as a tag to define UpValues?

ClearAll@foo;     foo[tag_] := (        tag /: tag[i_] := tag[[i]]        );     a = {7, 8, 9};     foo[a];     a[2]      I wanted the above to output `8`, but encountered an error: > TagSetDelayed::sym: "Argument {7,8,9} at position 1 is expected to be a > symbol. " I think I understand that. It's currently a List, not a Symbol. So, I tried adding               SetAttributes[foo, HoldFirst];      after which I encountered another error: > TagSetDelayed::tagnf: "Tag a not found in {7,8,9}[i$_]." Okay, so `tag` evaluated, I believe because it was in the form `_[___]`. So next, I added `Unevaluated`:               foo[tag_] := (        tag /: Unevaluated[tag][i_] := tag[[i]]        );      But this resulted in > TagSetDelayed::tagpos: "Tag a in Unevaluated[a][i$_] is too deep for an > assigned rule to be found." This, I don't understand...


Make a ragged list rectangular by trimming instead of padding

I have a ragged list               ragged = {{a,b,c,d,e},{x,y,z}}      that I would like to trim (on the right) to be rectangular. The desired result is               {{a,b,c},{x,y,z}}      It seems like this should be a one-word operation but I can't find the one word. So far the best I can do is to PadRight with Null and then delete everything with a Null in it.               Transpose[      DeleteCases[       Transpose[        PadRight[         ragged,         Automatic,         Null         ]        ],       a_ /; MemberQ[a, Null]       ]      ]      This seems way too complicated for such a simple operation. What is the simplest way to do this?


Is it possible to embed a cdf file into a GitHub Page

At the bottom of my page, I've added a piece of CDF js code, but it doesn't evoke the _Wolfram CDF Player_ or _Mathematica_ , so I can't play with it. And I wonder whether it's possible, since I know GitHub pages are some static pages. ![enter image description here](http://i.stack.imgur.com/AeczK.png) * * * # Update Today I found the cdf in my homepage could be aroused by CDF palyer. ???


Simulating a quick return mechanism

Last time, I got a satisfying answer for simulating a toggle mechanism, just as expected. `NDSolve` is great. I tried playing with it (as a matter of fact, @MichaelE2 left me with an exercise). Now, I'm trying to simulate the quick return mechanism (to incorporate that in another video of mine). In the toggle mechanism, the crank drives another crank by transmitting power through the connecting rod. But here, the crank itself drives the connecting rod whose end is fixed at some distance directly below the crank's center. The crank rotates. But since that drives the link fixed to one end, it slides over the link itself. Here's a similar one I found by googling. Um, I find those methods (quite old) really annoying, and it's not really nice. Moreover, they were using some kind of package called "Modeler 2D", which no longer exists now, in _Mathematica_ 9. ![](http://i.stack.imgur.com/x2VgN.gif) I think this can be done by using `NDSolve`. But, as I'm still dumb in _solving_ using _Mathematica_ , I don't understand how exactly should I add the constraint. I tried modifying the toggle mechanism, but I still fail because I should rotate the crank and cause it to slide along the link, so that it moves forwards and backwards. I personally feel that they've exaggerated a little bit in the simulation. Actually, the the slider should be placed towards the left or else that'd be a quick _forward_ mechanism. But, I just need how the crank slides along the rod. The rest, I can try it as an exercise :D


How to save plots in grayscale

As sophomoric as this question seems, how should I save plots in grayscale in Mathematica? I generally like eps images for their scalability and I use ghostscript or other third party perl scripts to convert my images to grayscale.


LevinRule and SphericalBessels

I'm currently looking at a simplified problem that approximates another problem I'm looking into. In this simplified problem I at least have an analytic integrand and can easily provide all info on here: Given the definitions               v = 0.6;     g = 1/Sqrt[1 - v^2];          ig[tau1_?NumericQ, tau2_?NumericQ, ωω_?NumericQ, ll_?IntegerQ] :=     (((2 ll + 1) ωω)/(4 Pi^2)) *      SphericalBesselJ[ll, ωω v g tau1] *      SphericalBesselJ[ll, ωω v g tau2] *      Exp[-I ωω g (tau1 - tau2)];      I would like to numerically integrate this:               f[ω_, l_, pg_, wp_] :=       2 Re[NIntegrate[         Exp[-I 1 s] ig[100, 100 - s, ω, l], {s, 0, 40},          PrecisionGoal -> pg, WorkingPrecision -> wp, MaxRecursion -> 20]]      But for example `f[2, 1, 15, 25]` etc I get a host of errors like `::slwcon`,`::einc`. I was wondering if I could use "LevinRule" here and if so what would the options be? I believe the problem gets worse at large $\omega$ maybe 100 or more. Where even putting the WorkingPrecision upto 40 and PrecisionGoal down to 10, things still scream, if I generate a table of these from 1 to 100 in omega.


FeynArts and FormCalc

I installed the `FeynArts` and `FormCalc` packages and there were no any errors during installation. Now I try to calculate an amlitude of a process `g g > sr sr` (where `sr` are octet scalars defined in a new model `SMS`) so I did the following:               z := CreateTopologies[0, 2 -> 2]               Ins := InsertFields[z, { V[4], V[4]} -> {S[14], S[14]},                          Model -> "SMS", GenericModel -> "SMS" ]          M = CreateFeynAmp[Ins];      Everything went all right, but when I switched to `FormCalc` ..:               CalcFeynAmp[M]      It gave the following error: > Function::flpar: !(*StyleBox["\"Parameter specification \"", "MT"])!\ > (*StyleBox[!({eta, e, ec, ((TopologyList[(([LeftSkeleton] 1 > [RightSkeleton]))])), zc, k, eT, eTc}), "MT"])!(*StyleBox["\" in \"", > "MT"])!(*StyleBox[!(Function[(((({eta, e, ec, > ((TopologyList[(([LeftSkeleton] 1 [RightSkeleton]))])), zc, k, eT, eTc})), > k))]), "MT"])!(*StyleBox["\" should be a symbol or a list of symbols.\"", > "MT"]) >> I am missing something in `FormCalc`, but can't figure out what ...


Collecting variables from Subscript

I have followings set:               t = Transpose[{x[#] & /@ Range[20], RandomInteger[15, 20]}];     Subscript[#[[1]], #[[2]]] & /@ t      The code is just to build my set.So my set of variables is something like:               {Subscript[x[1], 7], Subscript[x[2], 15], Subscript[     x[3], 3], Subscript[x[4], 4], Subscript[x[5], 0], Subscript[     x[6], 1], Subscript[x[7], 15], Subscript[x[8], 1], Subscript[     x[9], 0], Subscript[x[10], 2], Subscript[x[11], 0], Subscript[     x[12], 10], Subscript[x[13], 12], Subscript[x[14], 11], Subscript[     x[15], 9], Subscript[x[16], 8], Subscript[x[17], 11], Subscript[     x[18], 4], Subscript[x[19], 0], Subscript[x[20], 1]}      How can I pick and add up all variables which has the same subscripts from my set.For example like:               Subscript[x[14], 11]+Subscript[x[17], 11]


Improving the speed of evaluating Table with nested functions

I am a _Mathematica_ novice working with a stack of 1024 x 1024 `WatershedComponents` (or `MorphologicalComponents`) label matrices that have resulted from watershedding timelapse microscopy images. I am trying to automatically assign the labels in a previous `WatershedComponents` mask (from a prior timepoint) to the mask generated from `WatershedComponents` at the next timepoint. One approach I have tried is to calculate how much overlap there is for each component in the mask at the current time point with the masks that occupy the same positions in the matrix at the prior timepoint (i.e., this is basically a crude attempt at tracking the cells from time point to time point). To compute the amount of overlap, I am presently using the following functions below to generate a table of how much overlap there is (how many total positions in the two matrices overlap for each label). However, I am finding this is rather slow (takes about 30 to 40 seconds for matrices containing anywhere from 10 to 30 different labels). Is there a faster way to do this without using `Table`? Are there alternatives to `Position` or `Intersection` that might be faster? Would it help to use `Compile`? I don't know what is possible but achieving a 10-fold or better increase in performance would be more like what I was hoping for. I know best practice in _Mathematica_ is to avoid using Table when possible. Thanks for any suggestions you can provide.               overlapTable =        Table[Length @ Intersection[           Position[currentMask, currentMaskComponentList[[j]], -1],            Position[previousMask, previousMaskComponentList[[i]], -1]],          {j, Length[currentMaskComponentList]},          {i, Length[previousMaskComponentList]}]      To clarify what I am trying to do here are some examples of the images after watershedding I am working with: At timepoint #1 I get this WatershedComponents image: ![after using WatershedComponents I get this image at timepoint=1](http://i.stack.imgur.com/wDI1I.png) After joining components together that belong to the same cell and merging the rest of the components to the background (black) I get this final mask with 6 components (5 cells + black background) for timepoint #1: ![after joining components together that belong to same cell and merging everything else to background I get this mask for timepoint=1](http://i.stack.imgur.com/wgH9K.png) Now I move to timepoint #2 and get the next WatershedComponents image of the same cells (taken about 5 minutes later). I am trying to automatically label this image to match the labels in the label matrix in the image above with the joined components & black background so I don't have to take the time to join the components again by hand (and relabel the components to match the previous timepoint). ![\[after using WatershedComponents I get this image at timepoint=2](http://i.stack.imgur.com/LJuXF.png)


Combine multiple PDF files into one document

I have multiple single page PDFs I'd like to join together into a single file. (Obviously I mean the file format and not the probability distributions here!) I'm aware of free online services such as this one and I have used them several times. On this occasion, however, I have info I'd prefer not to upload to a server I don't know anything about. I know Mathematica can `Import` and `Export` PDFs, but is there any easy way to join them together? I've tried using `Join`, but it produces a single large page instead of a page 1, page 2, page 3 format. Also the file size balloons - joining a 500 kB and 208 kB pdf results in a 3,503 kB file.


How do I reverse the axis in ParametricPlot?

In astronomy, right ascension is usually plotted with positive values that increase from right to left. I have seen discussions of successful and unsuccessful attempts to reverse the order of an axis in _Mathematica_ , but I haven't seen anything that applies specifically to the `ParametricPlot[]` function, and perhaps I am not good enough at _Mathematica_ to see how the other solutions using `ScalingFunctions` or `Transpose` might be applied here. I tried a few to no avail. Plot 2 uses the default frame ticks, showing reversal of plotting order by reversing the signs of the $x$-coordinates of the plot objects. In the `Ticks` option, their specs seem to be ordered `{{left, right}, {bottom, top}}` with respect to the frame sides. I believe that replacing one of these terms, say left, with something like `{-1, 1}` would replace `-1` with `1` on the left side. But when I attempted to change the names of the ticks on the $x$-axis in plot 2 to positive numbers, the ticks and their names both disappeared, as in plot 3. I could replace the missing ticks with a cumbersome `Epilog` list, but I would prefer something more elegant. It strikes me as odd that the mathematicians who created _Mathematica_ would arbitrarily limit their orientation, so there must be a native way of reversing order, no? The following three scripts produce these three plots in a row: ![attempts to plot with reversed axes](http://i.stack.imgur.com/wl0M9.png)               Clear["Global`*"]          spiral[a_, t_, x_, y_] := {a*t*Cos[t] + x, a*t*Sin[t] + y} // N;          fs = 8; (* font size *)     objects = 5;     fl = {X, Rotate[Y, -Pi/2]}; (* frame label *)          unreversed =       ParametricPlot[       spiral[.002*#^(5/3), t, #, #] & /@ Range[objects], {t, 0, 10*Pi},        PlotRange -> {{0, objects + 1}, {0, objects + 1}},         PlotLabel -> Style["1. x axis not reversed", FontSize -> fs],         Frame -> True, FrameLabel -> fl, GridLines -> Automatic];          reversed1 =        ParametricPlot[        spiral[.002*#^(5/3), t, -#, #] & /@ Range[objects], {t, 0,          10*Pi}, PlotRange -> {{-objects - 1, 0}, {0, objects + 1}},         PlotLabel -> Style["2. x axis reversed", FontSize -> fs],         Frame -> True, FrameLabel -> fl, GridLines -> Automatic];          ticks = {{Automatic, None}, {{-#, #}, None}} & /@         Reverse[Range[objects]];          reversed2 =        ParametricPlot[        spiral[.002*#^(5/3), t, -#, #] & /@ Range[objects], {t, 0,          10*Pi}, PlotRange -> {{-objects - 1, 0}, {0, objects + 1}},         PlotLabel ->          Style["3. x axis reversed\nticks lost", FontSize -> fs],         Frame -> True, FrameLabel -> fl, GridLines -> Automatic,         FrameTicks -> ticks (* causes ticks to disappear *)];          GraphicsRow[{unreversed, reversed1, reversed2}]


How to make rational expressions formatted using FractionBox

This is what I get using Mathematica 9.0.1. ![enter image description here](http://i.stack.imgur.com/Ac0pt.jpg) ![enter image description here](http://i.stack.imgur.com/xlJ5j.jpg) Instead I want this: ![enter image description here](http://i.stack.imgur.com/2m6LW.jpg) I know how to use MakeBoxes, Format and I thought this code would work:               MakeBoxes[(1/2)(expr_), StandardForm]:=     FractionBox[ MakeBoxes[expr, StandardForm], MakeBoxes[2, StandardForm]]      But the code above and all variations that I tried have no effect. This has to be automated to get the look I want. My actual application is much more complicated.


Plot one set of "x" with at least three sets of "y" in different scale

I'm sorry if the question is too obvious, but I haven't been able to find a straight answer for Mathematica. I have 1 set of "x" with at least 3 sets of "y" in different scales. I need to plot them together but I cannot find a way to offset the third "y" axis so that it is "out" of the main frame. Producing plots separately and putting them together with `ImagePadding` works wonderfully for 2 sets of "y" data, but I cannot find a similar solution for 3 sets which require different scales. This is what I have: ![what_i_have](http://i.stack.imgur.com/jI4Im.png) This is more or less what I need: ![what_i_need](http://i.stack.imgur.com/u2SYi.png) Is there a way that I can shift one of the axis to the right so that they do not overlay? Thank you **Edit** After the answer provided by @bobthechemist, I modified his code to adapt it to the lists I usually work it rather than symbolic functions. The resulting plot is the following: ![enter image description here](http://i.stack.imgur.com/4mWKM.png)


UpValues evaluation with Dot operator

I would like to simplify some database notation, and I'm doing some tests with `UpValues` for that. For example, if I set this Upvalue fot tab1:               tab1 /: tab1.column1 = 1      When I evaluate               tab1.column1      I get `1` as expected. But if latter I set `column1 = "x"`, when I evaluate it again, I get `tab1."x"` instead of `1` as I need. There is some way that I can change this behavior? So I could get `1` and prevent variables name conflict? **Update** To avoid missinterpretation there is the sequence of evaluation. Quit the kernel and evaluate:               tab1 /: tab1.column1 = 1;     column1 = "x";     tab1.column1       The result is `tab1."x"` in the first evaluation.


Series not evaluating to numerical answer

I am working on an example from a book (An Engineer's Guide to Mathematica). The following code is in the book:               terms=1+Accumulate[2. Table[1/(1+(2 n)ˆ2),{n,1,500}]];      n={ 50,100,200,500} ;     p=terms[[n]];     exact=π/2. Coth[π/2.];     pd=100. (exact-p)/exact;     TableForm[{ { n,p,pd} } ,TableHeadings->{ None,{ "N","s",     "% diff"}}]      The output is supposed to look like this: > N s %diff > > 50 1.70279 0.578059 > > 100 1.70771 0.290481 > > 200 1.71019 0.145605 > > 500 1.71169 0.058329 But I do not get this output. The columns for p and pd are not evaluated, rather in the output I get long many series. I cannot see why this is happening. This is a confounding problem for me as I am trying to learn the platform.


Spectrogram of complex exponential functions in Mathematica 9

How can the v9.0 built-in `Spectrogram[list, n, d]` function be modified to accept complex exponential functions? The V8.0.4 code that produces the result I'm looking for follows. How do I adapt v9.0 to do the same thing?               *************     (* Spectrogram of complex exponentials using MMA_ 8.0.4 *)     Clear[se, \     fs, \[CapitalDelta]T, n]; se[amp_, f_] := amp*Exp[2 \[Pi] I f t]     fs = 100 ; \[CapitalDelta]T = 130 ; \[CapitalDelta]t = N[1/fs]; n =       fs*\[CapitalDelta]T; \[CapitalDelta]f =       N[1/(2 \[CapitalDelta]T)] ; fmax = N[1/(2 \[CapitalDelta]t)];     Clear[f1, f2, f3]; f1 = 10; f2 = 20; f3 = -13;      cs1 = N[Table[        se[1, f1] , {t, 0, \[CapitalDelta]T, \[CapitalDelta]t}] ]; cs1 =       Most[cs1];     cs2 = N[Table[        se[1, f2] , {t, 0, \[CapitalDelta]T, \[CapitalDelta]t}] ]; cs2 =       Most[cs2];     cs3 = N[Table[        se[1, f3] , {t, 0, \[CapitalDelta]T, \[CapitalDelta]t}] ]; cs3 =       Most[cs3];     w1 = Table[       1, {4000}];  Length[w1]; (* rectangular window *)     Length[cs1] ;     w1ls = ArrayPad[w1, {0, Length[cs1] - Length[w1]} ]; Length[w1ls] ;     wcs1 = w1ls*cs1; Length[wcs1];     ListLinePlot[Re[wcs1], Frame -> True, PlotRange -> All,        PlotStyle -> Blue, ImageSize -> 250];     w2 = Table[1, {4000}]; Length[w2];     Length[cs2];     w2ls = ArrayPad[       w2, {Length[w1] + 1 , (          Length[cs2] - Length[w1] - 1 - Length[w2])  }]; Length[w2ls];     wcs2 = w2ls*cs2; Length[wcs2];     ListLinePlot[Re[wcs2], Frame -> True, PlotRange -> All,        PlotStyle -> Green, ImageSize -> 250];     w3 = Table[1, {5000}]; Length[w3];     Length[cs3] ;     w3ls = ArrayPad[       w3, { (Length[w1] + 1 + Length[w2] + 1), (          Length[cs3] - Length[w1] - Length[w2] - 1 - Length[w3] -           1 )}];  Length[w3ls];     wcs3 = w3ls*cs3; Length[wcs3];     (********)     Clear[in]; in =       wcs1 + wcs2 +        wcs3 ;(* Composite Complex Signal *)     (********)     (* Set up STFT \     parameters *)     ns = 100 ;(*specify # samples/segment*)     insegs =       Partition[in, ns, 1, {1, 1}];     finsegs =        Chop[Fourier[#, FourierParameters -> {-1, -1}] ] & /@ insegs;      ffinsegs = Abs[finsegs]^2;     rffinsegs = RotateRight[#, (ns/2) - 1] & /@ ffinsegs;      p = ArrayPlot[Transpose[rffinsegs], DataReversed -> True,       FrameTicks ->         {   { { {             0, - 5*fmax/5}, {ns*(1/10), -4*fmax/5}, {ns*(2/10), -3*fmax/5},            {ns*(3/10), -2*fmax/5}, {ns*(4/10), -1*fmax/5},           {ns*(5/10), 0}, {ns*(6/10), fmax/5}, {ns*(7/10),             2*fmax/5}, {ns*(8/10), 3*fmax/5 }, {ns*(9/10),             4*fmax/5}, {ns*(10/10), 5*fmax/5 "Hz"} }, None } ,           { {{1000, 10}, {2000, 20}, {3000, 30}, {4000, 40}, {5000,             50}, {6000, 60}, {7000, 70}, {8000, 80}, {9000, 90}, {10000,             100}, {11000, 110}, {12000, 120}, {13000, 130 "sec"} },           None }  },        AspectRatio -> 1/3 , ImageSize -> 650 ,        BaseStyle -> {FontFamily -> "Arial", FontWeight -> Bold, 12}]          (* MMA_ 9.0: Using built-in command < Spectrogram[list,n,d] > *)          Spectrogram[in, 100, 1]     Spectrogram[Re[in], 100, 1]


Poor anti-aliasing in Rotated text with ClearType on

There is a problem on my system that occurs when text is rotated 90 degrees as it is in frame labels. This only happens when ClearType is turned on, and only around 90 degrees of rotation. I am running Mathematica 7 on Windows 7. Input:               Style["αβημπρτ", 20, FontFamily -> "Arial"]          Rotate[%, # °] & /@ {90, 90.1, -90, 85, 95, 45, 0}      Exhibit A: ClearType OFF ![Mathematica graphics](http://i.stack.imgur.com/Xg1xo.png) Ehibit B: ClearType ON ![Mathematica graphics](http://i.stack.imgur.com/K5IB1.png) Notice the strongly inferior rendering of the text rotated 90° and 90.1°, but acceptable rendering of text at the other rotations including -90°. A close inspection of the images above will reveal that sub-pixel-rendering is disabled on rotated text _except_ for the cases of 90°, 90.1°, and 0°. In the last case it works as as intended but it should apparently have been disabled (the default AA is used instead) for 90° and 90.1° as well. I do not want to turn off ClearType as it makes text more readable throughout my system except for this bug. I tried to be clever by nesting rotations but that does not work. Interestingly there _is_ a difference in rendering between 360° and -360° but not in the anti-aliasing.               text = Style["αβημπρτ", 20, FontFamily -> "Arial"];     Fold[Rotate, text, # °] & /@ {{90, 360}, {90, -360}, {45, 45}} // Row      ![Mathematica graphics](http://i.stack.imgur.com/4D0Qm.png)   1. What systems are affected by this bug? Is it fixed in newer versions?   2. Is there a work-around that **_can be applied to the output of_ `Graphics`**? I would rather not `Rasterize` the text.


How to get vertices of a polytope given by equalities and inequalities?

I have a polytope given by some equalities and inequalities, how can I get all the vertices of the polytope? If there's a way to deal with the one given by inequalities only, how can I reduce the equalities and inequalities to inequalities only? \--Updated 2013.12.11-- `m=SparseArray[Automatic,{28,56},0,{1,{{0,6,12,18,24,39,50,61,67,73,79,94,105,116,122,128,143,154,165,185,205,234,257,268,279,302,313,324,335},{{1},{2},{3},{4},{5},{6},{1},{7},{8},{9},{10},{11},{2},{7},{12},{13},{14},{15},{3},{8},{12},{16},{17},{18},{1},{2},{3},{4},{5},{7},{8},{9},{10},{12},{13},{14},{16},{17},{19},{1},{2},{3},{5},{7},{8},{10},{12},{14},{17},{20},{1},{2},{3},{4},{7},{8},{9},{12},{13},{16},{21},{1},{22},{23},{24},{25},{26},{2},{22},{27},{28},{29},{30},{3},{23},{27},{31},{32},{33},{1},{2},{3},{4},{5},{22},{23},{24},{25},{27},{28},{29},{31},{32},{34},{1},{2},{3},{5},{22},{23},{25},{27},{29},{32},{35},{1},{2},{3},{4},{22},{23},{24},{27},{28},{31},{36},{7},{22},{37},{38},{39},{40},{8},{23},{37},{41},{42},{43},{1},{7},{8},{9},{10},{22},{23},{24},{25},{37},{38},{39},{41},{42},{44},{1},{7},{8},{10},{22},{23},{25},{37},{39},{42},{45},{1},{7},{8},{9},{22},{23},{24},{37},{38},{41},{46},{1},{2},{3},{4},{7},{8},{9},{12},{13},{16},{22},{23},{24},{27},{28},{31},{37},{38},{41},{47},{1},{2},{3},{5},{7},{8},{10},{12},{14},{17},{22},{23},{25},{27},{29},{32},{37},{39},{42},{48},{1},{2},{3},{4},{5},{7},{8},{9},{10},{12},{13},{14},{16},{17},{22},{23},{24},{25},{27},{28},{29},{31},{32},{37},{38},{39},{41},{42},{49},{1},{2},{3},{4},{5},{7},{8},{9},{10},{12},{16},{17},{22},{23},{24},{25},{27},{31},{32},{37},{41},{42},{50},{1},{3},{5},{8},{10},{17},{23},{25},{32},{42},{51},{1},{3},{4},{8},{9},{16},{23},{24},{31},{41},{52},{1},{2},{3},{4},{5},{7},{8},{9},{10},{12},{13},{14},{22},{23},{24},{25},{27},{28},{29},{37},{38},{39},{53},{1},{2},{5},{7},{10},{14},{22},{25},{29},{39},{54},{1},{2},{4},{7},{9},{13},{22},{24},{28},{38},{55},{1},{2},{3},{7},{8},{12},{22},{23},{27},{37},{56}}},{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-2,-2,-2,-1,-1,-2,-2,-1,-1,-1,-1,-1,-1,-1,-2,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,-2,-1,-2,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-2,-2,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}}]; b={-(2/7),-(2/7),-(2/7),-(2/7),-(5/7),3/7,3/7,-(2/7),-(2/7),-(2/7),-(5/7),3/7,3/7,-(2/7),-(2/7),-(5/7),3/7,3/7,-(20/21),-(20/21),34/21,25/21,-(11/21),-(11/21),25/21,-(11/21),-(11/21),-(11/21)}; ` The equalities are m.x==b and the inequalities are x>=0


Autocomplete InputField

Is there a way to define a `InputField` that displays a list of options as you type? More specifically I'm looking for an `InputField` that specifically autocompletes as you type. The functionality is similar to an `InputField` and `MenuView` element. Examples of such feature would be the textbox here or here. ![enter image description here](http://i.stack.imgur.com/q9QAi.png) **EDIT:** Ideally the interface should work as much like Google's homepage as possible. Specific Features   1. Menu is **not case sensitive**   2. **Clickable items** in drop down menu   3. Ideally, the menu is **hidden** until user types into textbox   4. Restrict number of items in output. Here is some example code I am working on. It currently only meets criteria #2. **EDIT2:** Here is my next set of code which meets the following criteria: **case insensitive** , has clickable menus, and restricts the number of output. One funny thing, is that the menu isn't clickable all the way across, but only where the text is.


How to fix the orientation and scaling of Graphics3D?

To visualize an eigenvector and value calculation I tried to display the eigenvectors (scaled by the eigenvalues) as arrows in a Graphics3D plot using Manipulate. The (symmetric) matrix is a function of three variables, so I used the sliders to set the point at which I evaluated the matrix. This worked rather nicely, but as I change the Manipulate sliders, the box size and orientation and scaling changes which kills the effectiveness of the animation attempt. I'm looking for a Graphics3D option that would prevent this dynamic scaling of the bounding box size and orientation. ViewAngle and ViewCenter looked the most appropriate, but didn't produce the result I expected. Any idea how to do this? For reference (and possible experimentation), here's the notebook content for the visualization:               Clear[o, e, e1, e2, e3, standardBasis, ee, ev, arrows, \     arrowsReference,  x, y , z , p]     o := {0, 0, 0}     e1 := {1, 0, 0}     e2 := {0, 1, 0}     e3 := {0, 0, 1}     standardBasis := {e1, e2, e3}     Manipulate[      e := {{2 y, x, x}, {x, 0, z}, {x, z, -1}} ;      p := {x, y, z} ;      ev = Eigenvalues[e] ;      (*      Taking the orthonormal eigenvectors, and scaling them by their \     eigenvalues to get a feel for their magnitude and direction.       *)      ee := ev Map[ Normalize, Eigenvectors[e]]  //        N ; (* note: sneaky multiplication of lists, pairwise eigenvalue \     times eigenvector as in:      a = {1.5, 2}      b = {2, 3}       a b           which produces: {3, 6}      *)      arrows = Table[Arrow[{p, p + Part[ee, i]}], {i, 3}] ;      arrowsReference =       Table[Arrow[{p, p + Part[standardBasis, i]}], {i, 3}] ;      Graphics3D[{Red, Arrowheads[.05], arrows, Blue, Arrow[{o, p}],        Green, arrowsReference}, Boxed -> True, Axes -> True],      {{x, 1}, -10, 10},      {{y, 2}, -10, 10},      {{z, 4}, -10, 10}]


DSolve 2nd Order Coupled Partial Differential Equations

I am trying to use Mathematica to solve 2 coupled differential equations. My equations are of the form \begin{equation}\ddot{x}_i + A_{il} \partial^l A^{jk} ( \dot{x}_b \dot{x}_c - y_b y_c ) =0 \end{equation} where $x_a=x_a(t)$ are functions of $t$ and $y_a$ are constant vectors (I'm happy to set these to zero to begin with if it will help get a solution!) For the problem at hand, $a=1,2$ and so I have two coupled PDEs in $x_1$ and $x_2$. The $2 \times 2$ matrix $A^{jk}$ is given by \begin{equation} A^{jk} = \frac{1}{(x_1^3-x_1 x_2^2)^2} \begin{pmatrix} \frac{x_1^4+x_2^4}{4} & x_1^3 x_2 \\\ x_1^3 x_2 & \frac{x_1^4-2x_1^2x_2^2}{2} \end{pmatrix} \end{equation} and lastly, the matrix $A_{ad}$ is just the inverse of the above matrix. I have attempted to solve these using DSolve and have produced the following code (with $y_a=0$):               A = 1/((x1^3 - x1*x2^2)^2)*{{(x1^4 + x2^4)/4, x1^3*x2}, {x1^3*     x2, (x1^4 - 2*x1^2*x2^2)/2}}          xdot = {xdot4, xdot5}          y = {y4, y5}          S = {xdotdot1, xdotdot1} + 1/2*Inverse[A].{D[#, x1], D[#, x2]} &[     xdot.A.xdot - y.A.y];          St = S /. {xdotdot1 -> x1''[t], xdotdot2 -> x2''[t], xdot1 -> x1'[t],      xdot2 -> x2'[t], x1 -> x1[t], qx2 -> qx2[t], y1 -> 0, y2 -> 0};          system = {St[[1]] == 0, St[[2]] == 0};          DSolve[system, {x1, x2}, t]      I am fairly new to Mathematica and produced this code with a lot of help from a friend. The code works fine on simple examples where the PDEs are not coupled but in this case I just get the output               DSolve[.....]       i.e. it is not able to solve them. I understand that coupled PDEs are much harder for it to solve but given that it's only a 2x2 matrix, I hope it should be doable! I have thought about trying to use NDSolve to get a numerical solution since apparently Mathematica is good at this but the problem is I'm not sure about the initial conditions - if there's no way to get an exact solution then perhaps we can give this approach a bit more thought. I hope I've explained the problem well. Any advice/solutions greatly appreciated. Thanks.


How to unload automatically loaded packages?

I know that this has been discussed here (How do I clear all user defined symbols?), but my case is somewhat different. How does one unload packages during runtime that were loaded with the start of _Mathematica_? Occasionally, for deployment reasons, I would like to revert my system to the default state, to check whether a function works in that environment as well. I have a package that starts when _Mathematica_ starts, and it contains some modified system symbols too (e.g. extended usage messages for options). Should I include `CleanSlate`` in the same `init.m` file before loading my own package and then later refer to it when I want to return to the default _Mathematica_ state? Would it revert modified `System`` context symbols too? At the moment I manually have to edit the `init.m` to remove package loading and then the kernel must be restarted. This is quite tedious.


How to speed up the computation of a specific array

I am doing some calculations on superconductivity and I REALLY need to speed up the way I calculate one of my arrays. I will put the input to the matrix (of course a tiny toy model of what I am doing), just in case somebody wants to time it, but the important part, and the part which I am asking for help about is `delta`, which is in the lower part. Input to the matrix:               nn = 2; Nband = 2;     Nstates = 2*nn*Nband;          eigenvectors = Table[Range[Nstates] + i, {i, 1, Nstates}];          InverseFlatten[l_, dimensions_] := Fold[Partition, Flatten@l, Most[Reverse[dimensions]]];     uv = InverseFlatten[eigenvectors, {Nstates, Nband, 2, nn}];     u = uv[[1 ;; Nstates, 1 ;; Nband, 1]];     v = uv[[1 ;; Nstates, 1 ;; Nband, 2]];     f = Range[Nstates];     V = Table[Which[i == j + 1, 2],          {l, 1, Nband}, {m, 1, Nband}, {s, 1, Nband},{q, 1, Nband}, {i, 1, nn}, {j, 1, nn}];      Now, first I naively started by doing in it in a intuitive way, but it turned to be crazily slow!!               delta = Table[              Table[Which[i == j + 1,                 Sum[V[[μ, ν, q, s, i, j]]*Sum[u[[n, q, i]]*v[[n, s, j]]*f[[n]],                {n, 1, Nstates}],{q, 1, Nband}, {s, 1, Nband}]],              {i, 1, nn}, {j, 1, nn}],             {μ, 1, Nband}, {ν, 1, Nband}];      Then thanks to this forum, I learned that one should avoid `Sum` and that it was smarter to do `Dot` products of arrays and to use `Total`, then I wrote:               delta =       Table[        Total[Flatten[V[[μ, ν, ;; , ;; , ;; , ;;]]*           Table[              Table[                 Which[                     i == j + 1,                     f.(u[[;; , q, i]]*Conjugate[v[[;; , s, j]]])    ],                    {i, 1, nn}, {j, 1, nn}],               {q, 1, Nband}, {s, 1, Nband}], 1]],           {μ, 1, Nband}, {ν, 1, Nband}];      But this is still toooo slow. Does any of the bright minds of this forum see a faster way to compute `delta`? If somebody wants to time it using `Timing`, can make it bigger by increasing `nn` and `Nband`, in my real calculations `nn` goes up to 600 and `Nband` up to 5. (I do not care about the `Null` elements, just need the non `Null` elements) Thanks


Validating simplifications analytically

I have a rather complex expression which I would like to simplify and check my work along the way ( _Mathematica_ does not simplify very basic things and it is frustrating me). In the following example, all I am doing is writing the square root in the numerator and the square root in the denominator under one radical and _Mathematica_ will not tell me that they are the same thing. the first expression (on the top) is the original and I am subtracting my simplification which should give me zero but it does not. I end up having to plot the differences and the more changes I make to my simplification, the more the computer error propagates which makes that a poor solution for validation. How do I go about having _Mathematica_ validate these simplifications for me analytically?               -((2^(5/2 - 2*t)*(4 + 2*t)!*Subscript[a, 0]^(-3 - 2*t)*         (Subscript[a, 0] + Subscript[a, 1])^(4 + 2*t)*         Sqrt[-((64^t*(5 + 2*t)!^2*Subscript[a, 0]^(12 + 8*t)*Subscript[a, 1]^(5 + 2*t))/            ((4 + 2*t)!*(16^(2 + t)*(5 + 2*t)!^2*Subscript[a, 0]^(3 + 2*t)*               Subscript[a, 1]^(5 + 2*t) - (2*(3 + t))!*(4 + 2*t)!*               (Subscript[a, 0] + Subscript[a, 1])^(8 + 4*t))))])/(5 + 2*t)!) +       (2^(5/2 - 2*t)*(4 + 2*t)!*Subscript[a, 0]^(-3 - 2*t)*        (Subscript[a, 0] + Subscript[a, 1])^(4 + 2*t)*        Sqrt[-(64^t*(5 + 2*t)!^2*Subscript[a, 0]^(9 + 6*t)*Subscript[a, 1]^(5 + 2*t)*            (Subscript[a, 0] + Subscript[a, 1])^4)])/       ((5 + 2*t)!*Sqrt[(4 + 2*t)!*Subscript[a, 0]^(-3 - 2*t)*          (Subscript[a, 0] + Subscript[a, 1])^4*          (16^(2 + t)*(5 + 2*t)!^2*Subscript[a, 0]^(3 + 2*t)*Subscript[a, 1]^(5 + 2*t) -            (2*(3 + t))!*(4 + 2*t)!*(Subscript[a, 0] + Subscript[a, 1])^(8 + 4*t))])      ![TraditionalForm of the expression.](http://i.stack.imgur.com/yihPv.png)


_**How to achieve the real component of my expression?_** Input:               expr = Csc[θ/2] Sin[(n θ)/2] (Cos[1/2 (1 + n) θ] + I Sin[1/2 (1 + n) θ]);     Re[expr]      > >     Re[Csc[θ/2] Sin[(n θ)/2] (Cos[1/2 (1 + n) θ] + I Sin[1/2 (1 + n) θ])] >   But the result I need is: > >     Csc[θ/2] Sin[(n θ)/2] Cos[1/2 (1 + n) θ] >


Finding real and imaginary parts

> **Possible Duplicate:**   >  Extract real part of a complex expression better than Re does I have an expression and I would like to find its real and imaginary parts. As a simplification, suppose the expression is $(a+bi)^2$ with $a,b\in\mathbb{R}.$ Of course               Re[(a + b I)^2]      does not work, since Mathematica doesn't know that $a$ and $b$ are real. So I tried               Assuming[Element[{a, b}, Reals], Re[(a + b I)^2]]      which also fails, even if I hit it with `Simplify` or `FullSimplify`. Then I thought that perhaps `Re` was impermeable to the simplification engine, so I expanded it first:               FullSimplify[Assuming[Element[{a, b}, Reals], Re[Expand[(a + b I)^2]]]]      This gives > Re(a^2-b^2)-2 Im(a b) as the answer, which is closer but still maddeningly incomplete. (Either Mathematica doesn't know that the reals are closed under multiplication and addition or it doesn't know how to find the real or imaginary part of a real number.) Is there a way I can better express my intentions to Mathematica?


Span a function across several consecutive elements in a list

Suppose that I have a list called `list`. I would like to span an arbitrary function `f` across specified consecutive elements in `list`. Here is an example. Suppose the following:               list = {10, 20, 30, 40, 50, 60, 70};      I would like to obtain the following new lists:               {f[{10, 20, 30, 40}], 50, 60, 70}     {10, f[{20, 30, 40, 50}], 60, 70}     {10, 20, 30, 40, f[{50, 60, 70}]}      Is there a simple (perhaps even built-in) way to accomplish this in Mathematica 8? I have come up with the following function `spanMap`, but my method seems very complicated and clunky:               spanMap[function_, list_List, begin_Integer, end_Integer] :=       Module[{result},       If[begin == 1,        If[end == Length[list], result = list;];        If[begin < end < Length[list],          result =            Flatten[{function[list[[begin ;; end]]],              list[[(end + 1) ;;]]}];];        ];            If[begin > 1,        If[end == Length[list],          result =            Flatten[{list[[1 ;; (begin - 1)]],              function[list[[begin ;; end]]]}];];        If[begin < end < Length[list],          result =            Flatten[{list[[1 ;; (begin - 1)]],              function[list[[begin ;; end]]], list[[(end + 1) ;;]]}];];        ];            result       ]      where               spanMap[f, list, 1, 4]     spanMap[f, list, 2, 5]     spanMap[f, list, 5, 7]      yield the desired results:               {f[{10, 20, 30, 40}], 50, 60, 70}     {10, f[{20, 30, 40, 50}], 60, 70}     {10, 20, 30, 40, f[{50, 60, 70}]}      albeit in a complicated, clunky way.


How to determine how much of a table is generated?

If I'm generating a table from a slow function, like this:               foo = Table[SuperSlowExpression, {1000}]      is there a way to determine _after submission_ (so it is too late to instrument the call) to find out how many values already have been generated (so that when it takes longer than expected I can find out whether to wait a bit longer or to abort the calculation)? So is there still a way to get at the information? Note that there is no iteration variable in the call which I could read. Optimally, I'd also want to get the already calculated values, of course. **Edit:** Since this seems to have been consistently overlooked: **This is about a calculation which is already running. It is no longer possible to make changes to the call of`Table` or to the expression inside.**


Numerically solving an inhomogeneous partial differential equation

I'm trying to solve a cylindrical partial differential equation with boundary conditions. But I got an error message saying `NDSolve::ivone: Boundary values may only be specified for one independent variable. Initial values may only be specified at one value of the other independent variable.` Is there any ways I can solve it? $$\begin{align*}\frac1{r}\frac{\partial}{\partial r}\left(r\frac{\partial Y}{\partial r}\right)+\frac{\partial}{\partial z}\frac{\partial Y}{\partial z}-Y&=0\\\ r=0,\;Y=1,\;r=1,\;\frac{\partial Y}{\partial r}&=0\\\ z=0,\;Y=1,\;z=1,\;\frac{\partial Y}{\partial z}&=0 \end{align*}$$ And my _Mathematica_ input is :               eqn1 = {1/r*D[y[r, z], r] + D[y[r, z], {r, 2}] + D[y[r, z], {z, 2}] -              y[r, z] == 0, y[1, z] == 1,              y[r, 1] == 1, (D[y[r, z], {r, 1}] /. r -> 0) ==                             0, (D[y[r, z], {z, 1}] /. z -> 0) == 0};          NDSolve[eqn1, y, {r, 10^-20, 1}, {z, 10^-20, 1}];      Thank you!


How can a package use a variable of a notebook?

I have defined a function `g` in a **_package_**. It is:                g[x_]:=x/.t->3      Now I work in **_notebook_** with the command:                a=t+1;            g[a]      The result is not `4` but `1+t`. What can I do to get the result of `4`? The package file "pack1.m" is like this:               BeginPackage["pack1`"]          g::usage =""          Begin["`Private`"]             g[x_]:=x/.t->3           End[ ]         EndPackage[ ]      And I use `<<pack1.m` to load it.


Creating Marker (Tags) on Top of Plots

I am wondering and tried to plot a graph having labeling specified on top of the graphic. I kind of know a brute force method to accomplish it, but the results will not even look close to clean looking. Is there a more programmatic way or smoother way to accomplish getting a plot with labeling on it as such: ![enter image description here](http://i.stack.imgur.com/f1aym.png) > Instead though, I will like to have the $\mu = \frac{(2n+1)\pi}{2L}$ to be > shifted higher as so in the plot below. I guess, could it be made to easily > be able to adjust coordinates (placement's) or marker on top of the plot. ![enter image description here](http://i.stack.imgur.com/BWGuE.png)


Making a table with elements like {10i+j, i, j}

`Table[10i+j,{i,4},{j,3}]` will generate a table that looks like this: `{{11,12,13},{21,22,23},{31,32,33},{41,42,43}}` I would like to have a table with elements like `{10i+j, i, j}`, I mean `{{11, 1, 1}, {12, 1, 2}, ..., {43, 4, 3}}` How do I make such a table?


How can I turn off SingleLetterItalics in PlotLabels, etc, when the Options Inspector won't do it?

One of the requirements set for the graphing project I am working on is that plot and axis unit labels sometimes need to include superscripts. Here is an approximately minimal example (I have some plotting options set differently from the default, but these shouldn't matter here):               fakedata101 =        FoldList[0.92 #1 + #2 &, 0.,         RandomVariate[NormalDistribution[0, 0.5], 100]];     ListLinePlot[fakedata101, Filling -> Axis, PlotStyle ->Red,       FillingStyle -> Red,       PlotLabel -> "Test Label in k(\!\(\*SuperscriptBox[\(m\), \(2\)]\))"]      ![enter image description here](http://i.stack.imgur.com/kNR29.png) The `SingleLetterItalics` option appears to be turned _off_ in the Options Inspector, but that doesn't seem to work for `String`-format text labels. It _does_ work if set explicitly, e.g. when adding `Text` in an `Epilog` with an explicit `Style` wrapping:               Epilog ->       Text[Style["\!\(\*SuperscriptBox[\(Text with Footnote marker\), \((a)\)]\)",         SingleLetterItalics -> False], {10, -1.5}]      Is there a way I can robustly turn off `SingleLetterItalics` in styled text such as this? I would prefer not to have to catch every `String` passed to a `PlotLabel` or `AxisLabel` and send it through a `Style` command if I could help it.


What is the best way to produce a symmetric semi-definite matrix using as few variables as possible?

As we know, there are only $\frac{n(n+1)}{2}$ variables in a symmetric $n$-dimensional semi-definite matrix. Is it possible to produce a $n$-dimensional semi-definite matrix whose trace is $1$ using only $\frac{n(n+1)}{2}-1$ variables, $\frac{n(n+1)}{2}$ from symmetry and one from the trace constraint? If so, what is the best way? Till now, I can produce a $n$-dimensional semi-definite matrix $\rho$ whose trace is $1$ in the way               t = ({       {a, b, c, d},       {e, f, g, h},       {i, j, k, l},       {m, n, o, p}     });     ρ = t.t\[Transpose]/Total[Flatten[t]^2];      but I need $n^2$ variables and sometimes `Total[Flatten[t]^2]` may be zero because of semi-definiteness. Any help or suggestions will be appreciated.


Error when using FullForm with ?symbol

`Information[symbol]` shows information about a symbol and is equivalent to `?symbol`.               Information[symbol]     ?symbol      > Global`symbol               Information[symbol, LongForm -> True]     ??symbol      > Global`symbol Using `FullForm` with `?symbol` returns the following error:               FullForm[Unevaluated[?symbol]]      > Syntax::bktmcp: Expression "Unevaluated[?symbol]]" has no closing "]". > > Syntax::sntxi: Incomplete expression; more input is needed . But using `FullForm` with `Information[Unevaluated[symbol]]` returns the following expression without any error:               FullForm[Unevaluated[Information[symbol]]]      > Unevaluated[Information[symbol,Rule[LongForm,False]]] Why does this happen?


How to avoid writing $K$ loops?

I want to evaluate a mathematical function of $K$ variables each of variables varying between 1:N. One way to do this is writing $K$ loops and varying variables accordingly, as shown below:               For x1 = 1:N         For x2 = 1:N              ...                 For xK = 1:N                    A(x1,x2,...,xk) = f(x1,x2,...,xk)                 End xK              ...         End x2     End x1      I want to know is there any other way to do this without $K$ loops? Since I want to write a routine doing these evaluations for all possible $K$'s, it isn't possible to write varying number of loops in a routine, so what should I do?


Parametric plot using listplot?

I was searching in the list of questions here but I couldt find it. I have two vectors say x={0.1, 0.2, 0.3, 0.4, 0.5} and y={2, 3.5, 6, 7, 8}. I want to plot them with respect to each other using probably listplot or listlineplot. What is the easiest way of doing this? thank you!


Print out all functions in Mathematica

Sometimes I only remember parts of a function name and I want find that function name quickly, and if I search in the document center, it will give too much informations related to that and difficult to find what I'm looking for. So is there a way to print out all the MMA functions in alphabetical order in a notebook, so that I can search only in the function names? Thanks.


Error when putting ??symbol in a cell with another expression

Putting `??symbol` in a cell and another expression in a different row of the cell returns the following error:               ??symbol     1 + 2      > Information::ssym: symbol 1+2 is not a symbol or a valid string pattern. >> > > Information[symbol 1+2,LongForm->True] But this does not happen with `?symbol`:               ?symbol     1+2      > Global`symbol > > 3 Why does this happen?


Det and MatrixRank freezes on SparseArray with nonzero default value

Why does the following simple code never come to an end (at least with version 8)               n = 5;     mat = SparseArray[{i_, i_} -> 1, {n, n}, -1/(n - 1)];     MatrixRank[mat]      when the following clearly doesn't cause any problem?               n = 5;     mat = Normal@SparseArray[{i_, i_} -> 1, {n, n}, -1/(n - 1)];     MatrixRank[mat]      The same issue appears to exist with `Det` instead of `MatrixRank`.


Defining the function of list of parameters

I'm defining the functions in the following way                ClearAll[Ka, Po, r, P, L, PL];       params = {r, Po, Ka}       prmss = ToExpression[StringInsert[Map[ToString, %], "_", -1]]       eq = {Ka*P*L == PL, Po == P + PL, r*Po == L + PL};       variables = {P, L, PL};                 sol = Solve[eq, variables] // Last;           (*Define functoins of variables*)            Table[variables[[i]][r_, Po_, Ka_] :=          Evaluate[(variables /. sol)[[i]]], {i, Length[sol]}];                   Ka = 10000;       Po = 0.001;                 ParametricPlot[Table[{r, variables[[i]] @@ params}, {i, Length[variables]}], {r, 0.1, 5}]      I would prefer do not list them explicitly like [r_, Po_, Ka_] but to do something like @@prmss How I can do it in my case?


Simplifying a quadratic

I have a general query about simplifying expressions in Mathematica, which I will illustrate using quadratics. If I tell Mathematica to simplify $a x^2 + b x + c$ then   * `Simplify` will give the same (fully expanded) form $a x^2 + b x + c$    * `FullSimplify` will give a form like $((ax+b)x+c)$ Clarification: The coefficients in the simplified form (of course) need not be the same values $a,b,c$. The variable names are meant for demonstration of the format. Example               poly = x^2 + 4*x + 1     Simplify[poly] (* gives 1 + 4 x + x^2 *)     FullSimplify[poly] (* gives 1 + x (4 + x) *)     (*Desired answer (x+2)^2 - 3 *)      However, I desire the format: $a{(x-b)}^2 + c$ which I find to be more intuitive in "understanding" the expression.   1. What measure of "expression complexity" does Mathematica work with?   2. How could I get the kind of result that I want? If possible, I'd like to know how to do this for not just quadratics, but also more complicated polynomial expressions.


Opacity and overlapping points on ListPlot3D

I am plotting a dataset on ListPointPlot3D, and in order to give an idea of density of points I used opacity of 0.5. The problem is that that while the opacity of points behind one another is added, when multiple points overlap the opacity is not added; I need a way for the opacity of overlapping points to be added. A minimal example:               ListPointPlot3D[{{1, 1, 1}, {1, 1, 1}, {1, 2, 1}, {1, 2, 2}}, PlotStyle -> Directive[PointSize[0.1], Opacity[0.5]], ViewPoint -> {0, 0, Infinity}]       ![Mathematica graphics](http://i.stack.imgur.com/Cl1vt.png) The first two points overlap completely (thus their opacity does not add), the latter two points overlap in x and y but differ in z (thus their opacity adds). I want to get the opacity of the first two points to add as well.


How to write documentation in Wolfram Style?

Rather than craft my own stylesheets for documentation, I'd like to emulate (copy? ape? borrow?) the Wolfram style. Here is a very small example (type this in the help-box, which you get by pressing `F1`)               Quaternions/ref/UnitQuaternionQ      Here is a very large example               ContourPlot3D      I have zero experience creating styles, and I have only the most foggy understanding of how Notebooks work. I have gotten this far: If I scrape over the orange-and-yellow text at the top of the `UnitQuaternionQ` example, the cell just underneath the heading, then press `Command-Shift-E` or use the `Cell>Show Expression` menu item, then I see this magnificent bouillabaisse:               Cell[BoxData[GridBox[{        {"", Cell[TextData[{          Cell[BoxData[           RowBox[{"UnitQuaternionQ", "[",             StyleBox["q", "TI"], "]"}]], "InlineFormula"],          "\[LineSeparator]gives ",          Cell[BoxData[           TemplateBox[{Cell["True"],"paclet:ref/True"},            "RefLink",            BaseStyle->"InlineFormula"]], "InlineFormula"],          " if ",          Cell[BoxData[           StyleBox["q", "TI"]], "InlineFormula"],          " is a unit quaternion and ",          Cell[BoxData[           TemplateBox[{Cell["False"],"paclet:ref/False"},            "RefLink",            BaseStyle->"InlineFormula"]], "InlineFormula"],          " otherwise."         }]]}       }]], "Usage",      GridBoxOptions->{      GridBoxBackground->{       "Columns" -> {{None}}, "ColumnsIndexed" -> {}, "Rows" -> {{None}}, "RowsIndexed" -> {}}},      CellID->16193]      This gives me a lot of clues, but also a large number of things to look up, understand separately, and then piece back together, namely `Cell`, `GridBox`, `TextData`, `BoxData`, `RowBox`, `StyleBox`, `TemplateBox`, `paclet`s as URIs, and everything they depend on. I also find out that when I paste that expression into a new notebook and do `Command-Shift-E`, I get errors, most of which imply that there is a missing stylesheet. From this I infer that notebooks have a secret, implicit "style sheet" attribute, but I don't know how to set it or get it in a general way. When my mouse-focus is in the help box, the `Format` menu does not contain an obvious way for me to snip, copy, borrow, ape, or otherwise access the style sheet. I tried looking for an author's guide in the documentation, but a few quick searches didn't turn up anything on-point.


Filling between boundaries

I would like to visualize what it graphically means to integrate between two boundary values. Therefor I'd like to make a Filling between these two values. Is there a way to get this done?


Fourier Series of "Split" Defined Function

Not sure how to phrase this in a concise way, anyway it seems like the function FourierSeries assumes the interval for which to compute the Fourier coefficients of a given function is $[-\pi,\pi]$, which is all well and good. But if the function $f$ is defined as $g$ on, say, $[-\pi,a)$ and as $h$ on $[a,\pi]$, is there a way to define $f$ this way so that one can apply FourierSeries immediately on $f$? Also, is there a way to make Mathematica understand that $\cos{n\pi}=(-1)^n$ and $\sin{n\pi}=0$?


Inconsistency of output format in `Eigenvalue`

I am bothered by the output format of the last two elements of `efre`. Is there a way to make these two look like the same format as the first two in `efre`?               Remove["Global`*"]          coe = k/m SparseArray[{{i_, i_} -> -2, {i_, j_} /; Abs[i - j] == 1 ->            1} , {4, 4}];     efre = Sqrt[-coe // Eigenvalues] // Simplify      evec = coe // Eigenvectors // Simplify;     Column[Subscript[ω, #] & /@ Range@4 == efre // Thread,       Spacings -> 2]      ![enter image description here](http://i.stack.imgur.com/YcBoX.jpg)


Plotting attributes of vertices in WattsStrogatzGraphDistribution[n, p, k]

I have a graph `WS = RandomGraph[WattsStrogatzGraphDistribution[n, p, k]]`. I need to plot several characteristics of each `v`: the clustering coefficient, number of triples at `v`, eccentricity, vertex centrality, closeness, and betweenness. I'm relatively inexperienced with Mathematica and quite lost on how to achieve this. I don't expect the exact lines of the solution, I'd just like some pointers on how to approach this. First of all, how do I get a set of all the vertices of `WS`? Then, how do I get the values of the different measures for each `v` in `WS`?


Mathematica 10 : Where is the Mathematica Book?

The question is simple. In Mathematica 9, there used to be "The Mathematica Book" integrated with the software in the help system. I can't find it anymore in version 10. Do you know if it is still there ? Best regards, F.


How to choose a solution of a differential equation?

I am trying to solve the following differential equation:               delta = -(1/r D[#, r] + D[#, {r, 2}] - # l^2/r^2) &;     DSolve[delta[         g[r]] + (B l + B^2 r^2/4) g[r] == en g[         r], g[r], r]      The solution proposed by Mathematica is okay yet one can find an alternative, less complex representation with Whittaker functions. Is it possible to force Mathematica to use a certain type of function as a solution of a differential equation? We do not impose any boundary conditions. In this specific problem one can always use a transformation rule for the confluent hypergeometric function, for instance               rule = HypergeometricU[a_, b_, z_] ->        E^(z/2) z^(-b/2) WhittakerW[b/2 - a, (b - 1)/2, z];      but this is just a workaround. Perhaps there is a more elegant way. **Edit** For instance, consider the harmonic oscillator equation               DSolve[-y''[x] == y[x], y[x], x]     {{y[x] -> C[1] Cos[x] + C[2] Sin[x]}}      Is it possible to force a solution with exponential functions? Of course, the replacement rule can be used but perhaps there is a deeper solution.               {{y[x] -> C[1] Exp[I x] + C[2] Exp[-I x]}}      It would be great if Mathematica could provide a list of exemplary solutions (but this is just wishful thinking:-).


How to create an inverse pole figure color map

To interpret electron backscatter diffraction (EBSD) results, inverse pole figures are used. A three dimensional space of directions ([100], [110] and [111] for those who know about crystallography) is projected to a color map, such that purely [100] oriented points are colores red, [110] green and [111] blue, respectively. Mixtures of orientations are colored in mixed colors. Usually, a legend like this one is used: ![enter image description here](http://i.stack.imgur.com/Kfwkc.jpg) I want to recreate the legend in Mathematica, but unfortunately I don't know how exactly the thre dimensional orientation space is projected to the two dimensional wedge. Obviously, the colors used in the legend are those from half the surface of the $(r,g,b)$ color space, as shown in this plot:               RegionPlot3D[       And @@ Thread[0 <= {x, y, z} <= 1] && x + y + z > 1,       {x, 0, 1}, {y, 0, 1}, {z, 0, 1},       ColorFunction -> (RGBColor[#1, #2, #3] &),       Mesh -> None,        ViewPoint -> {20,20,20},       Lighting -> {{"Ambient", White}},       Boxed -> False     ]      > ![\(r,g,b\) color space](http://i.stack.imgur.com/gzei1.jpg) Since I dont't know how to project that surface onto the wedge, I tried to recreate the legend by hand. The wedge shape was easy, but I can't seem to get the `ColorFunction` right. Here's what I tried:               myColorFunction =        RGBColor[         Piecewise[{{1, #3 <= 0.5}, {(2*(1 - #3))^2, True}}],          Piecewise[{{1, #3 >= 0.5 && #4 < 0.5}, {(2*(1 - #4))^2, #3 >= 0.5 && #4 >= 0.5},           {(2*#3)^2, #3 < 0.5 && #4 < 0.5}, {(4*#3*(1 - #4))^2, True}}],         Piecewise[{{(2*#4)^2, #3 >= 0.5 && #4 < 0.5}, {1, #3 >= 0.5 && #4 >= 0.5},           {(4*#3*#4)^2, #3 < 0.5 && #4 < 0.5}, {(2*#3)^2, True}}]] &;          With[{rstart = 1, rend = 1.15, phi = 42 \[Degree]},        ParametricPlot[         r (1 + (p/phi)^2 (rend - rstart)) {Cos[p], Sin[p]}, {r, 0, rend}, {p, 0, phi},          ColorFunction -> myColorFunction,         Mesh -> None,         Frame -> False,          Axes -> False]]      > ![enter image description here](http://i.stack.imgur.com/DqmSs.jpg) I already like the outer part, but i can't reproduce the three triangular whitish lines in the middle (which obviously correspond with the edges of the $(r,g,b)$ box). How do I have to change my `ColorFunction` accordingly? Or even better: how can I project the colors from the surface of the box above to my two dimensional wedge?


How can I tell how much memory is taken by an expression?

`ByteCount` and `LeafCount` don't really work, as shown below. _Mathematica 9.0_ .. on a _32 bit Windows_ machine.               f[n_] := Block[{k = f[n - 1]}, {k, k}]     f[0] = x      `LeafCount[f[k]]` for particular small integers `k` returns the number `2^(k+1) - 1` e.g.   for `k = 3`, it returns `15`. But it returns the same answer for `k = 30`, `31`, .... It returns `2147483647`, which, probably not coincidentally, is `2^31 - 1`. `ByteCount` has a similar problem in running out of bits in its counter. Anyway, `ByteCount` also lies in a different way... because it doesn't take into account the sharing that (say) `f[70]` has. Without the sharing implicit in the formula above, I could not compute that -- it has $2.36 \times 10^{21}$ leaves. They are just not different leaves. Presumably techniques that produce expressions with smaller memory footprints should be preferable.


Overloading second argument of CountryData

For convenience I'm trying to add an extra property to `CountryData`               Unprotect[CountryData];     CountryData[c_String, "MyProperty"] := 0; (* actually call to another function *)     Protect[CountryData];      But when using it I get:               CountryData["Greenland", "MyProperty"]      > CountryData::notprop: "!(\"\\\"MyProperty\\\"\") is not a known property for > CountryData. Use CountryData[\"Properties\"] for a list of properties." What's the right way to do this? _There is high probability this is a duplicate, but I wasn't able to find how to do this, sorry in advance_


TrueQ returning False on true statement

Why does `TrueQ` return `False` on the following?               TrueQ[Log[2]/Log[8] == 1/3]     (* False *)      Shouldn't that be `True`? We can clearly see that the math checks out.               Log[2]/Log[8] // N     (* 0.333333 *)          8^(1/3)     (* 2 *)


Error trying to open a notebook in Wolfram Workbench

I recently set up Mathematica 9.0.1 on a new computer, along with x64 Eclipse Indigo with JRE 1.7, and the Wolfram Workbench 2 plug-in. Something is amiss, because when I try to do any sort of task involving Mathematica from inside Workbench, I get the same error message:               An internal error occurred during: "FrontEnd Job::Open Notebook".      com.wolfram.jlink.NativeLink.MLOpenString(Ljava/lang/String;[Ljava/lang/String;)J      Otherwise, Mathematica works fine, as does the Eclipse install when used for other purposes (Java and Scala development). This is a 64 bit Windows 7 machine.


Is it possible to circumvent a bug inside SeriesCoefficient?

As far as I can tell, there seems to be a bug in `SeriesCoefficient`:               In[4]:=        f[z_] := (-z + z Sqrt[1 - 4 z^2])/(2 (-1 + z));       SeriesCoefficient[f[z], {z, 0, 10}]       SeriesCoefficient[f[z], {z, 0, n}] /. n -> 10          Out[5]= 9          Out[6]= 93/256      Note that both outputs should be the same, but apparently the application general in `n` makes a mistake (`9` is the correct result). In fact, I know that the coefficients grow exponentially in `n` but we get:               In[9]:=        SeriesCoefficient[f[z], {z, 0, n},          Assumptions :> Mod[n, 2] == 0 && n >= 2] // FullSimplify          Out[9]= 1/2 (1 - Gamma[n/2]/(Sqrt[\[Pi]] Gamma[(1 + n)/2]))      This quantity, $\qquad\displaystyle \frac{1}{2} \cdot \biggl(1 - \frac{\Gamma\bigl(\frac{n}{2}\bigr)}{\sqrt{\pi} \cdot \Gamma\bigr(\frac{n+1}{2}\bigr)} \biggr)$, converges to 1/2 from below (odd `n` support the same series), so it's not even _close_ to being correct. Obviously, I can't tell what exactly goes wrong inside `SeriesCoefficient`. Since I have an interest in the general form of the coefficient (of the expansions of this and other functions), is there a way to circumvent the bug inside (or the application of `SeriesCoefficient`) so that it works more reliably? Less power would be acceptable in trade.


recursive integration

I am trying to do multiple integrations recursively. For instance, I would like to do the following equation for arbitrary integer $n$: $\displaystyle R_n(t) = \int_0^t \mathrm dt' R_0(t-t') R_{n-1}(t')$ where $R_0(t) = e^{-k t}\cos\omega_0 t$. I can do it by brute force, but I would like to be able to do it automatically for any $n$.


Making a symbol's new definitions be tried before all previously defined ones

Is there any way to "close" a package (or a symbol, or a context) in that if a user of the package adds definitions to the symbol they will be tried before the package defined ones, just like what happens with built-ins?


Fast randomization of a graph, while keeping the graph connected

I'm looking for a very efficient method for randomizing graph of a given size (N nodes, L links), but keeping them connected. Assume you have the adjacency matrix A of a given connected graph. You want to generate R (usually a big number) random adjacency matrices Aran1,Aran2,...AranR, with the same N, L, AND connected. I did the following code, I'm looking for a more efficient one.               randomization[Q_] :=        Module[{Aran = {0, 0}},         While[           Length[Select[Total[Aran], # == 0 &]]> 0,            Aran = Partition[Nest[RandomSample, Flatten[Q], 10], Dimensions[Q][[2]]]         ]     ];      Thanks!


Anchor Manipulate Controls to Edges of Content

I'm running into an issue with arranging Manipulate controls and a dynamic module around the content pane of the Manipulate. For example:               Manipulate[      Plot[a b c x, {x, 0, 100}, PlotRange -> {0, 100}],      {{a, 1}, 0, 2, Appearance -> "Labeled"},      {{b1, 1}, 0, 2, Appearance -> "Labeled"},      {{b2, 1}, 0, 2, Appearance -> "Labeled"},           Dynamic[       Plot[        Sin[t], {t, 0, 10}, AspectRatio -> 1.5, ImageSize -> {200, 300}        ]],           {{b, 1, Row[{Spacer[300], "a"}]}, 0, 2, Appearance -> "Labeled"},      {{c, 1}, 0, 2, Appearance -> "Labeled"},      ContentSize -> {400, 260},           ControlPlacement ->        Flatten[{Table[Left, {4}], Table[Bottom, {1}], Table[Right, {7}]}]     ]      ![Imgur](http://i.imgur.com/6YMFfWz.jpg) I want the slider on the bottom, labeled "a" (oops, should have been b), to be sitting right underneath the content of the Manipulate (the linear graph). However, the dynamic module on the left-hand side, which is a plot of a sine function, seems to "push" the control further down than I want it to. How can I fix this?