Making a flag with six vertical stripes

A flag is to be made with six vertical stripes by using colours yellow, blue, green and red in such a way that no two adjacent stripes should have the same colour. In how many ways is this possible? How could I compute this with _Mathematica_?


Cases do not return all expected result

I have the following line code:               Cases[g[h, r, t, b, m], x_[__, y_, __] -> y, {0, -1}]      I am expecting the results to be `{r,t,b}` because they match the pattern, but I am only getting `{r}.` Can anyone suggest why I am getting only `{r}?`


Shortcut for Range[]?

I use `Range` a lot. Is there any syntactic shortcut for it, or do you always have to spell it out?


How to impose control over vertex-to-vertex Graph edges?

I’m working on a Markov Chain and hope there is a way to impose control over how Mathematica places edges to connect vertices in a Graph. My Markov Chain currently consists of 4 vertices with 2 of the edges crossing and is shown below. The edge coming out of Vertex 4 labeled “m” and connecting to Vertex 1 is what I’d like to change. Rather than being orientated as a vertical straight line, is it possible to direct this edge from Vertex 4 to the right in an arc so that the arc passes to the right of the “k” and then connects to Vertex 1 ? This will remove the crossing, be easier for others to read and be more architecturally correct. ![enter image description here](http://i.stack.imgur.com/XWS7X.jpg) My code is below. Thanks for any help.               softwareapplication =      DiscreteMarkovProcess[     1, {{0, b, c, 0}, {e, f, g, h}, {i, 0, k, l}, {m, n, o, 0}}];          transitionmatrix =      MarkovProcessProperties[softwareapplication, "TransitionMatrix"] //      MatrixForm          vertexlabels = {1 -> Placed["1", Center], 2 -> Placed["2", Center],      3 -> Placed["3", Center], 4 -> Placed["4", Center]};          edgelabels = {     1 \[DirectedEdge] 2 -> transitionmatrix[[1, 1, 2]],     1 \[DirectedEdge] 3 -> transitionmatrix[[1, 1, 3]],     2 \[DirectedEdge] 1 -> transitionmatrix[[1, 2, 1]],     2 \[DirectedEdge] 2 -> transitionmatrix[[1, 2, 2]],     2 \[DirectedEdge] 3 -> Placed[transitionmatrix[[1, 2, 3]], .25],     2 \[DirectedEdge] 4 -> transitionmatrix[[1, 2, 4]],     3 \[DirectedEdge] 1 -> transitionmatrix[[1, 3, 1]],     3 \[DirectedEdge] 3 -> transitionmatrix[[1, 3, 3]],     3 \[DirectedEdge] 4 -> transitionmatrix[[1, 3, 4]],     4 \[DirectedEdge] 1 -> Placed[transitionmatrix[[1, 4, 1]], .25],     4 \[DirectedEdge] 2 -> transitionmatrix[[1, 4, 2]],     4 \[DirectedEdge] 3 -> transitionmatrix[[1, 4, 3]]     };          Graph[softwareapplication, VertexLabels -> vertexlabels,      EdgeLabels -> edgelabels, VertexSize -> Small, ImageSize -> Medium,      VertexCoordinates -> {{0, 2}, {-1, 1}, {1, 1}, {0, 0}}]


Hide input with multiple output cells

I want to hide my input, but not with "close cell". i also want to have fast access to the input cell. i found Mr.Wizard's AutoCollapse function, but it doesn't work with two or more Print-functions in the input. Also double-clicking the output cell is not the solution, because i have more output cells. merging them is just a temporary solution because i get new output cells with the next calculation of the input. here's a code example:               Print["Rechung:"]     l01 = -350;     Print[l01, "€"]     Print["---> bezahlt"]     Print["Trinkgeld:"]     l02 = -150;     Print[l02, "€"]     Print["---> bezahlt"]     Print["Total:"]     total = 0;     Print[total, "€"]      is there no easy way?


Does one need to be careful about loading multiple (many) contexts or packages in the same session?

I have a number of large pieces of precomputed data which I am considering putting into individual packages in order to load them (via `DeclarePackage`) and unload them (via Leonid Shifrin's `PackageManipulations` package) as needed. For what it's worth, I have some functions which will be defined on some objects using `UpValues`, and it is the `UpValues` which will be stored in the packages, one for each object. I am wondering if performance or other issues occur, either in the kernel or the front end, when any of the following becomes large (hundreds or thousands): 1) `$Packages`, 2) The number of defined contexts, 3) `$ContextPath`. Is it okay to create new contexts more-or-less at one's convenience, or does one need to be conservative, and if so, how? Some other questions in which this situation might occur are here, here, and here (in Leonid Shifrin's answer.


How can I get Mathematica to include size information in exported SVG?

When I use `Export` to export graphics in SVG format, the exported file contains no `width` `height` or `viewBox` attributes, so that the resulting files don't "scale" at all, which is the whole point. Is there a way to get `Export` to include size information in exported SVGs?


For any symbol, how can I get the full context-qualified name of the symbol as a string?

I'd like to have a function, whether built-in or not, that when given a symbol, whether bound to a value or not, returns a string giving the context and name of the symbol. Example: `f[a]` returns `"Global`a"` Example: `f[Developer`$MaxMachineInteger]` returns `"Developer`$MaxMachineInteger"`


How to adjust the parameters on a Nyquist Plot?

In order to see some details on a Nyquist Diagram I have used the function NyquistPlot that comes with Mathematica v8 and v9.               NyquistPlot[       TransferFunctionModel[(30000*(s + 3)^2)/(s*(s + 0.5)^2*(s + 20)^2), s],        Automatic,        PlotPoints -> 1000, ImageSize -> Medium]      ![Mathematica graphics](http://i.stack.imgur.com/4Mgr9.png) The first thing one can see is that there is a discontinuity (not in the actual diagram). Note that the dashed lines are departing from the wrong position of the branches. I have tried to adjust the range of frequencies so as to see "more" of the diagram but to no avail. One info: there are three crossings on the negative real axis (x-axis): -3.7, -56.5, -1074. I wonder whether there is a way to see them all. Any ideas?


Different expressions for an integral if I split the region of integration

Consider the assumptions               $Assumptions = 1 > v > 0 && y1 \[Element] Reals && y2 \[Element] Reals &&   k > 0 && 1 > t1 > 0       and define               y[t_, y1_, y2_, t1_] =            Piecewise[{{y1, 0 <= t <= t1}, {y2, t1 < t <= 1}}, 0];      and two different formulations of the same integral,               Assuming[t1 + v < 1,        Integrate[        Assuming[{0 <= t <= 1, t1 + v < 1},          Integrate[(1 +              Exp[-2 Integrate[y[s, y1, y2, t1]^2, {s, t - u - v, t - v}]])/           2, {u, 0, t}]], {t, v, t1 + v}]] // Simplify      and               Assuming[t1 + v < 1,         Integrate[         Assuming[{0 <= t <= 1, t1 + v < 1},           Integrate[(1 +               Exp[-2 Integrate[                 y[s, y1, y2, t1]^2, {s, t - u - v, t - v}]])/2, {u, 0,             t - v}]], {t, v, t1 + v}]] +        Assuming[t1 + v < 1,         Integrate[         Assuming[{0 <= t <= 1, t1 + v < 1},           Integrate[(1 +               Exp[-2 Integrate[                 y[s, y1, y2, t1]^2, {s, t - u - v, t - v}]])/2, {u, t - v,             t}]], {t, v, t1 + v}]] // Simplify      The two formulations differ for the region of integration, that in the second case is splitted in two parts, because the interval in u between 0 and t is splitted in [0,t-v]+[t-v,t],and then the integrals summed. Why Mathematica give me back two different expressions?


Have the Random functions changed?

I re-ran a program I wrote for Mathematica v8, now on v9, and it appears to generate different `RandomInteger` numbers, even though I use the same `SeedRandom` at the beginning.   Have Random functions changed in v9?


How to compute the Multifractal Spectrum of a Financial Series with WTMM

I would like to know if someone knows how to compute the Multifractal Spectrum of a Financial Time Series (Currency) througth the Wavelet Transformation Modulus Maxima (WTMM). I would highly appreciate any hint in order to calculate `Dq`, `Tau(q)`, `alpha`, `f(alpha)`. I am pasting here the code I am using to get the Multifractal Spectrum (Ref: Gerd Baumann - Mathematica for Theoretical Physics (Mathematica 6.0), Springer Second Edition (2005), page 892) Comments: The following code helps to get the MultiFractal Spectrum, with _Mathematica_ 6.0. I have updated the function `ListPlot` to `ListLinePlot` and `PlotJoined` to `Joined` as suggested in the Help of _Mathematica_ 8.0. The code seems to work when the input are the probabilities `pi ={p1,p2,....pn}` and when the values of each subset of the probability space one is seeking to characterize. The code doesn't work 100% and I still don't know why (I am new to _Mathematica_ ). The thing is, that the package provided by Mr. Baumann works when you give the input of the probabilities - yet I need that such process should be automated by the WTMM so I can see (analyze) the Whole Multifractal Spectrum. ----------------- ## ----------------------------               BeginPackage["MultiFractal`"];     Clear[Dq, Tau, Alpha, MultiFractal];     MultiFractal::usage = "MultiFractal[p_List,r_List] calculates the              multifractal spectrum D_q for a model based on the probabilities             p and the scaling factors r. This function plots five functions             Tau(q), D_q(q), Alpha(q), f(q) and f(Alpha).";     Begin["Private`"];          (*---calculate the multifractal dimensions---*)     Dq[p_List, r_List] := Block[{l1, l2, listrg = {}},        (*---length of the lists---*)        l1 = Length[p]; l2 = Length[r];        If[l1 == l2,         (*---variation of q and determination of D_q---*)         Do[gl1 = Sum[p[[j]]^q r[[j]]^((q - 1) Dfractal), {j, 1, l1}] - 1;          result = FindRoot[gl1 == 0, {Dfractal, -3, 3}];          result = -Dfractal /. result;          (*---collect the result in a list----*)          AppendTo[listrg, {q, result}], {q, -10, 10, .101}]         ,         Print[" "];         Print["  Lengths of lists are different!"];         listrg = {}];        listrg];          (*----calculate Tau---*)     Tau[result_list] := Block[{l1, listtau = {}},        (*----lengths of the lists---*)        l1 = Length[result];        (*---calcultate Tau---*)        Do[AppendTo[          listtau, {result[[k, 1]],            result[[k, 2]] (1 - result[[k, 1]])}], {k, 1, l1}];        listtau];          (*---Legendre transform---*)     Alpha[result_List] :=        Block[{l1, dq, listalpha = {}, listf = {}, listleg = {}, mlist = {},          pl1, pl2},        (*---lengths of the lists---*)        l1 = Length[result];        (*---determine the differential dq---*)        dq = (result[[2, 1]] - result[[1, 1]]) 2;        (*---calculate Alpha by numerical differentiation---*)        Do[AppendTo[          listalpha, {result[[k,              1]], (result[[k + 1, 2]] - result[[k - 1, 2]])/dq}], {k, 2,           l1 - 1}];        l1 = Length[listalpha];        (*---calculate f and collect the result in a list---*)        Do[AppendTo[          listf, {result[[k,              1]], -(result[[k, 1]] listalpha[[k, 2]] - result[[k, 2]])}];         listalpha[[k, 2]] = -listalpha[[k, 2]], {k, 1, 12}];        (*---list of the Legendre transforms---*)        Do[AppendTo[listleg, {listalpha[[k, 2]], listf[[k, 2]]}];          AppendTo[mlist, listf[[k, 2]]], {k, 1, l2}];        (*---plot f and alpha versus q---*)        pl1 = ListLinePlot[listalpha, Joined -> {True, False},           AxesLabel -> {"q", "\[Alpha]"}, Prolog -> Thickness[0.001]];        pl2 = ListLinePlot[listf, Joined -> {True, False},           AxesLabel -> {"q", "f"}, Prolog -> Thickness[0.001]];        Show[{pl1, pl2}, AxesLabel -> {"q", "\[Alpha],f"}];        (*---plot the Legendre transform f versus alpha---*)        ListLinePlot[listleg, AxesLabel -> {"\[Alpha]", "f"}];        (*---print the maximum of f=D_ 0---*)        maxi = Max[mlist];        Print[" "];        Print["   D_0 = ", maxi]];          (*---calcultate the multifractal properties---*)     MultiFractal[p_List, r_List] := Block[{listDq, listTau},        (*---determine D_q---*)        listDq = Dq[p, r];        ListLinePlot[listDq, Joined -> {True, False},            AxesLabel -> {"q", "Dq"}, Prolog -> Thickness[0.001]]          (*---calculate Tau---*)           listTau = Tau[listDq];        ListLinePlot[listTau, Joined -> {True, False},           AxesLabel -> {"q", "\[Tau]"}, Prolog -> Thickness[0.001]]         (*---determine the Hoelder exponent---*)          Alpha[listTau]];          End[];          EndPackage[];


Attaching WolframAlpha data

I have used WolframAlpha since it was launched (now a pro member) but am new to Mathematica 8. Is there a way to automatically add data from WA to a Mathematica dataset? For example, what if I have data on annual sales and I want to add the USA's GDP in the given year as the third column. I have used the WolframAlpha[] function but am not sure how to integrate it into my data. I'd want to add a "GDP" column to this data:               In[4]:= sales = Import["C:\\Users\\Andrew\\Desktop\\DemoData.xlsx"]          Out[4]= {{{"Year", "Sales"}, {2000., 105704.}, {2001.,      120042.}, {2002., 118973.}, {2003., 126539.}, {2004.,      105582.}, {2005., 126510.}, {2006., 101745.}, {2007.,      105821.}, {2008., 127313.}, {2009., 100908.}, {2010.,      115692.}, {2011., 116188.}}}      This isn't the best example, but this kind of thing would make my grad school life markedly easier. No more downloading, cleaning, and merging independent variable sets from random sources!


Automate mouse clicks with Mathematica

I need to automate mouse clicks with _Mathematica_. However, a similiar question was closed on this forum, without any answer. Consider the following steps:                Dynamic[MousePosition[]]      In this first step I dynamically show the mouse position.                DynamicModule[{col = Green}, EventHandler[ Style["text", FontColor ->       Dynamic[col]], {"MouseClicked" :> (col = col /. {Red -> Green, Green -> Red})}]]      In this second step I create a "clickable" text: when you click it, it changes its color between green and red. My objective here is twofold: **1)** automatically move the cursor position - this has already been answered here. So, following the original answer I can write               Needs["JLink`"];     ReinstallJava[];     robotclass = JavaNew["java.awt.Robot"];     robotclass@mouseMove[90, 196];      **2)** automatically click on the clickable text (and, of course, I want to see its color changing). Here is the code I'm trying to use:               robotclass@mousePress[InputEvent.BUTTON1_MASK];     robotclass@mouseRelease[InputEvent.BUTTON1_MASK];      Although I believe I'm using the correct functions (which belong to the Java Robot Class), I'm getting the following error message: > Java::argx1: Method named mouseRelease defined in class java.awt.Robot was > called with an incorrect number or type of arguments. The argument was > InputEvent.BUTTON1_MASK. Can anybody give me a hint to solve this problem?


3D scatter plot from a txt file

I have a txt file with space-delimited x, y, z coordinates of several points. The points are organized into groups of unequal size; the groups are delimited by skipping a line, like this:               2.3 3.4 5.5     2.4 3.3 5.6     2.5 3.5 5.6          1.2 4.3 3.3     0.7 4.0 3.5          -1.2 1.3 -0.7     -1.1 1.7 -0.5      I can't find a way to have _Mathematica_ just import these then plot the points! I've tried searching a little bit but didn't find a similar question. When plotting, it's not important to distinguish from which group each point came from. For example, I don't need different colours for each group or anything like that.


How to import a Microsoft Word document into Mathematica?

I have a _Microsoft Word_ document in DOCX format. I need to import it into _Mathematica_ as a `String` preserving all formatting (font, size, bold/italic style, colors, etc), tables and embedded images with highest possible fidelity ( _Mathematica_ strings support formatting and arbitrary embedded expressions including images). All text should remain editable, so it should not be converted to an image. Is there a way to do this? I can convert the document to RTF, PDF, XPS, MHT or ODT format before importing, if it helps.


How to catch complete error message information

If I evaluate this expression:               Module[{}, 1/0;0^0]; msg = $MessageList      I get:               "Power::infy: Infinite expression 1/0 encountered. >>"     "Power::indet: Indeterminate expression 0^0 encountered. >>"     {Power::infy,mrtError::function}      How can I collect the complete error messages in `msg`, instead of just the first part? Something for `msg` like:               {"Power::infy: Infinite expression 1/0 encountered. >>"     ,"Power::indet: Indeterminate expression 0^0 encountered. >>"}      Some clue?


Add new JDBC Driver to connect MM to SQL database

I cannot open a SQLConnection to a SQL vectorwise database and I assume the JDBC driver is the problem. A JAR file was provided to me - the only info additionally provided to me was the java class: **com.ingres.jdbc.IngresDriver** What would I have to do to add it to the JDBCDrivers that Mathematica can use? Hope this is sufficient information - please let me know, if more information is required. Thanks and regards Patrick


Alternate controls in manipulate

Is there a way to have two controls that govern a single variable in a Manipulate? Specifically, I am using a Locator to select an {x,y} coordinate, but I would also like the user to be able to directly specify x and y, in InputFields. Similar questions have been asked, but not with Manipulate and not with a 2D variable.


How to change the color of a button while it is pressed

I want to change the color of a button while it is pressed, pause for a short time and then change the color back to the original color. I can't seem to figure out how to do this (tried various forms of `DynamicModule` and `Dynamic`, but no luck). This is what I tried so far:               Manipulate[       DynamicModule[{simulationFlag, bgnd = Automatic},         simulationFlag = newSimulation;         Pause[0.5];         Dynamic[bgnd = Automatic; {simulationFlag}]],       {{newSimulation, 0.02}, ControlType -> None},       Row[{         Button["New Simulation", Dynamic[newSimulation = newSimulation+1; {bgnd=Yellow}],           Background -> Dynamic[bgnd]]}]     ]


A question about using Reduce

Can someone help decipher what is the meaning of this computation that _Mathematica_ has done?               Assuming[Re[x] >= 0 && a ∈ Reals,       Reduce [1 / ((x Tanh[π x]) / (x^2 +  a^2)) == 0, x, Complexes]]          (*       (C[1] ∈ Integers && x != 0 && (x == (-((I π)/2) + 2 I π C[1])/π ||           x == ((I π)/2 + 2 I π C[1])/π)) || (Sin[a π] != 0 && a != 0 && (x == -I a || x == I a))     *)      * * * My understanding is that the $\frac{x\;tanh (\pi\,x) } {x^2 + a^2 }$ blows up where $tanh(\pi\,x)= \infty $ and where $x^2 +a^2 = 0$. And these happen respectively at $x = i(\mathbb{Z} + 0.5)$ and $x = \pm i \vert a \vert$. But why is _Mathematica_ detecting a totally different set of imaginary zeroes for the reciprocal of the function than the first set of poles that I can see in the above?


How to install and configure Intel C++ Compiler for Mathematica correctly?

I wish to try the trial version of the latest Intel C++ Compiler for Windows with _Mathematica_. I have downloaded the current version of Intel® C++ Composer XE 2011 for Windows and installed only the "Intel C++ Compiler" component from this package. But _Mathematica_ does not recognize it:               In[1]:= Needs["CCompilerDriver`"]     CCompilers[]          Out[2]= {}      How to configure _Mathematica_ to use the Intel C++ Compiler?


How to animate 3-D figure using sequence of data

I have four points in 3-D, I want to join the points with a line. The points move with time. So I want to animate the jointed Point in three dimensions. I try to use `ListAnimate` and `Graphics` function. But I failed. For example: The initial point positions are `{0,0,0},{1,0,0},{2,0,0},{3,0,0}`. Then they move with time. I store the position of the four points with table. But I could not join the points in 3-D. And also failed to animate them. I used the `Manipulate` like this:                Manipulate[      Graphics3D[{Thick, Line[gan],         VertexColors -> {Red, Green}}], {{number, 1}, 3, 1}]      with:               gan = {{cx1[[number]], cy1[[number]], cz1[[number]]}, {cx2[[number]],          cy2[[number]], cz2[[number]]}, {cx3[[number]], cy3[[number]],          cz3[[number]]}, {cx4[[number]], cy4[[number]], cz4[[number]]}};     cx1={{1,2,2,2,2,3,3,3,4,4,4}}     cx2={{1,2,2,2,2,3,3,3,4,4,4}}     cx3={{1,2,2,2,2,3,3,3,4,4,4}}     cx4={{1,2,2,2,2,3,3,3,4,4,4}}     cy1={{1,2,2,2,2,3,3,3,4,4,4}}     cy2={{1,2,2,2,2,3,3,3,4,4,4}}     cy3={{1,2,2,2,2,3,3,3,4,4,4}}     cy4={{1,2,2,2,2,3,3,3,4,4,4}}     cz1={{1,2,2,2,2,3,3,3,4,4,4}}     cz2={{1,2,2,2,2,3,3,3,4,4,4}}     cz3={{1,2,2,2,2,3,3,3,4,4,4}}     cz4={{1,2,2,2,2,3,3,3,4,4,4}}      but it gives an error.


Two graphs in the same plot

I have the following plots for two graphs:               RegionPlot3D[x^2 + y^2 + 1 <= z <= 4, {x, -2, 2}, {y, -2, 2}, {z, 0, 5}]           ContourPlot3D[x^2 + y^2 + z^2 == 25, {x, -5, 5}, {y, -5, 5}, {z, -5, 5}]      How can i do to see this two graphs together in the same plot?


More stream lines in a ListStreamPlot

To provide a bit of background, I have a set of wind flow data from a two- dimensional computational fluid dynamics simulation in an urban environment. The data that are returned from the simulation are two matrices, u and v, that highlight the wind flow velocity in the horizontal and vertical directions of the plane: ![A false-color image of the u matrix: the wind flow in the horizontal direction.](http://i.stack.imgur.com/Sasco.png) ![A false-color image of the v matrix: the wind flow in the vertical direction.](http://i.stack.imgur.com/TNxo7.png) To briefly go over the above images, the first is a false-color plot of the u matrix. In this case, warm colors correspond to regions of high wind flow velocities in the horizontal direction (going from right to left) while cooler colors correspond to either regions with low wind flow velocities or those velocities going in the opposite direction. The light blue polygons in the image are the buildings, which have no horizontal wind flow velocity. The second image is a false-color plot of the v matrix. In a similar fashion as before, warm colors correspond to regions of high wind flow velocities in the vertical direction (going from top to bottom) while cooler colors correspond to either regions with low wind flow velocities or those velocities going in the opposite direction. The yellow-green polygons in the image are the buildings, which have no vertical wind flow velocity. As I have done in the past for my computational fluid dynamics plots, I combined both of these matrices into a form that could be understood by Mathemtica as a ListStreamPlot. That is, for each spatial location in my u and v matrix, I pass out an array of values: `{{{x_location,y_location},{u_value,v_value}},...}`. For this particular simulation, I only considered rows of u and v that were sandwiched between the buildings; a copy of the data contained within a Mathematica notebook can be obtained from here. When I went to go and make a ListStreamPlot,               ListStreamPlot[data, AspectRatio -> 0.5, StreamPoints -> Fine, PerformanceGoal -> "Quality", StreamColorFunction -> "Rainbow"]      however, I ended up with far fewer stream lines than I have been accustomed to seeing: ![A streamline plot of the wind flow data](http://i.stack.imgur.com/fR5Iw.png) Consequently, my question is this: how can I ensure that Mathematica includes more streamlines in the plot? (It is apparent, from the above images of u and v, that there should be more streamlines that could be generated.) Moreover, I would like to ensure that the arrows on the ListStreamPlot are included in the final visualization along with the chosen color scheme; the latter of these desires seems to be ignored in my ListStreamPlot, which leads me to believe that there might need to be some post-processing done to the data. Also, as a final note, I have already looked at the discussion here and the highest rated response from Jens has not worked in the context of my data.


How to assign special colors to the output of DensityPlot?

I have created the following function for plotting               plotDynamical[iterMethod_, points_] :=       DensityPlot[       iterAlgorithm[iterMethod], {t, xxMin, xxMax}, {s, yyMin,yyMax},        PlotRange -> {1,4}, ColorFunction -> {Orange, Blue, Black, Green},        PlotPoints -> points]      The possible results of " `iterAlgorithm[iterMethod]` " are 1 , 2, 3 or 4. I would like to assigning colours to numbers like so: Orange to 1,Blue to 2,Black to 3 and Green to 4. How can I do this? complete my Algorithm is:               F = Compile[{{t, _Real}, {s, _Real}}, {t^2 + s^2 - 4, -Exp[t] + s -           1}];     dF = Compile[{{t, _Real}, {s, _Real}}, {{2 t, 2 s}, {-E^t, 1}}];     invdF = Compile[{{t, _Real}, {s, _Real}}, {{1/(          2 E^t s + 2 t), -((2 s)/(2 E^t s + 2 t))}, {E^t/(          2 E^t s + 2 t), (2 t)/(2 E^t s + 2 t)}}];          rootF[1] = {-1.59832066552612835, 1.202235854627582} ;     rootF[2] = {0, 2} ;               rootPosition =       Compile[{{t, _Real}, {s, _Real}},        Which[Norm[{t, s} - rootF[1]] < 10.0^(-10), 3,        Norm[{t, s} - rootF[2]] < 10.0^(-10), 2, True,         1], {{rootF[_, _], _Real, _Real}}];          iterPsM10 = Compile[{{t, _Real}, {s, _Real}},       Block[{v = F[t, s], w = dF[t, s], u = invdF[t, s], x, y, z, dFz, Q,          uu, vv, Fu, vu, invdFvu},        x = {t, s};        y = x - (1/2 ) u.v;        z = 1/3 (4 y - x);        dFz = dF @@ ({z[[1]], z[[2]]});        Q = Inverse[w - 3 dFz];        uu = y + Q.v;        Fu = F @@ ({uu[[1]], uu[[2]]});        vv = uu + 2 Q.Fu;        vu = 1/2 (vv + uu);        invdFvu = invdF @@ ({vu[[1]], vu[[2]]});        uu - invdFvu.Fu]];          iterAlgorithm[iterMethod_, lim_] :=       Block[{ct, r}, ct = 0; r = rootPosition[t, s];       While[(r == 1) && (ct < lim), ++ct; {t, s} = iterMethod[t, s];         r = rootPosition[t, s]];       If[Head[r] == Which, r = 0];(*"Which" unevaluated*)Return[r]];          limIterations = 1000;     xxMin = -5; xxMax = 5; yyMin = -5; yyMax = 5;          plotDynamical[iterMethod_, points_] :=       DensityPlot[iterAlgorithm[iterMethod, limIterations],       {t, xxMin, xxMax}, {s, yyMin, yyMax}, PlotRange -> {0, 3},        ColorFunction -> {Green, Black, Orange, Blue},       PlotPoints -> points,        Epilog -> {White, PointSize[.02], Point[rootF[1]], Point[rootF[2]]}];               plotDynamical[iterPsM10, 56]


Some windows go off display

(I'm navigated from stackoverflow.com where I asked almost the same question) When I want to use additional windows, let's say for example "Basic Math Input", I feel reluctant to find visually where they are in the display. So I tend to "re-open" them by clicking "Palette" -> their name. However, when I do so, the window rearranges its position and goes up too high so that its bar (and often even some region of it that contains function panes) doesn't appear like this figure. !["Basic Math Input" windows lies left.](http://i.stack.imgur.com/bh8ll.jpg) "Basic Math Input" windows lies left. With this, I have no way to move this window. Luckily all function panes are shown so it still provides all functionality but like I said earlier some panes hide often. Tedious workaround on Mac is to arrange the displays (I'm using multiple displays) whatever. Then window's bar appears like this: ![After arranging displays' position, the bar of the window appears.](http://i.stack.imgur.com/CeWs1.jpg) Is there any easier way to resolve this? I've seen this happens to many other additional windows that are available in "Palette" section. ( **Environment** ) Mac OSX 10.7, Mathematica 8.0.4 Student Edition I've tested Ubuntu linux 11.10 with 2 displays, and it doesn't give the same issue.


bar and hat only apply to certain letters

(I'm navigated from stackoverflow.com where I asked almost the same question) I'm a beginner in `Mathematica`. Like shown in the image below, I'm trying to put hat and bar to some letters in a statement (I basically want to write vector notation) but only some letters can have them. What's wrong with how I do? ![enter image description here](http://i.stack.imgur.com/ehy3H.jpg) In the stackoverflow.com page I cited above, someone suggested functions `OverHat/OverBar`. These could do the similar work when I only want a letter in a line. But as I described, I want to write a `statement`, which consists of left-hand & right-hand sides, where those functions might not work as it seems. If you could provide online resource that covers these syntax, that would be more appreciable. Thank you. ( **Environment** ) { Mac OSX 10.7, Ubuntu 11.10, Ubuntu 10.10}, Mathematica 8.0.4 Student Edition


How to create Line Chart with real third coordinates?

I would like to generate something like 3D Line Chart in Excel. Like the following figure ![enter image description here](http://i.stack.imgur.com/MR5GG.png) but including third coordinates. **Example** I have a set of 2D data combied with 1D spatial data.               dxy = {{{0, 5.5`, 71.53`}, {0, 7.5`, 42.25`}, {0, 11.5`, 15.85`}, {0,           15.5`, 20.33`}, {0, 18.`, 43.555200000000006`}, {0,           22.833333333333332`, 24.47`}}, {{10.`, 5.5`, 48.5`}, {10.`, 7.5`,           40.44`}, {10.`, 11.5`, 14.69`}, {10.`, 15.5`, 14.65`}, {10.`,           18.`, 42.9104`}, {10.`, 22.833333333333332`, 24.16`}}, {{425.`,           5.5`, 44.46`}, {425.`, 7.5`, 83.82`}, {425.`, 11.5`,           21.88`}, {425.`, 15.5`, 71.99`}, {425.`, 18.`, 63.65`}, {425.`,           22.833333333333332`, 45.32`}}, {{650, 5.5`, 64.52`}, {650, 7.5`,           65.36`}, {650, 11.5`, 20.0512`}, {650, 15.5`, 66.8`}, {650, 18.`,           38.6984`}, {650, 22.833333333333332`, 30.3`}}, {{700, 5.5`,           105.49`}, {700, 7.5`, 118.6`}, {700, 11.5`, 17.1288`}, {700,           15.5`, 43.39`}, {700, 18.`, 29.276`}, {700, 22.833333333333332`,           23.18`}}, {{1300, 5.5`, 35.98`}, {1300, 7.5`,           59.976800000000004`}, {1300, 11.5`, 35.2768`}, {1300, 15.5`,           45.09`}, {1300, 18.`, 7.872800000000001`}, {1300,           22.833333333333332`, 7.86`}}};          ListPointPlot3D[dxy, Filling -> Bottom,       AxesLabel -> {"Distance", "Time", "Value"},       LabelStyle -> Directive[Bold]]      > ![enter image description here](http://i.stack.imgur.com/5zIeK.png) Almost does what I wanted, but I cannot connect the dots by options. If I use `Line`, I have to do the coloring manually. I plan to apply the code for more different size datasets.               ListPlot3D[dxy]      Gives an empty graph. Surprisingly, if I change the order of coordinates it works.               xyd = dxy /. {a_, b_, c_} -> {b, c, a}      > >     {{{5.5, 71.53, 0}, {7.5, 42.25, 0}, {11.5, 15.85, 0}, {15.5, >      20.33, 0}, {18., 43.5552, 0}, {22.8333, 24.47, 0}}, {{5.5, 48.5, >      10.}, {7.5, 40.44, 10.}, {11.5, 14.69, 10.}, {15.5, 14.65, >      10.}, {18., 42.9104, 10.}, {22.8333, 24.16, 10.}}, {{5.5, 44.46, >      425.}, {7.5, 83.82, 425.}, {11.5, 21.88, 425.}, {15.5, 71.99, >      425.}, {18., 63.65, 425.}, {22.8333, 45.32, 425.}}, {{5.5, 64.52, >      650}, {7.5, 65.36, 650}, {11.5, 20.0512, 650}, {15.5, 66.8, >      650}, {18., 38.6984, 650}, {22.8333, 30.3, 650}}, {{5.5, 105.49, >      700}, {7.5, 118.6, 700}, {11.5, 17.1288, 700}, {15.5, 43.39, >      700}, {18., 29.276, 700}, {22.8333, 23.18, 700}}, {{5.5, 35.98, >      1300}, {7.5, 59.9768, 1300}, {11.5, 35.2768, 1300}, {15.5, 45.09, >      1300}, {18., 7.8728, 1300}, {22.8333, 7.86, 1300}}} >                 ListPlot3D[xyd]      > ![enter image description here](http://i.stack.imgur.com/TJKpP.png) Works, but -of course - with wrong connections. `Dimensions[dxy] == Dimensions[xyd]` is obviously `True`, `Options[]` of the outputs are similar. I do not understand the difference.


NIntegrate: Catastrophic loss of precision

Below is a simplified code that I am trying to evaluate. I am basically getting the rms value of a Wakefield function. When I finally try to evaluate the rms, I get an error. Any help would be greatly appreciated.               sigmaS = 50*10^-6;          gaussian2[s_?NumericQ] := 1/(Sqrt[2 Pi] sigmaS) Exp[-(s^2/(2 sigmaS^2))]          fo2[s_?NumericQ] :=       NIntegrate[gaussian2'[sprime]/(s - sprime)^(1/3), {sprime, -Infinity, s}]          rms2 = Sqrt[       NIntegrate[         gaussian2[x] (fo2[x])^2, {x, -Infinity, Infinity}] - (NIntegrate[          gaussian2[x] fo2[x], {x, -Infinity, Infinity}])^2]


How would one minimize with respect to an unknown number of variables?

Say I had a function like the following:               f[n_] := Sum[a + Subscript[b, k], {k, 0, n}]      Such that `f[5] == 6 a + Subscript[b, 0] + Subscript[b, 1] + Subscript[b, 2] + Subscript[b, 3] + Subscript[b, 4] + Subscript[b, 5]` How would I go about minimizing `f` with respect to both a and all of the subscripted bs? How would I go about minimizing `f[5]` without manually supplying `{a, Subscript[b, 0], Subscript[b, 1], Subscript[b, 2], Subscript[b, 3], Subscript[b, 4], Subscript[b, 5]}` as the vars param? I'm asking about a specific simplified case here, but hopefully answers will be applicable in the general case and to other functions that take a vars param other than Minimize[]


efficient way to count the number of zeros at the (right) end of a very large number

If I want to count the number of zeros at the (right) end of a large number, like $12345!$, I can use something like:               Length[Last[Split[IntegerDigits[12345!]]]]      But this seems clumsy, since it's potentially doing the full work of `Split[]` to the whole list of digits when all I need is the length of the run of $0$s at the end of the list. Is there a more efficient (and particularly more Mathematica-elegant) way to do this? ( _edit_ : the answer for the example should be 3082)


Any way I can solve this integral?

So, _Mathematica_ can't solve it. Any workaround? \begin{equation*} \int_0^\pi \frac{1}{\sin\left(\frac{\theta}{2}\right)^\beta + 1} \mathrm{d}\theta \end{equation*} The code is:               Integrate[1/(Sin[θ/2]^β + 1), {θ, 0, π}]


Global vs local adaptive integration: lattice propagator

I was doing the first exercise in the paper Lattice QCD for Novices. This is the expected result: ![enter image description here](http://i.stack.imgur.com/Lo3sD.png) With the default "GlobalAdaptive" method for NIntegrate it threw errors saying that the error had increased more than 2000 times, so I switched to "LocalAdaptive". The result had some jitters, but was recognizable. ![enter image description here](http://i.stack.imgur.com/GnEwt.png) I decided to go back to "GlobalAdaptive" despite the warnings and slower time, and it actually looks really good despite the warnings. ![enter image description here](http://i.stack.imgur.com/RXlEw.png) However, the documentation says global adaptive is generally faster for multidimensional integrals. I'm looking for insight for why it is not true in this case, and in general, any settings that would give a better and faster result. I'm just getting into the options for the Monte Carlo methods. Here's the code:               stepSize = 1/2; stepCount = 8; potential[x_] := x^2/2; mass = 1;          action[x_List] :=       Sum[mass/(2 stepSize) (x[[j + 1]] - x[[j]])^2 +         stepSize potential[x[[j]]], {j, stepCount}]          ListLinePlot@      ParallelTable[       NIntegrate @@         Join[{E^-action[Join[{b}, Table[x[i], {i, stepCount - 1}], {b}]]},          Table[{x[i], -5, 5}, {i, stepCount - 1}], {Method ->            "LocalAdaptive"}], {b, 0, 2, .2}]          ListLinePlot@      ParallelTable[       Quiet[NIntegrate @@          Join[{E^-action[Join[{b}, Table[x[i], {i, stepCount - 1}], {b}]]},           Table[{x[i], -5, 5}, {i, stepCount - 1}]]], {b, 0, 2, .2}]


Question about Map and Total

Suppose I have a list and I want to generate a new list, such that $$ NewList[index] = \sum_{index \neq j}^{NumOfElts} \frac {1}{ \lvert OldList[index]-OldList[j] \rvert ^2 } $$ Can I do it using Map and Total on $OldList$? ### Edit Given `OldList = {a, b, c}`, I want `NewList` to be > >     {1/Abs[a - b]^2 + 1/Abs[a - c]^2, >      1/Abs[-a + b]^2 + 1/Abs[b - c]^2, >      1/Abs[-a + c]^2 + 1/Abs[-b + c]^2} >


How to open directly the help/reference window from a notebook

I'm used to do > ??symbol when I want the reference for a given symbol, then I click on the `>>` arrows to open the help window. Would it be possible to redefine the meaning of `??` in order to open the reference window directly ?


How can I iterate my code a 1000 times?

this is my solution to Exercise 5 of http://work.caltech.edu/homework/hw2.pdf Please help me make this more elegant. The exercise is about classifying random Points by a (randomly generated) target function to 2 classes (-1 and +1), build a new target function by linear Regression and compare where they don't classify to the same value. first I generate two Random Points to build the target function               funktionsPunkte = RandomReal[{-1, 1}, {2, 2}]      then generate the target function from it (to classify the data points)               targetFct[{x1_, x2_}] :=      With[{targetFunction = LinearModelFit[funktionsPunkte, {1, t}, t]},      x2 - targetFunction[x1]];      then I generate 100 data Points and classify them to either +1 or -1 ,depending if they are above or below the target function               data = With[{points = RandomReal[{-1, 1}, {100, 2}]},      Map[{Prepend[#, 1], If[targetFct[#] < 0, -1, 1]} &, points]];      one data Point is of the form {{1,x1,x2},y} where y is either +1 or -1. now Comes the ugly part. I Need the weight vector w = PseudoInverse[{1,x1,x2}].y               w = (PseudoInverse[#[[1]] & /@ data]).(#[[2]] & /@ data)      only {1,x1,x2} :               xlist = (#[[1]] &) /@ data;      the sign of each element w.x (-1 or 1 depending on which class we classify it)                sig = Sign /@ (w.# &) /@ xlist ;      only the y of our data Points               datasig = #[[2]] & /@ data;      now we Count the "misclassified" elements               Length[Select[      Table[sig[[i]] != datasig[[i]], {i, 100}], # == True &]]      now I Need to repeat this Experiment a 1000 times and take the mean. But how do I do that. I'm coming from an imperative Point of view and this would be trivial there. I'm also welcoming more elegant Solutions that more use functional and mathematica specific elements. edit: thanks to the comments, I made this               f := Module[{}, funktionsPunkte = RandomReal[{-1, 1}, {2, 2}];      targetFct[{x1_, x2_}] :=       With[{targetFunction = LinearModelFit[funktionsPunkte, {1, t}, t]},      x2 - targetFunction[x1]];      data = With[{points = RandomReal[{-1, 1}, {100, 2}]},       Map[{Prepend[#, 1], If[targetFct[#] < 0, -1, 1]} &, points]];      w = (PseudoInverse[#[[1]] & /@ data]).(#[[2]] & /@ data);      xlist = (#[[1]] &) /@ data;      sig = Sign /@ (w.# &) /@ xlist;      datasig = #[[2]] & /@ data;      Length[Select[      Table[sig[[i]] != datasig[[i]], {i, 100}], # == True &]]]      and then               f & /@ Range[1000]      it's awfully slow but it works (have not implemented the other suggestions yet)


Backslash commands in strings?

I discovered by playing around that               Text[DisplayForm@SubscriptBox["\[Lambda]", "k"]]      produces the same result as               Text["\*SubscriptBox[\"\[Lambda]\", \"k\"]"]      and, further, that the `\\*` is essential. This finding suggests that `\\*` means `DisplayForm` when inside a string. After more playing around, I found that               Text["\!\(\*SubscriptBox[\"\[Lambda]\", \"k\"]\)"]      produces the same result, but only if you have the bang _and_ the parens, that is, that `\\!` and `\\(`+`\\)` are _both_ necessary; either construct alone will not work. Where can I find the documentation for this magic? I don't know what to search for because I don't know what these kinds of constructs are called.


How would you efficiently implement BinListsBy?

Let's say I have a list like this:               data = {{21, "Alice"}, {27, "Bob"}, {22, "Charles"}, {34, "Dora"}, {75, "Eliza"}}      containing ages and names of persons. What I would like is a list of e.g. 10-year age brackets, containing a list of _{age,name}_ -pairs:               {       {{21, "Alice"}, {27, "Bob"}, {22, "Charles"}}, (* 20-30 years *)       {{34, "Dora"}}, (* 30-40 years *)       {}, (* 40-50 years *)       {}, (* 50-60 years *)       {}, (* 60-70 years *)       {{75, "Eliza"}} (* 70-80 years *)     }      `GatherBy[data, Floor[First[#]/10]&]` is close, but it leaves out empty bins. `BinLists[data[[All, 1]], 10]` is also similar, but it only returns the list of ages, I can't get it to include the names as well. Ideally, I'd like to have a function with similar syntax and performance to `BinLists`, i.e.: `binListsBy[data, {10,70,10}, First]`. And the function should be fast, because I'm going to use it on millions of entries (pixels of an image, in fact). (Following Mr.Wizard's meta discussion, I'm not going to add "what have I tried" in my question - I'm really looking for better ideas, or maybe even a built-in function I haven't noticed. Instead I'll post my attempts as an answer.)


How to create breathing wall effect?

I would like to recreate the effect of the one in this video: Breathing walls ![enter image description here](http://i.stack.imgur.com/8Pgul.gif) This is my first time manipulating images, and because of that, I don't even have a clue where to start. But I think the way to do this must be transforming the geometry of the image with sine waves, correct me if I'm wrong.


Combining key pivoting and lookup operators in Dataset

This question is related to this one re pivoting on keys. Because of the nesting, using Leonid's method as starting point - single key:               pivotUp[key_] := Query[GroupBy[Key@key], KeyDrop[key]]      How to extend the operation iteratively - but partially - to create hierarhical Datasets from tabular data. Interesting cases include duplicate values, which are pivoted to duplicate keys. Consider:               pivotUp[keys_List] :=       Sequence @@ (Flatten@{GroupBy[Key@#] & /@ keys, KeyDrop@keys})      Given:               data = AssociationThread[{"key1", "key2", "key3"} -> #] & /@  {{1,           "a", 10}, {1, "b", 20}, {2, "c", 30}} // Dataset      ![enter image description here](http://i.stack.imgur.com/aoo6T.png) One way to use pivotUp is this:                 data[pivotUp[Key@"key1"]][All, pivotUp[Key@"key2"]]       This is more compact:               data[pivotUp[{"key1", "key2"}]]                 <|1 -> <|"a" -> {<|"key3" -> 10|>}, "b" -> {<|"key3" -> 20|>}|>,           2 -> <|"c" -> {<|"key3" -> 30|>}|>|> (* normal form *)      But how can "key3" be accessed, either with given pivotUp or alternatives? These don't work:               data[pivotUp[{"key1", "key2"}], "key3"]      ![enter image description here](http://i.stack.imgur.com/DqFVg.png) The desired output is:               data[pivotUp[{"key1", "key2"}]][All, All, All, "key3"] // Normal          <|1 -> <|"a" -> {10}, "b" -> {20}|>, 2 -> <|"c" -> {30}|>|>      Ideally, these partial pivots should handle {__Association} structures.


Nested Sums to multiple sum

I would like to automatically "move nested sums to the left". I mean, just take out of an expression all the summations and go from a nested Sum to a multiple sum. Something like starting with:               Sum[f[y] Sum[g[x],x],y]      And changing it into:               Sum[ f[y] g[x],y,x]      But I can't think of a way to do it. Thanks!


Smarter way of manipulating plot style?

Say, I have a colorlist               listColor={Black,Brown,Red,Cyan}      Now, I have some Plot function that I can use this list:               Plot[{Sin[x],Cos[x],x,x^2},{x,1,100},PlotStyle->listColor]      Everything went fine. Now, I wanted to make the plot style "thick" But when I add:               Plot[{Sin[x],Cos[x],x,x^2},{x,1,100},PlotStyle->{Thick,listColor}]      The listColor breaks down. I understand I actually need               listColor={{Thick, Black},{Thick, Brown},{Thick, Red},{Thick, Cyan}}      But adding {Thick} to each entry of listColor is too hard. Is there anyway that I can append {Thick, } to each entry of the list elegantly? I notice that using               Transpose[{Table[Thick,{i,1,4}],listColor}]      might work but it looks unnecessary...


Am I entering this 2-variable recurrence correctly?

I'm trying to solve this recurrence with two variables.               RSolve[g[d, n] == 1 + g[d - 1, n] + g[d - 1, n - 1] &&        g[d, 0] == g[0, n] == 0, g[d, n], {d, n}]      My boundary conditions are that `g[d, 0] == g[0, n] == 0` for all `d,n` . But when I plug this in, I get the same input back with no error message. Am I inputting the recurrence incorrectly? Or is _Mathematica_ simply unable to find a closed form?


How to transpose x and y axes on a LogPlot?

Consider the following simple LogPlot:               LogPlot[Exp[x],{x,0,5}]      ![LogPlot of Exp\[x\]](http://i.stack.imgur.com/Rn3Er.png) Is there a nice way to switch the axes of a LogPlot? I'm aware that plotting the inverse function as follows               LogLinearPlot[Log[y],{y,Exp[0],Exp[5]}]      will do the job. The actual function I'm using is more complicated so I want to avoid using the inverse if possible. I've tried the various methods here How can I transpose x and y axis on a Plot? but they would seem to require some modification in order to work.


Different colors when comparing Plot3D V9 and V10

I am trying to create Plot3D with same color as we used to get in V9 but without success. I used `PlotTheme -> "Classic"` in V10 but the results looks like somehow not the same as V9. I have also copied the FullForm between V9 and V10 and again the plots are different. does anyone know the reason behind this? V9: ![enter image description here](http://i.stack.imgur.com/F4qSe.jpg) V10: ![enter image description here](http://i.stack.imgur.com/QG3LQ.jpg)


Problem about Solve

See this example :               Solve[x^2 == (a - b)^2, x]   (* {{x -> a - b}, {x -> -a + b}} *)          Solve[x^2 == 4 (a - b)^2, x]      (*{{x -> -2 Sqrt[a^2 - 2 a b + b^2]}, {x -> 2 Sqrt[a^2 - 2 a b + b^2]}}*)          Reduce[x^2 == 4 (a - b)^2, x]     (*x == 2 a - 2 b || x == -2 a + 2 b*)      More complicated,               Solve[{(x - x1)^2 + (y - y1)^2 == (x1 - x2)^2 + (y1 - y2)^2,       (x - x2)^2 + (y - y2)^2 == (x1 - x2)^2 + (y1 - y2)^2}, {x,  y}] // FullSimplify      gives $\left\{\left\{x\to \frac{1}{2} \left(\text{x1}+\text{x2}-\sqrt{3} \sqrt{(\text{y1}-\text{y2})^2}\right),y\to \frac{\sqrt{3} (\text{x1}-\text{x2}) \sqrt{(\text{y1}-\text{y2})^2}+\text{y1}^2-\text{y2}^2}{2 (\text{y1}-\text{y2})}\right\},\left\{x\to \frac{1}{2} \left(\text{x1}+\text{x2}+\sqrt{3} \sqrt{(\text{y1}-\text{y2})^2}\right),y\to \frac{\sqrt{3} (\text{x2}-\text{x1}) \sqrt{(\text{y1}-\text{y2})^2}+\text{y1}^2-\text{y2}^2}{2 (\text{y1}-\text{y2})}\right\}\right\}$ but I excepted result is $\left\{\left\{x\to \frac{\text{x1}}{2}+\frac{\text{x2}}{2}-\frac{\sqrt{3} \text{y1}}{2}+\frac{\sqrt{3} \text{y2}}{2},y\to \frac{\sqrt{3} \text{x1}}{2}-\frac{\sqrt{3} \text{x2}}{2}+\frac{\text{y1}}{2}+\frac{\text{y2}}{2}\right\},\left\{x\to \frac{\text{x1}}{2}+\frac{\text{x2}}{2}+\frac{\sqrt{3} \text{y1}}{2}-\frac{\sqrt{3} \text{y2}}{2},y\to -\frac{\sqrt{3} \text{x1}}{2}+\frac{\sqrt{3} \text{x2}}{2}+\frac{\text{y1}}{2}+\frac{\text{y2}}{2}\right\}\right\}$ both `Reduce` and `FullSimplify` can't gives a better result, How can I get the result as I want?


How to change the LabelStyle only for one axis?

I want to modify the style of just one axis, but I'm stuck with something like               Plot[x^2, {x, 0, 3}, LabelStyle -> Red]      which of course modifies both axes. How do I solve this problem?


plot probability

Hi I just want to flatten a function, I tied it with Joined->True, but it did not work, hope somebody of you can help me. This is my code:               Remove["Global`*"]     m = 30; (*number of banks*)     n = 5;(*number of defaults*)     AssetV = 100;(*asset value at T*)     DebtV = 80;(*debt value at T*)     μ = 0.2;(*annual drift*)     σ = 0.3;(*annual volatility*)     T = 5;(*years*)     ρ = 0.8;      Since I want to use a BinomialDistribution I calculated the individual probabilities through:               P = (CDF[NormalDistribution[], -(Log[             AssetV/DebtV] + (μ - 0.5*σ^2)*T)/(σ*Sqrt[           T])])      In the following I generated a table where I wanted to see the probabilities where k=n1, varies from 0 to 30 since n=30, and this is given by:               data1 = Table[       Probability[x >= n1,         x \[Distributed] BinomialDistribution[30, P]], {n1, 0, 30, 1}]      In order to plot the probabilities I entered:               Plot[Probability[x >= n1,        x \[Distributed] BinomialDistribution[30, P]], {n1, 0, 30},       PlotRange -> All, AxesLabel -> {"# of Defaults", "PD"},       Filling -> Axis]      and now I just want to flatten this function. I tried it with Joined-True, which did not work out. I want also to show the density by:               DiscretePlot[PDF[BinomialDistribution[30, P], n1], {n1, 0, 30},       PlotRange -> All, AxesLabel -> {"# of Defaults", "PD"},       Joined -> True]      However, is there the possibility to implement data1=Table[...] into the two functions, would it be then possible to generate the plot by the ListLinePlot function? thank you for your help.


Problem with plotting legends using the PlotLegends package

Here is my problem : I have a table composed of 3 "under"-Lists and I'd like to plot it with legends, but I can't find a way to do it.               DistSpat20084D = {        {7, 7, 44, 79, 121, 148, 152, 158, 153, 165, 182, 160, 163, 164, 169, 177, 198, 190, 177,         173, 159, 155, 147, 126, 142, 127, 129, 117, 13},         {7, 2, 10, 36, 53, 93, 108, 116, 134, 117, 115, 123, 84, 123, 127, 126, 153, 119, 147, 50,         43, 27, 23, 26, 21, 22, 28, 16, 18, 12,, 4, 5, 4, 3, 4, 1, 3, 0, 2, 4, 3, 4, 2, 5, 4,  0},         {7, 1, 6, 12, 3, 3, 2, 5, 4, 1, 3, 2, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0}};       My command to plot and add legends :               ListLinePlot[Table[{km/10, DistSpat20084D[[j, km]]}, {j, 3},        {km, Length[DistSpat20084D[[j]]]}],PlotLegend ->        {{"Speed1", "Speed2", "Speed3"}}, AxesOrigin -> {0, 0}]


ToBoxes Respect Spaces Code

Is there a way to force either `ToBoxes` or `MakeBoxes` to respect the spacing that occurs in the code? For example is there a way to force the following to print the code like so.               CellPrint@Cell[       BoxData@MakeBoxes[         f[          y          ]         ], "Input"]      would output               f[      y     ]


Combinatorica: Girth[] and FindCycle[] disagreement

Warning: run the following code in a fresh Mma session, as some symbols could be shadowed (depending on your Mma version) While trying to answer this question, I fell into the following:                (* Let's load a large Directed Graph and convert it to Combinatorica *)     g = Graph@Union@Flatten[          Thread[DirectedEdge @@ ##] & /@ Select[{#, IsotopeData[#, "DaughterNuclides"]} & /@              IsotopeData[], #[[2]] != {} &]];     Needs["GraphUtilities`"]     << Combinatorica`     cg = ToCombinatoricaGraph[g];      > Girth[cg] gives the length of a shortest cycle in a simple graph g. So, let's check if `cg` is Simple and calculate its Girth:               {SimpleQ@cg, Girth@cg}     (*     -> {True, 3}     *)      So there is at least one Cycle in `cg` of length 3. But look what happens when we try to find it by the two available methods in `Combinatorica`:               {ExtractCycles@cg, FindCycle@cg}     (*     -> {{},{}}     *)      So, two questions:   1. Is this a bug?   2. What is the easiest way to find all cycles in `g` without using Combinatorica? **Edit** BTW, the (now) standard Graph functionality also detects cycles:               AcyclicGraphQ[g]     (* -> False *)


How to Manipulate a ListLinePlot[Transpose[{T,B}]] if T is a Table and B is a list of minima built by using FindMinimum?

I need to Manipulate a ListLinePlot using a parameter P. The problem is that this Curve is a ListLinePlot of a Transpose[{T,B}], in which T is a normal table and B is a list of minima got using FindMinimum in f[x]. This is a simplified code that contains my concern:               f[x_] := (b/a)*x^2 + (x^2/b)     Quiet[Xmin = Table[        FindMinimum[{f[x], a >= 1, b >= 1}, {a, b}], {x, 250, 310, 20}]];          T = Table[T, {T, 250, 310, 20}];     B = b /. Take[Xmin, All, {2}] // Flatten;     Transpose[{T, B}];          ListLinePlot[Transpose[{T, B}]]      I'm able to plot this ListLinePlot as it is presented in the code but the idea is to insert a parameter P, multiplying the constant "a", inside of f[x] (P varies from 1 - 50). When I just put this ListLinePlot correctly inside the Manipulate expression, setting P as a changeable parameter and also insert the parameter P, multiplying the constant "a", the routine is not able to output B and I get a list of errors. I really need B, so, is there any way to Manipulate it? The Manipulate code that is not working is this:               Manipulate[ListLinePlot[Transpose[{T, B}]], {P, 1, 50}]      But with this Manipulate code above is evaluated only if I change "a" for "a*P" in the f[x]. Thanks a lot!


How to guarantee that NDSolve correctly detects abrupt changes in parameters?

When using `NDSolve`, I often have parameters that, in most of their domain, have a constant or null variation, but that suffer from abrupt variations on a very small interval. Mathematica variable step algorithm is unable to detect these singularities. On the following example, it misses the 15.0 to 15.1 abrupt rise:               variation[x_?NumericQ] := Which[       x < 10, 1,       x < 15, 0,       x < 15.1, 10,       x < 20, 0,       x < 30, 1,       True, 0]     points = {};     ans = accumulation /.         Flatten[NDSolve[{accumulation'[x] == variation[x],            accumulation[0] == 0}, accumulation, {x, 0, 40},             StepMonitor :> AppendTo[points, {x, accumulation[x]}]]];      ![plot of wrong integral](http://i.stack.imgur.com/Z71QK.jpg) What I do to guarantee a correct integration, is to define a `MaxStepSize`. In the following example `MaxStepSize -> 0.01`: ![plow with decreased MaxStepSize](http://i.stack.imgur.com/xzxdZ.jpg) But as you can see, this can cost me a lot of computation time. Since I know where exactly are the abrupt variations of my parameters, is there another way to guarantee the correct integration, without raising so high the number of steps? Something like listing to Mathematica points in the integration domain that have to be "seen"?


Custom Mathematica Shortcut: Copy as $\LaTeX$

If you edit the > `Wolfram > Research\Mathematica\8.0\SystemFiles\FrontEnd\TextResources\Windows\MenuSetup.tr` file you can make Ctrl+Shift+C copy not plain but in $\LaTeX$ format. Very useful. Look for the line in the file that says "&LaTeX" and the one that says "Plain &Text". The & sign gives the underscore letter in the menu. Then replace them with the following:               MenuItem["Plain &Text", FrontEnd`CopySpecial["PlainText"]],              MenuItem["&LaTeX", KernelExecute[ToExpression["FrontEnd`CopyAsTeX[]"]],              MenuKey["C", Modifiers->{"Control", "Shift"}],              MenuEvaluator -> Automatic],      Restart Mathematica and you are done. The question I have is if anyone knows what `MenuEvaluator` does, or if you know how to do this modification from a notebook in Mathematica rather than modifying the config file.


Z-Transforms and Floor Functions

When I take the $Z$-Transform of the `Floor` function:               ZTransform[ Floor[x], x, z]      I get > >     z/(-1 + z)^2 >   But when I do:               InverseZTransform[ z/(-1 + z)^2, z, x]      > >     x >   ... rather than `Floor[x]`... Is this an error in _Mathematica_ or is my understanding wrong? Is there a way to take the discrete-time $Z$-transform on a list, say: `{ 1, 2, 3, 4, 5, 6, 7, 8, 9}`... and then the inverse $Z$-transform?


Defining an anonymous function using another function but with fewer arguments

In MATLAB you can use an anonymous function with another function to define a new function with fewer arguments as long you define the excluded argument before, e.g.               z=1          f1=@(x,y) f(x,y,z)          x=2          y=3          f1(x,y)      Can you do that in Mathematica?


NSolve stalls when given an equation containing Log

Why does `NSolve` not work for this type of equation?               2.01224 == (0.954875 - 0.0084496 a) Log[         9 (0.954875 - 0.0084496 a)] + (0.0113946 - 0.00295146 a) Log[         9/4 (0.0113946 - 0.00295146 a)]      Here is my full script, where I solve got `a`, it just hangs there:               NSolve[2.01224 == (0.954875 - 0.0084496 a) Log[         9 (0.954875 - 0.0084496 a)] + (0.0113946 - 0.00295146 a) Log[         9/4 (0.0113946 - 0.00295146 a), ], a]


Fastest square number test

What is the fastest possible square number test in _Mathematica_ 7, both for machine size and big integers? I presume in version 8 the fastest will be a dedicated C LibraryLink function.


Can a Trie be implemented efficiently?

What is the most space and time efficient way to implement a Trie in _Mathematica_? Will it be practically faster than what is natively available in appropriate cases?


Understanding of method for NDSolve

I used automatic method for NDSolve. Then I asked myself - which method Mathemathica prefered? I got an answer for this question on this forum, that I need to use:               Select[Flatten[       Trace[NDSolve[{g[a[t]]*a''[t] + 0.5*dg[a[t]]*(a'[t])^2 + dV[a[t]] ==            0, a[0] == a0, a'[0] == -u}, a, {t, 0, t0}],         TraceInternal -> True]], ! FreeQ[#, Method | NDSolve`MethodData] &]      I got a long answer from Mathematica, from which I show you only two main unique strings:               NDSolve`InitializeMethod[NDSolve'LSODA,{Automatic, Automatic} ...     NDSolve`LSODA[NDSolve`MethodData[4, 22, {{}, False, 12, {NDSolve`Newton,{Automatic}}, None, False}]]      I understood, that Mathematica has chosen for method: LSODA and it's submethod: Newton. Whether I'm correct or this methods have another name? And what does LSODA stand for?


Mathematica 9 cannot solve a difference equation that Mathematica 8 can

Consider               RSolve[{a[n + 1] == 2 a[n] + n (1 + 2^n), a[1] == 1}, a[n], n]      _Mathematica_ 8 can solve this quickly, but _Mathematica_ 9, even after being allowed to run for a long time, cannot giva a result.


Background image in a polygon / CountryData

Is it possible to use a background image in a polygon without rasterizing the polygon? I tried with textures, but they seem to be viable only for simple polygons. I want to put a flag as the background of the polygon that represents a country shape. I can do this for one country by rasterizing the polygon:               ImageAdd[         Graphics[CountryData["Monaco", "Polygon"]],          CountryData["Monaco", "Flag"]     ]      ![monaco](http://i.stack.imgur.com/gQrkk.png) But by rasterizing the polygon, I make it difficult to apply this procedure to several neigboring countries and assemble them together. I would like to put each country flag in the background of, for example:               Graphics[         {EdgeForm[White],           CountryData[#, "Polygon"] & /@ {"Venezuela", "Colombia"}}]        ![colombia and venezuela](http://i.stack.imgur.com/6tCtL.png) * * * ## Solution After seeing cormullion answer, I was able to do what I wanted:               Graphics[      {EdgeForm[Black],       {{Texture[ImageReflect[CountryData[#, "Flag"], Top -> Right]],          CountryData[#, "Polygon"] /.            {Polygon[a_] :> Polygon[First[a], VertexTextureCoordinates ->             Transpose[Rescale /@ Transpose[First[CountryData[#, "Coordinates"]]]]]}} & /@      CountryData["SouthAmerica"]}}]      ![southamerica](http://i.stack.imgur.com/T2jnb.png) The key part is the use of Rescale[]. Thank you!


Mobius transformations revealed

Mobius Transformations Revealed is a short video that vividly illustrates the simplicity of Mobius transformations when viewed as rigid motions of the Riemann sphere. It was one of the winners in the 2007 Science and Engineering Visualization Challenge and the various YouTube versions have been viewed some 2,000,000 times. In the still image below, the colored portion corresponds to a simple square in the plane. The colored portion on the sphere is the image of the square in the plane under (inverse) stereographic projection; the sphere is then rotated into the position shown and finally projected back to the plane. The colored portion on the plane is the image of the original square under a Mobius transformation. ![enter image description here](http://i.stack.imgur.com/WzDfq.jpg) How can we implement this in Mathematica? Is it possible to create a dynamic version with `Manipulate` that allows us to interact with the image? Can we recreate a portion of the movie? Obviously, we can't create images of the quality of the original (which was produced with POV-Ray) but how close can we get? Can we generate color or should we stick with simple graphics primitives?


Pick bug: level 0 matching

A previous discussion of this issue (Is there a bug in Pick?) accepted that matching at level 0 is not a bug in `Pick`. Was that correct? I am not yet persuaded. Here is the documentation (http://reference.wolfram.com/language/ref/Pick.html): "`Pick[list,sel,patt]` picks out those elements of `list` for which the corresponding element of `sel` matches `patt`." This clearly speaks of _corresponding_ elements. It seems to me that either there is a documentation bug or there is an implementation bug. Why am I wrong? Furthermore, the documentation gives the obvious statement of intent, so I suspect an implementation bug. Here is (yet) another example that illustrates how bizarrely unexpected is the current behavior:               x = Range[20]     Pick[x, x/2, _Integer]  (* works as expected *)     Pick[x, x/2, Except[_Integer]]  (* does not work as expected *)      I find it almost impossible to believe that `Pick` was intended to cause this simple use of `Except` to fail by matching the entire list `x/2` rather than, as the documentation states, checking for a match in the _corresponding element_. Note that I am not asking how to get the intended match; I realize that `Except[_Integer|_List]` will accomplish that in this case. Also, I am using Mma 9.


Fast Trial Division

I'm going to write a custom Trial Division primality test. I know that `PrimeQ` will first try trial division and then switches to `PowerMod`.               TrialFactorFreeQ[N_, Max_] :=      (For[j = 1, j < Max && Divisible[N, Prime[j]] == False, j++];       Return[j == Max])      For example for testing a 300K digits number with first 100,000 primes, it took 4 seconds which is very slow since a real testing is applied for billions of primes.               In[179]:= Timing[TrialFactorFreeQ[3^1000000 + 2, 100000]]          Out[179]= {4.031, True}      Can it be optimized? * * * I wrote the parallel version and its timing seems good but when I wrap it in a function, the timing goes to sky:               p = 3^1000000 + 2;     max = Prime[100000];          In[85]:= ParallelTrialFactorFreeQ[Num_, Maxi_] := (IsFree = True;        ParallelDo[         If[Divisible[Num, i], IsFree = False; Break[]], {i,           Prime[Range[1, PrimePi[Maxi]]]}] If[! IsFree, AbortKernels[]];        Return[IsFree])          In[82]:= AbsoluteTiming[ParallelTrialFactorFreeQ[p, max]]          Out[82]= {18.2821829, True}          In[84]:= Timing[Num = p; Maxi = max;          IsFree = True;           ParallelDo[            If[Divisible[Num, i], IsFree = False; Break[]],             {i,Prime[Range[1, PrimePi[Maxi]]]}];            If[! IsFree, AbortKernels[]]; IsFree]          Out[84]= {0.609, True}      * * * **Updated** Based on the Daniel Lichtblau answer to my Fast Sieve Implementation question, I wrote a very fast Trial Division function which can be used for numbers that are larger than products of primes in the given range:               prod = Product[i, {i, Prime[Range[10^5]]}];          TrialFactorFreeQ2[n_] := GCD[n, prod] == 1      And a **10x** speedup               n = 3^1000000 + 2;          Timing[TrialFactorFreeQ2[n]]      > {0.375, True}


Manipulating a catenary in Mathematica

I have a catenary curve in Mathematica, and I wanted to add a variator (dimmer) with `Manipulate`, so that the user can modify the value of the x/y-coordinate of the hanging-points `A`, `B` and the point `C` on the curve. With my current code, I can just modify these values with the locator, but I can't see the current value and cannot set one directly. Is there a solution, so that I delete the rest of the curve, the part above the hanging-points `A` and `B`? Here is my code till now:               catenary[x_] := a*Cosh[(x - c)/a] + y          m = Manipulate[Module[{root},          (root = FindRoot[catenary[#[[1]]] == #[[2]] & /@ pt, {{y, 0}, {c, 0}, {a, 1}}];          Show[             Plot[catenary[x] /. root, {x, -2, 2}, PlotRange -> {-3, 3}, AspectRatio -> 3/2],              Graphics[{Red, Point[pt]}]])         ],          {{pt, {{-1, 1}, {1, 1}, {0, 0}}}, Locator}     ]


How To Track the Cursor Position?

I have 2 `InputFields` and 2 `Buttons`. I would like that when the user clicks the Pi `Button` or -Pi `Button`, that value will be assigned to that `InputField` only where the cursor was (either the first input field or the second).               Button["Range", (DialogInput[{range1 = 0, range2 = 0},      Column[{"Enter the Range",       Panel[Column[{InputField[Dynamic[range1], Number],          InputField[Dynamic[range2], Number],          Button["-Pi", (range2 = -3.14159;)],          Button["Pi", (range1 = 3.14159;)]}]]}]]), Method -> "Queued"]      ![Mathematica graphics](http://i.stack.imgur.com/ofOzG.png)


Mathematica package manager

I want to bundle up a Mathematica package that I've written and distribute it as open source. It has a couple of dependencies that I'd like to automatically download independently from my package as well. Is there any sort of established Mathematica package manager and package distribution site? (I'm thinking along the lines of pip for Python, gem for Ruby, nuget for .NET, hackage for Haskell, that sort of thing.) I've seen Wolfram MathSource, and as near as I can tell its aim seems to be to collect various contributed packages from around the web into a central place, but it doesn't feel very active (maybe I'm wrong?).


Tick marks on curves

I would like to put tick marks on a curve. In this trivial example I have managed to put some ticks.               ClearAll[fx, fy];     fx[t_] := 20 t - 0.1 t^2;     fy[t_] := 70 t - 5 t^2;     ParametricPlot[{fx[t], fy[t]}, {t, 0, 15}, AspectRatio -> Automatic,      Frame -> True, Axes -> False,      Epilog -> {Table[     Line[{{fx[t], fy[t]} + 3 #/Sqrt[#.#] &[{-fy'[t],          fx'[t]}], {fx[t], fy[t]} - 3 #/Sqrt[#.#] &[{-fy'[t],          fx'[t]}]}], {t, 0, 15, 0.5}]}]      ![Mathematica graphics](http://i.stack.imgur.com/I0Kcb.png) I began to write a module but then wondered if it had been done properly before but looked and could not find. My idea of a module is that it should enable the Epilog statement to look something like               Epilog -> {curveTicks[{fx, fy}, {t, tmin, tmax, tinc}]}      (Do I have to input the curve again?) My suggestion for a specification is as follows: The process will involve taking the derivative to get the tangent and then turning through 90 degrees. This could be done by taking the derivative of the function (as I have begun to do) or by using the lines that make up the curve. Alternatively, there may be a method using Mesh. Taking the derivative for each tick mark seems expensive (above is a trivial example). The length of the tick mark should be default or input. The tick line should stick out equally on both sides of the curve. If the aspect ratio of the plot is not automatic the line should be rotated so that it is still perpendicular to the curve. There should be a method of labeling some tick marks. Has this been done already somewhere? Thanks.


Internal Representation of ?name and ??name

## Code               FullForm[Hold[?name]]          Syntax::bktmcp: Expression "Hold[?name]]" has no closing "]".          Syntax::sntxi: Incomplete expression; more input is needed .      ## Question This is exercise 3.2 (page 47) of Power Programming w/ Mathematica The task is: "determine the internal representation of the expressions ?name and ??name" The above is what I tried. It failed. How do I win?


Support for Multidimensional Scaling (MDS)?

Does mathematica support MDS? Or, are there any libraries that support it? Basically, I have points and a distance function defined between them, and I want to plot them in 2D space, trying to minimize the error (stress) in the distance. This is what MDS does. R has support for MDS, but I can't find similar methods in Mathematica, which I think is strange because this seems like a really common thing to want to do...


Code Readability and Object-Oriented Code

The basic problem I have been running into is making readable code, where in other languages I am more familiar with I might have been using class or struct like objects. For example, you can imagine I might want to create a circle object, which would, at the very least, store the radius and position of the circle. In an object-oriented language, I might access the $x$-coordinate of the center of the circle using something like `circ.pos.x`. In Mathematica, however, I find myself using nothing more than nested lists, and as a result, wind up with code looking something like `circ[[2]][[1]]` (`circ[[1]]` is the radius and `circ[[2]]` is the position vector, say). You can imagine how code like this could become very unreadable very fast. Presumably, this is because I'm not 'doing it right'. So, then, what is the 'right' way to implement something like this? Does Mathematica support built- in object-oriented features I'm not aware of?


Counting number of inversions

Is there an inbuilt method to find the number of inversions in a set of numbers? I found `Inversions` in `Combinatorica` but when I tried to use it as `Inversions[{1,4,2,5,2,3,2}]` it doesn't return a number as a result. How are you supposed to use the function?


Question about VertexTextureCoordinates

Background: consider the following snippet:                gp := Graphics      bill = Import["http://i.stack.imgur.com/FyojA.jpg"];      poly1 = {{1, 0}, {.5, .86}, {-.5, .86}, {-1, 0}, {-.5, -.86}, {.5, -.86}};      g1 = {Texture[bill], Polygon[poly1, VertexTextureCoordinates -> poly1]};      poly2 = {{0, 0}, {1, 0}, {1, 1}, {0, 1}};      g2 = {Texture[bill], Polygon[poly2, VertexTextureCoordinates -> poly2]};      g1 // gp      g2 // gp      ![example of output](http://i.stack.imgur.com/hywwS.jpg) The option `VertexTextureCoordinates` isn't entirely clear to me. I want to put an image with the correct ratios in the hexagon left. So for example on {{-.5,-.5},{.5,-.5},{.5,5},{-.5,.5}}. (I have not been able to get this to work although I have tried all sort of possibilities) However with the restriction that if I rescale the (coordinates of the) hexagon the image should be scaled accordingly. EDIT-1: ![enter image description here](http://i.stack.imgur.com/FyojA.jpg) Image as requested. EDIT-2: This nicely sums up and demonstrates the answer by Heike:                rescale1[poly_, p1_, p2_] :=        Transpose[{Rescale[poly[[All, 1]], {p1[[1]], p2[[1]]}, {0, 1}],          Rescale[poly[[All, 2]], {p1[[2]], p2[[2]]}, {0, 1}]}]      Manipulate[       g = {Texture[bill],           Polygon[poly,            VertexTextureCoordinates -> rescale1[poly, leftbot, righttop]]} //          Graphics,       {leftbot, {0, 0}, {1, 1}}, {righttop, {0, 0}, {1, 1}},        Initialization :> {righttop = {1, 1}}, ControlPlacement -> Bottom]      Key is the mapping between the image and vertextexture coordinates.


Delete Missing data from coordinate sets

I have a list of pairs of coordinates, where some are missing.               coordinates = {       {{1, 1}, {1, 2}},       {{3, 4}, {5, 5}},       {{1, 2}, Missing[]},       {{9, 8}, {7, 7}},       {Missing[], {2, 3}}     }      I am trying to remove the pairs containing missing coordinates, to get               coordinates = {       {{1, 1}, {1, 2}},       {{3, 4}, {5, 5}},       {{9, 8}, {7, 7}},     }      I tried               coordinates = DeleteCases[coordinates, MemberQ[#, _Missing] &]      but that did not work. But the function `MemberQ` works on pairs directly:               MemberQ[coordinates[[1]], _Missing] (* returns False *)     MemberQ[coordinates[[3]], _Missing] (* returns True *)      What did I do wrong?


Mathlink and Parallelization

> **Possible Duplicate:**   >  How to run mathlink external commands in parallel? # Abstract I have a binary file compiled to work with MathLink. I can install the file and run the component functions from within Mathematica without any problems. But, when I try to use Mathematica's inbuilt parallelization with calls to my binary, I get an error that says               LinkObject::linkn: Argument LinkObject[/path/to/binary/file.binary,14,8] in      LinkWrite[LinkObject[/path/to/binary/file.binary,14,8],CallPacket[1,{1,2066455,5.,200000}]]      has an invalid LinkObject number; the link may be closed.      I understand this to mean that MathLink cannot set up links to my binary for some reason? How does one get this to work? # System Details I am on a system with 8 cores running x86_64-redhat-linux-gnu. # Mathematica Code that Produces the Error Assume `SwitchTimes` is a function defined inside my binary. It takes a number of inputs, but I want to loop over values for one particular input.               f[x_] := Module[{A, ma},         A = SwitchTimes[x, RandomInteger[10000000], 5.0, 200000];        ma = Mean[A];        ma        ];          B = ParallelMap[f, Table[i, {i, 1, 100, 2}]];      # Code that runs fine               f[x_] := Module[{A, ma},         A = SwitchTimes[x, RandomInteger[10000000], 5.0, 200000];        ma = Mean[A];        ma        ];          B = Map[f, Table[i, {i, 1, 100, 2}]];


Incorrect value of infinite sum

Wolfram Alpha and _Mathematica_ give an incorrect result (numerically) for the following infinite sum:               N[Sum[((-1)^n)/(n - (-1)^n), {n, 1, Infinity}]]     (* 0.700059 *)      Here's the result on Wolfram Alpha. Why the series isn't correctly evaluated?   The answer should be $\log(2)$.


File-backed lists/variables for handling large data

**Background** Currently I am working with some large data (most of it generated by Mathematica itself). I usually find it a hassle to do this. For example, I just exported a large amount of data to WDX on a machine with a lot of memory, just to find that I can't read it on my own machine (with little memory) because the file can only be read as a whole. It is also extremely slow to import (but using MX was not an option due to different architectures) Mathematica is excellent when working with in-memory data, as it's paradigms of operating on data as a whole (`Map`, `Outer`, `Table`, etc.) are very convenient. But it is not great at working with data that is too large to fit into memory, and it is not good at sequential processing of on-disk data. There have been discussions about this (see the comment discussions on this and this question), and the following idea came up more than once: it would be great to be able to use Mathematica's native paradigms to work on large on- disk data. The data would be loaded on-demand from disk, and discarded when not needed any more. I'd love to hear some ideas on how to implement a framework that does this, but read the next section for a more practical question. **Question** How can I conveniently work with data that doesn't fit in memory? Can we implement a list-like structure which fetches the data from disk as needed? (For example, when indexed, it would load only the requested list-item directly from disk. As processing of this item has finished, the memory it took up would be freed.) Alternatively could we implement variable which are loaded from disk on demand, but can be unloaded from memory? I'd prefer not to have to deal with things like file names (if this is backed my multiple files). I'm hoping to be able to have a nice abstraction, where I never need to do explicit reading from disk. I'd like to work with an object which acts and works similar to an in-memory list. **Ideas**   * This could be backed by the MX format, which is very fast to read and can store any expression. Unfortunately it's not portable between machines. For machine numbers, a flat binary file and `BinaryReadList` could be useful.   * `Stub` might or might not be useful.   * Are databases the right way to go? I'm not familiar with them.


Functional programming Style & Performance

Hello i have been spending time to convert my R tools into Mathematica Packages mainly because i like the functional programming style in Mathematica. In doing so it seems that i run into one conundrum. On one had functional programming suggests to avoid intermediate variables on the other side, a simple example like below clearly shows the potentially significant performance difference when avoiding intermediate (pre-calculated) steps. do i miss any better solution, or is this really a case where functional style, just looses out ?   * `dfm` is simply a List of Lists with some syntactic sugar   * `dfm["SER"]` is a vector of 25k real numbers   * `dfm["serial"]` is a vector of 25k string factors  * * *               (* check out the add variation as function of model *)     uSerial  = DeleteDuplicates[dfm["serial"]];     tt       = Transpose@{dfm["SER"], dfm["serial"]};     foo[z_] := Select[tt, (Last[#] == z) &][[All, 1]];     serMhdd = Mean /@ Map[foo[#] &, dfm["serial"]] // N; // AbsoluteTiming          uSerial = DeleteDuplicates[dfm["serial"]];     foo[z_] := Select[Transpose@{dfm["detSER"],                      dfm["serial"]}, (Last[#] == z) &][[All, 1]];     serMhdd = Mean /@ Map[foo[#] &, dfm["serial"]] // N; // AbsoluteTiming      happy holidays, Bernd


Center Manifolds

a[x_, y_] := -1     b[x_, y_] := x     c[x_, y_] := x     d[x_, y_] := -(1/2)          h[x_] = c1*x^2 + c2*x^3 + O[x]^4;          h[0] = 0;          D[h[x], x] = 0 /. {x -> 0};          cz3 = Solve[ h[a[x, y]*x + b[x, h[x]]] == c[x, h[x]]*h[x] + d[x, y], {c1, c2}]      I am using Implicit Function Theorem/center Manifold to determine stability of the fixed point give me P(x*)=1. But for the above `h`, I need to determine `c1` and `c2` but my programme gives me nothing. I know I think simple but I have recently started to use _Mathematica_. Please help me! I don't know what to use in here.


Control over the way matrix is displayed

I am wondering how to change the output format in _Mathematica_. For example, I have $x=\binom{3}{1}$ and $y=\binom{2}{5}$, and I want to find what linear combination of $x$ and $y$ produces $\binom{7}{11}$. What do I have to do to make _Mathematica_ display the output $x+2y$ ? I tried using `Solve`, but _Mathematica_ just returns the coefficients. I also tried to use the augmented matrix, but again _Mathematica_ still did not give me the output I want. P.S. I am working with a 16 by 16 matrix with 16 variables, so it's not very convenient to read off the coefficients for each variable.


How to extract phase angle from sinusoid

I'm doing some electric circuit calcualtions and I'm trying to get the phasor representation of some arbitrary function of Sin or Cos. Could be complex like:               (0. - 10. I) Sin[1000 t]      For instance, if I have:               Vin = 10Cos[1000t- 90Degree]      which is:               Vin = 10Re[Exp[-I*90Degree]*Exp[I*1000t]]      I want to get the magnitude angle form. i.e $10\angle-90^\circ$ I can get the magnitude with:               MaxValue[Abs[Vin], t]      but I can't get the phase angle correctly. I've tried:               Re[N[ArcCos[(Vin/MaxValue[Vin, t]) /. t -> 0]/Degree]]      but that gives $90^\circ$ not $-90^\circ$ So I have 2 questions actually:   1. Can I force mathematica to keep my function in $\cos\left(something - 90^\circ\right)$ form instead of changing it to $\sin\left(something + 0^\circ\right)$?   2. And how can I correctly obtain the phase angle


Bug in GeneratingFunction?

According to the documentation               GeneratingFunction[a[n],n,x]==Sum[a[n]x^n,{n,0,Infinity}]      However, for $a_n=1/(n+2)$ I obtain               {Sum[1/(n + 2) x^n, {n, 0, Infinity}], GeneratingFunction[1/(n + 2), n, x]} // FullSimplify     % /. x -> .2     (*{-((x + Log[1 - x])/x^2), PolyLog[2, x]/x}*)     (*{0.578589, 1.05502}*)      Thanks **Edit:** I'm using Mathematica 8.0.0.0 on a Linux x86 (32-bit)


Problem with NonlinearModelFit: "The function value... is not a list of real numbers..."

I'm trying to use NonlinearModelFit to fit the data:               Data = {{2.046204620462046`, 1.274347668`}, {2.012987012987013`,          1.131369542`}, {1.984`, 0.939944276`}, {1.952755905511811`,          0.721156437`}, {1.9224806201550388`,          0.614591638`}, {1.8931297709923665`,          0.572324748`}, {1.8674698795180722`,          0.536605273`}, {1.8397626112759644`,          0.49948005`}, {1.8128654970760234`,          0.478452409`}, {1.7867435158501441`,          0.455583518`}, {1.7613636363636365`,          0.439702881`}, {1.7342657342657342`,          0.411870668`}, {1.712707182320442`,          0.365204419`}, {1.6870748299319729`,          0.303633546`}, {1.6666666666666667`,          0.232056102`}, {1.6445623342175066`,          0.140710942`}, {1.6230366492146597`,          0.070744185`}, {1.6020671834625324`,          0.035633753`}, {1.597938144329897`, 0.044761696`}};          fit = NonlinearModelFit[Data, B/(       1 + g (x - (1.42 + Ea))^(-3/2)), {B, g, Ea}, x]      which gives: > NonlinearModelFit::nrlnum: "The function value {-1.22471-0.217191\ > I,-1.0682-0.243262\ I,-0.863406-0.265857\ I,-0.628591-0.289822\ > I,<<12>>,0.26533 -0.472365\ I,0.318041 -0.47811\ I,0.312374 -0.479155\ I}\n > is not a list of real numbers with dimensions {19} at {B,g,Ea} = > {1.,1.,1.}." The function I am using to fit my data gets imaginary values for some values of the parameters. But how can I force Mathematica to avoid these values?


How to resolve the duplicate error during interpolation

I have few hundred data points corresponding to an irregular shape closed curve. As the result I have data points that have the same value of y but different values of x. I want to create an interpolation curve and find the intersection of the curve with a straight line. When I try to interpolate the data _Mathematica_ tells me that there are duplicates. Is there any way of finding the intersection of the curve with a straight line? Here is how I was trying to do it               aa = Interpolation[Data, InterpolationOrder -> 1];     Interpolation::inddp: "The point -6.72 in dimension 1 is duplicated"          FindRoot[aa[x] - x, {x, bestguess}]      Thank you in advance.


is there a method to send different cell evaluation to different core

I am running _Mathematica_ on a computer with mulicpu and every cpu has multicore. I am wondering if there exist a method to send different cell evaluation to different core? So if I already have a cell being evaluating for a long time, I can still add other cells into evaluation at the same time, while won't have to stop the current evaluation or wait until the current evaluation to be done.


Detect when InputField gets keyboard focus

How might I detect when an `InputField` comes into focus? For example ideally something like this would work.               EventHandler[      InputField["default", String], {       "FocusGained" :> (MessageDialog["Focus"]),       "FocusLost" :> (MessageDialog["unFocus"]),       "Focus" :> (MessageDialog["Focus"])       }      ]      After reading this question I assumed "FocusGained,FocusLost or Focus" would do something but I haven't had any luck just yet.


Determine appropriate initial conditions for exit time

These are some constants:               b1b = 0.9;     b3b = .8;     a1b = 0.1;     a3b = 0.2;     eps = 0.1;     G = (1/eps^2)*b1b ; a1 = (1/eps^2)*a1b; a3 = (1/eps^2)*a3b;     xc = Sqrt[a1/a3];     Uc = a1*xc^2/2 - a3*xc^4/4      I have the following constraint for my system --> this was to find exit time:               const[x_, y_] := And[10^-8 <= y <= 10^-3, 0.9*(Uc) <= a1*x^2 - a3*x^4/4 <= 1.1*(Uc)]      Define the process (thanks to b.gatessucks):               x0 =    (* starting point for x[t] *)     y0 =    (* starting point for y[t] *)          proc = ItoProcess[      {\[DifferentialD]x[t] == y[t] \[DifferentialD]t,        \[DifferentialD]y[t] == (-G*y[t] - (a1*x[t] + a3*x[t]^3) - eps*b3b*y[t]^3) \[DifferentialD]t + Sqrt[2*eps*G] \[DifferentialD]w[t]},        {t, x[t], y[t], Boole[const[x[t], y[t]]]},        {{x, y}, {x0, y0}}, {t, 0}, w \[Distributed] WienerProcess[]]      Find exit time (output as **{t, x[t], y[t], Boole[const[x[t], y[t]]]}** ):               SeedRandom[3]     sim = RandomFunction[proc, {0, 1, 0.001}];     First@Select[sim[[2, 1, 1]], #[[4]] == 0 &]      I need help on how to choose the initial conditions: **(x0,y0)** so that I can find exit times that are non-zero. I need to find about 100 of these for every `eps`. `eps` is varying. Also, can someone kindly explain as to what:               SeedRandom[3]     sim = RandomFunction[proc, {0, 1, 0.001}];     First@Select[sim[[2, 1, 1]], #[[4]] == 0 &]      mean? Finally, the `const[x_, y_]` function need not be defined if there is some other way (algorithms) as to how I can find exit time for my dynamical system. If an answer is hard to come by then I would sincerely appreciate any leads or thoughts on this matter. Thanks!


Can I automatically stop operation that is too slow?

I need to write code like this: Do operation 1, but if it takes more that 5 seconds then stop it and do operation 2. Is it possible to do this somehow without manual interruption?


Can someone explain this code for joining two lists by the first element of each sublist?

**Background** (which may be skipped, unless context is needed) I've recently begun learning Mathematica (and only up to chapter 3 of Wellin), but wanted to write some code to get a better feel for syntax before reading on. I decided a good exercise would be to obtain a list of daily prices and volumes for a stock, _i.e._               P = FinancialData["QCOM", All];     V = FinancialData["QCOM", "Volume", All];      These returned, respectively,               {{{1991,12,16},0.47},{{1991,12,17},0.46},{{1991,12,18},0.48},{{1991,12,19},0.46},{{1991,12,20},0.47},{{1991,12,23},0.47},<<5447>>,{{2013,8,16},66.9},{{2013,8,19},66.33},{{2013,8,20},66.71},{{2013,8,21},66.57},{{2013,8,22},67.13},{{2013,8,23},67.15}}      and               {{{1991,12,16},143667200},{{1991,12,17},16176000},{{1991,12,18},10899200},{{1991,12,19},7299200},{{1991,12,20},5235200},{{1991,12,23},7894400},<<5448>>,{{2013,8,19},9063600},{{2013,8,20},9064900},{{2013,8,21},8471500},{{2013,8,22},6694200},{{2013,8,23},8335800}}      Probably all the dates would line up, but for sake of learning, I wanted to intersect the two lists by date. That is, obtain a list like               {{{1991,12,16},{0.47,143667200}},{{1991,12,17},{0.46,16176000}}, ... }      * * * **Problem** The canonical answer for combining lists seemed to be How do I obtain an intersection of two or more list of lists conditioned on the first element of each sub-list?, answered in main by @Mr.Wizard. But even after an hour of investigation, I cannot seem to wrap my mind around the following:               f1[a_List, b_List] :=         Reap[Sow[#2, #] & @@@ a ~Join~ b, a[[All, 1]] ⋂ b[[All, 1]], List][[2, All, 1]]      Here's where I've gotten:   1. `a ~Join~ b` is using the infix form to join the price and volume lists.   2. `Sow[#2, #] &` is a "pure function" (which confuses me, because they seem more like "anonymous" functions, distinct from "pure [virtual] functions" in C++), swapping the first and second parameters.   3. `@@@` is shorthand for `Apply`-at-level-1, so in other words, it's executing `Sow[{1991,12,16}, 0.47]; Sow[{1991,12,17}, 0.46]; ...` for all the prices, and then all the volumes. The prices (and volumes) are what's being "sowed", and each sowing is "tagged" by the date.   4. The intersection, `a[[All, 1]] ⋂ b[[All, 1]]`, simply returns all the "keys" (dates) that are common between the two lists. But, beyond that, **I don't understand how`Reap` brings it all together. Would someone explain the rest in simpler terms?** I'm a C++ developer, so I'm comfortable with programming terms. Either I'm not interpreting the documentation correctly, or my brain is fried from figuring out the rest. Thanks very much in advance.


Chi square: compare two different distribution

I try to compare two file with two different distribution of numbers. So i have random1.dat and random2.dat each one are vectors of more then 1000 rows. I saw from this question Doing a chi-square independence test in Mathematica that is it possible to make the comparison with Chi-square or Poisson but they attach the two files. How can i do that if my files are so long (or longer then 1000 rows)? Here my files: http://www.filedropper.com/random1_1: random1.dat http://www.filedropper.com/random2 : random2.dat Than I like, having in the same directory for instance 100 of this different files: random*.dat to compare all of them with a particular one (for instance random1.dat) is that possible in Mathematica? Thanks a lot !


NMinimize to optimize function Module

I am using `Nminimize` for simulation based optimization. I define the objective function (simulation with a variable "a") as a module to be used in the minimization. What I have found is if I do not print the function value (f[a]) using the EvaluationMonitor, NMinimize outputs 1000s of iterations of possible values for "a" extremely quickly without running the corresponding simulation run (because if it runs simulations, it will need few seconds for each simulation run and can not do 1000s of simulations in no time). However, when I include "f[a]" in the evaluation monitor, NMinimize runs the simulation for each possible value of "a" it outputs, but is disconnected to the optimization process. This is evident because NMinimize does not converge even after 1000s of iterations, when there are only 10 possible values "a" can take and I know the minimum occurs at "a"=10. Will someone help me understand what I am missing?               demand[n_,k_]:=Min[k Vf,n capacity];     supply[n_,k_]:=Min[(n Kj-k) w,n capacity];     flo[n_,Ku_,Kd_]:=Min[demand[n,Ku],supply[n,Kd]];     dx=Vf*dt;capacity=w*Vf*Kj/(Vf+w);Kj=150.;w=20.;Vf=100.;     n=Round[Flen/dx];m=Round[SimTime/dt];p=Round[Rlen/dx];RMLocation=Round[(2/3) p];     \[Alpha][a1_]:=1800.;\[Beta][a2_]:=0.1;L=1.;Flen=4.;Rlen=3.;delta = 1.;SimTime=15./60.;dt=6./3600.;     f[a_]:=Module[{k0=ConstantArray[0,n],kr=Table[Table[0,{i1,1,p}],{i2,1,n}],\[Gamma]=ConstantArray[1,n],\[Phi]},     Clear[j];j=0;RM[x_,t_]:=100 a;k=k0;     For[i=2,i<n,i++,kr[[i,1]]=\[Alpha][i dx] delta/Vf];     NtwrkTT=TT=Plus@@(Plus@@kr);     While[TT>0,      For[i=2,i<n,i++,       FQin=If[i==2,Min[demand[L,k0[[i-1]]],supply[L,k0[[i]]]],FQout];       dem=demand[L,k0[[i]]];dem=If[dem==0,0.001,dem];       \[Gamma][[i]]=Min[1,supply[L,k0[[i+1]]]/dem];       \[Phi]=\[Gamma][[i]] demand[1,kr[[i,p]]]/delta;       Qr=(\[Phi]-\[Beta][i dx] FQin) dx;       FQout=Min[demand[L,k0[[i]]],supply[L,k0[[i+1]]]];       k[[i]]=k0[[i]]+(FQin-FQout+Qr)/Vf;kr0=kr[[i]];       For[ir=2,ir<=p,ir++,        MR=If[ir==RMLocation+1,RM[i dx,j dt],capacity];        RQin=Min[MR,If[ir==2,flo[1,kr0[[ir-1]],kr0[[ir]]],RQout]];        MR=If[ir==RMLocation,RM[i dx,j dt],capacity];        RQout=Min[MR,If[ir<p,flo[1,kr0[[ir]],kr0[[ir+1]]],\[Phi] delta]];        kr[[i,ir]]=kr0[[ir]]+(RQin-RQout)/Vf];       kr[[i,1]]=If[j<=m,\[Alpha][i dx] delta/Vf,0]];      TT=Plus@@(Plus@@kr);      TT+=Plus@@k;      k0=k;NtwrkTT+=TT;j++];     NtwrkTT dt]     NMinimize[{f[a],3<=a<=12&&Element[a,Integers]},a,Method->"SimulatedAnnealing",EvaluationMonitor:>Print["a = ",a]]      **edit** : I edited this post extensively to make it clear. Apologize for any confusion.


GUI of a Karnaugh Map

I intend to implement a three-variables Karnaugh map with the following code. There are two points I failed to figure out. How to remove the outer double- line border? How to change the toggling into "1" and blank instead of black and white? Please help.               labels = {"00", "01", "11", "10"};     frame = Graphics[{         Line@Table[{{i, 0}, {i, 4}}, {i, 0, 2, 1}],         Line@Table[{{0, i}, {2, i}}, {i, 0, 4, 1}],          Table[Text[           labels[[3 - i + 1]], {-0.3, i + 0.3}], {i, {0, 1, 3, 2}}],          Table[Text[labels[[i + 1]], {i + 0.75, 4.25}], {i, {0, 1, 0, 1}}],          Line[{{0, 4}, {-0.75, 4.75}}],          Text[Style[ "A B" , 12], {-0.5, 4.}],          Text[Style["C", 12], {0., 4.5}]}, ImageSize -> {100, 200}];          Manipulate[       arrX = ConstantArray[0, {2, 4}];       EventHandler[       Dynamic[        mat = Reverse[ Transpose[arrX]] ;        Show[frame,         MatrixPlot[          mat,          Mesh -> All,          ImageSize -> {100, 200},          PlotRangePadding -> 0,          FrameTicks -> None,          ColorRules -> {1 -> Black, 0 -> None}]         ]],       {        "MouseClicked" :> (pos = Ceiling[MousePosition["Graphics"]];          arrX = ReplacePart[arrX, pos -> 1 - arrX[[Sequence @@ pos]]];          )        }],       AppearanceElements -> None,      FrameMargins -> 0      ]      ![enter image description here](http://i.stack.imgur.com/vlm1V.gif)


Wrong font selection for some characters in Mathematica 10 for Linux

I've just started using _Mathematica_ 10 on Linux and have immediately run into problems with the fonts. Fonts on Linux are always a headache, but I had managed to find a reasonable one in "Century Schoolbook L". However, in _Mathematica_ 10, this font and many others are being displayed with incorrect special characters and punctuation. It seems like _Mathematica_ is trying to assign sans-serif default (that is, not appearing in the font specified) characters when it needs to be using serif. I have tried messing with "OperatorSubstitution" and "FontSerifed". The former can change the parentheses, but neither affects the Greek. My only current recourse is to select one of the fonts that (seemingly randomly) does not suffer this problem; "Linux Libertine O", for example. Is this a bug? Is there a workaround? ![Example of problematic text; note the Greek and parentheses](http://i.stack.imgur.com/oCoPi.png)


Control formatting of a Text element in a plot?

Is it possible to define the format for a part of `Text` in a plot? For instance, is it possible to have `v` bold and `(a)` italic:               Show[Graphics3D[Line[{{0, 0, 0}, {1, 1, 1}}]],      Graphics3D[Text["v(a)", {1.1, 1.1, 1.1}, BaseStyle -> Large]],      PlotRange -> {{0, 2}, {0, 2}, {0, 2}}]      ![enter image description here](http://i.stack.imgur.com/50kbE.png)


Replacing values of a function

I have recently starting using _Mathematica_ and have recently come to what seems as an impasse in my understanding of the language. If this is too "tell me how to do it" I would certainly understand. I have written a program that applies commutator logic to a sequence of creation and annihilation operators to produce a string of Kronecker deltas. I then need to apply the Kronecker delta restrictions to my operators. This is purely symbolic algebra, no real numbers need be produced at the end of the day. For example,               (* KD[a,b] is a Kronecker delta with indices a and b. *)     (* KD Attributes: Orderless,NumericFunction *)     (* A[{x},{y}] is an operator with creation indices x and annihilation indices y*)          In:     A[{x},{y}] (KD[x,a1]*KD[y,a2]-KD[x,b1]*KD[y,b2])          Out:     A[{a1},{a2}]-A[{b1},{b2}]      What I have so far:               In:     rules=torules[(KD[x,a1]*KD[y,a2]]     A[{x},{y}]/.rules          Out:     {x->a1,y->a2}     A[{a1},{a2}]      This, however, is not quite what I need and converting from KD's to the rules list seems overly complicated. The main issues with this is that I cannot generate operator expressions that have plus within them. The structure of KD is not easily changed, but the input of the operator expressions is quite flexible. Another take on this, I am not sure if it will help, but its my current direction.               In:     SetAttributes[A, NumericFunciton]     A[{x},{y}] (KD[x,a1]*KD[y,a2]-KD[x,b1]*KD[y,b2])          Out:     A[{x},{y}]*KD[x,a1]*KD[y,a2]- A[{x},{y}]*KD[x,b1]*KD[y,b2]      This should be a fairly simple replacement pattern, but I cannot get any further.


How can I find the points of B Spline functions for a specific range?

Based on this question: I have a list of bspline functions (nearly 1000) provided by applying `BSplineFunction` to a list of points. I want to get the points each of bspline function for `Range[0, 1, .1]`. For instance:               functions = {bsplinefunc1, bsplinefunc2, bsplinefunc3};      The desired result is:               result =       {bsplinefunc1[0], bsplinefunc1[.1], bsplinefunc1[.2], ..., bsplinefunc1[1]},        {bsplinefunc2[0], bsplinefunc2[.1], bsplinefunc2[.2], ..., bsplinefunc2[1]},       {bsplinefunc3[0], bsplinefunc3[.1], bsplinefunc3[.2], ..., bsplinefunc3[1]}}      I tried to use the solutions of this question, mainly István Zachar's answer; however, I couldn't make it work. Any help is appreciated.


Create formatting wrapper for use with ToString

I'd like to create a custom number format for use with `ToString`. However if I do the obvious and create a function that calls `NumberForm` with modified options:               numberform =        NumberForm[#,          ExponentFunction -> (If[-5 < # < 5, Null, #]&),          NumberFormat -> (If[#3 != "", SequenceForm[#1, "E", #3],#1]&)]&        > >     Slot[1]& >   It works fine as a function:               numberform[1234567890.]        > >     1.23457E9 >   but not with `ToString`:               ToString[1234567890., numberform]        > >     ToString[1.23457*10^9, Slot[1]&] >   Is there some attribute I have to set to make it behave like the built-in forms? Is that even possible? Is there a workaround?