title: Pattern matching a pattern with patterns

text: Confusing title, I know. But the question is, if we have two patterns which have the same general structure but different names used in the patterns and different names:                a = HoldPattern[f[x_, y_, g_, h_]] :> g[x] + h[y];      b = HoldPattern[g[y_, z_, m_, l_]] :> m[y] + l[z];      And I would like to be able to define a pattern for these two pattens, letting {f,x,y,g,h} take arbitrary values. How would I go about this? To clearify. If I had `a=4;b=5`. I could define a common pattern through: `_Integer` and get `MatchQ[a,_Integer](*=>True*)` and `MatchQ[b,_Integer](*=>True*)`. But for my above two patterns, I cannot simply base my pattenr on a and substitute out {f,x,y,g,h} with `_` eg:               badpattern = HoldPattern[f_[Pattern[x_,_], Pattern[y_,_],                  Pattern[g_,_], Pattern[h_,_]]] :> h_[x_] + h_[y_];      I should not that what I want as a result is a working _pattern_ not just a method that accomplishes this. Why? Well because the I would have to reimpliment `MatchQ`, `Cases`, `Position` and so forth for everything that expects a pattern as it's input to still work. The code below accomplishes this, however in an ad-hoc fasion. This is wrong since the result does not distinguish between structural Blanks, and pattern blanks. **My initial code**   Just to get a pattern to match to itself I need to get rid of `HoldPattern` which I do as:               MatchQ[a, a /. HoldPattern -> hp_ /; hp === HoldPattern]     (* True *)      Of cause I could just use `Verbatim` however then I won't be able to do the next part. Where I extend the same type of pattern of switching out pattern components such as `HoldPattern`. To check `b` against a pattern based on `a`, I switch out a collection of heads inject new patterns and condition the pattern on the switched out heads:               myPatternPatternA=(a/.{HoldPattern->hp_,Pattern->p_,Blank->b_,RuleDelayed->rd_}        /.{f->f_,x-> x_,y-> y_,g-> g_,h-> h_ }      )/;And[hp===HoldPattern,p===Pattern,b===Blank,rd===RuleDelayed];              MatchQ[b,myPatternPatternA]      (* True *)      Note that I'm just using a as a template of the new pattern I construct, in the new pattern `{f,x,y,g,h}` can all take arbitrary values since I'm injecting a new pattern for them after removing `{HoldPattern,Pattern,Blank,RuleDelayed}`. It seems however that I'll occasionally have problems with other symbols, which means I need to extend the list for instance to include `Set` and `SetDelayed`, however only when they actually appear in the expression, since otherwise the check fails. As such it feels like a rather cumbersome method. So I'm wondering if others have dealt with such cases and how they have carried this out. **Update** I should add that I'm relying on the matching to return values aswell, eg:               myPatternPattern = (a/.{HoldPattern->hp_,Pattern->p_,Blank->b_,RuleDelayed->rd_}            /.{f->f_,x-> x_,y-> y_,g-> g_,h-> h_ }          )/;And[hp===HoldPattern,p===Pattern,b===Blank,rd===RuleDelayed]:>f;          Cases[{a,b},myPatternPattern]      (*{f,g}*)      Mr. Wizard inquired as to what exactly I mean by the two definitions having the same structure. So I'll clarify. If we have two different expressions: `f[3,4]` and `g[2,5]` and I wanted to describe their structure, then I could write `name_[_Integer,_Integer]` as one possible common structure. When I have two patterns this approach breaks down for obvious reasons, Consider; `_[varA_]` and `_[varB_]`. I would like to define a "pattern^2" that matches both of these patterns and assigns varA or varB to a name, so I just follow the same recipe as before and substitute `varA` in the first with `name_` and get: ``_[_name_]`. This obviously fails. So what I have above is a way to define a pattern for patterns such that I can match elements inside them. Confusing, I know.


title: Function output from DSolve

text: I want to get a function as output form DSolve. For Example :               sol = DSolve[{Q''[t] + 40 Q'[t] + 625 Q[t] == 100*Cos[10*t], Q[0] == 0, Q'[0] == 0}, Q[t], t]      I want to use Q[t] as a function to use in an another equation.


title: Getting R textual output into Mathematica

text: I use Mathematica with R because I am able to keep my code and output organized with the notebook interface. Although I can get R structures into _Mathematica_ using REvaluate, I can't figure out how to get textual output, from say:               summary(fit)      Perhaps this can be done by redirecting output to a temporary file, like the case of plots, but I wonder if there is a native solution.


title: How do I add arrowheads to circular arcs?

text: I have figures containing several arcs showing the extend of angular measures, and would like to indicate the directions in which angles are measured with arrowheads. How do I add an arrowhead at the "ends" of these arcs? (The "arrowheads" panel in the drawing tools palette is, worryingly, disabled.) For example, I have something like this to start with: ![enter image description here](http://i.stack.imgur.com/EVEqD.png) * * *               Show[      Graphics[{Red, Circle[{0, 0}, 1, {0 Degree, 90 Degree}]}],      Graphics[{Blue, Circle[{0, 0}, 1.25, {0 Degree, 270 Degree}]}],      Graphics[{Green, Circle[{0, 0}, 1.5, {0 Degree, 180 Degree}]}]]


title: What is the best way to clip a graphic to a region?

text: What is the best way to clip a graphic to a certain region? Here's a very simple implementation to show what I mean:               Show[      CountryData["World", "Shape"],      Graphics[{White,         FilledCurve[{{Line[{{-200, -100}, {200, -100}, {200, 100}, {-200,               100}}]}, {Line[{{-10.181224213835492, 65.15571149065886},                    {-4.290845998237188,               79.14535975270482}, {14.116585925507536,                      63.683116936759234}, {16.32547775635689,               43.80309045911497},                    {-0.6093596134882375,               35.70382041266731}, {-16.071602429433796,                      40.85790135131583}, {-13.126413321634658,               57.79273872116096}}]}}]}],      PlotRange -> {{-18, 18}, {35, 82}}, Background -> LightBlue      ]      ![Mathematica graphics](http://i.stack.imgur.com/oM5dk.png) My aim is to be able to clip arbitrary vector graphics to an arbitrary region. The region can be anything, and can have curved boundaries (but approximation with line segments is okay). The problem with the approach I showed here (i.e. simply overlaying a rectangle with a hole in it) is that it is cumbersome and it does not allow arbitrary layering of objects: imagine that I need this clipped graphic to be in the foreground and cover parts of the background objects. _Note:_ It is possible to clip raster graphics using `Texture`, as shown here. This question is about clipping arbitrary vector graphics. If it is not possible to do this in the current version of Mathematica, I accept that.


title: A good way to manage code in a complicated CDF?

text: When doing complicated programming in a Mma notebook I define several functions that I use in my higher level funtions, and I use a "Subsection" cell for each definition. For example I might write:               Cell["foo[x,y]", "Subsection"]     foo[x_,y_]:=(* complicated code *)          Cell["foo[x,y,z]", "Subsection"]     foo[x_,y_,z_]:=(* complicated code *)          Cell["goo[x,y]", "Subsection"]     goo[x_,y_]:=(* complicated code *)          Cell["UserIterface[x,y,z]", "Subsection"]     UserInterface[x_,y_,z_]:=DynamicModule[{a,b,c},       a=foo[x,y];       b=foo[x,y,z];       c=goo[x,y];       (* and so on  *)     ]      By using "Subsection" cells, I can close Subsections of code when I don't need to see them. However, I want to make my program a CDF that the CDF-Player can use. As far as I know, I have to use the following approach instead.               DynamicModule[{a,b,c},     a=foo[x,y];     b=foo[x,y,z];     c=goo[x,y];     (* and so on  *),          Initialization:>{     foo[x_,y_]:=(* complicated code *);     foo[x_,y_,z_]:=(* complicated code *);     goo[x_,y_]:=(* complicated code *)}     ]      This becomes unwieldly because I can't minimize the code that I don't need to see at any moment. Is there a better way to make a complicated CDF?


title: Making FindShortestPath a little bit sloppy

text: I have a dense graph, and I'd like to find multiple "almost shortest" paths from a source vertex, $v_s$, to a sink vertex, $v_s$, on an undirected graph $G$. How can I repeatedly run `FindShortestPath` so that it avoids some fraction $p$ of the vertices (or edges) on the path provided by its previous solution? Thought: Starting from an undirected graph, can we dynamically randomize the direction of the graph edges after each application of `FindShortestPath`? Whatever the best solution may be, $G$ is very large, so I'm hoping that the "surgery" for every iteration doesn't require too much overhead. * * * Actually, the more I think about it, the more I like the idea of generating $N$ copies of my graph with randomly directed edges. Can I modify an undirected graph to have randomly directed edges? Can I be even more clever and do this for only the edges that `FindShortestPath` searches through? * * *


title: Lines with label in Plot options syntax

text: I wrote a little function to add lines with labels to plots. It just creates customized `{GridLines -> ..., Epilog -> ...}` code:               LastOrEmpty[seq_] := If[Length[seq] > 0, Last[seq], {}];          AddLabel[lab_, pos_] :=        Inset[Framed[lab, Background -> White, FrameStyle -> None], pos];          AddLines[xs_, ys_, xlvl_, ylvl_] := {        GridLines -> {LastOrEmpty /@ xs, LastOrEmpty /@ ys},        Epilog -> Join[          Table[AddLabel[xs[[i, 1]], {xs[[i, 2]], ylvl}], {i, Length[xs]}],          Table[AddLabel[ys[[i, 1]], {xlvl, ys[[i, 2]]}], {i, Length[ys]}]          ]         };      But is using a little creepy syntax:               AddLines[       {label1 -> val1, label2 -> val2, ...}, (* <- vertical lines *)       {label3 -> val3, label4 -> val4, ...}, (* <- horizontal lines *)       xlvl, (* <- Horisontal align of labels*)       ylvl  (* <- Vertical align of labels*)     ] // Evaluate      For example:               ParametricPlot[{x1[w],         x3[w]}, {w, w1 - 5, w1 + 9},       AspectRatio -> 1/GoldenRatio,       AxesOrigin -> {0.10, 0},       AxesLabel -> {"x1(\[Omega])", "x3(\[Omega])"},       GridLinesStyle -> Dashed,       AddLines[         {T1 -> 0.2},         {K1 -> 2, Kgr -> 0.52, Baseline -> 1},         0.59, 2.9] // Evaluate       ]      ![enter image description here](http://i.stack.imgur.com/NrT7I.png) Now I would like to write something like:                 Lines -> {         {T1 -> 0.2},         {K1 -> 2, Kgr -> 0.52, Baseline -> 1},         0.59, 2.9}      And at the best I would like to make it to automatically calculate align, i.e. would look like:                 Lines -> {         {T1 -> 0.2},         {K1 -> 2, Kgr -> 0.52, Baseline -> 1}}      Have you any idea how to make it?


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

text: 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)


title: Tridiagonal matrix for any n

text: 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


title: Using one table for multiple arguments

text: 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?


title: Mapping and Interpolation

text: 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. –


title: Map function on the specified location

text: 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?


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

text: 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?


title: How to use mathematica to create school time-table?

text: 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?


title: Combining an imported PDB file with a set of Graphics3D objects

text: 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?


title: In a ListPlot of LinearModelFit, Fill to the regression line

text: 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."


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

text: 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?


title: Voronoi Diagram: Displaying site specific color in a voronoi diagram

text: 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?


title: Incremental build in Workbench 2 Is it possible?

text: 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?


title: Balanced n-ary Base Representation

text: 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?


title: Creating a R DataFrame like construct in Mathematica

text: 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.


title: Why is MenuCommandKey not working in my stylesheet?

text: 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)


title: Automatically check student answers in tests

text: 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?


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

text: 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?


title: Discard ODE singular solutions with Mathematica?

text: 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.


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

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


title: For-loop only executes first line in body

text: 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.


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

text: 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?


title: Expressions like <<1>>

text: 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?


title: Determine frequency of oscillations

text: 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.


title: Circular Orbit Velocity in Vector Components

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


title: What is wrong with my expression for compiling?

text: 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]


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

text: 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]


title: Which methods are available for NMinimize?

text: 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"`.


title: Partial factorization of multivariate polynomials in terms of given polynomials

text: 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?


title: Superscript prime symbol

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


title: Matrices and polynomials: MMA 8 vs. 9?

text: 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?


title: Making axis numbers larger on Mathematica plot

text: 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]


title: What algorithms does NSolve use?

text: 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.


title: Problem with SerialIO package and Lego NXT

text: 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?


title: Finding Local Minima / Maxima in Noisy Data

text: 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.


title: Another one problem with legends on GraphicsGrid

text: 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?


title: Restrict MousePosition to specific Graphics object

text: 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!


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

text: 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!


title: Ranking Function Allowing for Ties

text: 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.


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

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


title: Obtaining EditDistance[] from a List of Strings

text: 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.


title: How to embed an image into a string?

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


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

text: 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)


title: Matching parentheses size in plot labels

text: 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?


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

text: 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


title: How can I change the highlighting color of an InlineMathCell?

text: 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.


title: Visualization of Gaussian Curvature

text: 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).


title: Can Mathematica do this summation?

text: 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.


title: Absolute value and argument of a complex expression

text: 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`.


title: Which integration strategy to use for this product of polynomials?

text: 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\\}$?


title: Click on a curve to start Manipulating another function

text: 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.


title: ListPointPlot3D seen from above

text: 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)


title: Inactive derivative: extract constants

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


title: Why are these flow lines cut short?

text: 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?


title: Mathematica exit when calling plot. Bug?

text: 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


title: Set Page Width of PDF

text: 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?


title: Error function fit of data

text: 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)


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

text: 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?


title: references in a nested matrix

text: 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)


title: OpenCL pass local memory

text: 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


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

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


title: Saddle Point in Matrix

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


title: What function returns all possible permutations with repeating list elements?

text: 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}... ?


title: Finding a root of a parameterized integral

text: 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.


title: 3N-dimensional integral

text: 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}$?


title: DifferentialEvolution scaling factor randomization

text: 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`.


title: Is RemoveSymbolize the reverse of Symbolize?

text: 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?


title: Mathematica rule to express exponentials as multiplication

text: 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.


title: Speed up 4D matrix/array generation

text: 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?


title: Disentangling the data

text: 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.


title: How to influence Suggestion Bar in your package/code

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


title: plotting cumulative distribution function

text: 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?


title: What is the need for function parameters? Many possible inputs

text: 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 } ];


title: Young Tableaux Miscellanea

text: 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.


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

text: 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.


title: Count consecutive positions with the same value

text: 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!


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

text: 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]


title: Integral with unreliable result

text: 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


title: Strange behavior of Mathematica regarding calculation time

text: 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.


title: Three dimensional ParametricPlot

text: 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)


title: Compiled NormFunction

text: 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?


title: How to find maximum ConditionalExpression among all solutions

text: 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.}`


title: How do I find the best fit?

text: 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.


title: List all the directories under the current one

text: 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?


title: Converting StringForm output to a string produces unexpected results

text: 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?


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

text: 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?


title: What's going wrong with this button!

text: 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.


title: Asynchronous evaluation of a button's action

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


title: Evaluation order of Button[]'s action

text: 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;