title: Why does the evaluation of this series fail?

text: The following series expression holds:               BesselJ[1,a x]BesselJ[1,b x]==a b (x^2)/4*Sum[(-1)^n*(a x/2)^(2n)*Hypergeometric2F1[-n,-1-n,2,b^2/a^2]/(n!Pochhammer[2,n]),{n,0,Infinity}]      Where `BesselJ[1,x]` is the Bessel function of the first kind of order 1. `Hypergeometric2F1[a1,a2,b1,x]` is Gauss hypergeometric function. `Pochhammer[2,n]` is the Pochhammer Symbol. This series expression can be found in e.g. Bateman Manuscript Project, Higher Transcendental Functions, Vol.2, and it holds without any constraints. For this series expression, if the relatively small parameters are chosen, e.g. `a=1`, `b=2.5`, `x=3`, and just replace the sum index `Infinite` with `100`, the product of Bessel functions gives `0.045857190997445` and the series gives `0.045857190997469`. They coincide well. However, for a relatively large `x`, the product of Bessel functions must be decreasing, e.g. `a=1`, `b=2.5`, `x=100`, the product of Bessel functions gives `0.003338005199477126`, but the series gives `6.410492282570008*10^131` which is apparently divergent. The reason of this divergence is unknown for me. It can't be better to increase the terms of the series expression or improve the precision of the Gauss hypergeometric function. Could anyone help? Thanks!


title: Add lists with unequal lengths together to create a matrix

text: I'm trying to create a stacked bar chart using raw data coming from a MySQL server. The result coming back from one query is:               {{SQLDateTime[{2011, 7, 23, 13, 0, 0.}], 74},       {SQLDateTime[{2011, 8, 11, 15, 35, 54.}], 1},       {SQLDateTime[{2011, 8, 18, 9, 28, 14.}], 49},       {SQLDateTime[{2011, 8, 24, 21, 45, 29.}], 1},       {SQLDateTime[{2011, 8, 31, 10, 0, 18.}], 1},       {SQLDateTime[{2011, 9, 8, 10, 6, 45.}], 5},       {SQLDateTime[{2011, 9, 14, 9, 35, 40.}], 10},       {SQLDateTime[{2011, 9, 15, 6, 27, 12.}], 1},       {SQLDateTime[{2011, 9, 21, 9, 47, 26.}], 6},       {SQLDateTime[{2011, 9, 29, 10, 5, 2.}], 3},       {SQLDateTime[{2011, 10, 6, 9, 34, 26.}], 3},       {SQLDateTime[{2011, 10, 24, 9, 31, 42.}], 1},       {SQLDateTime[{2011, 10, 27, 9, 52, 7.}], 2},       {SQLDateTime[{2011, 11, 25, 10, 53, 27.}], 2},       {SQLDateTime[{2011, 12, 1, 11, 0, 21.}], 3},       {SQLDateTime[{2011, 12, 6, 10, 49, 42.}], 3},       {SQLDateTime[{2011, 12, 8, 14, 38, 54.}], 1},       {SQLDateTime[{2012, 3, 27, 8, 10, 31.}], 1}}      I'm going to get ten similar sets of results. The difference will be that they don't contain all of the same dates. I need to create a matrix like so: The first row is a list of dates. Each result set will contain different dates and some will be the same and some not, think of this first row as a list of unique dates pooled together from all result sets. Should be ordered chronologically. Row number two lists the correponding values in each column. Look at my example result set above. Each date has a value corresponding to it. All of these values make up a row, with each element under its corresponding date. There will be dates in the first row for which there are no corresponding values in this particular result set, these elements should be zero. There will be one row for each result set plus the top row consisting of dates. How can I do this?


title: Transform recursion for coefficients into differential equation for generating function

text: Assume, one is given a linear recursion with polynomial coefficients for a sequence $(a_i)_i$, such as               a[i] == i a[i-1]      I would like to convert this recursion into a differential equation for the (formal) generating function $G(x)=\sum_{i}a_i x^i$. In my example above, direct manipulation leads me to the equation $$ G(x)=2x^2 a_1+x^2 G'(x)+xG(x) $$ which Mathematica can solve in terms of special functions. Interestingly, the power series with coefficients $i!$ (the solution to $a_i=i a_{i-1}$) doesn't converge for any $x$. Since I'm only interested in formal power series, however, I still believe that my question makes sense. I'm particular interested in a method that also works for higher order recursions with higher degree polynomial coefficients. Thanks. I would like to add that I am familiar with the functions GeneratingFunction[] and RSolve[] but neither seems to be of much help for this problem. **Edit 18 April 2014:** In version 9 the behaviour of `GeneratingFunction` appears to have changed in such a way that it doesn't directly solve this problem any longer. I therefore reactivate this question and ask for a way to transform a linear recursion with polynomial coefficients into a differential equation for the generating function.


title: How to construct this matrix fast?

text: I write a function which is a matrix as below:               mat[kx_, n_] := (        Clear[a, b, h];        h = Table[0, {i, 1, 2 n}, {j, 1, 2 n}];        a[m_] := 2 m - 1;        b[m_] := 2 m;        t1 = 1;        aa = 1;        Do[        h[[b[i], a[i]]] =          t1 (E^(I kx ((Sqrt[3] aa)/2)) + E^(-I kx ((Sqrt[3] aa)/2)));        h[[a[i], b[i]]] =          t1 (E^(I kx ((Sqrt[3] aa)/2)) + E^(-I kx ((Sqrt[3] aa)/2)));        If[i + 1 <= n, h[[b[i + 1], a[i]]] = t1, Null];        If[i - 1 > 0, h[[a[i - 1], b[i]]] = t1, Null];        , {i, 1, n}];        h)      I test the speed of the matrix construction               In[90]:= Table[mat[kx, 7], {kx, 0., 1., 1/3000}]; // AbsoluteTiming          Out[90]= {1.971113, Null}      the dimension of the `mat[kx,7]` is 14, so I test the following randomreal matrix               In[91]:= Table[        RandomReal[{0, 1}, {14, 14}], {kx, 0., 1.,          1/3000}]; // AbsoluteTiming          Out[91]= {0.027002, Null}      it is 100 times faster. **So I wonder if my`mat` function could be 100 times faster. I know my programming is poor, but I don't know how to code it elegent and efficient.So can somebody help me with it and point it out which is the most important factor that make my `mat` function so slow?**


title: Front-end glitch when interacting with dynamic content

text: This is now bugging me too much to ignore it anymore. When I interact with a notebook that has dynamic content, for example moving a slider, _Mathematica_ regularly brings other open notebook windows to the front. This means that while I am interacting with the given notebook, some other notebook (already opened, but in the background) pops up in the front, either blocking my view or just staying in the lower-left corner (if it was minimized before). The focus is not changed, so I can still interact with the content of the original notebook now in the back. When I continue manipulation, the front notebook disappears, just to reappear again a few seconds later. This is extremely annoying and happens "if the `Manipulate` [or other dynamic content] contains something that's computationally expensive" (Sjoerd's comment below, and I can confirm this), mostly when complex 2D or 3D plots are manipulated directly (e.g. 3D rotate with mouse) or indirectly (mouse driven slider changes parameters of dynamic plot). For example rotating the following 3D figure with the mouse causes the behaviour to present itself.               Plot3D[Sin[x + y^2], {x, -3, 3}, {y, -2, 2}]      Reproducibility is occasional, sometimes it happens fairly frequently, sometimes not at all. A more or less solid way to reproduce the error:   * open a fresh _Mathematica_   * open a new notebook (by e.g. `ctrl`+`N`; this will be the one that will pop to the front; this can be _any_ notebook window)   * open another notebook, paste above code   * evaluate code (dragging the 3D plot now won't trigger the glitch, or only very rarely)   * bring in front any other application, e.g. Firefox (though the glitch could happen even if no other application is running)   * get back to _Mathematica_ (by e.g. minimizing Firefox)   * dragging the 3D plot around for some time (~5-10 sec) has a high chance to trigger the glitch, which can manifest as short "jumps" of open Mathematica windows where one gets in the front for a fraction of a second) **Does anyone else experience this annoyance?** **What causes this behaviour?** * * * This is still reproducible under Mathematica 9.0.1, Windows 7.


title: wordpress wolframCDF plugin 2.0 stopped working

text: setup and tried a simple CDF document and it worked like a charm. That was a couple of months ago - now the post does not show evidence that the shortcode is working at all - the shortcode is in the post - yet, nothing on the view. This has occurred on two sites that I've place test posts with CDFs. I do not recall an update to WordPress or WolframCDF recently - and may well have misted something. I do not know how long the CDF plugin hasn't been working The post http://nomtbf.com/2013/04/weibull-vs-exponential-pdfs/ should have a obvious CDF under the get player button. any ideas on what's happening here and how to fix it? I've deleted the plugin and reinstalled. No love. I checked my machines player (most current) and did a reinstall, no love. Ideas? cheers, Fred http://wordpress.org/extend/plugins/wolfram-cdf-plugin/


title: Updating a tracked symbol inside Refresh?

text: I have some code inside a `Manipulate`, whose goal is to allow the user to edit the upper half of the matrix while keeping it symmetric at all time. The minimal code is the following:               Manipulate[      Refresh[         i = i + 1;         Do[Cmat[[i, j]] = Cmat[[j, i]], {i, 2, 6}, {j, 1, i - 1}];       , TrackedSymbols -> {Cmat}];      {i, Grid[Array[InputField[Dynamic[Cmat[[#1, #2]]], FieldSize -> 5, Enabled -> #1 <= #2] &, {6, 6}]]}      ,      Initialization :> (        i = 0;        Cmat = ConstantArray[0, {6, 6}];        )]      I added the `i` variable as a counter, and I expected it to be only incremented when I actually change the value of one of the `Cmat` elements. What actually happens is that `i` increases near the speed of the runloop, and that code actually hogs the CPU (one core of it, anyway). I suppose what happens is that the modification of the tracked value inside `Refresh` actually triggers `Refresh` itself, hence the loop. How can I prevent this? I thought restricting `TrackedSymbols` to the upper half of `Cmat` would do the trick, but it changes nothing. Is there a way, inside of `Refresh`, to change `Cmat` without it being tracked? The opposition functionality exists, in the form of `Update`.


title: Expand list of {{t1,x1},...} with new set of t's

text: I have a list of the form `data={{t1,x1}, {t2,x2},...}` and a list `newt = {nt1,nt2,...}` and I want to expand `data` to these new times to become `{{nt1,x(1)},{nt2,x(2)},{nt3,x(3)},...}` where `x(i)` is equal to the `xi` of whichever data point is preceding `nti`. I assume that `t1<=t2<=t3<=..`, `nt1<=nt2<=...` and the old times is a subset of the new ones. I did this the following way, but it is far too slow:               PadDataList[l_, grid_] :=       Module[        {lind = 1, len = Length@l},        MapIndexed[(           If[# > l[[lind, 1]] && lind < len, lind++];           {#, l[[lind, 2]]}           ) &,         grid         ]];     data = Sort[RandomReal[1, {50000, 2}], First@#1 < First@#2 &];     newgrid = Union@Join[data[[All, 1]], RandomReal[1, {50000}]];     AbsoluteTiming[PadDataList[data, newgrid];]     (* 0.4 seconds *)      Is there a cleverer and more efficient way to do this? I am using this together with another function that takes multiple lists like above and creates a new list with elements `f[nti,x(i),y(i),...]` Excuse the abuse of (i) syntax


title: Improving the performance of a package for working with rational functions

text: As _Mathematica_ gets slow for large symbolic calculations, the cost of putting terms over a common denominator (`Together`), in particular, gets too high. It occurred to me that, if one has a small number of variables, it should be much faster if we represent our expressions by arrays of their coefficients. I have implemented a small package that does this with an improvement of a factor of 10 in both speed and memory (in putting `Together` a sum of rational terms, more or less independent of the size of the sum), but it seems to me that I should be able to do better. I post my package here with the hope that someone might point out glaring performance bottlenecks. First, the public initializations, with their usability comments.               AA::usage = "DATA STRUCTURE AA[num,den] that stores polynomials as their tensor coefficients of a basis, multiplication is the tensor product"     PolytoAA::usage = "PolytoAA[poly_,vars_List] returns an AA[num_SparseArray,1]"     AAtoPoly::usage = "AAtoPoly[aa_AA,vars_] gives back a rational function of the polynomials num/den"      The actual code begins here, `PolProd` takes care of multiplying polynomials               SetAttributes[PolProd, Orderless]     PolProd[i__Integer] := Times @ i;     PolProd[sa__SparseArray] := Outer[Times, sa];       (*multiplying 2 polynomials is the tensor product in their vector space*)     PolProd[i__Integer, sa__SparseArray] := Times[i] Outer[Times, sa];          (*It would be cleaner and more object oriented to call two instances of polprod        on i and sa but it would force more pattern matching so it would be less efficient*)      This code performs the arithmetic operations on the `AA[num,den]` data structure               AA /: i_Integer*AA[num_, den_] := AA[i*num, den]      (*absorb all integer into AA, this means that the sum rule has to do less         pattern matching and is more efficient, overall more efficient?*)     AA /: AA[a_, a_] := 1     AA /: AA[0, _] := 0     AA /: AA[num1_, den1_]*AA[num2_, den2_] :=        AA @@ (PolProd[#1, #2]& @@@ {{num1, num2}, {den1, den2}})     AA /: AA[num1_, den_] + AA[num2_, den_] :=        AA[num1 + num2, den]       (*can't check for a SparseArray cos it might be an Integer,          by dimensional analysis we should get two arrays here though*)     AA /: AA[num1_, den1_] + AA[num2_, den2_] :=        AA[PolProd[num1, den2] + PolProd[num2, den1], PolProd[den1, den2]]       (*together rule, this a recursive implementation that doesn't treat the          sum of many AA all at once, this is intentional cause it minimises the          number of array outer products that are calculated and I believe it's          the more efficient but maybe not*)     AA /: aa_AA^n_Integer :=        If[n < 0, Reverse @ #, #]& @ (PolProd[Sequence @@ ConstantArray[#, Abs @ n]]& /@ aa)       (*this takes care of both efficiency of recursively pattern matching the          product rule on large n and dividing by AA*)     (*NOTICE THE WEIRD SYNTAX/BUG If[n<0, Reverse @ #, #]& @ THERE ARE TWO INTANCES OF @*)      I also post the the functions that go between `AA` and the polynomials for the sake of clarity and completeness               AAtoPoly[aa_AA,vars_] := #1/#2& @@ (aa /. l_SparseArray :>        Dot[l, Sequence @@ ConstantArray[vars, Depth[l] - 1 (*gives rank of the tensor*)]])     PolytoAA[expr_^n_, vars_List] := PolytoAA[expr, vars]^n     PolytoAA[expr : (_Times | _Plus), vars_List] := PolytoAA[#, vars]& /@ expr     PolytoAA[expr_,vars_List] /; PolynomialQ[expr, vars] :=        AA[Last[CoefficientArrays[expr, vars]](*num*), 1 (*den*)]      **BENCHMARKS** I define some random, small polynomials               vars = a /@ Range[10]     pols = Table[        a[RandomInteger[{1, 10}]] + a[RandomInteger[{1, 10}]], {20}] //        DeleteDuplicates     % // Length      > {a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10]} > > {a[1] + a[7], a[4] + a[6], a[2] + a[4], a[5] + a[9], 2 a[8], a[5] + a[6], > a[2] + a[9], a[4] + a[7], a[4] + a[9], a[7] + a[9], a[3] + a[7], a[2] + > a[6], a[1] + a[9], a[2] + a[3], a[7] + a[10], 2 a[2], a[3] + a[9]} > > 17 First I put them `Together` using my code               aa = PolytoAA[#, vars] & /@ pols;     togaa = Sum[aa[[i]]/aa[[i + 1]], {i, Length@pols - 1}] //        AbsoluteTiming     % // ByteCount      > > {0.8960513,AA[SparseArray[<274432>,{10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}],SparseArray[<16384>,{10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}]]} > > 18614128 and now without my implementation               togpols = (Sum[pols[[i]]/pols[[i + 1]], {i, Length@pols - 1}] //          Together) // AbsoluteTiming//     % // ByteCount      > {8.2054693,...} > > 34567480 I check that both give the same result               togpols2 = AAtoPoly[togaa // Last, vars](*//Simplify*);     Last[togpols] - togpols2 // Together      > 0


title: Composite graphics with Row, Column, data aggregation and layout control

text: This chromogram shown here represents data (mouse activity patterns during visits) for ~20 physicians in a study, each of which may have a variable number of visits in the study (physicians are color coded; also the last 2 digits in the XXX-YY). So each row represents one visit. Row and Column are used to layout the graphical elements including the XXX-YY annotation (the arrow is due to using Rule in key-value pairs). The query looks something like this:               Column[#,ItemSize->90]&@  PACE[VISITS] /.            v_String:>Row@{PROVIDERCOLOR@v ->  Graphics[VGr[v/.PACE[V1]],ChromoGrOptions]}      Taking the resulting expression as argument, how can the spacing be adjusted so that there is more space between distinct physicians' data? A method I want to avoid, if possible, is to restructure the data and call `Column` separately perhaps with different padding parameters. Though perhaps it's possible to apply `Map` or `Thread` or combinations, to effect that rewrite. Thoughts?


title: Integrate and ConditionalExpression Output

text: I am integrating some difficult functions and using the conditional output to place bounds on parameters to ensure integrability, but it seems that not all of the conditions are being returned. The following simple example illustrates the issue. When I perform the 1D integration               Integrate[Exp[b y], {y, 0, Infinity}]      I receive the correct output               ConditionalExpression[-(1/b), Re[b] < 0]      but when I perform the 2D integration               Integrate[Exp[a x + b y], {x, 0, Infinity}, {y, 0, Infinity}]      I only receive               ConditionalExpression[1/(a b), Re[a] < 0].      That is, the condition on the parameter `b` ensuring integrability is not returned. In this case does Mathematica only return the condition associated with the last integration step? Thanks...


title: Adding a thick curve to a regionplot

text: Suppose we have the following simple RegionPlot:               f[x_] := 1 - x^2     g[x_] := 1 - 0.5 x^2     RegionPlot[{y < f[x], f[x] < y < g[x], y > g[x]}, {x, 0, 2}, {y, 0, 2}]      ![enter image description here](http://i.stack.imgur.com/ZPGQG.jpg) Now I'm trying to change the curve defined by $y=g[x]$ into a thick black curve, while leaving all other boundaries in the plot unchanged. I've tried adding the region $y=g[x]$ and playing with the plotstyle, which didn't work, and I've tried BoundaryStyle, which changed _all_ the boundaries in the plot. Now I'm kinda out of ideas... Any help would be appreciated!


title: Calculate integral for arbitrary parameter n in infinite square well problem

text: I'm continuing[1,2] the study of an infinite square well in the context of quantum mechanics. Ultimate goal is to calculate the product $\Delta x\Delta k$, for various eigenstates, that is for various values of number $n$. I have finished with $\Delta x$, but I'm stuck with $\Delta k$.               ClearAll["Global`*"];     (* The length of the well *)     L = 1;          (* The eigenfunctions, n=1,2,3,... *)     u[n_, x_] := If[x <= 0 || x >= L, 0, Sqrt[2/L] Sin[n π x / L]]          (* The Fourier transform of eigenfunctions u[n,x] from the position        domain onto the momentum domain *)     φ[n_, k_] :=         Simplify[             FourierTransform[u[n, x], x, k, FourierParameters -> {0, -1}],             n ∈ Integers]          (* The probability density function η(n,k) *)     η[n_, k_] :=          FullSimplify[φ[n, k] \[Conjugate] φ[n, k],         {n ∈ Integers, k ∈ Reals}]          (* Calculate (Δk)^2 = <k^2> - <k>^2 = <k^2> *)     Integrate[         k^2 η[n, k], {k, -∞, +∞},         (* Edited: Was: {n ∈ Integers, n > 0}, but this edit didn't            fix the problem. *)          Assumptions -> n ∈ Integers && n > 0]      The problem is that _Mathematica_ can't calculate the last integral for any arbitrary $n$, although it can, correctly, calculate its value for hardcoded $n$s. Like $n=1,2,...$. **My question is** : Do you have any idea on how I could calculate it, perhaps by rewriting it a bit, or by using some other trick? In case it helps, the result should be $n^2\pi^2$. **Note** : Actually it can be calculated with Cauchy's residue theorem, but I'd like to avoid taking that route, if possible. Though, if it can't be done otherwise, I will post a solution with residual calculation so that this question has an answer. **Mathematica.SE related (to the physical problem) questions** : Is there a more mathematica-y way to label these plots? Why does FourierTransform converge while same integral manually written does not?


title: joining lists based on content

text: I have lists created by other processing steps, which are basically constituted by elements like this:               {a, b, c, {d,e,f}, g, h}  (*this is the typical element in the first list*)      and                {a, b, c, {d,e,f}, i, l} (*this one of the second*)      What I'd like to do to is: for each element in the first list, each time that `a,b,c,{d,e,f}` are the same, join the elements and obtain a list of elements like:                {a, b, c, {d,e,f}, g, h, i, l}.      `a,b,c,{d,e,f}` are guaranteed to be in the same position, but of course they vary in value and order, hence the matching. Any ideas? Additionally, it would be great to do this in a "fast and efficient" way, since the lists I'll deal with will be rather long. Thanks! EDIT: to make the question clearer.               list1= {{a,b,c,{d,e,f},10,21},{m,n,p,{r,s,t},14,64}}     list2= {{m,n,p,{r,s,t},12},{a,b,c,{d,e,f},16}}      I would like to obtain:               {{a,b,c,{d,e,f},10,21,16},{m,n,p,{r,s,t},14,64,12}}      Thanks!


title: Defining a curved region for NDSolve

text: I have an equation to solve using `NDSolve` which involves two parameters: $en$ and $k$. The equation produces a set of curves when $en$ is plotted against $k$. In order to isolate the curves, I have currently defined a load of rectangular regions for `NDSolve` to work within (which each contain part of only ONE curve - I get problems if there is more than one in a region). I do know however, that all the curves lie within curved regions defined by a parabola and my code would be much simpler if I could use regions such as $\left \\{ k,0,4 \right \\}, \left \\{ en, f1(k),f2(k) \right \\}$ where the $f$'s are the known parabolas as functions of $k$ . Is there any way to get `NDSolve` to work within a curved grid when finding the solutions? The code I have:               L = 8; Clear[k, en]; Clear[uall];      solution1 =      NDSolve[{-D[uall[x, en, k], x, x] + ((x - k)^2 - en(*+V[x]*)) uall[x,         en, k] == 0., uall[0, en, k] == 0,      Derivative[1, 0, 0][uall][0, en, k] == 1},      uall, {x, 0, L}, {en, 1.8, 3.6}, {k, -.1, 0.6}];      solution2 =      NDSolve[{-D[uall[x, en, k], x, x] + ((x - k)^2 - en(*+V[x]*)) uall[x,         en, k] == 0., uall[0, en, k] == 0,      Derivative[1, 0, 0][uall][0, en, k] == 1},      uall, {x, 0, L}, {en, .95, 2.}, {k, 0.57, 1.05}];      solution3 =      NDSolve[{-D[uall[x, en, k], x, x] + ((x - k)^2 - en(*+V[x]*)) uall[x,         en, k] == 0., uall[0, en, k] == 0,      Derivative[1, 0, 0][uall][0, en, k] == 1},      uall, {x, 0, L}, {en, .95, 1.5}, {k, .95, 2.7}];      solution4 =      NDSolve[{-D[uall[x, en, k], x, x] + ((x - k)^2 - en(*+V[x]*)) uall[x,         en, k] == 0., uall[0, en, k] == 0,      Derivative[1, 0, 0][uall][0, en, k] == 1},      uall, {x, 0, L}, {en, .9, 1.2}, {k, 2.5, 4.1}];     (*Set up previous calculations as function with k as an argument*)     Eofk1[k_] :=        en /. FindRoot[(uall[8, en, k] /. solution1) == 0, {en, 2.4}];     Eofk2[k_] :=        en /. FindRoot[(uall[8, en, k] /. solution2) == 0, {en, 2.00}];     Eofk3[k_] :=        en /. FindRoot[(uall[8, en, k] /. solution3) == 0, {en, 1.2}];     Eofk4[k_] :=        en /. FindRoot[(uall[8, en, k] /. solution4) == 0, {en, 1.001}];     (*Plot the dispersion en(k) by using the function defined in the \     relevant ranges*)     c1 = Plot[Eofk1[k], {k, -.05, .58},        PlotRange -> {{-0.05, 5.}, {0, 12.}},        PlotStyle -> {RGBColor[1, 0, 0]}];     c2 = Plot[Eofk2[k], {k, .58, 1.}, PlotRange -> {{-0., 5.}, {0, 12.}},        PlotStyle -> {RGBColor[1, 0, 0]}];     c3 = Plot[Eofk3[k], {k, 1.0, 2.6}, PlotRange -> {{0, 5}, {0, 12.}},        PlotStyle -> {RGBColor[1, 0, 0]}];     c4 = Plot[Eofk4[k], {k, 2.6, 4.0}, PlotRange -> {{-0., 5.}, {0, 12.}},       PlotStyle -> {RGBColor[1, 0, 0]}];     Show[c1, c2, c3, c4]


title: Counting the size of the minimum cut produced by MinCut of GraphUtilities`

text: I want to use the `MinCut` function of the `GraphUtilities`` package to find minimum cuts for a few graphs. I'm completely new to _Mathematica_ , so I took a look at the documentation of the function and the tutorial. Here's what I did:               Needs["GraphUtilities`"]     g = {1 -> 2, 2 -> 3, 3 -> 1, 2 -> 4, 4 -> 5, 5 -> 6, 6 -> 4};     c = MinCut[g,2]      After the second line, I'm getting an output representing the cut sets, such as               {{1,2,3}, {4,5,6}}       If I plot the output, I can determine from the figure the size of the cut. With a bigger graph, that is not feasible. Hence the question: > How can I easily count the size of cut, that is the number of edges between > the two sets, i.e. the number of crossing edges?


title: Euler's method for a 2nd order ODE

text: This is my first post on this site. Also, I'm new to _Mathematica_. I'm trying to solve my first problem with _Mathematica_. It's about solving a 2nd order differential equation. I dont have the explicit `F[t]` instead I have a list of values for `{t, F[t]}`                {{0, 1.00799}, {0.1, 1.09268}, {0.2, 1.18921}, {0.3, 1.25086}, {0.4, 1.32473},        {0.5, 1.36879}, {0.6, 1.39813}, {0.7, 1.41114}, {0.8, 1.39531}, {0.9, 1.3986},        {1., 1.39468}}      The equation I want to solve is               n = 5     h = 0.1     i = 0     y[0] = 1     yy[0] = 1     zi[0] = Table[i, {i, {1, 1}}]     T1 = {{0, 1.00799}, {0.1, 1.09268}, {0.2, 1.18921}, {0.3,         1.25086}, {0.4, 1.32473}, {0.5, 1.36879}, {0.6, 1.39813}, {0.7,         1.41114}, {0.8, 1.39531}, {0.9, 1.3986}, {1., 1.39468}}     Tij = Table[T1[[i, 2]], {i, 1, 11}]     ij = Table[T1[[i, 1]], {i, 1, 11}]     F[t_] := {y[t], (Tij[[t + 1]] - 9*yy[t] - 13*y[t])/5}     While[i < n, zi[i + 1] = zi[i] + F[i]*h; y[i + 1] = h + i;       yy[i + 1] = zi[[2]]; i = i + 1]


title: Is there a way to make the MemberQ function apply to a list?

text: Is there any way to ask a boolean question if the elements of the list {2,5} are in the list {1,2,3,4,5}?


title: How to toggle visibility of all the evaluatable cells (but not their output)?

text: I know that I can select individual evaluatable cells and disable their `Open` property (through `Cell > Cell Properties`), but is there a simple way to toggle the `Open` status of all evaluatable cells?


title: What is the default ColorFunction for Image3D?

text: What is the default `ColorFunction` for `Image3D`? I find it a bit confusing that the most intense colour is not shown where the highest values appear:               data = Table[        Exp[-3 (x^2 + y^2 + z^2)], {x, -1., 1, .01}, {y, -1.,          1, .01}, {z, -1., 1, .01}];          Image3D[data, ClipRange -> {{100, 200}, {0, 200}, {100, 200}},       ColorFunction -> Automatic] (* default colour function *)      ![enter image description here](http://i.stack.imgur.com/4V39D.png) Note that the bright yellow is not in the middle of the sphere. I wanted to understand what causes this effect (possibly some interplay of opacity and colours?). Otherwise I like the default. Did anyone try to reconstruct the default `ColorFunction` for `Image3D`?


title: FormCalc Troubleshooting

text: I was wondering if someone knows enough about the FormCalc package to help me out: I am using FeynArts to generate Feynman-diagrams for certain tree-level processes in my own model and FormCalc to calculate the squared amplitude of these processes, the problem is that when I make               CalcFeynAmp[Amp]      it gives > preparing FORM code in /home/safi/Dro/FormCalc/fc-amp-12.frm running FORM... > ReadForm::formerror: !(*StyleBox[!("Illegal position for 33\nIllegal > position for 23\nIllegal position for 34\nIllegal position for 24"), "MT"]) > $Aborted One solution for that as on ( http://www.feynarts.de/formcalc/trouble.html ) FormCalc Troubleshooting page is to run fc-amp-12.frm manually by Form comes with FormCalc to see where does the problem come from, but when I make :               ./tform fc-amp-12       it gives > ./tform: cannot execute binary file Have I typed the command correctly .. any suggestions ?


title: netlink ikernellink. How to ignore unread data

text: I use IKernelLink class. When I call evaluate method, I get an exception, because I have unread data. How can I ignore it?


title: How can I get the beautiful font used in the Demonstrations web site in my notebook?

text: This question may be off-topic (if it is, I will delete it), but: What is the name of that beautiful monospace font used in the Wolfram Demonstrations source code snippets ? ![enter image description here](http://i.stack.imgur.com/xfmDa.png)


title: StreamPlot,smooth curves

text: Using the StreamPlot I observed that when the streamline is a small circle, this line is not smooth. How can I increase the number of points along the streamline? For example, these are the magnetic lines at `(x,y)` due to vertical electric currents at `(x1,y1)`:               bx[x_, y_, x1_, y1_] := -(y - y1)/((x - x1)^2 + (y - y1)^2)^(3/2);     by[x_, y_, x1_, y1_] := (x - x1)/((x - x1)^2 + (y - y1)^2)^(3/2);          pts = Flatten[Table[{x, y}, {x, -2., 2., .21}, {y, -2, 2, 0.2}], 1];          StreamPlot[{1.7 bx[x, y, -1.2, 1.5] - 0.4   bx[x, y, -1.1, 1.1],                +1.7 by[x, y, -1.2, 1.5] - 0.4  by[x, y, -1.1, 1.1]},              {x, -2., -.5}, {y, 0.5, 2.},        PerformanceGoal -> "Quality", AspectRatio -> Automatic,        StreamPoints -> {pts, Automatic, Scaled[2]}, StreamScale -> None]      ![enter image description here](http://i.stack.imgur.com/uoSCn.png)


title: TetGenLink Assertion failure

text: Needs["TetGenLink`"];          TetraMaker[pts_, surface_, TetGenString_?StringQ] :=      Module[{inInst, outInst, coords, surface1, meshElements, facets},              inInst = TetGenCreate[];             TetGenSetPoints[inInst, pts];             facets = Partition[surface, 1];             TetGenSetFacets[inInst, facets];             outInst = TetGenTetrahedralize[inInst, TetGenString];             coords = TetGenGetPoints[outInst]; (* element point *)             surface1 = TetGenGetFaces[outInst]; (* element face *)             meshElements = TetGenGetElements[outInst]; (* element indices *)           {coords, surface1, meshElements}];           TetrahedraVolume =               Compile[{{coords, _Real, 2}, {elements, _Integer, 1}},               Block[{p}, p = coords[[elements]];                  1/6*Abs[Det[p[[{1, 2, 3}]] - p[[{2, 3, 4}]]]]],                    RuntimeAttributes -> {Listable}, RuntimeOptions -> "Speed"];                          {coords1, surface1, meshElements1} = TetraMaker[data01, polysurface1, "pqa.8"];       vb = Total[TetrahedraVolume[coords1, meshElements1]]       Graphics3D[GraphicsComplex[coords1, Polygon[surface1]]]      Error dialog appears when running code below:                {coords2, surface2, meshElements2} = TetraMaker[data02, polysurface2, "pqa.8"];       vb = Total[TetrahedraVolume[coords2, meshElements2]]      > Assertion failed! > > Program: ... File: M:\Builds\2615350\checkout\Mathematica...\tetgen.cxx > Line: 21962 > > Expression: dir !=COLLOSIONFACE > > For information on how your program can cause an assertion failure, see the > Visual C++ documentation on asserts > > (Press Retry to debug the application - JIT must be enabled) I am trying to calculate volume. I wonder if both data sets are similar then why does it not work for 2nd data set? Is there any way I can fix this error?


title: Calling variables with use of numbers in their names

text: I have got few huge matrices named by ascending numbers, e.g. `x1, x2, x3,...` and I need to do the same operation with all of them - to multiply their components, obtain the absolute value etc. As I am beginner with _Mathematica_ I usually copy the expression and rewrite indexes as `x1 -> x2`, but this is very lengthy. I would like to have only one expression with something like `xX`, where I just change `X` by index of particular matrix.


title: Filling a plotted line both below and above the line

text: I'm relatively new to _Mathematica_. I tried looking for a solution online but couldn't find anything. I want to fill a plotted line both above the line (one color) and below (another color). For example, the line might be given by `y = 1 - x` over domain (0, 1) and with range (0, 1). Any suggestions?


title: ParallelTable slowdown for a task involving ComponentMeasurements

text: I'm having trouble understanding a slowdown associated with code I'm running, which should be trivial to parallelize. My code looks something like this:               DistributeDefinitions[Movie];          List =        ParallelTable[        ComponentMeasurements[          {            MorphologicalComponents[EdgeDetect[Movie[[frame]]], Method -> "ConvexHull"],             Movie[[frame]]          },           "IntensityCentroid"][[All, 2]],         {frame, 1, 100}];      This works, but takes about 14.265 seconds to run on 12 cores. However, changing "ParallelTable" to just "Table" reduces the running time to about 2.791. Changing {frame, 1, 100} to {frame, 1, 10} still yields the same result that "Table" runs about 5x as fast as "ParallelTable". The "Movie" data set is a few gigs in size, but shouldn't that not matter if I'm applying "DistributeDefinitions" to it? * * * For a self-contained example, we can use the "Mandrill" example data image in Mathematica 9:               Movie = Table[ExampleData[{"TestImage", "Mandrill"}], {x, 1, 5000}];     DistributeDefinitions[Movie];     ParallelTable[       ComponentMeasurements[         {           MorphologicalComponents[EdgeDetect[Movie[[frame]]], Method -> "ConvexHull"],            Movie[[frame]]         },          "IntensityCentroid"][[All, 2]],        {frame, 1, 20}];      Running "ParallelTable" here takes about 6.85 seconds of time on a 12 core machine. Running "Table" 7.24 seconds. However, changing the number of frames in the movie from 5,000 to 10,000               Movie = Table[ExampleData[{"TestImage", "Mandrill"}], {x, 1, 5000}];      to               Movie = Table[ExampleData[{"TestImage", "Mandrill"}], {x, 1, 10000}];      yields the same `Table` computation time of 7.26 seconds and increases the `ParallelTable` computation time to 9.71 seconds.


title: on convergence in optimization

text: I am trying to solve a nonlinear programming problem using FindMinimum solver on Mathematica. When I execute, it is printing FindMinimum::eit: "The algorithm does not converge to the tolerance of 4.806217383937354`*^-6 in 500 iterations. The best estimated solution, with feasibility residual, KKT residual, or complementary residual of {0.00499384,0.00461499,2.68875*10^-6}, is returned" Can we still use this solution for when I calculate one of the constraints using printed data, it is outside the defined range?


title: Importing data into an array, column by column

text: I'm building a large matrix having different sized rows consisting of a few columns. The different columns are imported .txt files. Why can't I build the matrix column by column? For example, I thought I could populate the first column by evaluating               NumberConcentration [[All, 1]] =       Import["C:\\Users...NumberConcentration.txt", "Table"][[87]]      _Mathematica_ gives me an error saying this part of the array does not exist. > Set::partd: Part specification NumberConcentration[[All, 1]] is longer than > depth of object. >> Do I have to define intermediate values and then combine all of them to one matrix? Or is my syntax wrong?


title: Convert array from {{...}} to "[[...]]"

text: I have made this function:               conv01 = Map["["<>StringJoin@@Riffle[#,","]<>"]"&,Map[ToString,#,{2}],{0,1}]&      to convert:               list = {{1, 2, "test3"}, {3, 4, "test4"}}      to               "[[1, 2, \"test3\"], [3, 4, \"test4\"]]"      I know that I can do: `conv02 = StringReplace[ToString[#], {"{" -> "[", "}" -> "]"}] &` but it's not same if I have `{` or `}` inside it. I have tried:               conv03 = Map["[" <> ToString@Row[#, ","] <> "]" &, list, {0, 1}]      but it doesn't work and I don't understand why if this works:               "[" <> ToString@Row[{1, 2, 3, 4}, ","] <> "]"      Some clue on the last method? Some idea of simpler solution?


title: Creating a highly customized BarChart

text: I am trying to create a BarChart visualization for multi-step data filtering. Think of a traditional sales funnel: many leads, fewer prospects, few customers, very few return customers. The only kicker is, I want to show the percentage of data being lost by using Percentile layout for the BarChart, and I want to show that the slice of previous bar is the entirety of the content of the next bar using lines similar to Joined option, and if possible, fill the joining lines with color similar to the one used for selection. Lastly,for my data content, there are 2 types of filters: binary (e.g. lead becomes prospect or not) and slice-of-pie (e.g. customers who spent between X and Y, where the slice would appear in the middle of the column, with rest of sales with lower amount appearing below, and higher amount appearing above). I can draw this using Graphics and basic primitives, but was really hoping that there's a clever way to adapt BarChart, so that I could use the built-in labeling or legending features, as well as the vertical axis. Or even go from Percentile to Stacked, as needed. Here's a simple drawing of what I envision this could look like: ![Example of funnel barchart](http://i.stack.imgur.com/cNU2k.png) And if anyone can suggest an alternate visualization which will serve the purpose, I'd really appreciate it. I thought of using TreeGraph with VertexSize option, but it's less than trivial to visualize not only what made it into the filter, but also how much are you losing and where the loss occurs. **UPDATE:** Thanks to @Verbeia's clever solution, and a little bit of additional engineering, this is what I came up with. Clearly there's endless room for improvement, but the automation works great.               data = {{4, 3, 4.5, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 3, 5, 6, 0,          0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 0}, {0, 0, 0, 0,          0, 0, 0, 0, 0, 1, 1, 1}};     lines = Flatten[Table[{          {{1.501 n,             100 data[[n, 3 n - 2]]/Total@data[[n]]}, {1.5 n + .499,             0}}, {{1.501 n,             100 (data[[n, 3 n - 2]] + data[[n, 3 n - 1]])/             Total@data[[n]]}, {1.5 n + .499, 100}}}         , {n, 1, 3}], 1];          Show[       BarChart[data, ChartLayout -> "Percentile",         BarSpacing -> {None, .5}, ChartStyle -> "Pastel"],       ListLinePlot[lines,         Filling ->          Table[(2 n - 1) -> {{2 n},             Directive[Opacity@0.75,              ColorData["Pastel"][(3 n - 2)/(3 4)]]}, {n, 1, 3}],         PlotStyle -> Directive[Dashed, Gray]]       , ImageSize -> 850]      And the result: ![funnel_barchart_new](http://oi42.tinypic.com/w0t9wh.jpg)


title: How to find the area between two curves

text: Find the area between `y = 1 - x/π` and `y = Sin[x]`. Here is what I have typed in so far into _Mathematica_ :               Clear[f, g, x]     f[x_] := 1 - x/π     g[x_] := Sin[x]     Plot[{f[x], g[x]}, {x, 0, 2 π},        PlotStyle -> {Red, Blue}, PlotRange -> {-1.2, 1.2}, Filling -> {1 -> {2}}]      The graph worked, so I have that. However, when I try to do the next step, `Solve[f[x] = g[x], x]`, it will not give me the intersects. I have even tried retyping the equations in: `Solve[Sin[x] = 1 - x/π, x]`, but nothing is working. What am I doing wrong?


title: How to build a list of constraints for NMinimize

text: Let's say I have a`set = {-1, 0, 2}`. I would like to create a variable `Var` that takes values from that set, i.e. `var = -1` or `var = 0` or `var = 2`. What I'm trying to do is using the variable in `NMinimize` as a constraint. A simple example could be as follow:               NMinimize[{a + 1, var == -1 || var == 0 || var == 2, a > 0}, a]      The result is, obviously: > >     {1., {a -> 0.}} >   But if the set is much larger I can't write down constraints for each element. Is there a more efficient way to do this? ### Edit Both answers work (see comments). However, if I change the code a bit,               set = {b^2, b^2 + 1, b^2 - 1};     NMinimize[{a + 1, Or @@ (a == # & /@ set)}, {a, b}]      gives > >     {-7.45058*10^-9, {a -> -1., b -> -7.43726*10^-9}}` >   while               NMinimize[{a + 1, Times @@ ((a - #)& @ set) == 0}, {a, b}]       gives > >     {-3.53148*10^-9, {a -> -1., b -> -7.29659*10^-9}} >   Both results are satisfactorily correct. However I notice that the second result is a little bit more accurate.


title: Specify positions in a SparseArray using patterns with functions

text: I spent some time trying to figure out what was what was making so slow the calculation of the following array(actually this is only a SUPERsimple toy model): Input to the array:               Nx=2;     Ny=1;     nn =Nx*Ny;      Nband = 2;     Nstates = 2*nn*Nband;          eigenvectors = Table[Range[Nstates] + i, {i, 1, Nstates}];          InverseFlatten[l_, dimensions_] := Fold[Partition, Flatten@l,Most[Reverse[dimensions]]];     (*************)     N1[i_] := Module[{ix, iy, n1x},     ix = Mod[i, Nx, 1];     iy = Quotient[i, Nx, 1] + 1;     If[ix + 1 > Nx, n1x = 1, n1x = ix + 1];     {n1x + (iy - 1)*Nx}];     (*************)     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[MemberQ[N1[i], j] == True, 2],      {l, 1, Nband}, {m, 1, Nband}, {s, 1, Nband},{q, 1, Nband}, {i, 1, nn}, {j, 1, nn}];      Array:               delta =      Table[     Total[Flatten[V[[μ, ν, ;; , ;; , ;; , ;;]]*       Table[          Table[             Which[                 MemberQ[N1[i], j] == True,                 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}];      After having tried several things like using Packed arrays, using Compile...and seen that nothing really helped, I thing that what it actually slows down the thing is Which. I think, that the process should be a lot faster if instead of using Which, which gives a condition for which matrix elements to calculate, I directly specify the positions for which I would like to calculate the matrix element; I think so because the number of elements to be calculated is really small compared to the number of elements(for big nn). Then looking at the SparseArray list manipulating tutorial I saw that one can do this using patterns, for example:               Normal[SparseArray[{{i_, i_} :> 1}, {nn, nn}]]      Now, what specifies the second index of my matrix is the function N1 defined above, therefore, I would like to use something like:                A=Normal[SparseArray[{{i_, N1[i_][[1]]} :> 1}, {nn, nn}]]        SparseArray::posd: The left-hand side of {i_,n1x$671+2 Quotient[i_,2,1]}:>1  in {{i_,n1x$671+2 Quotient[i_,2,1]}:>1} is not a position or a pattern that will match the position of an element in an array with dimensions {2,2}. >>      but it complaints. I expect to get:                A={{0,1},{1,0}}      since N1[1][[1]]=2 and N1[2][[1]]=1. Does anybody now how could I make a "pattern SparseArray" having this function N1 in the pattern? Thanks


title: How to color a contour plot over a subset of colors displayed in the bar legend

text: This seems real easy but I can't find the answer. I have a few contour plots that I am combining and want to use only one bar legend that captures all the values. Given that I know the range of values, how to get the colors to correspond so that, say, if one plot only ranges over 1/3 of the total range, it only displays 1/3 of the range of colors. The following code only plots the BarLegend correctly but leaves the colors in the contour plot unchanged:               ContourPlot[X^2+Y^2,{X,-3,3},{Y,-3,3},PlotLegends->BarLegend[{"LakeColors",{0, 100}}, 10]]      Edit: I should have been more precise. Here is a more explicit example. The goal is to make the contour colors quantitatively consistent between the plots.               h1 = ContourPlot[X^2 + Y^2, {X, -3, 3}, {Y, -3, 3}, PlotLegends -> Automatic];     h2 = ContourPlot[X^2 + Y^2, {X, -5, 5}, {Y, -5, 5}, PlotLegends -> Automatic];     GraphicsRow[{h1, h2}, ImageSize -> 500]      As @David_Park mentions, I need to use ColorFunction. But I don't know how with ContourPlot.


title: Multilpe matrix (mxm) and vector (n), wich are unequal, so get a (three dimensional matrix) mxmxn matrix

text: For example I have this matrix:               mk = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}      and I'd like it to multiple with this:               ot = Table[5, {4}]      > >     {5,5,5,5} >   to get this one:               {{{ 5, 5, 5, 5}, {10,10,10,10}, {15,15,15}},       {{20,20,20,20}, {25,25 ...}...}...}      but `KroneckerProduct` gives me `3` rows instead of a `3 x 3 x 4` matrix (similar but not identical). Of course I have really large lists...               KroneckerProduct[mk, ot]      > >     {{5, 5, 5, 5, 10, 10, 10, 10, 15, 15, 15, 15}, >      {20, 20, 20, 20, 25, 25, 25, 25, 30, 30, 30, 30}, >      {35, 35, 35, 35, 40, 40, 40, 40, 45, 45, 45, 45}} >


title: Efficient storage of Kronecker sum of circulant matrices+diagonal matrix

text: I have a square matrix of the form $$M=D+\overset{N}{\underset{n=1}\bigoplus}R_n,$$ where $R_n$ are circulant matrices, $D$ is a diagonal matrix and $\oplus$ is Kronecker sum. Its size is quite big, but as can be seen from its form, it's in fact not very dense in a way. Namely, its elements can be generated by a simple procedure not needing much memory - the only things needing storage are a vector for diagonal of $D$, and a set of smaller vectors for first rows of $R_n$ (i.e. totally two vectors matching dimensions of $M$). Actually, diagonal matrix is simple to get with `SparseArray`, but I don't know how to make "sparse" circulant matrices. So the question: is there a nice way to store this matrix sparsely so that it could be operated on by e.g. `Eigensystem[]` with Arnoldi method or something similar?


title: How do I obtain the Fisher Information Matrix from a data set?

text: My apologies in so much as this is probably in large part a problem of me not being aware of the necessary mathematics but since this should be a common issue in machine learning and Mathematica now seems to have tools in this area, I'm hoping there is some simple way of doing this. Say I have some data set together with knowledge of how it changes when I vary some parameter               \[Mu] = 0;     data = Table[     RandomVariate[NormalDistribution[\[Mu], \[Sigma]], 10^3], {\[Sigma], 1, 100, 1}];      How can I find things like the Fisher Information Matrix? Of course I'm assuming that I do not know that this data set is obtained from the normal distribution. The idea is that this is just some black box which generates a data set and I can study how the data set changes when I change various input parameters.


title: How to get the absolute difference between two angles

text: I need a function that will give me the shortest separation between angles that range from -pi to pi. For example if I have two angles 3pi/4 and -3pi/4, I would like a function that will tell me pi/2 instead of 3pi/2.


title: Filling in explicit zeros in a (x,y) list for nonexisting y values for discrete Fourier transform in Mathematica

text: I have a list of (x,y) values in Mathematica for various discrete x values, as in               intensities={{26, 10}, {27, 289}, {28, 90}, {29, 1079}, {30, 30}, {33, 10}, {39,        179}, {40, 40}, {41, 2269}}      I would now like to insert into this list explicit zeros for each discrete value of x that has a nonexisting y value, as in               intensities2={{0,0},{1,0},{2,0},....,{26,10},{27,289},{28,90},...,{41,2269}}      Out of these I would then like to extract just the y values to be able to do a discrete Forier transform on them. Any thoughts how I could do this most efficiently? cheers & many thanks for any advice! Tom


title: Specify values for X-axis and Y-axis ticks and control their format

text: I have following problem: I want to set the values for the X-and Y axis by myself, but the values (e.g. 0.800) are not plotted as I defined them (see image 0,8), mathematica removes the zeros.               Data = {{58.771, 0.792}, {53.532, 0.801}, {48.083, 0.795}, {57.343,0.794524}};     AxisY = {0.795, 0.800};     AxisX = {48, 53, 58};     ShowLegend[        Show[         {ListPlot[Data]},         Frame -> {True, True, False, False},         FrameTicks -> {{AxisY, Automatic}, {AxisX, Automatic}}       ],       {{{Graphics[{Blue, Disk[{0, 0}, 1]}], "ABC"}}}     ]      ![enter image description here](http://i.stack.imgur.com/gDxcy.jpg) I tried to solve this problem with _NumberForm_ , but that does't work, the Y-axis disappears. SetPrecision doesn't work in my case, because I don't want to set total positions, I want to set positions after decimal point. Have someone an idea to solve this problem with an easy way?               ShowLegend[        Show[         {ListPlot[Data]},         Frame -> {True, True, False, False},         FrameTicks -> {{NumberForm[#, {4, 2}] &@{Axisy}, Automatic}, {Axisx,Automatic}}       ],       {{{Graphics[{Blue, Disk[{0, 0}, 1]}], "ABC"}}}     ]


title: video image recognition

text: Has anybody experience with video and image recognition? I've made a video of two teams playing soccer. Now I would like to translate each soccer-player to a (x,y) coordinate and follow them during the match.


title: How to measure the speed of ball from a video or a set of pictures?

text: Suppose a camera and the need to measure the speed of a ball such as a tennis ball. Usually, the speed of ball is measured with Doppler effect where the pulse difference reveals the speed. Now I want to measure the speed of the ball from the images with _Mathematica_. You can suppose 1/30 sec shutter speed. > **How would you measure the largest speed of the ball in Mathematica?** **Different Methods** > > **I. Image Difference method** >> >>> Shoot two pictures in 1 second interval. From the difference of images, you get the length travelled. By the $\Delta t$ and $\Delta l$ you get the speed over that range. Simply use _Mathematica_ 's Image Difference here. >> >> **II. Long shutter time method with a glow ball** >> >>> Like in light-painting, use a fire-ball or glow-ball or light-ball. Now get one photo with long shutter time in a black room with only ball glowing. Measure the length of the glow over certain time. Programmatically, the task is to measure the length of the flight path. >> >> **III. Motion blur method** >> >>> A camera experiences a motion blur with a fast ball. An user suggested a motion-blur method but I could not understand it. Perhaps just sharpen and use the method I above. Two test images are here and here where the ball has travelled about 4 meters in 23 frames. >> >> **IV. Some other method to get the speed of ball from images or a video?**


title: Shaping/simplifying equations in a certain way

text: A problem I am occasionally facing is to simplify an equation not to it's shortest form but to a form that is simple by other means. Often, this is grouping the term according to certain functions, for example exponential functions from a Fourier series. For example,               1 Exp[i k t] + 2 x Exp[i k t] + (2 x + 1) Exp[i k t]^2 // Simplify      will give `E^(i k t) (1 + E^(i k t)) (1 + 2 x)`. Instead,               (2 x + 1) Exp[i k t] + (2 x + 1) Exp[i 2 k t]      is often desired. Is there any simple[1] way to achieve that? [1] I once achieved that using the `FourierTransform` and replacing the `DiracDelta` with 1 or 0 to get the coefficients, but that is neither elegant nor always possible.


title: Help with interactive plot?

text: The following interactive plot causes Mathematica 9 to become unresponsive. Could someone please tell me what is wrong with it?               Manipulate[      Module[{tbl1},        tbl1 = Table[         Tooltip[{effS,            B + EQ (P - P pfold) +             pfold (P + V) + (-1 - 2 EQ (-1 + pfold) + pfold) effS}], {effS,           0.05, Min[S, T], 0.01}];       ListLinePlot[{tbl1}, PlotLegends -> {"EV"},          PlotStyle -> {Directive[Orange]}, Mesh -> All,         MeshStyle -> Opacity[0], GridLines -> {Automatic},         AxesLabel -> {"eff stack", "EV"}]], {{B, 180, "Hero bet"}, 0.05, S,        0.01, Appearance -> "Labeled"}, {{V, 400, "Villain bet"}, 0.05, T,        0.01, Appearance -> "Labeled"}, {{S, 1280, "Hero remaining stack"},        0.05, 10000, 0.01,        Appearance -> "Labeled"}, {{T, 870, "Villain remaining stack"},        0.05, 10000, 0.01, Appearance -> "Labeled"}, {{P, 260, "Pot"}, 0.05,        10000, 0.01, Appearance -> "Labeled"}, {{EQ, 0.25, "Hero Equity"},        0, 100, 0.01,        Appearance -> "Labeled"}, {{pfold, 0.5,         "Probability villain folds"}, 0, 1, 0.01, Appearance -> "Labeled"}]


title: managing custom Ticks

text: I am trying to create a meaningful Operating Characteristic curve for use in Quality Lot Acceptance sampling. I have the following example (thanks to some help), yet when I alter the number of units sampled, or the lot size - the ticks are not right anymore.               DiscretePlot[      Probability[x <= 0, x \[Distributed] HypergeometricDistribution[8, d, 500]],      {d, 0, 250},      Ticks -> {Table[{i 500/100, ToString@i <> "%"}, {i, 0, 50, 5}],Automatic}     ]      Basically how does the Ticks work? such that I can alter the hypergeometric parameters and get appropriate Ticks? cheers, Fred


title: ParametricPlot Options Problem: PlotStyle and AxisLabel issues

text: I am plotting the best response functions in a basic quantity setting Duopoly model using the `ParametricPlot` function. The issue is that the resulting graphs are both "black" even thought I have specified the `PlotStyle -> {{Blue,Thick},{Red,Thick}}`, and the `AxisLabel -> {q1,q2}` option is also not be working. Any ideas on what I might be doing wrong here?               BRq1[q2_, c1_, a_] := 1/2 (a - c1 - q2);     BRq2[q1_, c2_, a_] := 1/2 (a - c2 - q1);     Manipulate[     ParametricPlot[{{q2, BRq1[q2, c1, a]}, {BRq2[q1, c2, a], q1}}, {q1,      0, 100}, {q2, 0, 100}, PlotStyle -> {{Blue, Thick}, {Red, Thick}},      PlotRange -> {{0, 100}, {0, 100}}, AxesLabel -> {q1, q2}, AspectRatio -> 1,      PlotLabel -> Style["Best Response Curves", Blue, 20]],      Style["Parameters", Bold, Medium], {c1, 0, 50}, {c2, 0, 100}, {a, 10,130}]


title: Can JavaScript query the actually used dimensions of an HTML embedded CDF?

text: I have an HTML embedded CDF on my website. The size that is actually being used up by the single manipulate in the CDF changes when you use the CDF; you can make more sliders appear, and then it will take up more space. ![enter image description here](http://i.stack.imgur.com/CJC2i.png) I have jQuery embedded in the page, so you can easily snoop around in the HTML DOM tree. If you view the page in Firefox, and you got the Firebug extension, you can type in Firebug `$("embed").height()` which will give you the result 400, which is the hardcoded value I gave for the height of the embedded CDF content. I can change that height later on, if I want to, for example `$("embed").height(300)` will make the cdf take up less space. However, there appears to be no way to find out from JavaScript how much space is currently being used up by the CDF (or by the single Manipulate within the CDF, to be precise). I'm actually pretty sure that it's impossible, but I would love to be proven wrong. Any ideas? **update** if you know of a way to specify something like "height='100%'", meaning, "height = whatever is needed", that would be even better. "100%" for the height parameter in the JavaScript call to cdf.embed does not work, I tried that. **update** @Vitaliy: Thanks, I figured it out thanks to your comment, will post solution shortly.


title: Is using undocumented functionality a Bad Idea™?

text: Mathematica has a lot of very useful undocumented features. For example a hash table, a built-in list of compilable functions, additional options to CurrentValue, `{"Raw", n}` histogram bin specification, etc... A natural question that arises is: **Why is this functionality undocumented?** Is it because the feature is under development? Or because the syntax has not been finalized and may be changed? Something else? Also: **Is using this functionality safe in the sense that it will not cause problems when a new version is released?**


title: Saving graphics object in order to manipulate  it later?

text: I've generated a bunch of graphics using `ContourPlot` wich, given the nature of my problem, take a long time to create, and I was wondering if there is a way to save the _object_ (not the image) to a file so I can retrive it later to manipulate, i.e. use `Show`, change colors, add text, etc. For example, suppose I define something like               conic = ContourPlot[x^2/9 + y^2/16, {x, -10, 10}, {y, -10, 10},          ContourStyle -> Red, ContourShading -> None, Contours -> 15,          Axes -> True, AxesLabel -> {x, y}]      then by doing               Definition[conic]      I can see the objetc: ![enter image description here](http://i.stack.imgur.com/2L2JK.png) Now, what I'd like to do is save the object in such way that I'll be able to change the color from red to blue, the labels, the aspect ratio, etc. by just importing it and modifying the proper options _without_ having to calculate it again. I guess a rudimentary solution would be to export the object to a txt file, and later import it, manipulate it and then use `ToExpression`, but I was wonderign if there is a more "within" approach. I hope this isn't a duplicate. I've tried to search for the answer but the keywords save and graphics made it impossible.


title: BUGS-type calculations in Mathematica

text: Recently I have been teaching myself how to Bayesian calculations with the BUGS language (JAGS, in particular). However, I find myself wondering how one might use Mathematica to do similar calculations (perhaps based around NIntegrate). I would be most interested in building up models using the awesome combined computing/graphing facilities that Mathematica provides. I have a copy of "Bayesian Logical Data Analysis for the Physical Sciences" and while it is an excellent and enjoyable book, I think that it more focused on "analytic" solutions than "numerical"--it seems that more complicated models would quickly outpace the ability to obtain analytic solutions. For example, consider the problem of inferring the difference between two rates, taken from Lee and Wagenmaker's book:               model {     # Prior on Rates     theta1 ~ dbeta(1,1)     theta2 ~ dbeta(1,1)          # Observed Counts     k1 ~ dbin(theta1,n1)     k2 ~ dbin(theta2,n2)          # Difference between Rates     delta <- theta1 - theta2     }      Given k1, n1, k2, and n2, how might I translate this into Mathematica to get, e.g. the posterior density of theta, the difference in rates, I suppose p(delta | k1,k2,n1,n2) ? (For example, k1=5, k2=7, n1=n2=10). Knowing how this is done would go a long way toward me being able to build and solve other models!


title: Indefinite Integral long time plotting

text: I have this equation:               PwD = (1/200)*       Integrate[(1/(E^(0.25/\[Tau])*\[Tau]))*         Integrate[(1 +              2*Sum[(Cos[0.8*n*Pi]*Cos[(n*Pi)/2 - (n*Pi*z)/100])/                E^((n^2*Pi^2*\[Tau])/10000), {n, 1, 100}])/           E^((Tan[\[Psi]*Degree]^2*(z + 30)^2)/(4*\[Tau])), {z, -50,            50}], {\[Tau], 0, t}]      ![Mathematica graphics](http://i.stack.imgur.com/Lhgl1.png) Now, to generate graphics for different angles `\[Psi]` this is what I did:               Pw1 = (Exp[-0.25/t]/t)*        Integrate[         Exp[-(((Tan[0 Degree]^2)*(z + 30)^2)/(4*t))]*(1 +             2*Sum[Exp[-((n^2)*(Pi^2)*t)/(100^2)]*Cos[0.8*n*Pi]*               Cos[(n*Pi/2) - (n*Pi*z/100)], {n, 1, 100}]), {z, -50, 50}];     Pw2 = (Exp[-0.25/t]/t)*        Integrate[         Exp[-(((Tan[30 Degree]^2)*(z + 30)^2)/(4*t))]*(1 +             2*Sum[Exp[-((n^2)*(Pi^2)*t)/(100^2)]*Cos[0.8*n*Pi]*               Cos[(n*Pi/2) - (n*Pi*z/100)], {n, 1, 100}]), {z, -50, 50}];     Pw3 = (Exp[-0.25/t]/t)*        Integrate[         Exp[-(((Tan[60 Degree]^2)*(z + 30)^2)/(4*t))]*(1 +             2*Sum[Exp[-((n^2)*(Pi^2)*t)/(100^2)]*Cos[0.8*n*Pi]*               Cos[(n*Pi/2) - (n*Pi*z/100)], {n, 1, 100}]), {z, -50, 50}];          PD1[y_] := 0.005*NIntegrate[Pw1, {t, 0, y}, MaxRecursion -> 20];     PD2[y_] := 0.005*NIntegrate[Pw2, {t, 0, y}, MaxRecursion -> 20];     PD3[y_] := 0.005*NIntegrate[Pw3, {t, 0, y}, MaxRecursion -> 20];          T1 = Table[{y,          PD1[y]}, {y, {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 2,           2.2, 2.5, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,           18, 19, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85,           90, 100, 110, 120, 130, 140, 150, 200, 250, 300, 350, 400, 450,           500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000, 1100,           1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900, 2000, 2100, 2200,           2300, 2400, 2500, 2600, 2700, 2800, 2900, 3000, 3500, 4000,           4500, 5000, 5500, 6000, 6500, 7000, 7500, 8000, 8500, 9000, 9500,           10000, 11000, 13000, 15000, 17000, 19000, 20000, 22000, 24000,           26000, 28000, 30000, 35000, 40000, 45000, 50000, 55000, 60000,           65000, 70000, 75000, 80000, 90000, 95000, 100000, 150000, 200000,           250000, 300000, 350000, 400000, 450000, 500000, 550000, 600000,           700000, 800000, 900000, 1000000}}];     T2 = Table[{y,          PD2[y]}, {y, {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 2,           2.2, 2.5, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,           18, 19, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85,           90, 100, 110, 120, 130, 140, 150, 200, 250, 300, 350, 400, 450,           500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000, 1100,           1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900, 2000, 2100, 2200,           2300, 2400, 2500, 2600, 2700, 2800, 2900, 3000, 3500, 4000,           4500, 5000, 5500, 6000, 6500, 7000, 7500, 8000, 8500, 9000, 9500,           10000, 11000, 13000, 15000, 17000, 19000, 20000, 22000, 24000,           26000, 28000, 30000, 35000, 40000, 45000, 50000, 55000, 60000,           65000, 70000, 75000, 80000, 90000, 95000, 100000, 150000, 200000,           250000, 300000, 350000, 400000, 450000, 500000, 550000, 600000,           700000, 800000, 900000, 1000000}}];     T3 = Table[{y,          PD3[y]}, {y, {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 2,           2.2, 2.5, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,           18, 19, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85,           90, 100, 110, 120, 130, 140, 150, 200, 250, 300, 350, 400, 450,           500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000, 1100,           1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900, 2000, 2100, 2200,           2300, 2400, 2500, 2600, 2700, 2800, 2900, 3000, 3500, 4000,           4500, 5000, 5500, 6000, 6500, 7000, 7500, 8000, 8500, 9000, 9500,           10000, 11000, 13000, 15000, 17000, 19000, 20000, 22000, 24000,           26000, 28000, 30000, 35000, 40000, 45000, 50000, 55000, 60000,           65000, 70000, 75000, 80000, 90000, 95000, 100000, 150000, 200000,           250000, 300000, 350000, 400000, 450000, 500000, 550000, 600000,           700000, 800000, 900000, 1000000}}];          PwD1 = Interpolation[T1];     PwD2 = Interpolation[T2];     PwD3 = Interpolation[T3];          P1 = LogLogPlot[{PwD1[y], y*PwD1'[y]}, {y, 0.1, 1000000},         PlotRange -> {0.01, 10}, PlotStyle -> {{Black}, {Dashed, Black}},         Frame -> True, FrameLabel -> {tD, "PD e tD*PD'"},         BaseStyle -> {FontSize -> 12}];     P2 = LogLogPlot[{PwD2[y], y*PwD2'[y]}, {y, 0.1, 1000000},         PlotRange -> {0.01, 10}, PlotStyle -> {{Brown}, {Dashed, Brown}}];     P3 = LogLogPlot[{PwD3[y], y*PwD3'[y]}, {y, 0.1, 1000000},         PlotRange -> {0.01, 10}, PlotStyle -> {{Purple}, {Dashed, Purple}}];          Show[P1, P2, P3]      The problem is that it takes a very long time to compute these codes, due to the summation limit (1 to 100)! ... Could anyone propose an alternative way to computing this plot?


title: Calculating the area under a curve, but above a certain threshold value

text: so here I am with a time series of data (hours (t) and corresponding measurements (a)).               a = {0, 2, 5, 6, 3, 6, 5, 8, 2, 1, 10};     t = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};      The plot looks like this:               ListLinePlot[Partition[Riffle[timepoints, a], 2],  GridLines -> {{}, {4}}]      ![enter image description here](http://i.stack.imgur.com/DiGYC.jpg) Using a trapezoidal rule function, I get an AUC of 43.               auc[data_, times_] := (     merged = Inner[List, times, data, List];     merged = DeleteCases[merged, {x_, y_} /; Not[NumericQ[y]]];      N@Total[Partition[merged, 2, 1] /. {{x1_, y1_}, {x2_, y2_}} -> (x2 - x1) ((y1 + y2)/2)] )      What I am trying to do now is modify the function to get the AUC for values above a certain threshold, let's say 4. This is indicated by the horizontal grid line in the graph. First thought was replacing the values exceeding 4 by 4, calculating a second AUC and substracting. Of course this changes the shape of the curve.               a2  = a /. x_ /; x > 4 -> 4;     GraphicsGrid[{     {ListLinePlot[Partition[Riffle[timepoints, a], 2],        PlotRange -> {All, {0, 10}}, GridLines -> {{}, {4}}],     ListLinePlot[Partition[Riffle[timepoints, a2], 2],        PlotRange -> {All, {0, 10}}, GridLines -> {{}, {4}}] }     }]      ![enter image description here](http://i.stack.imgur.com/Mxq2i.png) I figure the solution is along the lines of linear interpolation of where the curve intersects the threshold and adding intermediate points and I really have no idea where to start implementing this. Any pointers? Or are there biomedical packages that will calculate this stuff from raw data? Thx!


title: Visualization of Bivariate Distributions

text: I know it is perfectly possible to show the bivariate probability distributions in MMA. But my question is can we show each dimension of distribution in 2D dimension while we are showing the 3D plot? The same as here: ![enter image description here](http://i.stack.imgur.com/B4cuc.png) How we can have the 2D histograms in the sides and 3D histogram in between?


title: Define an operator with commutative, associative and distributive properties

text: I need to define a symbolic operator with commutative, associative and distributive properties, in the same way as the sum and product operator for real numbers. I have started with:               op[a_, b_] = a⊕b;     op[a_, b_] = a⊗b;     op[1, 2];     op[1, 1⊕2];     Distribute[op[1, 1⊕2], CirclePlus]      when I use the `Distribute` command I don't get the parenthesis. How can I define an operator with all this properties in ones.


title: How to improve visualisation of trajectories in 3D space

text: I have a list of trajectories from a bunch of photons that travel inside a scattering medium. Each trajectory is a list of $(x,y,z)$ pairs. I'd like to visualise them in 3D space. I came up with the simplest (and ugliest) way:               data = Import["http://dl.dropboxusercontent.com/u/25202446/dat.3d", "List"];     data = ToExpression /@ data;     Graphics3D[Line /@ data, Axes -> True, AxesLabel -> {"x", "y", "z"}]      ![enter image description here](http://i.stack.imgur.com/uJIP7.png) I also tried with `Point`s instead of connected lines but of course the result is also very "primitive". Another idea was to use the `SmoothDensityHistogram[]` and `SmoothHistogram3D[]` like this (I did some modifications in the code so that it works outside the context of my notebook. I hope that it does indeed):               plot1 = SmoothDensityHistogram[        Take[#, 2] & /@ Flatten[data, 1],            ColorFunction -> "Rainbow", Ticks -> None, Frame -> False];          plot2 = SmoothHistogram3D[         Take[#, 2] & /@ Flatten[data, 1],                ColorFunction -> "Rainbow", ViewPoint -> {1, 1, 1}, Ticks -> None,              Boxed -> False, Axes -> False];          comb = Style[Grid[{{plot1, plot2}}], ImageSizeMultipliers -> 1]      **NOTE** : The graphs that are generated may not look like entirely identical to the ones that I embedded, because the sample size is different. ![enter image description here](http://i.stack.imgur.com/vAh8E.png)


title: The gap between MapAt and ReplacePart for 2D data tables with headers

text: Consider a relational table derived from survey data, where each column (`"001-01"` ...) represents a responder and each row (`"MDQ1"`...) a survey question. To help intuition, response data is represented graphically by color-scaled disks, but the underlying data matrix is just a table of integers and bordered by the aforementioned string metadata in the first row and column. ![enter image description here](http://i.stack.imgur.com/QGb2S.jpg) A small submatrix is given here:                 data = {{"ID", "MDQ1", "MDQ2", "MDQ3"}, {"001-01", 3, 2, 5}, {"002-01", 4, 1,            5}, {"003-01", 2, 2, 5}}      Further, define a variable for the headers               ids = {"ID", "MDQ1", "MDQ2", "MDQ3"}      To clean this data, the response values for a subset of questions, for example `{"MDQ1", "MDQ3"}` must be transformed, for example, by the function `(6-#)&` (Note: in the figure I highlighted `"MDQ1"` and `"MDQ5"` \- that's just for illustration) I would prefer to use `ReplacePart` but afaik, pattern matching can only be applied to position index and _not_ to the data values - but in this case the metadata (headers) is part of the data. The alternative for this task is `MapAt`, but it requires the intermediate generation of the positional index and barely readable code:               MapAt[If[NumericQ[#], 6 - #, #] &, data,       Flatten[Table[{i, First@First@Position[ids, #]}, {i, 2,            Length@data}] & /@ {"MDQ1", "MDQ3"}, 1]]      Is there a way to close the semantic gap between `MapAt` and `ReplacePart` and achieve more terse, more readable code?


title: FunctionInterpolation error when specifying AccuracyGoal

text: In the help page `ref/message/FunctionInterpolation/ncvb`, it is mentioned that one should specify `AccuracyGoal` for some (even very simple) functions:               FunctionInterpolation[Sqrt[x], {x, 0, 1}, AccuracyGoal -> 2]      However, when I evaluate it, a lot of error messages are generated, such as > Thread::tdlen: Objects of unequal length in {-(1/8),-(1/24),1/24,1/8}^{} > cannot be combined. FunctionInterpolation::nreal: "Near x = 1/8, the > function did not evaluate to a real number. Also, the precision I got is very bad (as one can check using `Plot[%[x] - Sqrt[x], {x, 0, 1}, PlotRange -> All]`). The error is about 5% so not usable for realistic work (and the situation does not change when I increase AccuracyGoal). Is it a bug? Perhaps I have to do `Interpolation` or `ListInterpolation` by hand myself.               $Version      > "9.0 for Linux x86 (64-bit) (February 7, 2013)" PS: I found this thread may be related but still different FunctionInterpolation Errors / Question re Evaluation Order and Options


title: Bug in RepeatedNull?

text: `RepeatedNull` appears to be buggy (versions 8.0, and 9.0). Define `f` as follows:               In[1]:= f@s:{h_@___...} := List @@@ s      `f` is intended to accept (possibly empty) List of non-atomic (possibly empty) expressions with the same head and change that head to List. It seems to work properly at first:               In[2]:= f@{g[x], g[y]}     Out[2]= {{x}, {y}}      (Calculates as intended.)               In[3]:= f@{g[x], h[y]}     Out[3]= f[{g[x], h[y]}]      (Pattern does not match.) However, `f` behaves unexpectedly on an empty List:               In[4]:= f@{}     Out[4]= {1}      The pattern does match, as it should, but the appearance of `1` is a complete mystery. I expected `f@{}` to be `List @@@ {}`, which is `{}`. Tracing didn't tell me anything:               In[5]:= Trace[f@{}, TraceInternal -> True]     Out[5]= {f[{}], List@@{1}, {1}}      It's probably a bug. Defining `f@{}` as a special case seems to fix the problem. However, 1) it's not actually a special case, and 2) I'm not sure in the correctness of the definition since there may be something wrong with the pattern I picked.   1. Was `{h_@___...}` the right choice of pattern for “(possibly empty) List of non-atomic (possibly empty) expressions with the same head”?   2. Is there a plausible explanation where does `1` come from? **UPD:** To clear things up I'll elaborate on a test example by @m_goldberg (from the answer) and a note by @sebhofer (from a comment):               In[6]:= ReleaseHold[ClearAll /@ Hold[test1, test2]];     In[7]:= test1[patt1: {h_@___ ...}] := Row@{"With named head: ", patt1}             test2[patt2: {_@___ ...}] := Row@{"Without named head: ", patt2}      Results vary with use of named vs unnamed pattern. That's one aspect convincing me to calssify the issue as bug:               In[9]:= {test1@{}, test2@{}} // Column     Out[9]= "With named head:"              "Without named head:" {}      (Here and after, output formatting is adjusted manually.) What also concerns me is that existing definitions don't get overwritten:               In[10]:= ClearAll@test     In[11]:= test[patt1 : {h_@___ ...}] := Row@{"With named head: ", patt1}              test[patt2 : {_@___ ...}] := Row@{"Without named head: ", patt2}              DownValues@test     Out[13]= {HoldPattern[test[patt2:{_[___]...}]]  :> "Without named head:" patt2,               HoldPattern[test[patt1:{h_[___]...}]] :> "With named head:" patt1}     In[14]:= test@{}     Out[14]= "Without named head:" {}      `DownValues` is prepended with the subsequent ones:               In[15]:= test[patt1 : {h_@___ ...}] := Row@{"Newdef, with named head: ", patt1}              test[patt2 : {_@___ ...}] := Row@{"Newdef, without named head: ", patt2}              DownValues@test     Out[17]= {HoldPattern[test[patt2:{_[___]...}]]  :> "Newdef, without named head:" patt2,               HoldPattern[test[patt1:{h_[___]...}]] :> "Newdef, with named head:" patt1,               HoldPattern[test[patt2:{_[___]...}]]  :> "Without named head:" patt2,               HoldPattern[test[patt1:{h_[___]...}]] :> "With named head:" patt1}     In[18]:= test@{}     Out[18]= "Newdef, without named head:" {}      While output satisfactorily corresponds to new definition, this probably should not happen due to 1) unpredictability; 2) garbage accumulation. (Additional examples of unstable pattern matching with `RepeatedNull` may be found in comments.)


title: How to make a function that can return the box with information?

text: In the version 10, a lot of functions returned a box with brief information which is very useful. For example:               Interpolation[{1, 2, 3, 5, 8, 5}]      ![enter image description here](http://i.stack.imgur.com/ae6Xk.png) So what's that little box, and how can I make a function that return a similar box which contains some of the information?


title: Mathematica's "POV" export format ignores ColorFunction

text: I was playing with xslittlegrass's Pov-Ray package and more generally with the POV-conversion function `ExportString[#, "POV"] &`, and noticed that `ExportString[#, "POV"] &` seems to ignore colors given to objects using `ColorFunction`. For example:               ParametricPlot3D[{Cos[ϕ] Sin[θ], Sin[ϕ] Sin[θ], Cos[θ]}, {ϕ, 0, 2 π}, {θ, 0, π},      PlotPoints -> 100, Mesh -> None,       ColorFunction -> Function[{x, y, z, ϕ, θ}, Hue[Sin[6 ϕ] Sin[6 θ]]],      ColorFunctionScaling -> False]      ![enter image description here](http://i.stack.imgur.com/4Z90o.png) However, applying `ExportString[#, "POV"] &` to the previous graphics object yields a POV-Ray script which, when rendered, consists entirely of white triangles: ![enter image description here](http://i.stack.imgur.com/7MHB4.png) So it seems that the surface coloration provided by the `ColorFunction` specified in the plot does not get converted to the POV output at all. Is there some way to correctly export the plot colors provided by `ColorFunction`?


title: Using With to scope over pure functions

text: Consider this example: given an option for a function `func` as `"x" :> (a&)`, how can one assign different values to `a` locally inside `func`?               a = False; (* global value of a *)     func[opt_] := With[{a = True}, Evaluate["x" /. opt]]; (* oversimplified function *)          func["x" :> (a &)]    (* ==> a & *)      No amount of `Evaluate` seems to help here. The problem with `With` is that in this case it is interpreted as `With[{a$ = 1}, a&]`, thus no replacement will be done. If I use `Block` instead of `With` the problem boils down to this (as `Block` won't replace variables inside `Function`):                Block[{a = True}, a &]   (* ==> a & *)      I do not want to define the option to be a function depending explicitly on `a`: I expect the user to write his own pure function for `"x"` where he can also use `a` that should acquire its local value when the `With/Block` is evaluated. Also, the problem disappears, if the code is simplified, but of course this is a no-go, as I need a function:               opt = "x" :> (a &);     With[{a = True}, Evaluate["x" /. opt]]   (* ==> True & *)      I've checked the following posts (mostly by Leonid and Mr.W), none of which offered a clear solution: this, this and this.


title: Importing Data and Devoting Their Names to Them

text: There are some files in a directory. I have used of _SetDiroctory_ to access all of them.               SetDirectory["C:\\Users\\SE7EN\\Desktop\\mathematica\\test"];      I can visit all theirs contents with               filenames = FileNames[]     {"Ronaldo.txt", "Messi.txt", "Beckenbauer.txt", "Zeydane.txt"}     loaddata[filenumber_] := Import[Part[FileNames[], filenumber]]      For example:               loaddata[4]     2    8    7     13   77      These are contents of Zeydane file. But I want to have imported files with the respectively devoted names. For example, desired result after that process, (which I do not know how it can be done), be same as bellow:               Ronaldo={2,3,5,8,0,1}     Messi={21,2,45,6}     Beckenbauer={11,42,5,2,7,21}     Zeydane={2,8,7,13,77}      One way is: importing them separately, `Messi=Import{.....,'data'}`. But it is not the desired process, The desired process must be done automatically. Automatically importing data from directory and devoting their names in that directory to the imported list. Thanks in advance.


title: Probability and distribution from actual data

text: Let's say I have some data from a real world system:               data = {0.026666156, 1.27421*^-6, 0.027878597, 0.017035598,         0.011036215, 0.038684388, 0.025161479, 0.021353902, 0.027487123,         0.021190747, 0.029328752, 0.014554109, 0.040037348, 0.020063044,         0.018363514, 0.0116034, 0.02609979, 0.024298555, 0.020568345,         0.017299039, 0.005427133, 0.023453297, 0.037443984, 0.031152865,         0.020158735, 0.014362383, 0.034687449, 0.01472421, 1.29928*^-6,         0.023887209, 0.014531724, 0.03055792, 0.027206875, 0.02227913,         0.01618167, 0.032540959, 1.26651*^-6, 0.021810796, 0.038698191,         0.014228248, 0.020261827, 0.031292827, 0.01142724, 0.039466342,         0.035504951};      If I generate histograms for this data it looks like this:               Column[{         Histogram[data, {.005}, "Probability", ImageSize -> Large],          Histogram[data, {0.005}, "CDF", ImageSize -> Large]     }]      ![PDF](http://i.stack.imgur.com/AJxQWm.png) ![CDF](http://i.stack.imgur.com/Zq9xMm.png) My question is twofold.   1. Is there a way to "fit" this data with a distribution? Or make a pseudo-distribution with this data? I've found `d = EmpiricalDistribution[data]; DiscretePlot[CDF[d, x], {x, 0, .05, .0001}]`, but is this the best way?   2. How do you programmatically calculate the P50 value from this data? (50% confidence that the value will be realized. y = 0.5 on CDF plot)


title: With versus Function

text: I've seen people compare `Block` with `Module` and `With` as scoping constructs, and try to figure out when to choose which. Also, I've seen posts about `Function` versus `#` versus downvalue functions. However, I already understood the differences between those, but still find myself more often doubting between functions and `With`... Does `With` have any advantage in any case over `Function`? I am talking about this constructions               With[{sth=inj}, code code sth code]      versus               (code code # code)&[inj]      or               Function[sth, code code sth code][inj]      Apart from the fact that its syntax is better suited for defining constants since the variable name and value are "together", or other elegance issues I mean. They are both scoping constructs, and `Function` among other uses can also inject code as `With`. If `With`'s variables are set with `:=` you can always use `Function` version with attributes. I know, this doesn't hold in the infrequent situation when you would use a `With` with, e.g, 2 `:=`s and 2 `=`s which can't be emulated by a function attribute. In the (not so extensive) tests I've done it doesn't seem to be faster.               In[127]:= TimingAverage[      With[{sum = 2 + 8},       {sum*x, sum*y}]]          Out[127]= 3.42178*10^-6          In[124]:= TimingAverage[      Function[{sum}, {sum*x, sum*y}][2 + 8]      ]          Out[124]= 3.36266*10^-6          In[122]:= Module[{lalala},      lalala[sum_] := {sum*x, sum*y};      TimingAverage[       lalala[2 + 8]       ]      ]          Out[122]= 2.88582*10^-6          In[123]:= TimingAverage[      {#*x, #*y} &[2 + 8]      ]          Out[123]= 2.67792*10^-6      Just out of curiosity, this very same test seem to be consistent with the common knowledge of `Module` being slower than `Block` being slower than `With`               In[119]:= TimingAverage[      Module[{sum = 2 + 8},       {sum*x, sum*y}]]          Out[119]= 7.19833*10^-6          In[120]:= TimingAverage[      Block[{sum = 2 + 8},       {sum*x, sum*y}]]          Out[120]= 4.58145*10^-6      As to the holding version of the tests, we get marginally better results with `With`               In[129]:= TimingAverage[      Function[{sum}, {sum*x, sum*y}, HoldFirst][2 + 8]      ]          Out[129]= 4.22668*10^-6               In[128]:= TimingAverage[      With[{sum := 2 + 8},       {sum*x, sum*y}]]          Out[128]= 3.8681*10^-6               In[131]:= Module[{lalala},      SetAttributes[lalala, HoldFirst];      lalala[sum_] := {sum*x, sum*y};      TimingAverage[       lalala[2 + 8]       ]      ]          Out[131]= 3.45039*10^-6      **EDIT** As to style and elegance, I guess that functions are more suited when the expressions you're injected are big and the code you're injecting them into is small, and `With` otherwise. Any thoughts on all this issue? Am I missing something?


title: how to set initial conditions when solving recursive equation with tables

text: I am solving a recursive expression with `ParallelTable`. Here is a MWE showing how I do it, and how I set the initial condition:               SetSharedVariable[vals]     t[n_] := t[n - 1]*i*NIntegrate[Exp[-i*x^2], {x, -Infinity, Infinity}];          t[0] = 1;          vals = ParallelTable[{i, t[3]}, {i, 1, 500}];      The expression `t` depends on `i` implicitly. Now I want to make this dependency explicit, as shown here (note, it is **not** a functioning example!):               SetSharedVariable[vals]     t[d_, n_] :=        t[n - 1]*d*NIntegrate[Exp[-d*x^2], {x, -Infinity, Infinity}];          (* WHAT TO DO WITH THIS, THE INITIAL CONDITION? *)     t[i, 0] = 1;          vals = ParallelTable[{i, t[i, 3]}, {i, 1, 500}];      My concern is regarding the initial condition. When I am dealing with `tables`, is there an easy way to implement initial conditions, or do I have to use a `For`-loop for that (where `i` is the variable)?


title: Prandtl-Meyer function

text: I'm trying to solve for Mach number based on the given Prandtl-Meyer function, however I keep getting odd error. Here is my code:               g = 1.4          v2 = 54          Solve[v2 == (Sqrt[(g + 1)/(g - 1)]*             ArcTan[Sqrt[(g - 1) (M2^2 - 1)/(g + 1)]] -             ArcTan[Sqrt[M2^2 - 1]])/Pi*180, {M2}];      This is the website that has the function I'm trying to solve. Any help would be greatly appreciated. ## UPDATED:               g = 1.4          v2 = 54.76          M2 := FindRoot[       v2 == (Sqrt[(g + 1)/(g - 1)]*             ArcTan[Sqrt[(g - 1) (x^2 - 1)/(g + 1)]] -             ArcTan[Sqrt[x^2 - 1]])/Pi*180, {x, 3}]     M2


title: DumpSave for the forgetful

text: A few weeks ago I created a big matrix, and in order not to have to recreate it, I stored it using `DumpSave["file.mx", variable]`. Now I want to read it back in and so I use `<<file.mx`. It appears to work fine and to load the file (which takes a few moments because it is 54 MB in size). Now the problem: I have forgotten what I called the matrix, that is, what name `variable` I used in when I saved it. My generating command is unfortunately not around any more. Is there any way of figuring out what my variable was called or more directly, how to access my data now that it is loaded?


title: Mass Symbolic Manipulation with Subscripts? (from plaintext Input)

text: The simplest example of the change being sought is a greek letter, typed in as plaintext nu, and its may be replaced by the symbol, ν: `expr = 3nu*kx*ky`\+ `expr /. nu -> ν` yielding `3νkxky` However, I need to make a variable with a subscript correspond **_to a large number of different subscript values_** (many different possibilities for x in "k_x"). In any one of my (100+) equations, it's easy enough to change its couple of variables to their more visually comprehensible counterpart manually using the above method along with `Subscript`, but I am having trouble finding an efficient way to have _Mathematica_ take _ANY_ given `kz` and output the corresponding `Subscript[k,z]` output. A method of achieving this here automatedly from _Mathematica_ taking a glance at my plaintext system of equations would be great. Thank you! Edit: After talking with Bill S briefly in the comments, he suggested I upload an example of what I have so far and what I hope to accomplish. If arrays are a better way to handle a majority of my input, even in conjunction with subscripts at times, I am more than willing to use them. Here's an examplary 3 equations where R# signifies the rate of change of Z[#], where Z[#] on the RHS **_only coincidentally_** contains the function bracket notation due to use of other software.               R6 = kf*(z[1] + mu*z[5]) - 2*z[6] + mu*kd^2*z[7] - kd^2*z[6]     R7 = kf*(z[1] + mu*z[6] - 2*z[7]) + kd^2*z[8] + kd^2*z[7]     R8 = kf*(z[1] + (mu*z[7] - 2*z[8]) + kd^2*z[9] + kd^2*z[8]      As you can see, the number of options for x in k_x is only 2: f & d, so I can input the `/. rules` easily manually. However, to avoid confusion between my plaintext input form's z[x] and _Mathematica's_ traditional single-function notation, I would like to change ALL z[x] to z_x (z with subscript x), regardless of specific x. However, here there are 140 different values rather than 2, so manually inputting each `/. rule` is less practical. My current goal is to simplify the appearance and allow for symbolic manipulation of all the parameters, but I do hope to do curve-fitting eventually. Does anyone have advice on how to approach this scenario, either via subscripts or `Array`? I suspect # and possibly `ToRules` will be involved but am not sure yet how to do this. _**Answered!_** Please see the answer and, if you're **only** interested in efficiently replacing any symbolic expression with another, see the comment on the answer.


title: How to simplify the complex result with trig-abs-sqrt obtained related with Cosine symbolic Matrix of EulerAngles

text: Here in X-convention Extrinsic               RotationMatrix3DExtrinsic[\[Phi]_,\[Theta]_,\[Psi]_]:=RotationMatrix[\[Pi]-\[Psi],{0,0,1}].RotationMatrix[\[Theta],{1,0,0}].RotationMatrix[\[Pi]-\[Phi],{0,0,1}]      Intrinsic               RotationMatrix3DIntrinsic[\[Phi]_,\[Theta]_,\[Psi]_]:=RotationMatrix[\[Pi]-\[Phi],RotationMatrix[\[Theta],RotationMatrix[\[Pi]-\[Psi],{0,0,1}].{1,0,0}].{0,0,1}].RotationMatrix[\[Theta],RotationMatrix[\[Pi]-\[Psi],{0,0,1}].{1,0,0}].RotationMatrix[\[Pi]-\[Psi],{0,0,1}]      In Numeric values, they got the same results.               RotationMatrix3DExtrinsic[\[Pi]/3, \[Pi]/4, \[Pi]/5]//N     RotationMatrix3DIntrinsic[\[Pi]/3,\[Pi]/4,\[Pi]/5]//N      ![enter image description here](http://i.stack.imgur.com/0yUxO.png) But RotationMatrix3DIntrinsic does not work well in symbolic value, alpha,beta,gamma. After a long time calculation, I see some complex result with Conjugate Abs... So how to develop it. * * *               result=RotationMatrix3DIntrinsic[a,b,c];     t=Assuming[Element[{a,b,c},Reals],result];      failed.               t=Assuming[Element[{a,b,c},Reals]&&0<a<\[Pi]/2&&0<b<\[Pi]/2&&0<c<\[Pi]/2,result//Simplify];      failed.               t=Simplify[result,Element[{a,b,c},Reals]&&0<a<\[Pi]/2&&0<b<\[Pi]/2&&0<c<\[Pi]/2];      failed. * * * There are a lot Abs, Trig functions * * *   * Simpler case two angle the result show that we should add suitable range of angles, however it cost too much time. ![enter image description here](http://i.stack.imgur.com/VOnOQ.png) * * * a solution: how to speed up?               IntrinsicRotation3D[\[Phi]_,\[Theta]_,\[Psi]_]:=Module[{},          rot1=FullSimplify[RotationMatrix[\[Phi],axisZ={0,0,1}],\[Psi]\[Element]Reals&&0<\[Phi]<\[Pi]/2];          rot2=FullSimplify[RotationMatrix[\[Theta],axisX=rot1.{1,0,0}],Element[{\[Theta],\[Phi]},Reals]&&0<\[Theta]<\[Pi]/2&&0<\[Phi]<\[Pi]/2];          rot3=FullSimplify[RotationMatrix[\[Psi],axisZNew=rot2.axisZ],Element[{\[Theta],\[Psi],\[Phi]},Reals]&&0<\[Theta]<\[Pi]/2&&0<\[Psi]<\[Pi]/2&&0<\[Phi]<\[Pi]/2];          result=rot3.rot2.rot1//FullSimplify]


title: Convert Graph to Graphics

text: In Mathematica 9, a graph is returned as an object with head `Graph`:               In[8]:= CompleteGraph[8] // Head     Out[8]= Graph      Right-clicking on a `Graph` object brings a menu with the option "Convert to Graphics". Selecting this option returns a new object which has head `Graphics`. I need to do this programmatically, but I haven't found any command that, applied to `CompleteGraph[8]` (to put an example), returns an object with head `Graphics`, with a plot of the graph. Is there a command in Mathematica to convert a `Graph` to a `Graphics`?


title: How to send output of Information[] command to a text file?

text: I am having little hard time sending output of `Information[]` command to a text file. related question How to write output to an external text file in addition to the standard output stream? I'd like to find what is the correct way to do this. I tried the following 3 things, including what is in the above link, but nothing worked for me. I am using version 8.0.4 on windows 7.               s = OpenWrite["test.txt", FormatType -> OutputForm] (*without FormatType also error*)     $Post = Write[#, s] &     Information["DSolve", LongForm -> False]     Close[s]     $Post =.      second attempt               s = OpenWrite["test.txt"]     $Output = s     Information["DSolve", LongForm -> False]     Close[s]      Third attempt (using the same solution given in the above link)               output = OpenWrite["out.txt", FormatType -> OutputForm];     $PrePrint = (Write[output, #]; #) &;     Information["DSolve", LongForm -> False]      I see the file out.txt gets created, but it is empty. Nothing is written to it. Even after I close Mathematica or the kernel, it is empty. I also get an error when I close it               Close[output]  (*Write::noopen: "Cannot open OutputStream["out.txt",19]"*)      Basically, I want to issue many commands in my notebook, in the form of `Information[...]` for many topics, and I want this otuput to go to a text file to process later. What would be the right way to do this? thanks, **edit** fyi, this is the final version. A small example, to show how it is now working: (this is part of a larger code I use to generate all the symbols in all packages in Mathematica). I was cleaning it to get ready to run it when V 9 is out.               Get["Utilities`CleanSlate`"]     SetOptions[CleanSlate, Verbose -> False];     addOnPackages = {"ANOVA", "Audio"};     output = OpenWrite["info.txt", FormatType -> OutputForm, PageWidth -> Infinity];     $Output = output;     $Urgent = output;          Do[{        packageName = addOnPackages[[i]];        Print["<", packageName];        Get[packageName <> "`"];        funs = Names[packageName <> "`*"];        Information[#, LongForm -> False] & /@ funs;        CleanSlate[Evaluate[packageName <> "`"]]        }, {i, 1, Length[addOnPackages]}       ];          Close[output];      Thanks for Todd and Mike help in this. **update 12/1/2012** FYI, Based on what I learned from the replies here, I made this little function that allows one to capture the output from ? on command into a string. (if you want ?? output, then just change the `LongForm->False` to `LongForm->True` (will update this function later to add this as an option to the call. But for now, just to give an idea)               help[fun_String] := Module[{s, file},       SetDirectory[NotebookDirectory[]];       file = OpenWrite["s.txt", FormatType -> OutputForm, PageWidth -> Infinity];       Block[{$Urgent = file},        Information[fun, LongForm -> False] ];       Close[file];       Import["s.txt"]       ]      To use it               s = help["DSolve"];      and now `s` is a string of what would have gone to screen.


title: Partitioning an image based on features

text: I have an image that has various characters hand drawn in it, like numbers and letters. I'm trying to partition each character into it's own image so I can run it through `Classify[]` and identify them one at a time (since `TextRecognize[]` doesn't work well on individual characters). My images look like this: ![enter image description here](http://i.stack.imgur.com/GjN95.jpg) That's a bunch of 1's for putting into `Classify[]`. So it should be pretty easy to partition each one, but I'm not sure what the best way to do it is. I tried adapting this example: http://reference.wolfram.com/mathematica/example/AnalyzeSegmentedCellsInAnImage.html but I couldn't get it to work.               characters =        SelectComponents[        DeleteBorderComponents[Binarize[a, {0, .7}]], {"Area"},         100 < #1 < 1000 &];          outlines =        ComponentMeasurements[         ImageMultiply[a, characters], {"BoundingBox"}][[All, 2]];          Show[a, Graphics[{Red, Thick, Circle @@ # & /@ outlines}]];      This just returns a slightly lighter version of the original image with no red anywhere.


title: Change values in string under condition

text: ### how to change the width and height in the `HTML` code into some other values decided by ratio and a fixed width? The background is that you can adjust a image in your web-page to fit the fixed-width. * * *               string="";      Here is my tries, a snippet of my terrible codes. I want to change the $\text{width}>800$ into $800$, here it is $882$. `And` height becomes the corresponding value.               StringCases[string,(*strT:*) imgTag : Shortest[""] :>   StringReplace[imgTag,    widthString :        Shortest["width=\"" ~~ width__ ~~ "\" "] ~~ (heightSring :         Shortest["height=\"" ~~ height__ ~~ "\" s"(*Here,          there is a strange thing I felt, try delete the 's'.*)]) ~~       pp__ /; (heightE =         ToExpression[         ToExpression[(ttt =             StringDrop[StringDrop[heightSring, 7], -1])]];        widthE =         ToExpression[         ToExpression[(tt = StringDrop[widthString, 6])]]) > 800 :>     "width=\"800\" height=\"" <> ToString[N[800 heightE/widthE]] <>      "\" " <> pp]]          (*         {,}     *)      The value of `ttt` is               ttt          (*         "21"      *)      It's Ok, but there is a problem, see the comment of the above code. ### question1: * * * in the `heightString` pattern, delete the "s" of "style"(I think/hope "\" " is enough to work well like that in `widthString`, but why it dosn't work well?)               StringCases[string,(*strT:*) imgTag : Shortest[""] :>   StringReplace[imgTag,    widthString :        Shortest["width=\"" ~~ width__ ~~ "\" "] ~~ (heightSring :         Shortest["height=\"" ~~ height__ ~~ "\" "]) ~~       pp__ /; (heightE =         ToExpression[         ToExpression[(ttt =             StringDrop[StringDrop[heightSring, 7], -1])]];        widthE =         ToExpression[         ToExpression[(tt = StringDrop[widthString, 6])]]) > 800 :>     "width=\"800\" height=\"" <> ToString[N[800 heightE/widthE]] <>      "\" " <> pp]]          (*         {,}     *)          ttt          (*         "21" style="padding-right:2px; border:0px solid white; vertical-align:middle;"     *)      ## question2 * * * of course, my codes are urgly, as you see, too many `ToExpression`,and `StringDrop`. I definitely know you can think up a simpler method? how to optimize my codes? Welcome to comment, if you're interested with the question and feel hard to understand and badly I'm always poor at expressing. here is my page in GitHub with code formatted better One problem need under consideration is the spaces, and that in my method it's sensitive, for example: maybe not all `style`s are after `width=\"20\" height=\"21\" [other...?]style=\"padding...` . * * * @ssch's answer is good, but I wanna see some `StringManipulation` answers, since I'm learning `StringManipulation` via this example. Welcome to post your answers.