How do I constrain the region where I can drag a Locator?

How do I constrain the region where I can drag a `Locator` to conform to rules, including rules that apply to computations resulting from the value of the `Locator`? I understand how I can impose some very general constraints using `LocatorRegion`'s `Automatic` and `Full` settings, but these don't (appear to) allow me to:   1. Limit a single coordinate the `Locator` can assume, while allowing the other coordinates to cover the entire range of a plot.   2. Limit the coordinates `Locators` can assume based on a constraint placed on a function they generate. For example, in the following, code, how do (1) I constrain `c5` to the right hand edge of the figure (i.e to have an x value of 1) and (2) constrain all other `Locators` so that the resulting function never goes above the line y=x?               Manipulate[Show[       Plot[x, {x, 0, 1}],       ParametricPlot[f[{{0, 0}, c1, c2, c3, c4, c5}][x], {x, 0, 1}]],      {{c1, {.2, .2}}, Locator},      {{c2, {.4, .4}}, Locator},      {{c3, {.6, .6}}, Locator},      {{c4, {.8, .8}}, Locator},      {{c5, {1, 1}}, Locator},      {{f, BezierFunction, "Form"}, {BezierFunction, BSplineFunction}}]      That is, I want to prevent this, ![enter image description here](http://i.stack.imgur.com/g2qaE.png) by ensuring (1) that `c5` stays at x=1, while being free to assume a range of y values; and this ![enter image description here](http://i.stack.imgur.com/4wF2s.png) by (2) preventing any of the `Locators` from being moved to locations that would result in the generated plot from passing above the y=x line -- though a `Locator` may still be allowed above that line if this condition is not violated: ![enter image description here](http://i.stack.imgur.com/LSAqA.png)


Tridiagonal matrix for any n

I'm pretty new to _Mathematica_ and I need to figure out how to create a $n\times n$ tridiagonal matrix for any $n$. I don't have the slightest clue where to begin. Edit: got this far, not sure how to set it to nxn               SparseArray[{Band[{1, 1}] -> x, Band[{2, 1}] -> y,  Band[{1, 2}] -> z}, {5, 5}]     // MatrixForm


Using one table for multiple arguments

So I want to plot two graphs (on the same plot). One which is the $\frac{\sum_{i=0}^n x_i}{n}$ and the other $\frac{\sum_{i=0}^n x_i}{n-1}$ where x is a set created by `RandomInteger[{a,b},n]` and then have n slowly increase. I was wondering if this would be a sort of nice convergence plot over a large interval. The problem is as seen I want all of them to use the one {n,c,d} table for their iteration but Sum wants a copy, Plot wants a copy and RandomInteger wants the length of it. How can I use one of it for all of those?


Mapping and Interpolation

Does _Mathematica_ have a mapping function like scipy or any of the multidimensional ones? By this I mean something like mapping $[1,100]$ onto $[7,20]$ for example. Looking at Interpolate I only see interpolation with regards to estimating a line given points. To make it more clear I mean a simple example using a linear mapping would be $[0,512]$ onto $[0,10]$ would give 5 for a value of 256. Edited: (Comments added for greater precision):   1. What would make the question more clear? An example would be reading in a sensor that gives values on $[0,256]$ and using those to operate say a servo which accepts values on $[0,10]$   2. in this scale that is exactly what I'm looking for! thanks. Is it possible to use mappings of other orders, ex. a normal distribution or a quadratic mapping? This being a linear mapping. –


Map function on the specified location

list = Symbol /@ CharacterRange["a", "n"];     MapAt[Style[#, Red] &, list, List /@ {4, 9, 2}];     MapAt[Style[#, Green] &, %, List /@ {3, 5, 7}];     MapAt[Style[#, Blue] &, %, List /@ {8, 1, 6}]      ![enter image description here](http://i.stack.imgur.com/hKx4M.png) I am sure there is a better way do this, could you give any better ideas?


How to get the results of Tally split into two separate lists

This is a kind of a followup to my previous question. I am starting with a long list of plane coordinates, like this one:               lst = {{0.399933, 0.0904781}, {0.449966, 0.545239}, {0.724983, 0.27262},            {0.362492, 0.13631}, {0.681246, 0.0681549}, {0.840623, 0.0340774},            {0.920311, 0.0170387}, {0.960156, 0.00851936}, {0.480078, 0.00425968},            {0.240039, 0.00212984}, {0.370019, 0.501065}, {0.18501, 0.250532},            {0.0925049, 0.125266}, {0.546252, 0.0626331}, {0.273126, 0.0313166},            {0.636563, 0.0156583}, {0.568282, 0.507829}, {0.284141, 0.253915},            {0.39207, 0.626957}, {0, 0}};      Then I apply `Tally[]` as follows:               lst2 = Tally[Map[Round[#/(0.5)^2] &, lst]];      (The particular values 0.5 and 2 above are just examples) The result is a "ragged" list of the kind that compilers do not like:               {{{2, 0}, 3}, {{2, 2}, 2}, {{3, 1}, 1}, {{1, 1}, 3}, {{3, 0}, 3}, {{4, 0}, 2},      {{1, 0}, 2}, {{1, 2}, 1}, {{0, 1}, 1}, {{2, 3}, 1}, {{0, 0}, 1}}        My question is: What would be the most efficient way (compilable) to get the same result but in two separate uniform (tensor) lists rather than in one ragged list?


How to use mathematica to create school time-table?

I wonder if it is possible to use Mathematica for helping myself to create school timetable. I have a feeling that it requires quite simple optimization algorithm, but I have never been into optimization, so I don't really know where to start. The task looks like that:   1. I have a given free class rooms at certain time points.    2. I have an information about how much time and places require certain lessons    3. Also I do have some teacher preferences - some would prefer mornings, some evenings etc. Is there any function that would help solve that matter?


Combining an imported PDB file with a set of Graphics3D objects

Imagine we import a PDB file like so (using the example from ref/format/PDB in the help directory):               Import["http://www.rcsb.org/pdb/download/downloadFile.do?fileFormat=pdb&compression=NO&structureId=1tf6", "PDB", ImageSize -> Medium]      The help file says that it should be possible to treat the imported PDB image as a `Graphics3D` object, but I can't seem to get it to display with other `Graphics3D` objects after using `Import` with the specification:               Import["my_duplex.pdb", "Graphics3D"]      How would I scale and translate an imported PDB graphic and get it to display with other `Graphics3D` objects, like say a cylinder or sphere?


In a ListPlot of LinearModelFit, Fill to the regression line

In the help for LinearModelFit, the regression line can be added to the scatter plot like this:               Show[ListPlot[data], Plot[lm[x], {x, 0, 5}]]      Is it possible to fill from the points to the regression line? This can illustrate the distance whose sum of squares is being minimized. I tried variations on this:               Filling -> Table[ lm[data[[i]][[2]]],  {i, Length[data]}]]      Here the Table will be a list of predicted values for y at each observation of x, but this results in the error "not a valid filling specification."


How to make Missing[] invariant for some functions without redefining them

Missing[...] "is a symbolic object, with no default evaluation rules defined." Missing data can be tagged and enables use of filters like DeleteMissing. So it's worthwhile to normalize various types of missing values, like "" or "NA" to `Missing[...]`. EDIT: Suppose a set of functions `{foo,bar}` are interatively applied a data column that contains `Missing[]` elements. Unless the `{foo,bar}` are implemented to handle Missing, increasingly long unevaluated expressions `bar[foo[Missing[]]` are generated, which often throw `Dataset` Failures. Is there a global way to make `Missing[]` invariant, ie `f[m_Missing]` \--> `m`, for any `f` without actually overloading `f` on _Missing?


Voronoi Diagram: Displaying site specific color in a voronoi diagram

I am using Voronoi Poligonization as a support form simulating island erosion; my data are the output of `VoronoiDiagram`, `DelaunayTriangulation`, the starting point and the list of point that now are sea. I am not working whit `BoundedDiagram` so I made sure all unlimited poligons are in sea. Now I need to show this output like in `DiagramPlot`, but with sea cells colored blue, and land cells colored in brown.   Can you give me some code example or indications on where to search? More in general, I need to have a planar graph of which I know vertex coordinates and the edges, what function should I use to choose the color for the faces of the graph?


Incremental build in Workbench 2 Is it possible?

I am developing a package which currently has 129 symbols and 13 tutorials. Each time I run a build WB takes about 11 minutes to build the documentation files. Each time I make a small change in just one of the symbol pages or in one tutorial, I need to run a Build. Is it possible to "build" only some (selected) pages (symbol or tutorial) of the documentation, without having to rebuild everything else?


Balanced n-ary Base Representation

This may be a repeat question, but I was wondering how one would implement the expression/calculation of a representation of a given number h in base balanced n-ary, where n>1 is odd. (For example, for balanced quinary (5-ary), the digits are "+2", "+1", "0", "-1", "-2"). I see that BaseForm can be used to convert h into (non-balanced) n-ary, but how do you make it balanced?


Creating a R DataFrame like construct in Mathematica

I kept getting my data mixed up so I decided to see if I could construct a package adding a R DataFrame like construct to Mathematica. I managed to cobble something together that sort of works, but I've run into some snags. I decided to use replacement rules as the basic data structure for the dataframe. I was really the only solution I could think of that wouldn't be too convoluted to construct. What I have thus far package-wise is this:               BeginPackage["DataFrame`"]          CreateDataFrame::usage="CreateDataFrame[data] creates a data frame out of the data table. It assumes the first row is the header."          FrameNames::usage="Names[dataframe] gives the header names of the dataframe."          Begin["`Private`"]          CreateDataFrame[data_]:=     Dispatch@Table[         Rule[i,Rest@First@Select[Transpose@data,First@#==i&]],         {i,First@data}     ]          FrameNames[dataFrame_Dispatch]:=Table[dataFrame[[1,i,1]],{i,Length@dataFrame[[1]]}]          End[]          EndPackage[]      I also tried to created some custom notation to access parts of the dataframe but I haven't yet figured out how to get it to work when using a package:               Needs["Notation`"]     Notation[ParsedBoxWrapper[     RowBox[{"x_Dispatch", " ", "$", " ",           "y_String"}]] \[DoubleLongRightArrow] ParsedBoxWrapper[     RowBox[{"ReplaceAll", "[",      RowBox[{"y_String", ",", "x_Dispatch"}], "]"}]]]      So I have a number of problems I was hoping someone here could help me with: How would I go about defining the custom notation from within the package. Currently I have to define it in the notebook to get it to work? Could I somehow give the dataframe a custom head of `DataFrame`, preferably without breaking anything? Is there any way to make the formatting of the output of `CreateDataFrame` nicer? While the `FrameNames` function works as it is I feel it would be more Mathematica-like if it were possible to access it like this instead: `dataframe["Names"]`, but I'm not sure how to make it so. The custom notation I defined with `$` sort of works it is still a bit awkward. To use it I have to make sure I manually include the space between that dataframe name and the `$`, as well use quotation marks for the variable name. Any ideas for streamlining it more would be wonderful. Then there is the performance side. The performance isn't terrible, but it is not great either, especially not when creating the dataframe. Any possible recommendations for improvements here would always be appreciated. P.S. I realise I am piling on a bunch of questions here but I suspect there is a lot of overlap in the answers to them and so splitting the questions up into separate posts would not be helpful.


Why is MenuCommandKey not working in my stylesheet?

Here is the cell style data for my custom version of Section:               Cell[StyleData["Section"],      MenuCommandKey->"1",      MenuSortingValue->10000,      CellFrame->{{0, 0}, {0, 0}},      CellMargins->{{10, Inherited}, {8, Inherited}},      CellFrameMargins->1]      But when I type command+1 I still get the old red Title cell. ![enter image description here](http://i.stack.imgur.com/8nND0.png)


Automatically check student answers in tests

I am a physics teacher and I am looking for a way to create homework assignments within Mathematica so that each problem has an input field that students can use to check their answers. For example, if the problem reads "What is the integral of 2x^2" I want an input field immediately after the question that students can type their answer into. If they type in the correct answer, it will confirm that it is right where as if it is not right it will tell them it is incorrect. Anyone have any ideas of how I could do this?


How do I plot a Taylor polynomial of various degrees in two variables?

I want to plot the Taylor polynomials of $f(x,y)= Sin(1 + x + y^2)/(4 + x^2 + y^2)$ of degrees 4 and 7 around the point $(0,0)$ over the rectangle $[-\pi,\pi]\times [-\pi,\pi]$ I am currently using               Plot3D[      Series[(Sin(1 + x + y^2))/(4 + x^2 + y^2), {x, 0 , 4}, {y, 0, 7}],       {x,-pi, pi} , {y, -pi,pi}]      Nothing actually happens. I also tried just computing the points and then graphing those, but I have quite a few of these plots to do and it seems like a hassle. Anyone have any ideas?


Discard ODE singular solutions with Mathematica?

The solution for a homogeneous second order linear ODE is generally a constant times one function plus another constant times a different function. Sometimes one of the solution functions is singular, i.e. it blows up for some value of the independent variable. An example is Bessel's ODE. If one is just looking for nonsingular solutions, is there some way to have Mathematica discard the singular function so that the required solution is nonsingular? This would be helpful in the case where a large number of ODE's are generated. Otherwise there is a lot of human intervention needed to proceed. In my case, I have the ODE's, and the specific solutions found by DSolve with the singular solutions obvious by inspection. I just want to see if Mathematica can be used to remove the singular solutions.


Why does show combined plots and graphics fail in CDF Player but not in Mathematica?

The question is, how might I get the following script working as a CDF demo of complex inversion in a circle? It works fine in my home edition of MMA 8 run on OS X Mavericks. When saved as a CDF file and opened with the CDF Player, it produced an error: Show::gcomb: "Could not combine the graphics objects in Show[{circleK,circleAPlot[2\ oCircA],circleBPlot[2\ oCircA],invLineGraphics[2\ oCircA],invAVGrPts[2\ oCircA],invLVGrPts[2\ oCircA],caption},labels[2\ oCircA],Axes->False,PlotRange->{xBnds,yBnds},Background->GrayLevel[1]]" SaveDefinitions -> True has no visible effect. Normally, I would simplify for a question like this, but having scant experience with CDF files, I don't really know where to begin, and perhaps the comments and labels will help to reveal the structure of the program.               Clear["Global`*"]          (* CONSTANTS *)          radCircA = 1/4; (* Radius of A *)          oCircA = (1+I)/(4 Sqrt[2]); (* Center of A *)          radR = 1; (* Radius of K *)          q = 0; (* Center of K *)          (* PLOTTING BOUNDARIES *)          bnds = 4;          xBnds = {-bnds,bnds};          yBnds = {-bnds,bnds};          (* FUNCTIONS *)          (* THE POINT OF THE PLOT IS TO DEMONSTRATE THE BEHAVIOR OF THIS FUNCTION, Subscript[I, k](z), R = 1 *)          zInv[z_,q_,R_]:=(q Conjugate[z] + (R^2 - Abs[q]^2)/(Conjugate[z]-Conjugate[q]))          (* CONVERT COMPLEX TO VECTOR w REAL ELEMENTS *)          v[z_]:={Re[z],Im[z]};          (* CIRCLE WITH ORIGIN AT q AND RADIUS OF radR *)          circleK := Graphics[Circle[v[q],radR]];          (* CALCULATE COMPLEX POINTS OF CIRCLE A AND USE TABLE TO CREATE LIST OF POINTS *)          circleATable[centerA_] := Table[radCircA Exp[I \[Theta]]+centerA, {\[Theta], 0, 2Pi, .1}];          (* INVERT COMPLEX POINTS OF CIRCLE A BY MAPPING zInv[] TO LIST OF COMPLEX POINTS; RETURNS A LIST *)          circleBTable[centerA_] := zInv[#,q,radR]&/@circleATable[centerA];          (* MAP LISTS OF COMPLEX POINTS TO LISTS OF VECTORS *)          circleAVectors[centerA_] := v[#]&/@circleATable[centerA];          lineBVectors[centerA_] := v[#]&/@circleBTable[centerA];          (* CREATE LINE PLOTS FROM LISTS OF VECTORS *)          circleAPlot[centerA_] := ListLinePlot[circleAVectors[centerA],AspectRatio->1,PlotStyle->{Blue}];          circleBPlot[centerA_] := ListLinePlot[lineBVectors[centerA],AspectRatio->1,PlotStyle->{Blue}];          (* INVERSION POINTS IN A, SHOWN WITH RED DOTS AND ARROWS *)          invAngles := Range[Pi/4, 3Pi/4, Pi/8];          invACPts[centerA_] := (radCircA Exp[I (#-Pi/4)]+centerA)&/@invAngles;          invLCPts[centerA_] := zInv[#,q,radR]&/@invACPts[centerA];          invAVGrPts[centerA_] :=Graphics[{Red,Point[v[#]]}&/@invACPts[centerA]];          invLVGrPts[centerA_]:= Graphics[{Red,Point[v[#]]}&/@invLCPts[centerA]];          invLineObjs[centerA_] := {Gray, Dashed,Arrowheads[.02],Arrow[{v[0],v[#]}]}&/@invLCPts[centerA];          invLineGraphics[centerA_] := Graphics[invLineObjs[centerA]];          (* LABELS *)          labelK=Text[Style["K", Bold, 12], v[-.5-.5I]];          labelA[centerA_] := {Blue,Text[Style["A", Bold, 8], v[centerA]]};          labelB[centerA_] :={Blue,Text[Style[If[Abs[centerA] == Abs[oCircA], "B = L","B"], Bold, 8], v[zInv[centerA +radCircA Exp[I  Pi/4],q,radR]+.2+.2I]]};          labelq = Text[Style["q", Bold, 12], v[0]-{.1,.1}];          (* CONVERT TEXT PRIMITIVES TO GRAPHICS OBJECTS *)          labels[centerA_] := Graphics[{labelK, labelA[centerA], labelB[centerA],labelq}];          caption = Graphics[{Text[Style["Complex inversion of circle A in unit circle K\nto circle B or to line L if origin q of K in A\nSubscript[I, k](z) =(q Overscript[z, _] + ((R^2)-|q|^2) )/(Overscript[z, _]-Overscript[q, _]), R=1", Bold,12], v[-2.2I]]}];          (* GRAPHICS AND PLOTS COMBINED USING SHOW; LAST ITEM IN TRUMPS PREVIOUS *)          Manipulate[     Show[{circleK,circleAPlot[offset oCircA],circleBPlot[offset oCircA],invLineGraphics[offset oCircA],invAVGrPts[offset oCircA],invLVGrPts[offset oCircA],caption,labels[offset oCircA]},Axes->False,PlotRange->{xBnds,yBnds},Background->White],     {{offset,2,"origin A multiplier"}, {3,2.5,2,1.5, 1, .5, 0,-.5}}     ]


For-loop only executes first line in body

I have a simple For[] loop:               For[rPos = 0, rPos<=(2 N[Pi]), rPos += radiusInc,         zPotential = 0;         xPos = rDistance Cos[rPos];         yPos = rDistance Sin[rPos];         zPos = planeDepth;         AppendTo[zField, {xPos,yPos, zPos, zPotential}];          ];      The only line of the body that is executed is:               zPotential = 0;      At the end, zField has zero items. If I set a breakpoint on the second or third line it never hit. I know that For[] and Do[] loops are discouraged, but I do not see the cause of this problem.


I get weird <<...>> symbols in my output — what does it mean?

After I input the following:               data = Table[{3 + i + RandomReal[{-3, 7}],      i + RandomReal[{-2, 5}]}, {i, 1, 20}];          model = LinearModelFit[data, x, x]      I got something weird:               (*   FittedModel[-1.65238+<<19>>x]     *)      Does anyone know what `<<19>>x` means?


Expressions like <<1>>

In a function where I call the `Maximize` function, I am getting an error that says               "The function value -0.956338\ (Abs[<<1>>]^3+Abs[0.918621 (<<1>>)+<<19>> (<<1>>)]^3)^(1/3) is not a number at {x$16906[1.],x$16906[2.]} = {0.9186212148724066`,0.7166887533790196`}"      What does the expression <<1>> mean?


Determine frequency of oscillations

I am wondering how I could determine the frequency of oscillations of a differential model equation? How could I find the frequency from this example given in _Mathematica_ Documentation:               s = NDSolve[{y'[x] == y[x] Cos[x + y[x]], y[0] == 1}, y, {x, 0, 30}]     Plot[Evaluate[y[x] /. s], {x, 0, 30}, PlotRange -> All]      ![Mathematica graphics](http://i.stack.imgur.com/3ofHF.png) I am asking because I need to determine the frequency of one model term as a function of a the strength of a second model term, in a much more complicated model than described above.


Circular Orbit Velocity in Vector Components

I'm trying to find out how to calculate the initial velocity needed to keep a spacecraft in a circular orbit around the Earth given its initial position and an initial angle theta in a Cartesian coordinate system. I know the formula for the magnitude of a circular orbit is $v_{\mathrm{circular}} = \sqrt{GM/r_{\mathrm{orbit}}}$ but this only works nicely as it is (i.e. in its magnitude form) if the orbital radius vector makes an angle of 0, 90 or 270 degrees in a Cartesian coordinate system. What I want to do is be able to use the formula for any angle $\theta$. As an example, let's say I have a spacecraft at a radius of 300000 meters above the Earth's surface and its radius vector makes an angle of 45 degrees in an x-y Cartesian coordinate system. Then we have $r = r_{\mathrm{earth}} + 300000$, whereby $r_x = r \cos(45^\circ)$ and $r_y = r \sin(45^\circ)$. Here's a little picture I made to better understand the problem: ![enter image description here](http://i.stack.imgur.com/fJAOy.png) If theta = 45 degrees, then I get a nice circular orbit, but any other value of theta gives me very undesirable results (i.e. the spacecraft crashes into the planet or flies of into the cosmos) Does anyone know what I'm doing wrong?               G = 6.672*10^-11;     m[1] = AstronomicalData["Earth", "Mass"];     tmax = 20000;     r[1] = AstronomicalData["Earth", "Radius"];     rx = (r[1] + 300000 ) Cos[45 Degree]     ry = (r[1] + 300000 ) Sin[45  Degree]     vx = Sqrt[(G  m[1])/(r[1] + 300000)] Cos[45  Degree]     vy = Sqrt[(G  m[1])/(r[1] + 300000)] Sin[45  Degree]          soln = NDSolve[{     x''[t] == -((G  m[1] x[t])/(x[t]^2 + y[t]^2)^(3/2)),     y''[t] == -((G  m[1] y[t])/(x[t]^2 + y[t]^2)^(3/2)),           x[0] == rx, y[0] == ry,      x'[0] == vx, y'[0] == -vy}, {x[t],      y[t]}, {t, 0, tmax} , MaxSteps -> 1000000,      Method -> "StiffnessSwitching"]          Show[ParametricPlot[Evaluate[{x[t], y[t]} /. soln], {t, 0, tmax},      AxesLabel -> {x, y}, PlotStyle -> Automatic, PlotRange -> Full,      ImageSize -> Large], Graphics[{Green, Disk[{0, 0}, r[1]]}]]


What is wrong with my expression for compiling?

Following code was translated from a snippet matlab code. Without compiling it worked slowly. I want to compile it, but am getting a numerical error. How do I compile this in a correct way? ![enter image description here](http://i.stack.imgur.com/Vlkx6.png)                data = Compile[{},            Table[(1/49 1. x^2 Sqrt[Abs[Abs[x] - 3]/(Abs[x] - 3)] +                1/9 y^2 Sqrt[ Abs[y + (3 Sqrt[33])/7]/(y + (3 Sqrt[33])/7)] -                1) (Abs[x]/2 - 1/112 (3 Sqrt[33] - 7) x^2 - 3 +                Sqrt[1 - (Abs[Abs[x] - 2] - 1)^2] -                y) (9 Sqrt[Abs[(Abs[x] - 1) (Abs[x] - 0.75)]/((1 - Abs[x]) (Abs[x] -                  0.75))] - 8 Abs[x] - y) (3 Abs[x] +                0.75 Sqrt[ Abs[(Abs[x] - 0.75) (Abs[x] - 0.5)]/((0.75 -  Abs[x]) (Abs[x] -                0.5))] -  y) (2.25 Sqrt[ Abs[(x - 0.5) (x + 0.5)]/((0.5 - x)               (x + 0.5))] -  y) ((6 Sqrt[10])/ 7 + (1.5 - 0.5 Abs[x]) Sqrt[                 Abs[Abs[x] - 1]/(Abs[x] - 1)] -               3/7 Sqrt[10] Sqrt[4 - (Abs[x] - 1)^2] - y),              {y, 4.5, -4.5, -0.041}, {x, -7, 7, 0.041}]           ][] // Abs // Log;     ArrayPlot[data]


Plotting a function only non-zero for discrete values of argument

I have a function like: $$ f(E)= \Sigma_{n=0} \Sigma_{\ell=0} \, \delta\left(E+\frac{\ell+2n+2} {R\sec{\rho}}\right) w(n,\rho,\ell)\,, $$ i.e. the function is zero unless $$ E=-\frac{(\ell+2n+2)}{R\sec{\rho}} $$ and $(n,\ell)$ can take only integer values from zero (the function $w$ is boring and not important for the problem, and $\rho$ and $R$ are just constants.). How can I use Mathematica to plot this function against $E$? 1) I was thinking of use `Solve` with the domain `Integers` to spit out the (one or) two pairs of $(n,\ell)$ corresponding to each integer value $m=-(\ell+2n+2)$. Then I know that $E_m=-m/(R\sec{\rho})$, and I can compute $f(E_m)$ by summing the (one or) two corresponding $w(n,\rho,\ell)$ functions. Finally I can make a `ListPlot`. This didn't quite work as `Solve` spits out these `ConditionalExpression`s rather than `Integers` for some reason. Any other ideas? The `Solve` code I was using: (for example with $m=-7$)               Solve[7 == ell + 2 n + 1, {ell, n}, Integers]


Which methods are available for NMinimize?

I can't find in the documentation the list of methods available to `NMinimize[]`. Is there a way to get this? The NMinimize page in Documentation Center mentions only `Method -> "DifferentialEvolution"`.


Partial factorization of multivariate polynomials in terms of given polynomials

I have calculated several homogeneous polynomials in 4,5 or 6 variables $t_1,\dots,t_6$.   I would like to rewrite them as a sum of products of specific lower degree polynomials, which have a meaning in the problem I'm solving. For example, the simplest polynomial I have is $$ P_4(t_1,t_2,t_3,t_4) = t_1t_2+t_1(t_3+t_4)+t_2(t_3+t_4) $$ which I would like to express in terms of $t_1+t_2, t_2+t_3+t_4, t_1+t_3+t_4$ (only them, although not necessarily all of them). For example, it's easy to see that $$P_4(t_1,t_2,t_3,t_4) = (t_1+t_2)(t_2+t_3+t_4) - t_2^2$$ but I'd prefer something like $$P_4(t_1,t_2,t_3,t_4) = a(t_1+t_2)(t_2+t_3+t_4) + b(t_1+t_2)(t_1+t_3+t_4) + c(t_1+t_3+t_4)(t_2+t_3+t_4)$$ **Question** : Is there a way to ask Mathematica this sort of partial factorization? Thank you in advance! _Note_ : I don't know if a solution exists for my exact polynomials (maybe I have to search for a different interpretation), but I think the general problem is interesting in its own right.


Does Mathematica allow you to change the shape of your graph? Say I use a sin or cos function or some sort of function, do they allow you to change the amplitude or phase shift on the graph? would you manipulate this of some sort?


Superscript prime symbol

`x\[Prime]` looks like $x_'$, ugly right? Is there a way to make a symbol with prime to look like $x'$? * * * That's what I'm trying right now:               Notation[ x_', Primed[x_]]     Primed[x_] := Symbol[SymbolName[x] <> "\[Prime]"]      But how then I use it in patterns? If I do this:               f[q_, q':_] := q + q'      Weird syntax errors appear:               Syntax::sntxf: "T[r_," cannot be followed by "q':_]".     Syntax::tsntxi: "q':_" is incomplete; more input is needed.     Syntax::sntxi: Incomplete expression; more input is needed .      If we replace `q':_` with `Pattern[q',_]` another error:               Pattern::patvar: "First element in pattern Pattern[q',_] is not a valid pattern name. "      But `Head[q']` returns `Symbol` and `Pattern` requires a `Symbol` as first parameter. What is wrong?


Matrices and polynomials: MMA 8 vs. 9?

I want a function to take a polynomial from a list, plug a certain matrix _T_ into that polynomial, and return the answer as another matrix. My program uses the _applyPoly_ function suggested by a user in response to: http://stackoverflow.com/questions/17394035/in-mathematica-how-calculate-pa- where-p-is-a-polynomial-and-a-is-a-square-mat Here is my code:               applyPoly[poly_, var_, A_?MatrixQ] :=        With[{c = CoefficientList[poly, var]},          c.MapIndexed[MatrixPower[A, #2[[1]] - 1] &, c]]          Compute[a_, b_, c_] := (       p[x_] := x^4 - c*x^3 - b*x^2 - a*x;        T := {{0, 0, 0, 0}, {1, 0, 0, a}, {0, 1, 0, b}, {0, 0, 1, c}};        L := FactorList[p[x]]; s = Length[L]; R = {};        Do[R = Append[R, Simplify[p[x]/L[[i + 1, 1]]]], {i, s - 1}];        u = Length[R];        Do[r[x_] := R[[i]]; Print[applyPoly[r[x], x, T]], {i, u}])          Compute[1,2,3]      In Mathematica 8, this returns the correct matrix output:               {{-1,0,0,0},{-2,0,0,0},{-3,0,0,0},{1,0,0,0}}          {{0,0,0,0},{1,0,0,1},{0,1,0,2},{0,0,1,3}}      But in Mathematica 9, I get an error: > Dot::rect: Nonrectangular tensor encountered. >> > > {-1,-2,-3,1}.{MatrixPower[{{0,0,0,0}, > {1,0,0,1},{0,1,0,2},{0,0,1,3}},0],{{0,0,0,0}, > {1,0,0,1},{0,1,0,2},{0,0,1,3}}, {{0,0,0,0}, {0,0,1,3},{1,0,2,7}, > {0,1,3,11}}, {{0,0,0,0}, {0,1,3,11}, {0,2,7,25}, {1,3,11,40}}} > > Dot::rect: Nonrectangular tensor encountered. >> > > > {0,1}.{MatrixPower[{{0,0,0,0},{1,0,0,1},{0,1,0,2},{0,0,1,3}},0],{{0,0,0,0},{1,0,0,1},{0,1,0,2},{0,0,1,3}}} I understand that 8 and 9 must handle matrix or list objects in different ways. What is the difference, and how can I alter my program so that it works in 9?


Making axis numbers larger on Mathematica plot

I want the numbers along the axis to be larger than the default value. Can this be done? The reason I am asking is because I frequently make charts in _Mathematica_ and use them in Word. I export the charts as bitmap files and then paste the images in Word. The default text size for the axis is too small to be as clearly legible as I would like them to be when the chart is in bitmap form. My problem would be solved if   * there is a better way to use _Mathematica_ charts in Word   * I can get larger text numbers along the axis of the chart . As an example, the following gives a plot of $\sin(x)$. How do I make the numbers on the axis larger in size?               Plot[Sin[x], {x, 0, 22}, PlotLabel -> Style["sin(x)", FontSize -> 18],         Background -> LightYellow]


What algorithms does NSolve use?

I've been using `NSolve` to find roots and now I've been wondering what underlying algorithm mathematica uses. It's probabaly similiar to `FindRoot` so is it the _Newton-Raphson_ method?   In class we've been told that it probably is a mix of the _Newton-Raphson_ and the bisection methods.


When I evaluate this code:               RSolve[{y[0] == y0, y[t + 1] == (1 - (t + 1)/100) y[t]}, y[t], t]      I get an RSolve::bvnul error. I don't understand why. Yet, if I run this code, I get the sequence I want.               FoldList[#1 (1 - #2) &, 1, Range[1/100, 1, 1/100]]      The motivation for this problem is a discrete mortality model in which hazard increases in a linear way until age 100. I'd like a closed form solution for the sequence for an arbitrary maximum life span.


Problem with SerialIO package and Lego NXT

I'm following a guide from The Mathematica Journal that describes how to use Mathematica with the Lego Mindstorms NXT but have some trouble getting started and got stuck with the SerialIO package. I use Mac OSX and I have installed the package to:               /Applications/Mathematica.app/AddOns/ExtraPackages/SerialIO/      The command `Needs["SerialIO`"]` gives me the following error message:               LinkOpen::linke: Could not find MathLink executable.      And trying               SetDirectory[FileNameJoin[{$InstallationDirectory, "AddOns", "ExtraPackages", "SerialIO", $SystemID}]];      Does not help either, it gives:               SetDirectory::cdir: Cannot set current directory to /Applications/Mathematica.app/AddOns/ExtraPackages/SerialIO/MacOSX-x86-64.      There seem to be some problem with the alias/symbolic link in the SerialIO folder. By default they pointed to an absolute directory on the machine that this library was built on:               MacOSX-x86-64 -> /Files/schofield/Packages/SerialIO/Build/Mac/build/Deployment/Package/SerialIO/MacOSX      I tried deleting the alias and creating a symbolic link in the terminal:               # ln -s MacOSX MacOSX-x86-64      Running the `SetDirectory` command again result in... no result, so I guess thats good. The commands seem to have been loaded as when typing _Serial_ it want to autocomplete to `SerialOpen` etc. However, using the command `mybrick = SerialOpen["NXT"]` does not put the NXT in connected mode (<> on NXT display). Does anyone else got it to work?


Finding Local Minima / Maxima in Noisy Data

I'm trying to find local minima / maxima in noisy data, consisting of data values taken at certain time intervals. Ideally, the function should take a pair of lists (one containing time values and one containing observed data values) and return the coordinates of the maxima and minima. An example of the data is found below:               temptimelist = Range[200]/10;     tempvaluelist = Sinc[#] &@temptimelist + RandomReal[{-1, 1}, 200]*0.02;      While the questions here, here and here have a good range of answers, they don't fit with my requirements since (as far as I can see) they determine whether data is a local maximum / minimum by comparing it with the adjacent values. If I apply such an algorithm, my extrema will be identified as follows: ![data with peaks identified](http://i.stack.imgur.com/Zm2sX.png) What I've done is to write the following code.               NoisyExtremaFinder = Function[{timeList, valueList, aroundRange},        (*NoisyExtremaFinder[] takes a pair of lists timeList_ and valueList_ and determines extrema in valueList_, returning a list containing the coordinates (as pairs of time_ and value_) of the minima as the first entry and the maxima as the second entry.              As the data is assumed to be noisy, we provide the option aroundRange_ to allow the user to determine the sensitivity of the search. Specifically, when aroundRange_=n, the function will compare each value with the preceding and subsequent n values to determine whether it is an extrema*)             extremaPosition =          Flatten@Position[            Map[#, Partition[valueList, 2*aroundRange + 1, 1, {-(1 + aroundRange), 1 + aroundRange}, {}]] - valueList, 0.] &;         (*extremaPosition[] is a custom function that determines the position of local Maxima or Minima in valueList_, with the sensitivity determined by the value of aroundRange. When aroundRange_=n, the function will compare each value with the preceding and subsequent n values to determine whether it is an extrema. You can either do extremaPosition[Max] or extremaPosition[Min] *)             extremaPoints =          Transpose@{timeList[[#]], valueList[[#]]} &@extremaPosition[#] &;       (*extremaPoints[] is a custom function that determines the coordinates of local Maxima or Minima in valueList_             Custom Functions Used: extremaPosition[]*)             {extremaPoints[Min], extremaPoints[Max]}];      Basically, instead of deciding whether a point is an extrema by comparing it only with adjacent terms, it decides whether the point is an extrema by comparing with the `aroundRange` preceeding and `aroundRange` subsequent points. Then, by adding the following lines of code, we can see the final results:               NoisyExtremaFinder[temptimelist, tempvaluelist, 10]; (*parameter "10" chosen by estimating the distance from peak to peak*)     ListPlot[Transpose[{temptimelist, tempvaluelist}],       Epilog -> {PointSize[Medium], Red, Point[extremaPoints[Min]], Green,         Point[extremaPoints[Max]]}, ImageSize -> 700]      ![better peaks](http://i.stack.imgur.com/ViK9c.png) > Is there any better way to code to achieve the goal I have in mind of > comparing a point with `n` preceeding and subsequent points? > > I was also advised by rm-rf (in chat) to consider smoothing the noisy data > first before trying to find the local minima / maxima. However, I was > concerned that I could add unwanted artifacts into the data by the smoothing > process. With regards to smoothing, is there an algorithm that is commonly > used to filter experimental data? Filters that I have looked at include the > Savitsky-Golay filter and the Low-Pass filter. PS: My data sets have around 10,000 data points each.


Another one problem with legends on GraphicsGrid

I have used ListLinePlot to generate this grid of plots: ![enter image description here](http://i.stack.imgur.com/P4KfG.png) and I want to add a legend in Row Layout below this grid. My code, has as follows:               graphs = Table[        ListLinePlot[         Table[Transpose@{vdd, power[[i, j, All]]}, {j, 1, Wl}],         PlotLabel -> "T=" <> ToString[T[[i]]] <> "\[Degree]C",         Frame -> {{True, False}, {True, False}},         FrameLabel -> {"\!\(\*SubscriptBox[\(V\), \(DD\)]\)(V)","P(nW)"},         AspectRatio -> 1/GoldenRatio,         ImageSize -> Medium         ],        {i, 1, Tl}];     a = {graphs[[1 ;; 3]], graphs[[4 ;; 6]]};     grid = GraphicsGrid[a, Spacings -> Scaled[0],         AspectRatio -> 0.6/GoldenRatio];      where vdd[[...]], W[[...]], T[[...]],power[[...,...,...]] are lists with the measured values and each colored curve in the above plots, corresponds for a different (but known) value of W. I was thinking to use               Column[{grid,        LineLegend[{...colors...}, Table[ToString[W[[n]]]<>"nm",{n,1,Wl}],         LegendLayout -> "Row"]}]      but I cannot generate the default colour pallete, which Mathematica uses. Also, I need the legend to be justified to the center (presentation purposes, as you can see). Any help please?


Restrict MousePosition to specific Graphics object

I have a problem using `MousePosition`. I want to restrict the value returned by `MousePosition` to a specific Graphics object. Consider the following example:               g1 = Graphics[{Green, Disk[]}];      g2 = Graphics[{Blue,Disk[]}];     {g1, g2, Dynamic[MousePosition["Graphics"]]}      I would like to have the mouse position updated only if the mouse is on the second (blue) disk and not on the first one (green). This seems to be an easy problem, but I can't figure out how it works in _Mathematica_. Thanks for help!


How to apply function f for each time value t, to each pixel from image, resulting in t images

I have a 2D array of complex values and I want to apply a function to every entry of the array, for every timepoint t in a list. I know how to apply my function to one entry for every time t in a list, and I know how to apply my function for one t to every entry in an array. (I keep finding answers to those problems when searching with google and on SE) Somehow I cant get both to work at the same tim, and I cant find an explanation of how to do it either. Maybe someone has experience in doing this? Example:               In:     function[source_, t_] := source(1+Sin[2Pi*t]);     lena = Import["ExampleData/lena.tif"];     size = ImageDimensions[lena];     data = ImageData[lena];     times = Table[i, {i, 600}]/10;     complexred = Fourier[data[[1;;size[[2]],1;;size[[1]],1]]];     newdata = function[complexred, times];          Out:     Thread::tdlen : Objects of unequal length in      {{...some complex values here...}{<<1>>},<<48>>,<<430>>} cannot be combined.      Thanks!


Ranking Function Allowing for Ties

I have a list that I need to be able to assign ranks to individual elements in, giving it a number related to its position if the list were to be sorted, allowing for ties. For example, `{ 6, 3, 3, 6, 4, 4, 6, 4}` would be transformed to `{ 1, 3, 3, 1, 2, 2, 1, 2}` or `{ 3, 1, 1, 3, 2, 2, 3, 2}` depending on if I were sorting for higher values or lower values. This is for a variant on PageRank, in which after assigning each point or edge a value, the set of all edges or points is ranked, with the highest ranked point(s) getting the number 1, the second highest point(s) getting 2, and so on. I have tried using `Sort` and other approaches, but have not encountered anything that could be described as elegant.


How to use the circledot in 3 (or any) series in ListPlot?

How to use the dots in the 2 series, with diferent color?. I know use symbols "O" instead of Automatic... but... tu use de dot?               a3={2,3,4,5};     a4={6,2,3,6};     ListPlot[{a3, a4}, PlotMarkers -> {Automatic, Medium}]


Obtaining EditDistance[] from a List of Strings

Consider the following question. I have a long selection of files (some 5,000), arranged linearly, and I want to view to what degree the files have changed between each other. For a small example, here are some (nonsensical) strings:               string1 = "i am a cheese ball";     string2 = "i am a cheese bull";     string3 = "i am a cheese frog";     string4 = "i am a cheesy frog";     string5 = "i am a cheesy frog";     string6 = "i am a cheesy curd";     stringlist = {string1, string2, string3, string4, string5, string6};      Here is how to manually get my answer, which is `{1,4,1,0,4}`:               list = {EditDistance[string1, string2],        EditDistance[string2, string3], EditDistance[string3, string4],        EditDistance[string4, string5], EditDistance[string5, string6]}      There must be an automated solution, however, that moves through the list and gets the `EditDistance[]` between each set of things (i.e. 1 to 2, then 2 to 3, then 3 to 4, then 5 to 6, etc.). Outside of a convoluted set of `Do[]` loops, however, I can't find the proper command. I suspect the issue is that I'm having trouble expressing mathematically what I want to do here.


How to embed an image into a string?

**Note:** The bug described in the post is in _Mathematica_ 9, and has been fixed in 10.0. The documentation for `String` contains the following statements: > Strings can contain any sequence of ordinary and special characters:   >  …   >  Strings preserve internal formatting:   >  …   >  Strings can have any expression embedded:   >  …   >  `"ab \[Integral]\!\(\*FractionBox[\(1\), \(x\)]\)\[DifferentialD]x cd"` > > Strings can contain graphics:   >  …   >  `"ab \!\(\*\nGraphicsBox[DiskBox[{0, 0}],\nImageSize->{34., Automatic}]\) > cd"` So I assumed that an image could be inserted anywhere in the string. I tried to copy images in different ways:   * from other _Mathematica_ notebook cells, explicitly `Import`ed before   * from web pages opened in a browser   * from image editors e.g. _Paint_   * taking screenshots and paste them into expressions (as list elements, function arguments etc) and it all worked perfectly well. But when I try to paste images into string literals, then the string looks good (with the image embedded) in the input cell, but the expression gets corrupted when evaluated -- it is not even a `String` anymore:               (* In[1]:= *) logo = Import["http://wolfram.com/favicon.ico", "Image"]     (* Out[1]= *) ![](http://wolfram.com/favicon.ico)          (* In[2]:= *) Shallow["Mathematica ![](http://wolfram.com/favicon.ico)", 1] (* The image was copy-pasted from the previous cell *)     (* Out[2]//Shallow= *) Times[<&lt5;>>] **Question 1:** Is it a bug? It is interesting that inserting plots into string literals works well. I need a solution to insert images into strings programmatically. It could also serve as a workaround for this bug. I was not able to find a built-in function that does exactly this, so I tried to use `"\!\(\*…\)"` markup mentioned in the documentation for `String`. I was not able to find a documentation for this markup, so I started experimenting. **Question 2:** Is there a complete documentation for this markup? After several attempts, I ended up with the following function:               (* In[3]:= *) imageToString[image_Image] :=          "\!\(\*" <> ToString[ToBoxes[image], InputForm] <> "\)";          (* In[4]:= *) "Mathematica " <> imageToString[logo]     (* Out[4]= *) Mathematica ![](http://wolfram.com/favicon.ico)      It seems to do what I need. **Question 3:** Are there any shortcomings in my implementation? Is there a more simple/standard way to do this?


Plotting a pattern made of repeating unit blocks but of changing width

I am plotting a pattern as illustrated in link shown below. I want to create an image of fixed size. The whole image should be filled by repeating unit blocks which consist of black and green regions. The width of a unit block and its black region change from `0` to `100` (or even larger values), and from `1` to `0`, respectively. The ratio between a black region and a unit block is given as `1.055^(-lambda0)`. More preferably, the width of a unit block changes randomly from `Lambda0(1 - errorfactor)` to `lambda0(1 + errofactor)`, so that the average value of the unit blocks are still `lambda0` but each individual block may vary slightly. ![diagram](http://i.stack.imgur.com/jZJvh.jpg)


Matching parentheses size in plot labels

I am attempting to do a seemingly-simple task: label ordered pairs in a `Plot` that display with parentheses that grow to match the expression within. I've trawled the documentation and searched the posted questions here to no luck. The problem is that parentheses are internally special, so they are very difficult to force into a displayed expression. I can use something similar to `Graphics[Text[f[0,1/2]]]` and the resulting output form has correctly-sized parenthesis, albeit with the pesky `f`. I can use any bracketing operator to achieve the same result, e.g. `Graphics[Text[\[LeftAngleBracket]0,1/2\[RightAngleBracket]]]`, but no luck with parentheses. Am I missing something incredibly simple?


Split one string about a fixed width with `SyntaxQ=True`

How to split one string about a fixed width, the string may come from the input or output cell of Notebook. sample string               samplestring="{\"a,b,{4, 6, 8, 2, 1}\", \"a,b,{4, 2, 1, 10, 3}\", \"a,b,{2, 8, 7, 4}\", \\\r\n\"a,b,{8, 7, 9, 0, 5}\", \"a,b,{6, 9, 10, 3, 7}\", \"a,b,{2, 9, 9, 4, 2}\", \\\r\n\"a,b,{1}\", \"a,b,{0, 3, 4}\", \"a,b,{}\", \"a,b,{1, 5}\", \"a,b,{6, 10, 9, \\\r\n1, 8}\", \"a,b,{2, 7, 10}\", \"a,b,{3, 1, 2}\", \"a,b,{3, 10, 0}\", \"a,b,{2, \\\r\n1, 8, 6}\", \"a,b,{8, 5}\", \"a,b,{3, 8}\", \"a,b,{0, 10, 10, 5}\", \\\r\n\"a,b,{8}\", \"a,b,{10}\"}"      The tricky is to make substrings `SyntaxQ` True as much as possible. And the final substring's `StringLength` should not greater than the fixed width unless width is too small. My little try, seems not so easy as my first thought, maybe I'm too fool. And maybe someone asked before.               strGet[str_ , width_:20] :=     (     StringTake[str, spec = SyntaxLength[StringTake[str, width]]];     {strNew, strRest} = StringTake[str, {{1, spec}, {spec + 1, -1}}];     )      test               (*In [1]*):= strGet @ samplestring      > >     (* >     Out[2]= { >     *)   >   One simple string split function without SyntaxQ               stringSplit[str_, width_] := Module[{strNew = str},      test = StringTake[strNew,       {First[#], Last[#]} & /@ Partition[Range[StringLength @ strNew], width, width, 1, {}]]]      * * * without SyntaxQ, see a example in bills answer of one of my prevous question. http://mathematica.stackexchange.com/a/26525/6648 * * * My background is trying to copy _Mathematica_ Code to SE with good form. So the following is related in the large direction. Programmatically copy code so that all output is commented out * * * In this post, you can see clearly `sample1` really with some fixed-width but not so well splitted. For example, string > >     "anything but", "around/round the clock" >   was splitted into > >     "ar   >     ound/round the clock" >   How to look up the dictionary for some bad-form phrase


How can I change the highlighting color of an InlineMathCell?

When using the InlineMathCell one types `Ctrl`+`9` within the text cell, and gets a slot for starting typing the InlineMathCell part. When typing the content of the InlineMathCell is slightly highlighted by a light pink color. As soon as the typing goes outside of the InlineMathCell, the highlighting disappears, and the InlineMathCell background looks white. My question is: How can I change the highlighting color of an InlineMathCell to make it more visible? Reaction to the statement that this question already has an asnwer: NO IT HAD NOT BEFORE THE PRESENT ANSWER OF SILVIA. See the discussion below.


Visualization of Gaussian Curvature

I need to visualize Gaussian Curvature of a parametric surface. there is a solution here How to visualize the Gaussian curvature of a 3D surface? but Im not sure its working because when I draw a sphere its all white but it should be red or brown(because its Gaussian curvature is positive). how can I modify that code such that for any point on the surface if its Gaussian curvature is positive it turns red and if its zero it turns to white and for negative it turns to blue. if I can do this with any other software please tell me. please help me out,(sorry for my bad English).


Can Mathematica do this summation?

I was very pleased to discover that Mathematica could do this summation and produce a symbolic result.               s1 = 1/nn Sum[Cos[2 π a (n - 1)] E^(-I (n - 1) (s - 1)/nn), {n, nn}] // Simplify      The answer is long but very useful for me. I also discovered that Mathematica could do some variants of this sum. However, Mathematica cannot do this summation.               s2 = 1/nn Sum[          Cos[2 π ((a - ϵ) (n - 1) + ϵ/(nn - 1) (n - 1)^2)] E^(-I (n - 1) (s - 1)/nn),           {n, nn}]      Note that nn >> 1. Is my sum s2 in some way pathological so that it cannot be done? Can my sum be coerced into a solution? These sums come from Fourier analysis, where it is useful to have a symbolic expression for results that are often calculated numerically using the discrete Fourier transform (Fourier in Mathematica). In order to investigate my sum, I looked at the continuous Fourier transform in which time is equal to n -1 and frequency is (s - 1)/nn. The continuous Fourier transform is given by the integral               1/t2 Integrate[Cos[2 π ( (a - ϵ) t + ϵ/t2 t^2)] E^(-I 2 π f t), {t, 0, t2}]      Mathematica can do this integral which comes out in terms of error functions. However, I can't see how to use this to help get the symbolic solution to the sum s2. Is there any hope for getting a symbolic solution for my second sum? In a previous question what-summations-can-mathematica-do? I had the naive idea that if the integral is possible then a similar sum should also be possible but although comments on this would be interesting it is probably too broad for this forum. Thanks.


Absolute value and argument of a complex expression

I would like to find the absolute value and the argument of the expression: $ x + \sqrt { x^2 + y^2 } $ under the assumption that the absolute values of $ x $ and $ y $ are equal. I have written:               Simplify[ComplexExpand[Abs[x + (x^2 + y^2)^(1/2)], {x, y}, TargetFunctions -> {Abs, Arg}],        Assumptions -> Abs[x] == Abs[y]] // FullSimplify      Why does _Mathematica_ return the un-evaluated expression? I would like to have a solution that will also find a simplified version of my expression when `Arg` is substituted for `Abs`.


Which integration strategy to use for this product of polynomials?

What would be the ideal integration strategy for a function like this: $$f(x_1,x_2,\dots,x_N)=\prod_{i=1}^Nx_i^{c_i}\Theta(x_i-p_i)$$ where $x_i,p_i\in \mathbb{R}$, $\Theta$ is the Heaviside function and $c_i\in \mathbb{N}^+$ when trying to integrate something like $$\int_0^1\mathrm{d}x_1\int_0^{1-x_1}\mathrm{d}x_2\dots\int_0^{1-x_1-x_2\dots- x_{N-1}}\mathrm{d}x_Nf(x_1,x_2,\dots,x_N)?$$ **Edit:** $N$ is usually rather small, namely $N<10$; the $c_i$, however, can be of the order of $10^2$. **Edit 2:** I am aware that this question is quite general, but maybe there are general rules how to `NIntegrate` monotonous functions like this. **Edit 3:** An example for $f$ would be               f[x1_,x2_,x3_] = x1^23 x2^45 x3^123 HeavisideTheta[ x1-1/20 ] HeavisideTheta[ x2-1/20 ]       **Edit 4:** Since I was apparently confusing some people, here's roughly what I want to compute:               NIntegrate[f[r1, r2, r3], {r1, 0, 1}, {r2, 0, 1 - r1}, {r3, 0, 1 - r1 - r2}]      This gives a result `(2.8227403075197916*^-78)` but also states: > NIntegrate::slwcon: Numerical integration converging too slowly; suspect one > of the following: singularity, value of the integration is 0, highly > oscillatory integrand, or WorkingPrecision too small My question is: What is the fastest and most robust NIntegrate Integration Strategy when I wand to do this with arbirtary $1<N<10$ and $\left\\{c_i\right\\}$?


Click on a curve to start Manipulating another function

I'm able to plot two lists with a tooltip on the curves to display the name of the curve:               list1 = {{{0, 1}, {1, 2}, {2, 4}}, {{0, 3}, {1, 1}, {2, 5}}};     names = {"curve1", "curve2"};     ListLinePlot[Table[Tooltip[list1[[i]], names[[i]]], {i, Length[list1]}]]      ![enter image description here](http://i.stack.imgur.com/I6GRm.png) Now I would like to evaluate this action when I click on a curve:               Manipulate[dummyFunction[nameOfTheCurve, variable], {variable , {0, 1}}]      with dummyFunction being               dummyFunction[t_, u_] := If[u == 1,       Graphics[{Green, Disk[], Black, Text[t]}],       Graphics[{Red, Disk[], Black, Text[t]}]     ]      and `nameOfTheCurve` being the name of the clicked curve. I've tried               ListLinePlot[Table[Button[list1[[i]], Manipulate[dummyFunction[names[[i]], variable], {variable , {0, 1}}]], {i,Length[list1]}]]      but this doesn't work (I can't click on the curve). What's the correct syntax? And more precisely, I would like to plot the output of dummyFunction (the Disk) under the first graph, not replacing it.


ListPointPlot3D seen from above

I have a couple of {x,y,z} points               a = {{0, 1, 0.}, {50, 1, 0.018931}, {100, 1, 0.02}, {0, 2, 0.}, {50, 2, 0.131}, {100, 2, 0.2}};      and I'm visualizing them with               ListPointPlot3D[a, PlotLegends -> Automatic, ImageSize -> 400, ColorFunction -> "Rainbow", PlotStyle -> PointSize[0.03], PlotRange -> {0, 1}]      it gives me this view: ![graph](http://i.stack.imgur.com/BjGuY.jpg) Now I don't need to see this graph in 3D because the color already codes for height. So is there a function that would allow me to see this graph "from above"? Ideally, each {x,y,z} point would be represented by a big square of coordinates {x,y} and of color representing z. I would also like to be able to label all squares with the same y, as they represent different entities (we can imagine the x axis is time (from 0 to 100), and I have recorded sound levels (z) in two conditions "noisy" (y = 0) and "quiet" (y = 1). I would like to label "noisy" and "quiet" close to my data). So in the end I could get something like this (I took this image on the internet so of course labels are wrong, but it gives this idea of a coloured matrix) : ![enter image description here](http://i.stack.imgur.com/LcJTS.jpg)


Inactive derivative: extract constants

I have a problem with an unevaluated derivative. In the example code below, i need the integration wrt to y be evaluated, while the differentation wrt x needs to stay unevaluated. I see the point that it is exactly the purpose of Inactive[ ] to hold the function to be differentiated "as is", but i would like to know if there is a workaround to "extract" anything not dependent on x from the inactive derivative. Any help would be highly appreciated.               Integrate[Cos[y]*Inactive[D][-Cos[y]*f[x]*Inactive[D][f[x], x], x], {y, 0, 2*Pi}]


Why are these flow lines cut short?

I want to plot some flow lines for a certain vector field, but _Mathematica_ doesn't seem to plot the entire flow line, only a small piece of it. How can I fix this?               VectorPlot[{Re[Sqrt[x + I y]], Im[Sqrt[x + I y]]},      {x, -1, 1},      {y, -1, 1},      VectorPoints -> Fine,       StreamPoints -> Coarse,      StreamStyle -> Red,      StreamScale -> None]      ![enter image description here](http://i.stack.imgur.com/skPZv.png) ### Update: I feel dumb for not realizing the discontinuity, but I'll mention that what I really want are flow lines of slope fields, not vector fields. I didn't see how to do this in _Mathematica_ "directly," and hence used VectorPlot. How can I plot the lines of a slope field?


Mathematica exit when calling plot. Bug?

I'm currently studing the behaviour of some integral for which I cant find an analytic solution. As this function depend on a vector on the unit sphere, I first defined it with 3 parameters before making a second one taking eulers angle and calling the first one. However, when I try to plot my function I don't get my result. Either :   * I get my first graph, and the worksheet resets   * Mathematica exits I'm using 9.0.1.0 on linux (Archlinux 3.13.6-1 x86_64) Here is my worksheet               w[a_, b_, c_] :=       NIntegrate[(a x + b y + c) (x^2 + y^2 + 1)^(-2)*        HeavisideTheta[a x + b y + c], {x, -1, 1}, {y, -1, 1}]     w3D[theta_, phi_] :=       w[Sin[theta] Cos[phi], Sin[theta] Sin[phi], Cos[theta]]     w[0, 0, 1] + 4 w[0, 1, 0]          Plot[w3D[theta, 0], {theta, 0, Pi}]     Plot[w3D[theta, Pi/4], {theta, 0, Pi}]     Plot3D[w3D[theta, phi], {theta, 0, Pi}, {phi, 0, Pi/2}]      Edit: adding               PrecisionGoal -> 10, AccuracyGoal -> 5      to my Nintegrate solves the problem


Set Page Width of PDF

I have a very simple question. I am using the student version of Mathematica 9, and I often do my homework in it. I type up a notebook, and then save it as a PDF using the "save as" option. However, the resulting PDF's word wrapping freaks out, and I often get lines of printed text that only go about halfway across the page before jumping to the next line. I just want to be able set my page width to match an ordinary 8.5"-11" document for the whole notebook so that is displays correctly as a PDF. Is there a simple way of doing this?


Error function fit of data

I have this experimental data set which I know should follow the Complementary error function. My goal is to find the **σ of the associated gaussian distribution**. However, I cannot seem to do it in any way using `NonlinearModelFit`. Could you please give me some hints? The data is in a list of lists, e.g.:               data = ToExpression@Import["http://pastebin.com/raw.php?i=BtcXHh9c"];      And when plotted it looks like this: ![ListPlot\[Transpose@data\]](http://i.stack.imgur.com/YzFbh.png)


How to bail out from a non-applicable transformation function?

I provide a custom function in `TransformationFunctions` options of `FullSimplify` that can do a transformation only for some values of its argument. What is the proper way to bail out from the function and instruct `FullSimplify` to skip this transformation for the current argument when the transformation is not applicable to it?


references in a nested matrix

I have a nested matrix `n`:               n = {{a, b}, {c, d}}     a = {{0, t, q, dh}, {0, 1, 0, th}, {1, 0, 0, sh}}     b = {{0, t, q, dh}, {0, 0, 0, th}, {0, 0, 1, sh}}          c = {{0, t, q, dh}, {1, 0, 1, th}, {0, 0, 0, sh}}     d = {{0, t, q, dh}, {0, 1, 0, th}, {1, 0, 0, sh}}      With thanks to Kuba and Mr.Wizard 'comparison-operation-for-nested-matrices' I could get a _combined_ nested matrix: _ncombined_ (on which a comparison operation was applied)               ncombined= {{        {{0, t, q, dh},          {0, 1, 0, th},          {1, 0, 1, sh}}},        {{{0, t, q, dh},          {1, 1, 1, th},          {1, 0, 0, sh}}                }}      and with thanks to Kgular getting-good-looking-matrix..I could add a vector `m` as:               m = {rr, kk}      to the _ncombined_ as bellow:               pp = Transpose[Insert[Transpose[ncombined], Flatten@m, 1]];     ppgoodlook=MapAt[MatrixForm, pp, {{All, All}, {}}]      ![enter image description here](http://i.stack.imgur.com/Xgvwm.png) I am so sorry if my question maybe will not well written while I have so much tried to write it more obviously. Also I will bring the image of the desired result. question: Since, number `1` is not repeated in the same elements of `a` and `b` , also for `c` and `d`, how can I refer each of `1` in the `ppgoodlook` to the main sub_matrices such as `a`, `b`, `c` or `d` (from which, `1` is gone to `ppgoodlook`) in order to obtain the bellow result (However this referring is regardless to the letters of sub_matrices such as `sh`,`th`, `q`, `t` and `dh`) : ![enter image description here](http://i.stack.imgur.com/u40sz.png)


OpenCL pass local memory

I've got the following OpenCL function:               __kernel void mergeSort(__global const float * in,__global float * out, __local float *aux)      When I try to call it, I only receive an internal error               OpenCLFunction::invprop: OpenCLLink encountered an invalid property.       I've allocated the memory with               OpenCLMemoryAllocate["Float", 8]      When I remove the "__local", the kernel can be executed. The kernel works fine in a standalone C++ application. Thx


How to prevent notebook from moving/reshuffling code around while one is typing?

Is there a way to configure Mathematica so that the code does not move around while one is typing? It is driving me crazy and I can't see what I am typing as the code is being reformatted _while_ typing. This is standard notebook, V10. Here is a small animation to show the problem. This happens while I am changing some code, where I see other lines are moving based on what I type in a different line. This below is just an example. This happens in many other cases. I once tried a code cell, but that caused many other problems, so I do not use Code cell anymore. Is there a setting or some solution to prevent this? I am on windows 7. ![enter image description here](http://i.stack.imgur.com/5wT60.gif) Here is the actual code snippet above if needed.               SetDirectory[NotebookDirectory[]];     Do[      fileName = "ode" <> ToString[i] <> ".tex";      DeleteFile[fileName];      PutAppend[TeXForm[ode[[i]]], fileName];      res = DSolve[ode[[i]] == 0, y[x], x];      PutAppend[TeXForm[res], fileName];      , {i, 10}]


Saddle Point in Matrix

Here is the Problem how to find out the Saddle Point inside Matrix.               m = {{9, 3, 1, 8, 0},       {6, 5, 4, 6, 7},       {2, 4, 4, 3, 8},       {5, 6, 2, 2, 1}}


What function returns all possible permutations with repeating list elements?

Let's say I want to find a sample space of such experiment: There are three exits from the box: Left (L), right (R) and front (F). Three mice have been put in that box. Find the sample space of an event which mouse has chosen which exit. Function Permutations[] gives all different outputs.               L={L,R,F}     Permutations[L]      How can I find also outcomes like {F,F,L}, {R,R,R}... ?


Finding a root of a parameterized integral

I have a function given as a parameterized definite integral:               f[a_] := Integrate[BesselJ[0, x - a] BesselJ[0, x + a], {x, -∞, ∞}]      I suspect it has a root near `a = 0.8`. How can I evaluate this root to an arbitrary precision? Unfortunately, _Mathematica_ cannot evaluate this integral symbolically, and I don't know if it's possible at all, but I would be glad if anybody could suggest how to do it. * * * _Update:_ It seems that the integral is actually divergent except some isolated values of `a` (when `a` is an odd multiple of `π/2`, see http://math.stackexchange.com/a/878420/19661), and it's never zero when it converges.


3N-dimensional integral

I'm trying to compute a multidimensional integral with a variable number of dimensions. The integral is as follows: $$ \int d^{3N}\\!p~e^{-\frac{\beta}{2m}\vec p^2}. $$ I have tried this               Integrate[e^(-a*{p1,p2,p3}^2),{{p1,p2,p3}^N,-Infinity,Infinity}]      but it's not working at all. I guess I have to determine the vector before, or? More generally, to what extent can _Mathematica_ compute such integrals for arbitrary $N$ and arbitrary integrands in place of $e^{-\frac{\beta}{2m}\vec p^2}$?


DifferentialEvolution scaling factor randomization

Using `NMinimize` for finding global minima, one can choose the `DifferentialEvolution` method. You can find a (not so) detailed description in the link Constrained Optimization. That being said, I would like to know if there is a simple way to implement the randomization of the value attributed to the option `ScalingFactor`. Such a feature should enhance the method: > It has been found recently that selecting F from the interval [0.5, 1.0] > randomly for each generation or for each difference vector, a technique > called dither, improves convergence behaviour significantly (Differential > Evolution Homepage) where the `F` mentioned in the quote corresponds to the value of `ScalingFactor` in _Mathematica_. Probably, this is my lack of knowledge on the details of _Mathematica_ showing up, but I don't know how to tell that in each step of `NMinimize` it should put `RandomReal[{0.5,1.}]` in the option `ScalingFactor`.


Is RemoveSymbolize the reverse of Symbolize?

why cann't I use               RemoveSymbolize[ParsedBoxWrapper[SubscriptBox["_", "_"]]]       to remove all subscripts? Just like               Symbolize[ParsedBoxWrapper[SubscriptBox["_", "_"]]]       ![enter image description here](http://i.stack.imgur.com/tScGV.jpg) After RemoveSymbolize[], q1 should be subscript, why isn't?


Mathematica rule to express exponentials as multiplication

I'm sorry if this has been asked before, but it is a very simple question and I would imagine it shouldn't be terribly hard for someone that knows to answer. I'm essentially trying to tell mathematica to _not_ simplify               Exp[x] Exp[y] -> Exp[x+y]      I am using an add on package which is having a hard time with some replacement rules. So, the question is, is it possible to force mathematica to express `Exp[x] Exp[y]` as is and not simplify it? A secondary question, which should just be an extension of the first, I would like `(Exp[x] Exp[y] )^2` to be replaced as `Exp[x]^2 Exp[y]^2` not `Exp[2x+2y]`! Or even being left as is is ok.


Speed up 4D matrix/array generation

I have to fill a 4D array, whose entries are $\mathrm{sinc}\left[j(a-b)^2+j(c-d)^2-\phi\right]$ for a fixed value of $\phi$ (normally -15) and a fixed value of $j$ (normally about 0.00005). The way I'm trying to speed this up is by first creating a "lookup matrix".               lookup = ParallelTable[Sinc[0.00005 (i^2 + j^2) - 15.],        {i, -2 lim, 2 lim, step},        {j, -2 lim, 2 lim, step}] // Chop      And then use it in this way:               matrix = ParallelTable[lookup[[(a - b) + dim, (c - d) + dim]], range]      where `range` stands for `{a, -lim/step, lim/step, 1}, {b, -lim/step, lim/step, 1}, ...` (hence `matrix` is 4-dimensional) and `dim = 2lim/step + 1` In this way (I normally choose `lim/step` to be an integer) up to values of `lim/step` $\simeq$ 25 my six-year-old MacBook can do it, but for values higher than that it just freezes up. The same entries in `lookup` are read several hundreds if not thousands of times. It seems that there should be a more clever way of doing this. The slow step is the creation of `matrix`, not the creation of `lookup`. Am I missing an obvious (or not so obvious) way of optimising this?


Disentangling the data

An experiment yields a functional dependence on two variables $F(x,y)$, can be imagined as a 2D map. It is known that the function can be factored as follows $F(x,y)=fx(x) gy(y) +gx(x) fy(y)$. Given the tabulated $F(x,y)$ I would like to numerically find the four unknown functions $fx$, $fy$, $gx$, $gy$. It is clear that in full generality the problem is ill posed and has no unique solution. There are however several constraints that are known a priori: i) $fx(x)$, $fy(y)$ are non-zero only on a finite interval ii) $gy(y)$ has a gaussian profile, $gx(x)$ decay exponentially for $x>0$. Just to give an example let us use the following definitions:               fx[x_] := 1/(Exp[-x - 7] + 1) + 1/(Exp[x - 7] + 1) - 1     gy[y_] := Exp[-y^2]     fy[y_] := (1/(Exp[-y - 10] + 1) + 1/(Exp[y - 10] + 1) - 1) (5 + 0.5 Sin[y])     gx[x_] := Exp[-0.4 x]/(Exp[-5 x] + 5)     F[x_, y_] := fx[x] gy[y] + gx[x] fy[y]      looking as ![four graphs](http://i.stack.imgur.com/rBPsQ.gif) The resulting function has a cross shape                Plot3D[F[x, y], {x, -15, 15}, {y, -15, 15}, PlotRange -> All, PlotPoints -> {50, 50}]      ![3dplot ](http://i.stack.imgur.com/da7Gm.jpg) I do not have many ideas how to find $fx,fy,gx,gy$ numerically. I was trying to use a fitting procedure, however, it works like you get what you put in. I am seeking for a more general solution, perhaps with the help of Fourier or wavelet analysis. I would be grateful for any ideas.


How to influence Suggestion Bar in your package/code

> **Possible Duplicate:**   >  Is it possible to customize the Suggestions Bar? I have written a little code (like a minipackage) of different functions. In using my code, the user typically starts by running my integration function `integratePV[]`. Then, typically, the most natural thing to do from there is to use one of two functions: `refinePV` or `expandPV` on the output of the previous expression. How can I influence the Suggestion Bar to make these two user-defined functions `refinePV` and `expandPV` appear right after the function `integratePV[...]` has been called?


plotting cumulative distribution function

c = 2;     P = N[n*Log[n]]     K = N[c*Log[n]]          Needs["PlotLegends`"];          PrDEqK[P_, K_, n_, c_, k_] := Module[{p, q, r, ps, qs, m, tmp},         r = Sqrt[(c*Log[n])/(n*\[Pi])];         p = \[Pi]*r^2;         q = 1 - p;         ps = 1 - Binomial[P - K, K]/Binomial[P, K];         qs = 1 - ps;             N[Sum[Binomial[n - 1, m]*p^m*q^(n - 1 - m)*Binomial[m, k]*ps^k*           qs^(m - k), {m, k, n - 1}]]             ];     Plot[CDF[{PrDEqK[P, K, 20, c, k], {k, 1, 8},Filling -> Axis     ]      i'm not getting the CDF plot...what is the problem?


What is the need for function parameters? Many possible inputs

If I have many possible variables related to one another, why do I need to define my function with parameters for plotting? For example, if I have an equation like:               output_value := a * b * c * d / ( e * f * g * h );      Assuming that all values are defined and have some default value, why can't I just do this to plot:               Plot[ output_value, { b, 0, 100 } ];      The annoying thing is having to do this:               output_value[aparam_, bparam_, cparam_, dparam_, eparam_, fparam_, gparam_, hparam_] := aparam * bparam * cparam * dparam / ( eparam * fparam * gparam * hparam );      and then:               With[ {aparam=a,cparam=c,dparam=d,eparam=e,fparam=f,gparam=g}, Plot[ output_value, { bparam, 0, 100 } ];


Young Tableaux Miscellanea

I have a problem which is mostly neatly described by using Young Tableaux. Mathematica seems to have these Tableaux built in, except that the `Tableaux` function is only in Combinatorica. When I `Needs[Combinatorica]` I get a warning suggesting that I look at the Compatability Guide for Combinatorica, which I can't seem to find. Does anyone have a link, or know if any of the `Tableaux`-related functions are the problematic ones? The Tableaux function itself is hardly documented at all, and its output is quite tough to read. I am hoping there is a nice built-in way to draw the Tableaux in the nice YT in English notation (longest rows on top) [A custom drawing function is in How to insert a function into OptionsPattern? ]. Is there such a function? Finally, can anyone explain what the format of the input to `Tableaux` should be? Here are some examples that work:               In[1]:= Needs["Combinatorica`"]              General::compat: Combinatorica Graph and Permutations functionality has been superseded by      preloaded functionality. The package now being loaded may conflict with this. Please see      the Compatibility Guide for details.          In[2]:= Tableaux[3]     Out[2]= {{{1, 2, 3}}, {{1, 3}, {2}}, {{1, 2}, {3}}, {{1}, {2}, {3}}}          In[3]:= Tableaux[{3}]     Out[3]= {{{1, 2, 3}}}          In[4]:= Tableaux /@ IntegerPartitions[3]     Out[4]= {{{{1, 2, 3}}}, {{{1, 3}, {2}}, {{1,          2}, {3}}}, {{{1}, {2}, {3}}}}      while something like `Tableaux[{1, 2, 3}]` gives errors. Does `Tableaux[integer]` give all possible tableaux with `integer` entries?   Does `Tableaux[{int1, int2, ..., intk}]` give all possible tableaux of `k` rows of length `int1` ... `intk` respectively? This would explain why `Tableaux[{1,2,3}]` throws errors---it would be a malformed tableaux.


How to process binary-encoded data without writing to file and importing?

I am consuming a webservice through NETLink that returns data directly in the response as a gzipped csv file. I can successfully process the data like this:               binz=response@data     BinaryWrite["tmp.csv.gz", binz]     Close["tmp.csv.gz"]     Import["tmp.csv.gz", "CSV"]      However, I am curious if there is a more direct way to achieve this? Thanks for any advice.


Count consecutive positions with the same value

I want to program a function that counts the successive positions with the same value:               In[]= ConsecutiveValues[{1, 1, 1, 1, 2, 2, 1, 0}]     Out[]= {4, 2, 1, 1}      In fact, I can program this using loops and such, but I have the feeling that there is a nicer, more Mathematicaesque way to do it. Thanks!


How do I fill in a circle made by ParametricPlot with one solid color?

I have a very simple question but I am new with _Mathematica_. I made a circle on a parametric plot and I made the line black. I want to make the inside of the circle on the parametric plot red. So the result: A red-filled circle with a black outline on an x and y axis (Parametric Plot) Code:               ParametricPlot[{Cos[u], Sin[u]}, {u, 0, 2 Pi}, PlotStyle -> Black]


Integral with unreliable result

I want to calculate $\int_R^1 \sqrt{r} |\cos((k+\frac{1}{2})\pi r)|dr $ and I get a result from Mathematica. Then I try to check the result putting the value of $k$ and $R$, (k=1 and R=0.5) in the result and performing a NIntegrate with the same value and the result is different. In the analytical result if you put $k=10$ and $R=0.5$ the result is negative and of course wrong, but if I use Nintegrate the result is posivite. What happened? I am interested in the following function of $R$ and $k$. $$\text{Assuming}\left[R>0\textrm{&&}k>1\textrm{&&}R<1\textrm{&&}k\in\textrm{Integers},\int_0^R \sqrt{r} \textrm{Abs}\left[\cos\left(k+\frac{1}{2}\right)\pi r\right] dr\right]$$ and Mathematica gives the answer $$\frac{2 S\left(\sqrt{2 k R+R}\right) \sec \left(\pi k R+\frac{\pi R}{2}\right)-2 \sqrt{2 k R+R} \tan \left(\pi k R+\frac{\pi R}{2}\right)}{\pi (2 k+1)^{3/2} \sqrt{\sec ^2\left(\pi k R+\frac{\pi R}{2}\right)}}$$ and if you evaluate this function in $R=0.2$ and $k=1$ the result is $-0.0488018$. This result is different from the definite integral with the same value for the parameters. Thank you in advance again


Strange behavior of Mathematica regarding calculation time

Today I witnessed the following strange behavior of _Mathematica_ , when it comes to calculation time involving larger nested lists. The following is the short example that I setup, I am sure one can reproduce that behavior with other functions:               div[x_] := (RotateLeft[#, {1, 0}] - #) & @ x[[;; , ;; , 1]] + (RotateLeft[#, {0, 1}] - #) & @ x[[;; , ;; , 2]]      Which is some kind of discrete divergence operator, but this does not really matter here. And then I defined the corresponding lists to be evaluated by `div`:               testArray = Table[RandomReal[], {i, 1, 256}, {j, 1, 256}];     testArray2D = Table[{testArray[[i, j]], testArray[[j, i]]}, {i, Dimensions[testArray][[1]]}, {j, Dimensions[testArray][[2]]}];     testArray2Dnew = Table[{RandomReal[], RandomReal[]}, {i, 1, 256}, {j, 1, 256}];      It is obvious, that `testArray2D` and `testArray2Dnew` should be pretty much identical from a numerical standpoint (i.e. same dimensions, same kind of numbers and same precision). But when I apply `div` on both of them I get completely different calculation times:               Timing[div[testArray2D];]      delivers 0.035085 seconds and               Timing[div[testArray2Dnew];]      delivers 0.006100 seconds Executing the above Timing commands over and over again does not change the results, so there is about a factor of 6 regarding calculation time. Can somebody explain that behavior to me, because right now I am just confused.


Three dimensional ParametricPlot

Why do I get nothing from the ParametricPlot3D,               s = NDSolve[{\[Theta]''[t] + 0.5 \[Theta]'[t] + Sin[\[Theta][t]] ==     0.97 Cos[(2/3) t], \[Theta][0] == -2.1, \[Theta]'[0] == -2.1},     \[Theta], {t, 0, 8}];          ParametricPlot3D[{(2/3)t, Evaluate[{\[Theta][t], \[Theta]'[t]} /. s]}, {t, 0, 8}]      Result, ![enter image description here](http://i.stack.imgur.com/ZmazP.jpg)


Compiled NormFunction

I would like to use a user-defined NormFunction with NDSolve, e.g.,               NormFunction -> (Norm[Take[#, 2], \[Infinity]] &)      which says that the infinity norm should be used on the first two state variables. How can I use a compiled version of the NormFunction above? When using a user- defined NormFunction integration seems to take longer time, and this seems to be because the NormFunction is not compiled. I believe that this is the case since when I define a user-defined norm returning the default norm it takes longer time compared to when not specifying it (and hence get the default norm automatically). Any suggestions?


How to find maximum ConditionalExpression among all solutions

For example I want to find solution with maximum value among solutions (and possibly plot it):               answers = Piecewise[List @@@ Last @@@ N @Solve[{            z == 40 x + 50 y,            6 x + 10 y <= 672,            0.25 x + 0.15 y <= 24,            1.5 y <= 42,            0 <= x,            0 <= y            }, {z}, Integers]]      In this case it is : `{4230.,x\[LongEqual]87.\[And]y\[LongEqual]15.}`


How do I find the best fit?

I am trying to solve following system of three differential equations               r = {       -cab'[t] == k*cab[t] - kb*ca[t]*cb[t],       ca'[t] == k*cab[t] - kb*ca[t]*cb[t],       cb'[t] == k*cab[t] - kb*ca[t]*cb[t],       cab[0] == 0.071176,       ca[0] == 0.003697,       cb[0] == 0.002845     };      and fit them to the following experimental data               cab = {0.071176, 0.05493, 0.04287, 0.03391, 0.02767, 0.02355,             0.02096,0.01825, 0.017029, 0.016582, 0.01421, 0.01432, 0.01431};     ca = {0.003697, 0.021051, 0.033007, 0.04154, 0.047609,0.052086, 0.05529,            0.057088, 0.05842, 0.05966, 0.06114, 0.06079,0.06153};     cb = {0.002845, 0.01949, 0.03078, 0.03714, 0.04476, 0.04939, 0.05214,            0.05327, 0.05526, 0.05573, 0.05859, 0.05774, 0.05868};     t = {0, 3600, 7200, 10800, 14400, 18000, 21600, 25200, 28800, 32400,82800, 86400, 90000};      I want to get the best `k` and `kb` values. Could you help me since I am novice in _Mathematica_. I would like a step-by-step tutorial on hoe to do it.


List all the directories under the current one

I feel like I am forgetting something obvious, and will remember or be ashamed as soon as an answer turns up. However, I cannot for the life of me get all of the directories in the current working directory. That is, given the following folder structure:               a     -c     b     -c      I would expect               FileNames["*",{"*"},Infinity]      to return               {"a","b","a/c","b/c"}      But instead I get               {"a/c","b/c"}      I tried playing around with `Infinity` in the typical `Level`s in Mathematica (such as {1} vs. 1), but MMA complains about syntax. For the above example, how can I view a complete list of subdirectories. I came up with the following, but it doesn't seem exactly elegant:               RecursiveDirectory[dir_] :=       Module[{allDirs, allDirsCheck = {}, tempDirs},       allDirs = Select[FileNames["*"], DirectoryQ[#] &];       While[allDirs != allDirsCheck,        allDirsCheck = allDirs;        tempDirs = Select[FileNames["*", allDirs], DirectoryQ[#] &];        allDirs = Union[allDirs, tempDirs]        ];       allDirs       ]      This function gives me:               In[30]:= RecursiveDirectory["*"]     Out[30]= {"a", "a\\c", "b", "b\\c"}      As expected. What is a nicer way of doing this?


Converting StringForm output to a string produces unexpected results

I want to compose a string that contains newlines, so I tried the following:               ToString@StringForm["SomeText='`1`'\[NewLine]as well as OtherText='`2`'.", "textA", "textB"]      I would expect this to produce a string that looked like:               SomeText='textA'     as well as OtherText='textB'      Instead, I get a string that looks like               SomeText='textA'                      textB'.                     as well as OtherText='           Directly entering the string `"SomeText='textA'\[NewLine]as well as OtherText='textB'"` gives me the correct result. What is going on here?


How can I get a Button to evaluate an expression containing Get?

I have problems making `Button` evaluate an input like this one:               Button["Load", Get["/Users/simonlausen/Desktop/Input/ex1.mx"]]      I have tried a bunch of things, but haven't found any elegant solution. What to do?


What's going wrong with this button!

I'm implementing an Adaline algorithm where all inputs are 1x5526 and the output is a number from 1 to 10. I have this two functions defined and worked outside the `Manipulate` environment:               test[in_, weights_] := (a = Round[Total[Most[weights]*Most[in]] + Last[weights]];  Return[a])     train[in_, out_, alpha_, delta_] := ((*uweights holds also the bias with 1*)           sizePattern = Length[in[[1]]];     sizeOutput = 1;     Length[out];     uweights = ConstantArray[0, {sizePattern}];     dweights = {};     flag = True;     cont = 0;     Error = {};     While[flag == True && cont < 10000,         flag = False;         perror = 0;         cont++;         (*Checking each input-output*)     For[i = 1, i <= 1(*Dimensions[out][[1]]*), i++,         (*Checking each neuron*)         For[k = 1, k <= Length[out](*Dimensions[out][[2]]*), k++,             est = Total[Most[uweights]*Most[in[[k]]]] + Last[uweights];             If[out[[k]] + delta <= est || out[[k]] - delta >= est,                 (*Print["Estimated different"] ;*)                 flag = True;                 dweights = alpha*1*(out[[k]] - est)*Most[in[[k]]];                 dbias = alpha*1*(out[[k]] - est);                 perror = perror + .5*(out[[k]] - est)^2;                 uweights = uweights + Flatten[{dweights, dbias}]]]]];     Return[uweights])      In these lines, they gave the amount of good answer I get with these weights:               AbsoluteTiming[w = train[Samples, AOutput, 0.00001, 0.4];]     uweights = w;     Report = Table[test[Samples[[i]], w], {i, 30}];     Count[Table[Report[[i]] == AOutput[[i]], {i, 30}], True]      > {28.516558, Null} > > 30 The problem emerges when I put the functions `test` and `train` inside the `Manipulate` environment:               Manipulate[         Grid[{{Text@Style["Saída ", "Large"]}, {Text@Style[answer, "Large"],              Text@Style["    ", "Large"]},              {ArrayPlot[ArrayReshape[Samples[[dato]], {85, 65}]]},              (*This line was add to verify if train is working!!!*)             {weights // MatrixForm}}],         {{weights, {}}, ControlType -> None},         {{answer, {}}, ControlType -> None},         {{dato, 1}, ControlType -> None},         {{alpha, 0.00001, "Learning rate "}, 0.0000001, .0001, 0.0000005,          Appearance -> "Labeled"},         {{delta, 0.5, "Error range "}, 0.01, 0.5, 0.01,          Appearance -> "Labeled"},         Row[{PopupMenu[Dynamic[NumberPicked], Range[0, 9]],             PopupMenu[             Dynamic[FontType], {1 -> "Comics", 2 -> "Times", 3 -> "Calibri"}]}],         Row[{Button["Train", weights = train[Samples, AOutput, alpha, delta],         Background -> Yellow, ImageSize -> Medium],         Style["                    ", 14],         Button["Test",             If[FontType == 1,                Switch[NumberPicked, 0, dato = 1, 1, dato = 4, 2, dato = 7, 3,                dato = 10, 4, dato = 13, 5, dato = 16, 6, dato = 19, 7,                dato = 22, 8, dato = 25, 9, dato = 28]];             If[FontType == 2,                Switch[NumberPicked, 0, dato = 2, 1, dato = 5, 2, dato = 8, 3,                dato = 11, 4, dato = 14, 5, dato = 17, 6, dato = 20, 7,                dato = 23, 8, dato = 26, 9, dato = 29]];             If[FontType == 3,                Switch[NumberPicked, 0, dato = 3, 1, dato = 6, 2, dato = 9, 3,                dato = 12, 4, dato = 15, 5, dato = 18, 6, dato = 21, 7,                dato = 24, 8, dato = 27, 9, dato = 30]];             answer = test[Samples[[dato]], weights],             Background -> Green, ImageSize -> Medium]}]]      And the output is this: ![enter image description here](http://i.stack.imgur.com/vPC7a.png) After push the button train, it seems that the `train` function was executed, but no values are returned as you can see below the zero. I appreciate any help with this! maybe it seems a silly mistake but I cannot see it.


Asynchronous evaluation of a button's action

What would be the best way to have the value of x update before the pause (or a similarly slow function) finishes executing?               x = 0; Dynamic[{x, Button["+1", x++; Pause[3]]}]


Evaluation order of Button[]'s action

it looks like it should be well known issue but I haven't found answer anywhere. Please tell me why the result (after clicking) of this:               Button["X", Print@1; Pause@1; Print@2;]      is different from result of this:               Print@1; Pause@1; Print@2;


Revolving an axisymmetric image for volumetric rendering

I have a series of axisymmetric images of a jellyfish swimming in fluid. Overlaid on these images are plots of the Lagrangian coherent structures associated with swimming, which highlight the fluid transport and mixing: ![A plot of the jellyfish bell kinematics and the Lagrangian coherent structures](http://i.stack.imgur.com/W76CQ.jpg) Since these images are axisymmetric, I was wondering: is there a way that I can revolve a single two-dimensional image about its x axis, so as to create a three-dimensional surface, and then visualize this as a volumetric render? If possible, I'd like to retain the same colors as in the two-dimensional image, as they are significant. As well, I'd like to create a cut-away that removes a fourth of the volume, like in the following image: ![A three-dimensional plot of the jellyfish bell kinematics and the Lagrangian coherent structures](http://i.stack.imgur.com/7DP4F.jpg) I'm aware of the following posts: How to show solid bodies using volumetric rendering? and How to create blurred Graphics3D objects?. However, they don't cover a crucial step: how to do the x-axis revolution.


Mathematica File Organization

Last year I asked how to integrate notebooks to the documentation center in stackoverflow. Back then I was only interested in seeing those notebook and being able to search for them. Unfortunately, it has been painful to write the documentation because of the lack of a good organized stylesheet (Still working on a simple one that does the job). In any case, I would like to revisit part of this question by looking at complete tree of the file organization of a package. In the answers I posted I showed mainly the part for the documentation. ![example](http://i.stack.imgur.com/ogsPR.png) In the picture above I show the folder `SOPackage` which is supposed to be located either in `$UserBaseDirectory` or `$BaseDirectory`. Now that I know a little bit more of stylesheets, palettes and mathlink programs I would like to be able to incorporate them to applications. The question is, can anyone show a a complete tree of an application located in either `$UserBaseDirectory` or `$BaseDirectory` with the folders necessary to make everything work? (By everything I mean, documentation, mathlink/NETlink/LibraryLink programs, stylesheets, palettes and any other thing that you can think of). A place to start is at: http://reference.wolfram.com/mathematica/tutorial/MathematicaFileOrganization.html But it doesn't seem to have everything. The reason I found out about how to create the structure in the picture above was because of a link acl showed in one of his answers. To clarify again, the question at hand is: Can we show the complete structure of an application in `$UserBaseDirectory` that contains the directories where we put:   1. Documentation   2. Source Code for Mathlink/NETLink/LibraryLink (any other link)   3. Stylesheets   4. Palettes If you can think of anything else that would make the application more complete please add it. At some point I wanted to just ask if it was possible to put stylesheets in an application instead of               $UserBaseDirectory <> "/SystemFiles/FrontEnd/StyleSheets/";      but instead I decided to make a question that can bring all of us the complete file organization for a complete application in _Mathematica_.


How to minimize a list of data points?

I have a list called diff1:               axis = Table[i, {i, 1, 20}];     data1 = Table[Sin[i/(2*Pi)], {i, 1, 20}];     model1[t_] := a*Sin[b*t];     model1points = Map[model1, axis];     diff1 = (model1points - data1)^2;      One example of the entry of diff1: (a Sin[3 b] - Sin[3/(2*Pi)])^2 I want to minimize the elements of this list with respect to `a` and `b`. How can I do that?


Reducing the memory footprint of lists of machine numbers

I have a large 1D dataset of double precision numbers that are stored in many external database files. In order to load the whole dataset into Mathematica 8 I iterate over the files `AppendingTo` a `List`. The problem is that my computer keeps running out of memory even though the memory available should be more than enough to store the whole set. When researching the issue I discovered a strange behaviour (see the code below). The list produced by `AppendTo` consumes much more memory than would correspond to the size of an integer. I presume that, in the latter `List`, Mathematica uses some different kind of objects to store the data. Any suggestions on how to reduce the memory usage?               In[78]:= ByteCount[Range[1, 10000]]     Out[78]= 40168          In[79]:= data = List[];     For[i = 0, i &lt 10000, ++i,       AppendTo[data, i];     ];          In[81]:= ByteCount[data]     Out[81]= 320040


Exporting BSplineSurface to STL

I have encountered some difficulties getting `BSplineSurface` to export to STL. The following code works and generates a triangulated polygon mesh from the NURBS spline (adapted from a `BSplineSurface` example):               cpts = Table[{i, j, RandomReal[{-1, 1}]}, {i, 4}, {j, 4}];     b = Graphics3D[BSplineSurface[cpts]]     Export["surface.stl", b, "STL"]      However, decreasing the number of control points in each dimension from **4** to **3**               cpts = Table[{i, j, RandomReal[{-1, 1}]}, {i, 3}, {j, 3}];     b = Graphics3D[BSplineSurface[cpts]]     Export["surface.stl", b, "STL"]      results in               GeometricFunctions`BSplineSurface::deglen: -- Message text not found -- (3)     Export::nodta: Graphics3D contains no data that can be exported to the STL format. >>     $Failed      (Mathematica version 10).    Why is the success of exporting a `BSplineSurface` to STL dependent on the number of control points? Is there a reliable way to get arbitrary spline surfaces to export to STL? Convert Graphics3D containing BSpline to polygon primitives for export to 3DS? seems somewhat related though not identical. I am aware that Mathematica cannot actually export NURBS surfaces, so a triangulation will suffice, just as it happens already for the surface with 16 control points.


Possible Bug in ProbitModelFit when used in a Dataset

Since upgrading to _Mathematica 10_ on Mac OSX I have come across a number of instances of this error, which occurs using Probit and Logit model fit. ![enter image description here](http://i.stack.imgur.com/1gD6T.png) A bit of googling show this is something to do with the estimation algorithm. But the issue is more complex. When I estimate the model straight from this dataset I get the error, but when I first take the values of the data, then fit the model, I get the expected result. Here's an example               var = {age, gender, photo6};          mTest = SemanticImport[        "https://dl.dropboxusercontent.com/u/3997716/test.csv"];          testFit =       mTest[ProbitModelFit[#, var,          var] &, {#age, #gender, #photo6, #rawM} &]          testFit2 =       ProbitModelFit[#, var,          var] &@(mTest[All, {"age", "gender", "photo6", "rawM"}] //           Normal // Values)      Output of this is ![enter image description here](http://i.stack.imgur.com/WeBRA.png) Why the two different results for the same calculation? Is there a workaround that allows the estimation to proceed when directly using the dataset?


Imaginary term in Integration procedure

How do you remove the imaginary term in the integrated output? Compare the outcome from the operations below. The first operation yields an imaginary term, while the second one has none.               Clear[a, c];     Integrate[q^2 ((4 (c π))/((a q^2 - c) (c + a q^2))), {q, 0, ∞}]     Integrate[q^2 ((4 (c π))/((a q^2 - c) (c + a q^2))), q]     Limit[(Sqrt[c] π (2 ArcTan[(Sqrt[a] q)/Sqrt[c]] +            Log[Sqrt[c] - Sqrt[a] q] - Log[Sqrt[c] + Sqrt[a] q]))/a^(3/2), q -> ∞]


Find a word's linguistic pronunciation

Is there a way to get a word's linguistic pronunciation given the word as a string? I would like a function `LingusticPronunciation` such that, for example, `LingusticPronunciation["Dog"]` would return `"Dawg"` or maybe even `"dȯg"` or `"däg"`, depending on what type of pronunciation dictionary is used. Ultimately I am trying to search for all homophones in a document and would prefer not having to use the internet to check for different homophone/pronunciation information.


Defining a function with global parameters

What I would like to do in Mathematica is something like               f[x_] := a x     g[a_] := NIntegrate[f[x], {x, 0, 1}]      But then of course I get               g[1]         NIntegrate::inumr: The integrand a x has evaluated to non-numerical values for all sampling points in the region with boundaries {{0,1}}. >>     Out= NIntegrate[f[x], {x, 0, 1}]      But I found that I can circumvent the problem with               g[a_] := Hold[NIntegrate][f[x], {x, 0, 1}] // Evaluate // ReleaseHold // Evaluate         NIntegrate::inumr: The integrand a x has evaluated to non-numerical values for all sampling points in the region with boundaries {{0,1}}. >>     g[1]     Out= 0.5      I don't really understand why this works nor why the definition of `g` throws an error. As I haven't found any other solution to my problem, I would really like to understand why my "solution" works which should also provide an answer to whether there is a simpler solution. (I understand I can solve this simple problem with `f[x_, a_]` but I have in fact a more complex environment in hand where this approach becomes inconvenient.)


Combine multiple outputs into a pane

**Probably unnecessary detail:** So here's what I'm envisioning. I have several outputs from different calculations (perhaps several ListAnimated tables of GraphicsGrids of plots). In one, I did all the calculations with x=0.13 and everything is a function of y. In a second output, I set y=0.36 and everything is a function of x. Now I want to produce a single box with perhaps tabs at the top that lets me switch between the different outputs. In the limited case above, I could accomplish the whole thing with another nesting of ListAnimate, but what I'm really going for here is something more general. What I would like to be able to do is something like "OutputTabbedPane[{%487, %488, %496}]" and have it produce a single box or whatever that combined the (already computed, possibly long-time computations) outputs and let me click and cycle through them. Pipe dream? Anyone know how to move in this direction?


How to use Compile for accelerating matrix multiplications?

I am trying to find the inverse of the matrix $A$                m = n = 500;      SeedRandom[123456];      A = RandomReal[10, {m, n}];      iteratively using the following matrix iterative method $$X_{k+1}=X_k(2I-AX_k)$$ when $X_0=\frac{2}{\sigma_1^2+\sigma_r^2}A^*$, with $\sigma_1$ and $\sigma_r$ as the largest and the smallest singular values of $A$, and $I$ is the identity matrix. This iterative methods can simply be coded in what follows:                Schulz[X_] := With[{XX = A.X,Id = SparseArray[{{i_, i_} -> 1.}, {m, m}]}, X.(2 Id - XX)];      The whole of this iteration to reach the prescribed tolerance can then be given by the following two-argument function               inverse[A_, tolerance_] := Module[{smax = SingularValueList[A, 1][[1]],         smin = SingularValueList[A, -1][[1]]},        X0 = (2./(smax^2 + smin^2))*ConjugateTranspose[A];        Schulz[X_] := With[{XX = A.X,           Id = SparseArray[{{i_, i_} -> 1.}, {m, m}]}, X.(2 Id - XX)];        FixedPoint[(Schulz[#] &), X0,          SameTest -> (Norm[#1 - #2, Infinity] <= tolerance &)]];      This function could converge to the inverse $A^{-1}$. For example,               tolerance = 10^-6;     B = inverse[A, tolerance]; // AbsoluteTiming     B.A // Chop // MatrixPlot      My main question is here: the running time of finding the inverse using the above piece of code is too much in contrast to the built-in function `Inverse[A]`. In fact, the above implementation takes 6.2 seconds in my machine while `Inverse[A]` takes around 0.2 seconds. So, is there anyway to accelerate the above code by using `Compile` on the matrix iterations? I think the most time consuming parts are the two matrix-matrix multiplications per step, but is there anyway to use `RunTimeAttribute` or `Parallelization -> True`, to become it faster than it is? I will be thankful if anyone could revise the above implementation.


Importing a ragged array while ignoring rows that start with "#"

I am new to _Mathematica_ , and I find that there may be a lot of ways of doing this. I was wondering which one might be the most general. I am importing data from `.txt` files, resulting in a ragged array due to many lines containing parameters and other comments which I want to ignore. I just want to import the numbers, and ignore the comments. I am using this:               Import["filename.txt", "TSV", "HeaderLines" -> 15]      I have no TrailerLines that I need to skip, however, there are many rows halfway through the data which I would like to remove. These lines all start with `#`, which makes me think that there is a way to just specify that any line starting with `#` be skipped. Thanks a lot in advance to anyone who might be able to help me with this.