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

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?


Creating a highly customized BarChart

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)


How to find the area between two curves

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?


How to build a list of constraints for NMinimize

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.


Specify positions in a SparseArray using patterns with functions

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


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

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.


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

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}} >


Efficient storage of Kronecker sum of circulant matrices+diagonal matrix

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?


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

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.


How to get the absolute difference between two angles

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.


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

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


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

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"}}}     ]


video image recognition

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.


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

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?**


Shaping/simplifying equations in a certain way

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.


Help with interactive plot?

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"}]


managing custom Ticks

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


ParametricPlot Options Problem: PlotStyle and AxisLabel issues

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}]


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

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.


Is using undocumented functionality a Bad Idea™?

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?**


Saving graphics object in order to manipulate  it later?

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.


BUGS-type calculations in Mathematica

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!


Indefinite Integral long time plotting

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?


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

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!


Visualization of Bivariate Distributions

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?


Define an operator with commutative, associative and distributive properties

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.


How to improve visualisation of trajectories in 3D space

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)


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

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?


FunctionInterpolation error when specifying AccuracyGoal

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


Bug in RepeatedNull?

`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.)


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

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?


Mathematica's "POV" export format ignores ColorFunction

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`?


Using With to scope over pure functions

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.


Importing Data and Devoting Their Names to Them

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.


Probability and distribution from actual data

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)


With versus Function

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?


how to set initial conditions when solving recursive equation with tables

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)?


Prandtl-Meyer function

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


DumpSave for the forgetful

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?


Mass Symbolic Manipulation with Subscripts? (from plaintext Input)

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.


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

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]


Convert Graph to Graphics

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`?


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

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.


Partitioning an image based on features

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.


Change values in string under condition

### 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.


How can I combine two Pick expressions into one?

I want to speed up my code, i.e., replace `Select` by `Pick`. I think using two `Pick` expressions isn't pretty, but I have no good idea on how to combine them.               Select[Permutations@ Range@9,         #1 < #4 < #7 && #1/(10 #2 + #3) + #4/(10 #5 + #6) + #7/(10 #8 + #9) == 1 & @@ # &]          Pick[#, #1/(10 #2 + #3) + #4/(10 #5 + #6) + #7/(10 #8 + #9) & @@ Transpose @ #, 1] & @       Pick[#, Thread[#1 < #4 < #7] & @@ Transpose@#] & @ Permutations @ Range @ 9


Expression for the real 7/3 power

I need an expression for the real 7/3 power of a real-valued function, i.e., a reformulation of               f[x_] := g[x]^(7/3)      that works for negative values of `g[x]`. This function and its first and second derivatives are used in heavy computation (i.e. in objectives to `FindMinimum`) and need to be well-defined at all values of `x`. In particular, I've tried the following, which don't work:               f[x_] := g[x]^(7/3)      which gives complex values at negative values of `g[x]`, and               f[x_] := Surd[g[x],3]^7      which gives a "Infinite expression" error when its derivative is evaluated at 0.


Working with abstract vectors

I often need to compute derivatives or integrals involving N-dimensional vectors (where the dimension could be equal to 2 or 3 but is not particularly relevant for the sake of the derivation). The only way I know to translate this into valid Mathematica input is to specialize to a particular N and define all quantities component-wise. A simple example: computing the time derivative of a normalized quantity ![Time derivative of a normalized quantity](http://i.stack.imgur.com/QnzXB.png) While correct, this can obviously get extremely messy fast. At that point, I find it easier to just do the computation by hand using generic vector calculus identities which work for vectors of any dimension. I was wondering if there is a way of doing such computations using an abstract vector type? This post references a `Vectors` command that is potentially related, but it was not clear to me how to use it for calculus. **Edit** : After some more experimentation with `Vectors`, I was able to get quite close to what I was looking for:               $Assumptions = V[t] \[Element] Vectors[3, Reals];     Simplify[D[V[t]/Sqrt[Dot[V[t], V[t]]], t]]      $$\frac{2 V(t).V(t) V'(t)-V(t) \left(V(t).V'(t)+V'(t).V(t)\right)}{2 (V(t).V(t))^{3/2}}$$ However, neither `Simplify[]` nor `TensorReduce[]` could simplify the commutative dot product in the expression above.


Potential pollution of Global` context in fresh kernel

If I evaluate, with a fresh kernel               Names["Global`*"]      I get > >     {"rhs", "z"} >   I think this is not caused by any packages in `$UserBaseDirectory` or `$BaseDirectory`, because if I evaluate the same expression under V9.0.1, which has the same strings for these variables (directories), I get               Names["Global`*"]      > >     {} >   As expected. I was wondering if others are getting the same result. `rhs` and `z` do not have values, but still I am a bit concerned about the safety of               Remove["Global`*"]      when certain functions may depend on the existence of these symbols in Global`. For example if I set               sys`f[Global`xxxx_] := Global`xxxx      and evaluate               Remove[Global`xxxx]      then the following looks a bit scary                sys`f // Definition      > >     sys`f[Removed[xxxx]:_]:=Removed[xxxx] >   `sys`f` still works, but I still think it may lead to trouble (e.g. with `Save`). Kirma came up with the nice idea of testing this on the cloud. I get               Apply[And,       MemberQ[CloudEvaluate[Names["Global`*"]], #] & /@ {"z", "rhs"}]      > >     True >   But there are many other symbols in the `Global`` context there. So, is this a bug?


Variable name string to expression

I'm not sure how to name this problem appropriately. But anyway. I have, say, three variables (arrays in my case), which I call:               A1, A2, A3      I would like to perform a certain operation on all of these arrays. Obviously I don't want to duplicate the code. What I figured is the following:               For[id = 1, id <= 3,     INPUT = ToExpression["A" <> ToString[id]];     INPUT = Table[{INPUT[[j, 1]], 10^4*INPUT[[j, 2]]}, {j, 1, Length[INPUT]}];     id += 1;     ];      This unfortunately does NOT work. It's just an example. But the big question is how to handle names of variables in "such" cases? Any help greatly appreciated.


Keeping Integrate from making unnecessary assumptions

I would like to evaluate the integral $\int_{-\infty}^\infty \mathrm{d}x \, \exp\left(- a x^2 - x^4\right)$ for any real value of $a$. _Mathematica_ 8.0.4 gives the following result:               Integrate[Exp[- a x^2  - x^4], {x, -∞, ∞}, Assumptions -> {a ∈ Reals}]      > >     ConditionalExpression[1/2 Sqrt[a] E^(a^2/8) BesselK[1/4, a^2/8], a >= 0] >   Can I keep _Mathematica_ from restricting its answer to non-negative values of $a$, especially since it can do the integral also for negative values:               Integrate[Exp[- a x^2  - x^4], {x, -∞, ∞}, Assumptions -> {a < 0}]      > >     (Sqrt[-a] E^(a^2/8) π (BesselI[-(1/4), a^2/8] + BesselI[1/4, a^2/8]))/(2 > Sqrt[2]) >   I can construct the solution for all real $a$ from these two restricted solutions using `Piecewise`, but I'd rather not do that.


Stop Computation - Is Exit[] overkill?

The following example either finds a factor of the number $n$ or returns a message saying that the number in question is prime (I specifially wrote this to demonstrate my question below).               n = 125;     For[i = 2, i <= Sqrt[n], i++,         If[Mod[n, i] == 0, Print["Factor found: ", i]; Break[];]      ]     If[i <= Sqrt[n], Exit[];]     Print[n, " is prime."]     ...      I know I could simply include the last Print statement in the if-condition, but I am specifically looking for a command that makes Mathematica skip the last _Print_ statement (and all other statements that might come thereafter...). I tried _Break_ , _Abort_ and _Interrupt_ , but none have the desired effect. Now the commands _Exit_ and _Quit_ work, but they terminate the entire Mathematica kernel, which is a bit of an overkill. How could I bypass this issue? I need something like _SkipRemainingCommands_.


How to solve system of integral equations

I have two integral equations               -Sin[v]*Integrate[          (x[v, z]*b*Sin[v])/Sqrt[(a^2*(Cos[v])^2 + b^2*(Sin[v])^2 + z^2)^3],          {v, 0, 2*Pi}, {z, -l, l}] == 0          -Cos[v]*Integrate[         (x[v, z]*a*Cos[v])/Sqrt[(a^2*(Cos[v])^2 + b^2*(Sin[v])^2 + z^2)^3],         {v, 0, 2*Pi}, {z, -l, l}] == 0      I would like to find a solution for `x[v,z]`, that is going to solve bough equations. Than I would like to plot 3D graph with axes `v,z,x[v,z]`. Can anyone help me in finding a solution?


expression contained across multiple cells

Is it possible to span one expression across multiple cells? E.g. long if statement or function evaluation. I looked in documentation and searched forum/google and could not find.


Creating event handler with ImplementJavaInterface inside a package

I am trying to make my Mathematica function to serve as an event handler for the events generated by a Java object. Specifically, I have a Java object that connects as a client to a server that periodically pushes updates to all clients. I also have an observer object that calls it's `update` method whenever the client receives any updates. My goal is to catch this updates inside Mathematica, and handle them with a Mathematica function It appears that JLink has a way of doing this with `ImplementJavaInterface` command http://reference.wolfram.com/mathematica/JLink/ref/ImplementJavaInterface.html. Here is how I've used it:               (* create a client that connects to localhost:3000 *)     client = JavaNew["me.kutrumbos.DdpClient", "localhost", MakeJavaObject[3000]];          (* create an observer that monitors client's events *)     observer = JavaNew["me.kutrumbos.examples.ObservableDdpClientObserver"];          (* create a variable that will be updated with data from incoming events *)     collections = {};          (* define event handler that updates collections variable with the new value *)     onCollectionUpdate[msg_] := collections = observer@getJSONObjectsList["coll"];          (* add event handler to the observer *)     observer@addMessageHandler[        ImplementJavaInterface["me.kutrumbos.examples.MessageHandler",          "update" -> "onCollectionUpdate"]];          (* add observer to the client *)     client@addObserver[observer];          (* connect to the server *)     client@connect[];      When I run this inside a notebook, everything works. Every time an event occurs, `collections` variable gets updated with the data contained in the event. However, when I put this code in the package, and expose `collections` by adding `collections::usage = "global var"` in the preamble of the package, the variable doesn't update, and the event handler doesn't even seem to run. I tried inserting `MessageDialog["Event Handler alert"]` inside the event handler to see if the event handler is even called, and I am not getting any pop-up alerts when I generate new events on the server. Any idea why this might be happening?


VariationalD giving the wrong solution?

EDIT: As pointed out in the comments, `VariationalD` gives a variational derivative (which I don't want), not a derivative with respect to a function (i.e. $\frac{df[x]}{dlog_e(x)}$ as a simple example - this is what I thought it did the first time I read the description). Is it even possible in Mathematica to take the derivative of a function with respect to another function? I know you can use the chain rule to rewrite, using the example just above, $\frac{df[x]}{dlog_e(x)}=x\frac{df[x]}{dx}$. In my case the equivalent would be much more cumbersome and I want to be able to change the function w.r.t. which I'm differentiating. Is it possible to do this in Mathematica?   _ I am using the `VariationalMethods`` package, specifically the `VariationalD` command. I am trying to take the derivative of one (complicated) function fitted to experimental data with respect to another (complicated) function. First I wanted to make sure that the command does what I wanted. So I inputted the example given in `VariationalD`'s "Examples" section:                VariationalD[y[x] Sqrt[y'[x]], y[x], x]      This gives a result of $$ \frac{d}{dy[x]}(y[x] \cdot y'[x]^{1/2})=\frac{2 y'[x]^2+y[x] y''[x]}{4 y'[x]^{3/2}}. $$ Trying to reproduce this by hand I started with the product rule: $$ \frac{d}{dy[x]}(y[x] \cdot y'[x]^{1/2})=y[x]\frac{d}{dy[x]}y'[x]^{1/2}+y'[x]^{1/2}\frac{d}{dy[x]}y[x] $$ The second term is just $$ y'[x]^{1/2}\frac{d}{dy[x]}y[x]=y'[x]^{1/2}. $$ The first term, you use the chain rule on: $$ y[x]\frac{d}{dy[x]}y'[x]^{1/2}=y[x]\frac{1}{2}y'[x]^{-1/2}\frac{d}{dy[x]}y'[x] $$ $$ \frac{d}{dy[x]}y'[x]=\frac{dx}{dy[x]}\frac{d}{dx}y'[x]=(\frac{dy[x]}{dx})^{-1}y''[x]=\frac{y''[x]}{y'[x]}. $$ Putting all of that together: $$ \frac{d}{dy[x]}(y[x] \cdot y'[x]^{1/2})=y'[x]^{1/2}+\frac{1}{2}\frac{y[x]y''[x]}{y'[x]^{3/2}}. $$ Simplifying: $$ \frac{d}{dy[x]}(y[x] \cdot y'[x]^{1/2})=\frac{2 y'[x]^2+y[x]y''[x]}{2 y'[x]^{3/2}}, $$ which is identical to the solution given by `VariationalD` except for a factor of 2. So I assumed it was a mistake I made somewhere (and it might be) and tried comparing every step I made when doing it by hand with the corresponding step in `VariationalD`. Eventually I discovered one difference in the step                VariationalD[Sqrt[y'[x]], y[x], x]      which gives an answer of $\frac{y''[x]}{4y'[x]^{3/2}}$, a factor of 2 different than when I do it. I'm still not sure where the factor of 2 in the $y'[x]^{1/2}\frac{d}{dy[x]}y[x]$ step comes from. I kept messing around with it and found that                VariationalD[y'[x],y[x],x]=0      which can't be right. For example, if $y[x]=x^2$ and $y'[x]=2 x$, $$ \frac{dy'[x]}{dy[x]}=\frac{d(2x)}{dx^2}=2(\frac{dx^2}{dx})^{-1}=2(2x)^{-1}=\frac{1}{x}. $$ So why is `VariationalD` giving a zero answer? It's even weirder because $\frac{dy'[x]}{dy[x]}$ comes up when you perform the original differentiation by hand as well. It can't be zero there either or the first term would vanish and the answer would just be $y'[x]^{1/2}$. So am I making a stupid mistake in my differentiation? Even if so, why is `VariationalD` giving zero for the derivative with respect to a function of its derivative? I've spent about an hour searching for anything relevant online, and...nothing. Any help would be appreciated! EDIT: I've been looking at the description of `VariationalD` more closely and now I'm not sure it does what I think it does, i.e.                VariationalD[f[x],g[x],x]      gives $\frac{df[x]}{dg[x]}$ as output. Is this correct? Looking at the description it now seems to me that it would give $f[x]\frac{df[x]}{dg[x]}$. But if that's the case then the output for my original expression is still wrong.


Can I enter the traditional form for Binomial as input in an expression?

Is there a way to enter the traditional form of a binomial coefficient, i.e. ${n \choose k}$ instead of `Binomial[n,k]`, like I would enter a radical sign $\sqrt{x}$ using control-shift-2? I would like to enter it that way in a notebook, and see it in that form in the input as well as output equations, just like the radical. I know that I can use `TraditionalForm` to convert it on output, but I don't need to do that to see radicals instead of `Sqrt`.


Why does Mathematica list the variables in a double integral backwards?

I am an advanced novice Mathematica user and have done a fair amount of single-variable calculus things with it. This semester I am using Mathematica for multi-variate calculus and when I tried to use Mathematica to solve a double integral I got incorrect results. I discovered that the syntax for the Integrate command has you list the variables in the opposite order they appear in the integrand. At first blush this seems dumb and annoying but perhaps there is a good reason for it. If so, I'd like to know what it is. If not, is anyone else annoyed by this?


Correct way to remove matrix columns?

I start off with `m = 1000 x 5` matrix, and I would like to remove first column to get `1000 x 4` matrix and repeat again for `1000 x 3` and so on. Is there an efficient way to do this? I see Insert to add columns or rows but don't see command for removing? I see maybe use the extract but is this only for a single vector extraction?


Behavior of $PreRead in Kernel

I am interested in making a simple accounting style line calculator that allows me to interact with it something like this:               In[]:   4 + 5     Out[]:  9     In[]:   +3     Out[]:  12     In[]:   *2     Out[]:  24     In[]:   /4     Out[]:  6      In the front end, I can do this with:               $PreRead = (ReplaceAll[#, {"*" :> "% *", "+" :> "% +", "-" :> "% - ",       "/" :> "% /"}] &)      (And stop it by `$PreRead =.`) which works nicely, however I would like to use the numberpad, and the + key on the number pad starts a free form input. So, I thought I'd be sneaky and open up a kernel window. Sadly, the above assignment of $PreRead doesn't seem to execute in the Kernel, even though it looks like the variable has been assigned properly. I'm interested in why $PreRead isn't behaving the same in the Kernel window as it would in the front end, and it wouldn't hurt to know if it is possible to shut off the keymapping of the numberpad + key to free form input.


Hold expression with RandomInteger

One more question for today: I'm trying to show two random integers with a plus (+) sign between them, in an unevaluated form. I know how Hold and HoldForm work, but they hold everything, including the RandomInteger:               Hold[RandomInteger[100] + RandomInteger[100]]      I've tried then Evaluate before RandomInteger, but that doesn't seem to do the trick. Any help with this? Very much appreciated, as always!


CDF Player: MathKernel.exe uses a lot of memory

When I run this CDF document http://x6174x.blogspot.pt/2013/04/bankroll- growth-simulator.html on my desktop, each time I press "Run again" the Task Manager shows that the MathKernel.exe process associated with the CDF player uses increasingly more RAM. However if I try it on a laptop with the same OS (Win 7 Ultimate) the memory usage remains more or less constant. What could be wrong with the first CDF Player? I tried to reinstall it but the problem persists. I should add that the first computer has Mathematica 9 installed but the laptop has only the CDF Player. Could this be some interaction between the CDF player and Mathematica? Even if I have Mathematica closed when I run the CDF document it will show a Mathematica.exe process running. Thanks.


How to simplify an expression with special functions to zero

The following is a well-known Bessel function identity: $$J_{-n}(z)=(-1)^n J_n(z),\qquad n\in\mathbb Z$$ To check this, I used the following code and the result is as what I expected.               In[2]:= FullSimplify[(-1)^n*BesselJ[n, z] == BesselJ[-n, z], n ∈ Integers]     Out[2]= True      The problem is that _Mathematica_ does not return zero when I try to simplify the following expression: $$(-1)^n J_{n}(z)-J_{-n}(z),\qquad n\in\mathbb Z$$ I tried the following code, but the output is as complex as the input:               In[3]:= FullSimplify[(-1)^n*BesselJ[n, z] - BesselJ[-n, z], n ∈ Integers]     Out[3]= -BesselJ[-n, z] + (-1)^n BesselJ[n, z]    (*result I expected : 0*)      My goal is to command _Mathematica_ to reduce the expression to zero, and I need some advice.


How to delete all rows in datafile that contain a string

I'm importing some data from a file. However, the file was created by an unreliable instrument, such that the data looks like this:               in: data = Import["D:\\6000s.txt", "Table"]       out: {...{5,0,46.4109},{6,0,46.6017},{7,0,No,Data},{8,0,45.7324}...}      The lines containing "No Data" can be safely deleted, but I don't know how to do this well. How can I efficiently map over my table and erase all rows that contain a string? Thanks in advance for your help. Edit: An example of my data is  here . Also, a closely related question is here Edit 2: @RunnyKine's and @MikeHoneyChurch's answers in the comments did the trick. I ended up doing the following:               data = Import["my_data.txt", "Table"];     data = DeleteCases[data, {__, _String, _String}]      This is _much faster_ than the ugly for loops I had used previously. Thanks for your help!


Assigning symbolic operators to built-in functions

Can I do something like this: $$\partial_t = D[f, t]$$ i.e. create a symbol instead of a function so that each time I call it, it executes the operation as defined?


storing rescaled images in new variables

I'm trying to assign random image files that undergo rescaling to a list of variable names. The images I'm trying to assign are the result of mapping the ImageResize function of two arguments to the Randomly generated images, where the 2nd argument has a fixed value. However when I assign the values to a list of variables, the `Scaled[50]` argument is not being applied to the images. Thanks. I store 15 random images in variables `tmp[1]`, `tmp[2]`, ... using a Do statment and recall them using another statement:               Do[tmp[i] = Image[RandomReal[1, {8, 12, 3}]], {i, Range[1, 15]}];     tmp /@ Range[1, 15]      (See Assigning values to a list of variable names) Now I want to Scale all the images 50x and store them in a list of variables. It can overwrite the tmp variables, but for simplicity I'll use new variables:               Do[var[j] = ImageResize[#, Scaled[50]] & /@ tmp[j], {j, Range[1, 15]}];      (See Mapping a function of two arguments where the 2nd arg has a fixed value) When I recall them using               var /@ Range[1,15]      they are not scaled, it is the same images as in `tmp /@ Range[1,15]` unscaled. This code produces the desired result on a single image               var[1]=ImageResize[tmp[1], Scaled[50]]      so I'm not sure why the second Do statment does not produce the desired list of rescaled images. If there is a way to do it in the initial creation of the images (in the first Do statement) that is better.


How to get more accurate orthonormal eigenvectors?

I have a matrix `M` with real entries in `MachinePrecision`. I compute its eigenvectors and construct matrix `U`:                 ev = Eigenvectors[M];           U = Transpose @ ev;      `U` is supposed to be an orthogonal matrix and thus `Transpose[U].U == IdentityMatrix[ Length @ U]`.   _Mathematica_ gives the latter equality with the accuracy of `10^(-16)`:               Transpose[U].U - IdentityMatrix[ Length @ U]// Abs// Max == 8.8131 * 10^(-16).      Is it possible to make this difference smaller, let's say, order of `10^(-32)`? I need to get eigenvectors which are orthonormal with accuracy of order of `10(-32)` or higher.


Checking if a number is a perfect power

I wanted to know how would I use Mathematica in order to check if the number is a perfect power I saw the algorithm but couldn't grasp it enough to implement it, so can anybody help?


Infinite loop with While is very processor-intensive

This simple line of code:               While[True, Pause[1]]      uses 55% of one CPU core on my computer. Are there more efficient ways to construct simple infinite loops in Mathematica? _Edit_ I'm on OS X 10.9.1 using Mathematica 10.0. Further inspection: `While[True,]` uses 100% CPU; `While[True, x]` also uses 100% CPU; `Pause[10]` uses 55% CPU for the time it is waiting, so 10 seconds in this case.


Counting and extracting hit circles/triangles for randomly chosen points

Below, you see a triangle in which the incircle was inscribed. As we know, the center of this circle is the intersection of the angle bisectors. At this point, one could go further and find the points, where each of the angle bisectors intersect with the circle and create a tangent of the circle which will divide three new triangles from the big one. Each of the new triangles has again an incircle which can be created and cutting (from now on) only one triangle from each new one and repeating this process brings us to the picture: ![Right_Triangle_Incircles](http://i.stack.imgur.com/DytE7.png) First question: Is it possible create this figure in _Mathematica_? Unfortunately, I have no clue and cannot provide some code myself, but I have asked a similar question at TeX.SE and got some pretty nice answers. What I would like to do in the end is not only to create the figure; I want to _shoot_ random points at the figure and want to find out where the points hit the figure in a circle or not. I would be delighted to hear some ideas or if possible to collect sample code for my problem.


How to set up and minimize a large system of equations to resolve the individual components

I am trying to set up a system of 400*N equations to deconvolute spectral data for four different compounds. I monitored 400 different wavelengths in N solvents (3 solvents in this case). In order to do this, I want to try to minimize the following function: $A_{\lambda_i, N_i} - (\epsilon_{1 (\lambda_i, N_i)}C_1 + \epsilon_{2 (\lambda_i, N_i)}C_2 + \epsilon_{3 (\lambda_i, N_i)}C_3 + \epsilon_{4 (\lambda_i, N_i)}C_4 = 0 $ Here $A$ is the absorbance of the spectrum I want to deconvolute at specified wavelength ($\lambda$) in solvent ($N$).   $\epsilon$ is the molar extinction coefficient for each different compound that corresponds to the absorbance at the given wavelength and solvent. Then unknown quantities are $C_1$ to $C_4$ https://drive.google.com/folderview?id=0B5gGZ4-SD7-ZdHFveVY5b2J3OTQ&usp=sharing My data is organized as follows. Each row has 5 entries and I have 400 rows one (for each wavelength) [$A \; \epsilon_1 \; \epsilon_2 \; \epsilon_3 \; \epsilon_4$] Each solvent has a table organized just like this one. How do I used mathematica to set up this system of equations and get the error associated with the minimization? Also, the solution needs to be constrained such that C$_n$ is positive. Import the data (uploaded on google drive)               phosBB = Import["/home/marco/LatexDocs/analytical/uvvis/PHOS_BB.CSV"];     phosMR = Import["/home/marco/LatexDocs/analytical/uvvis/PHOS_MR.CSV"];     phosPT = Import["/home/marco/LatexDocs/analytical/uvvis/PHOS_PT.CSV"];     phosTB = Import["/home/marco/LatexDocs/analytical/uvvis/PHOS_TB.CSV"];     phosUI = Import["/home/marco/LatexDocs/analytical/uvvis/PHOS_UI.CSV"];      PreProcess data to get rid of headings:               phosBB = Delete[phosBB, 1];     phosMR = Delete[phosMR, 1];     phosPT = Delete[phosPT, 1];     phosTB = Delete[phosTB, 1];     phosUI = Delete[phosUI, 1];      Calculate $\epsilon$ from the known solutions (BB-TB):               \[Epsilon]PhosBB = phosBB[[All, 2]]/concPhosBB;     \[Epsilon]PhosMR = phosMR[[All, 2]]/concPhosMR;     \[Epsilon]PhosPT = phosPT[[All, 2]]/concPhosPT;     \[Epsilon]PhosTB = phosTB[[All, 2]]/concPhosTB;      Setup data table [$A_{unk} \; \epsilon_1 \; \epsilon_2 \; \epsilon_3 \; \epsilon_4$]               phosDataTable =        Transpose[{phosUI[[All, 1]], \[Epsilon]PhosBB, \[Epsilon]PhosMR, \[Epsilon]PhosPT, \[Epsilon]PhosTB}];


Replace a column in table with a list of numbers?

I have a Table of values e.g. {{x,y,z},{x,y,z},{x,y,z}…} How do I replace the the "z" column with a List of values?


Issues with $MachineEpsilon

I'm attempting to add `$MachineEpsilon` to numbers I am pulling from the domains of 3 interpolating functions. I pulled 3 numbers, and for one of these numbers adding `$MachineEpsilon` produces a number slightly larger than the first (as expected). For some reason for the second two numbers, adding `$MachineEpsilon` does nothing - the number stays the same. I noticed that there are more significant digits in the first number than the last two, which I suppose could have something to do with this, but how can I fix this so that adding `$MachineEpsilon` will create a higher number for the last two numbers? Below is the output that I got by adding `$MachineEpsilon` to my numbers (lim,lim1,lim2):                eps=$MachineEpsilon     InputForm[lim]          (*     1.7775896893621104 *)          InputForm[lim + eps]     (* 1.7775896893621106 *)          InputForm[lim1]     (* 4.925661999190314 *)          InputForm[lim1 + eps]     (* 4.925661999190314 *)          InputForm[lim2]     (* 8.10371456559119 *)          InputForm[lim2 + eps]     (* 8.10371456559119 *)      Additionally, this is how I'm pulling the numbers from the interpolating functions (leaving out some unneccessary code for simplicity):               dom = InterpolatingFunctionDomain[First[r /. g1]];     dom1 = InterpolatingFunctionDomain[First[r /. g2]];     dom2 = InterpolatingFunctionDomain[First[r /. g3]];     dom3 = InterpolatingFunctionDomain[First[r /. g4]];     {lim, b} = dom1[[1]];     {lim1, b1} = dom2[[1]];     {lim2, b2} = dom3[[1]];      Thanks for any help! I'm using the pulled numbers and their next closest in plot and have continued to get the pllp error message saying the two numbers are the same.


Log-Plots and PlotRange

Why does the `PlotRange` option in               list=Table[{x,Exp[Sqrt[x]]},{x,0,25}];     ListLogLogPlot[list,PlotRange->{0,10},Joined->True]      not work although there is no error-output? The same holds for `ListLogLogPlot`.


Speeding up ReplaceRepeated while truncating to desired order

I need to program in an algorithm that recursively makes algebraic replacements which leads to an utterly complicated algebraic function of $x$, but whose final result is only needed at fixed order in the Laurent series in $x$. I wish to use this fact to make the algorithm go faster. Here is sample problem that mimics the realistic problem: \begin{align}f_n(x) &= \sum_{j=1}^4\frac{1}{6+j x}n\left(\frac{1}{x}+j \,f_{n-1}(x)\right); \qquad f_0(x) = {\tt f[0]}\\\ F(x) &= \sum_{n=1}^6\frac{1}{2+n x}\left(\frac{n}{x}+f(n)\right) \end{align} The algorithm is to repeatedly insert the first equation into the second one until all instances of $f_n(x)$ turn into $f_0={\tt f[0]}$. All that is needed in the end is the Laurent expansion out to $\mathcal{O}(x^0)$ (just need the $1/x$ and constant terms). _nota bene: The sums are there only to lengthen the expression to make Mathematica work harder._ Here is a naive implementation (with the result on my machine):               (*Implementation 1*)     f[n_] /; n > 0 -> Sum[1/(6 + j x) n (1/x + j f[n - 1]), {j, 1, 4}];     Sum[1/(2 + n x) (n/x + f[n]), {n, 1, 6}] //. %;     Timing[Series[%, {x, 0, 0}]]      ![Result of implementation 1](http://i.stack.imgur.com/hRqaV.png) Performing the actual recursion in the second line is lightening fast. But the final step `Series` function is painfully slow (4.109 seconds), since the $x$ in the denominators forces _Mathematica_ to appeal to its analytical routines to expand things like $\frac{1}{1+x}\approx 1 -x$. Since all that I need is the first two terms of the Laurent series, I went ahead and, by hand, expanded the fractions $\frac{1}{6+jx}\approx(\frac{1}{6}-\frac{j x}{36})$ and $\frac{1}{2+nx}\approx(\frac{1}{2}-\frac{n x}{4})$, with the intention of partially freeing _Mathematica_ of painful analytics.               (*Implementation 2*)     f[n_] /; n > 0 -> Sum[(1/6 - (j x)/36) n (1/x + j f[n - 1]), {j, 1, 4}];     Sum[(1/2 - (n x)/4) (n/x + f[n]), {n, 1, 6}] //. %;     Timing[Series[%, {x, 0, 0}]]      ![enter image description here](http://i.stack.imgur.com/03tCw.png) This is 8 times faster; the more I save _Mathematica_ from doing analytic manipulations, the faster it goes. But I need it to go faster, yet. How can I carry out the alogorithm to minimize the extent _Mathematica_ has to do computationally costly analytic work? Here's my failed attempt: ask _Mathematica_ drop higher order terms at each stage in the recursion by adding an `O[x]` to the end of the line:               (*Implementation 3 [FAILURE]*)     f[n_] /; n > 0 -> Sum[(1/6 - (j x)/36) n (1/x + j f[n - 1]), {j, 1, 4}];     Timing[Sum[(1/2 - (n x)/4) (n/x + f[n]), {n, 1, 6}] + O[x] //. %]      ![enter image description here](http://i.stack.imgur.com/mYBD6.png) Very fast, but the wrong answer. It gets the wrong answer because it drops terms like `x*f[n]` as it thinks `f[n]` is order `O[x]^0` when in reality there is a `1/x` part. What can I do to speed this up?


Save icon in toolbar in v9

In previous versions of MMA there was a 'Save" icon in the toolbar when you do the "Show Toolbar" from the "Window" menu. This is not present in v9. Anybody know how to get it back?


Rapidly binning 3D data

I have a set of data (about 20 million datapoints for my real data) of the form `{x, y, z, m}`. There are 3 spatial coordinates `x`, `y` and `z` and a fourth value, the mass (`m`) of the element at that point. I want to bin the data onto a integer spaced 3D grid. And then bin the masses into a series of specific ranges. I want the number of masses that fall into each mass range for each point on the grid. I guess, for `n` ranges I will need `n` 3D arrays or alternatively a 3D array where each point has a list of `n` values. Let's start with some random data               coords = RandomReal[{-100, 100}, {10^5, 3}]; (*these can be negative*)     masses = RandomReal[400, 10^5]; (*these can't be negative*)      and some random ranges to bin the masses, we'll make 50 as this is about how many I have in my real data:               ranges = Partition[Union[Round[RandomReal[400, 100], 0.001]], 2];      Based on this related question: http://stackoverflow.com/questions/8178714/mathematica-fast-2d-binning- algorithm. I started by rounding the coordinates, I want to bin onto unit bins so I simply used `Floor` on the coordinates.               indices = Floor[coords];      and in my case the masses have more precision than the mass range specifications so lets round those now too.               roundedmass = Round[masses, 0.001];      Now based on the related question I used `GatherBy` to collect like coordinates into lists.               gathered = GatherBy[Transpose[{indices, roundedmass}], First];      However, I'm stuck as to how to quickly bin the masses in each of the gathered coordinate-bins into the various mass ranges. In the end I guess I will have 50 3D arrays where each coordinate-bin has a value corresponding to the number of masses in the specified mass-range. 50 mass ranges = 50 3D arrays (probably sparse as there will be lots of empty space), or alternatively a 3D array where each point has a list of 50 values. I've tried to use `BinCounts` but this also bins in between the mass ranges so I had to drop ever other bin that was returned, seems wasteful...:               fbinmasses = BinCounts[#, {Flatten@ranges}][[;; ;; 2]] &     binnedmass = ParallelMap[fbinmasses, gathered[[All, All, 2]]];      combinedoutput = Transpose[{gathered[[All, 1, 1]], binnedmass}];     sortedoutput = Sort[combinedoutput, OrderedQ[{#1[[1]], #2[[1]]}] &];      Now, I would need to make a sparse array, maybe like this (going to have issues with negative inidices...? And it seems like you can't store a list in a sparse array.               output = SparseArray[gathered[[All, 1, 1]] -> binnedmass]


What is an alternative to using backticks in separating namespaces from function names?

What is an alternative to the backtick (```) in separating the namespace from the function name? Can the function be called without using this symbol? I think in early versions of Mathematica one could use `::` but it does not seem to work now.


Exporting notebook to HTML, using conversion rules

The idea is to export the whole notebook to HTML with all the math equations in latex form. In this way we can add the mathjax script and it will take care of the math. Suppose we have the following in a notebook: > This is an equation: $f(x) = x^2$. We let $x \in [0,1]$ for this example. The following is the expression that generates the above.               Cell[TextData[{      "This is an equation: ",      Cell[BoxData[       FormBox[        RowBox[{         RowBox[{"f", "(", "x", ")"}], " ", "=", " ",          SuperscriptBox["x", "2"]}], TraditionalForm]],       FormatType->"TraditionalForm"],      ". We let ",      Cell[BoxData[       FormBox[        RowBox[{"x", " ", "\[Element]", " ",          RowBox[{"[",           RowBox[{"0", ",", "1"}], "]"}]}], TraditionalForm]],       FormatType->"TraditionalForm"],      " for this example."     }], "Text"]      If you look here you will find an example of how to use the conversion rules. Unfortunately, I haven't been very lucky with it, as you can see in one of my previous posts. In any case, here is an attempt:               ExportString[      Cell[TextData[{"This is an equation: ",          Cell[BoxData[           FormBox[RowBox[{RowBox[{"f", "(", "x", ")"}], " ", "=", " ",               SuperscriptBox["x", "2"]}], TraditionalForm]],           FormatType -> "TraditionalForm"], ". We let ",          Cell[BoxData[           FormBox[RowBox[{"x", " ", "\[Element]", " ",               RowBox[{"[", RowBox[{"0", ",", "1"}], "]"}]}],             TraditionalForm]], FormatType -> "TraditionalForm"],          " for this example."}], "Text"       ],      "HTML", "ConversionRules" -> {"TraditionalForm" -> {"$",               Convert`TeX`BoxesToTeX[#] &, "$"}}]      The result is the following html code:               <?xml version="1.0" encoding="UTF-8"?>     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN"             "HTMLFiles/xhtml-math11-f.dtd">                               <title>       Untitled      </title>      <link href="HTMLFiles/m0001756441.css" rel="stylesheet" \     type="text/css" />
      This is an equation: . We let \     x ∈ [0,1] for this example.

                    Created with Wolfram Mathematica 8.0
                     If we try to export to TeX I'm not so lucky either, instead of the dollar signs Mathematica just ignores it and it gives me:               \documentclass{article}     \usepackage{amsmath, amssymb, graphics, setspace}          \newcommand{\mathsym}[1]{{}}     \newcommand{\unicode}[1]{{}}          \newcounter{mathematicapage}     \begin{document}          This is an equation: \(f(x) = x^2\). We let \(x \in  [0,1]\) for this \     example.          \end{document}      The question is: How do we export a notebook to HTML and TeX so that the math is wrapped around the dollar signs? Any other tips or comments are welcomed. # EDIT: This conversion rule for HTML might be more useful:               "Text" -> {"
\n",       If[MatchQ[#, _FormBox],          "$" <> Convert`TeX`BoxesToTeX[#[[1]]] <> "$", #] &, "\n
"}      Using that we obtain:
     This is an equation: $f(x) = x^2$. We let     $x \in  [0,1]$ for this example.
      Question now is... how do we get rid of the span tag?


Where do I get the mdefs.h file?

I want to generate some C code, and the reference here says that Mathematica comes with a `mdefs.h` file, but I cannot find it. Is there a place where I can download it?