title: How to specify initial condition including integral equations in the case of the dirac equations?

text: Hi I am trying to solve a system of differential equation with `NDSolve`. The problem is I have like $3$ (maybe $5$) boundary conditions, but only $2$ differential equations. The equations to solve are the Dirac equations in a hydrogen like potential. My code is:                   k := -1; n := 1; Z := 82; α := 1/137         u[r_] := (Z*α)/r; ζ := (1 + (Z*α)^2/(n - Abs[k] + Sqrt[k^2 - (Z*α)^2])^2)^(-1/2)         eqn := {g'[r] == -(k/r) g[r] + (ζ + 1 + u[r]) f[r],                 f'[r] == k/r f[r] - (ζ - 1 + u[r]) g[r]}         bound := {g[10^(-20)] == 0, f[10^(-20)] == 0}              dirac = NDSolve[{eqn, bound}, {g, f}, {r, 10^(-10), 20},                          Method -> {"ExplicitRungeKutta"}]              Plot[Evaluate[{g[r], f[r]} /. dirac], {r, 0, 15}, PlotRange -> {{0, 15}, {-0.2, 0.6}}]      If I run this code, the solutions will be the $0$ functions. But that is not what I want. The other boundary condition is The normalization of those functions, but I don't know how to express it as a boundary condition:                   Integrate[Abs[g[r]]^2 + Abs[f[r]]^2, {r, 0, Infinity}] == 1      This condition somehow include the conditions:                   g[Infinity]==0, f[Infinity]==0      If I exchange one of my condition with the integral or the others, mathematica won't find a solution. The solution of those equations should be `0` at `r = 0` and they should vanish for `r = ∞`, but the area under the curve should not be `0`. I hope someone can help me soon.


title: Is it possible to change to a functional approach in this game-based procedural algorithm?

text: First of all, I'm aware that Mathematica StackExchange prefer specific questions, not discussions, but I need some enlightenment with this issue for I have nowhere else to ask :) The thing is, our teacher wants to implement a program that simulates a game (The Fish Game, of The Cloud Institute for Sustainability Education) with N rounds, and each round have N players, and each player does N actions in its turn. The results of the game (e.g. fish catched by each player, cumulative catch and population over time) are important stats, but even more important is the fact that each step should be present and not omitted. So it's a game more than a simulation with graphs and sliders to see tendencies and behaviors, because each iteration asks for the user to do something (catch fish). This is a fully procedural approach. After some research, I've found that loops are not efficient nor desirables in Mathematica and there are some others built-ins able to do the job. I've been fiddling around with the `Do` loop, and got myself a 'decent' text-based simulation. However, I'm not sure if there is a more appropriate way to represent the nature of the game. `Do` looping the rounds, and nesting another `Do` loop for the players is what I have now. I know you need some code insight, so here's an extract:               Do[         Print["Starts round ", round, "!"];         Pause[doublewait];         suma = {};         Do[             Print["Starts Player ", player, " turn!"];             Pause[wait];             catch = RandomInteger[{1,3}];                  popafterdraw = actualpop - catch;                       If[actualpop >= catch, (* Validate population before draw *)                 Print["Player ", player, " draws ", catch, " fish!"];                 Pause[wait];                 AppendTo[playerlist[[player]],catch];...]];      It's basically looping `players` times each player's action, which loops `rounds` times or till fish is depleted. Full code is available here. Be careful, it's a mess. So, long story short, my question is: **do you think this could be changed to a more functional approach?** or should I stand up and tell the whole class that Core Language is not the way to do it and I'll get way further programming a Python script? If, in any case, there's another way (and a more efficient one) to approach this program, then I'll be more than glad to hear your recommendations; changing programming paradigms is kinda difficult to do if all your life procedural was the way to go. And, if my question doesn't belong here or is not specific enough to be in a StackExchange site, I apologize in advance. Please moderate as usual. Thank you. PS: If anyone is intrigued why we're using Mathematica for this, is because "the software is cool but expensive and we need to use it along iPads to create iOS applications". CDF Player is not even available in iOS, so...


title: Adding various combinations of rational expressions

text: as a newbie to Mathematica I wonder if someone can help... I'm generating a puzzle worksheet for some students and wish to add linear rational expressions, three at a time from a pool of six. e.g.   a) -1/(2x+1) b) -3/(x-1) c) 2/(3x+2) d) 2/(x-1) e) -3/(2x+1) f) -1/(3x+2) I want to be able to swiftly add (a) + (b) + (d) for example, or (b) + (d) + (f) Can I store the expressions and add them as I have done here. I've not had much success so far. I'd like to have a worksheet which I could tweak expressions a - f without then having to manually copy & paste endlessly into arithmetic expressions. I'm then combining them with ExpandNumerator@Together[%] ExpandDenominator[%] // TraditionalForm And will give the output to the student for Partial Fraction Decomposition. Thanks Rob


title: Plot several lines with different starting points on the x-axis

text: First of all, I would like to apologize in advance if I don't use the correct terms or if I express myself unclear but I just started to work with Mathematica. I'm simulating electricity prices and therefore created a table which show 10 possible price movements (the rows) over the next 10 days (the columns). But as I'm only interested in the prices if they once moved over a limit of 1.2 I used the function `LengthWhile` and then `Take` and got the following output:               {{1.14213, 1.22155, 1.23436, 1.35038, 1.35104, 1.48351}, {1.0484,        1.42157, 1.57688, 2.07304, 1.61537, 1.326, 1.18823, 1.4154, 1.56133,        1.93402}, {1.06792}, {1.19792, 1.77863, 2.24724, 2.27939, 2.15542,        2.47559}, {1, 1.31003, 1.06341, 1.17975, 0.966335, 0.90843, 0.70606,        0.683366, 0.762621, 0.716291,        0.631823}, {0.428993}, {0.636747}, {1, 1.35605, 1.06939, 1.09904,        1.14575, 1.05545, 1.13386, 0.868574, 0.846754, 0.702533,        0.864972}, {1.08078, 1.29863, 1.17577, 0.995288,        1.05625}, {0.637442}}      If I use `ListLinePlot` now, all lines are starting at 1 on the x-axis and then ending on different points. But I want them all to end at 10 on the x-axis and therefore starting at different points on the x-axis. Can anybody help me here? Thanks!


title: Plot a graph in a plane

text: I have a 3D graphics and i must plot a trajectory on a costant plane but i don't understand how to do this. With a simple Show[] command i can't do this. This is the code to plot the graphics:               PMotion[mu1_,{x0_,y0_,vx0_,vy0_},tmax_,step_:10000]:=     Module[{rrule,Urule,eqMotion,r1,r2,mu,U},     rrule={r1->Sqrt[(mu+x[t])^2+y[t]^2],     r2->Sqrt[(-1+mu+x[t])^2+y[t]^2]};     Urule={U->(1-mu)/r1+mu/r2+0.5(x[t]^2+y[t]^2)};          eqMotion=     {x''[t]-2y'[t]==D[U/.Urule/.rrule,x[t]],     y''[t]+2x'[t]==D[U/.Urule/.rrule,y[t]]};     NDSolve[{eqMotion/.mu->mu1,x[0]==x0,     y[0]==y0,x'[0]==vx0,y'[0]==vy0}//     Flatten,{x,y},{t,0,tmax},     MaxSteps->step]//Flatten]          Mgraph[fx_,fy_,t_,tfinal_,Opts___]:=     ParametricPlot[{fx[t],fy[t]}//Evaluate,     {t,0,tfinal},     Opts,     AspectRatio->Automatic,     DisplayFunction->Identity];     Protect[PMotion,Mgraph];          Clear["Global`*"];          u=0.000954;     x0= 0.93902099; (*0.1;*)     y0= 0.34177569; (*0.21;*)     vx0= 0.;        (*0.133;*)     vy0= 0.;        (*0.231;*)     tfin=200.;          sol=PMotion[u,{x0,y0,vx0,vy0},tfin,50000];     fx[t_]:=x[t]/.sol;     fy[t_]:=y[t]/.sol;          pt1=Mgraph[fx,fy,t,tfin,     PlotPoints->100,     PlotStyle->Black,     Epilog->{     {     AbsolutePointSize[7], Hue[0.7],     Text["\!\(\*SubscriptBox[\(M\), \(1\)]\)",{0.000954,-0.05}],     Text["\!\(\*SubscriptBox[\(M\), \(2\)]\)",{1-0.000954,-0.05}],     {Point[{0.000954,0}],Point[{1-0.000954,0}]}     }     ,     {     AbsolutePointSize[7],Hue[0.3],     Point[{x0,y0}]},     Text["\!\(\*SubscriptBox[\(x\), \(0\)]\),\!\(\*SubscriptBox[\(y\), \(0\)]\)",{x0,y0+0.06}]     }     ,     DisplayFunction->$DisplayFunction,     ImageSize->700]      This is the surface and the plane:               a=0.5;     J=-3.00;          U[x_,y_,a_]:=-((1-a)/Sqrt[(x-a)^2+y^2])-a/Sqrt[(x+1-a)^2+y^2]- 0.5*(x^2+y^2);     t=       Show[         Plot3D[2*U[x,y,a],{x,-1.5,1.5},{y,-1.5,1.5},PlotRange->{-2.6,-4.0},Mesh->False,         PlotStyle->Directive[Gray],AxesLabel->{Style["x",Italic,20],Style["y",Italic,20],Style["J=2U(x,y,a)",Italic,20]}],         Plot3D[J,{x,-1.5,1.5},{y,-1.5,1.5},Mesh->False,PlotStyle->Directive[Green,Opacity[0.5]]],       ImageSize->700]      I must plot the trajectory ON the green plan. Someone can help me please?


title: Using stateful web services with Mathematica 9

text: The WebServices package in _Mathematica_ 9 no longer seems to support stateful web sessions. This requires the client (i.e., the WebServices package) to pass back the HTTP Cookies that it receives from the web service. With _Mathematica_ 8 this worked without problems. In _Mathematica_ 9 this is no longer the case. Each request looks like a newly established session on the web service server side. Is there a way to re-enable support for stateful web services in _Mathematica_ 9?


title: Displaying primes as a 3D array of spheres

text: I am currently learning my way through _Mathematica_ and have stumbled upon a strange problem. It is asking me to implement `PrimeQ` into `Graphics3D` (specifically for spheres). I typed it up and displayed a picture in the notebook uploaded at the link below. If someone could explain this to me, I would greatly appreciate it and will move on to the next chapter, _Pure Functions_. Disregard the input I entered. I was just trying a generic example to see how both compare in front of each other. http://ge.tt/4Xi1kvZ1/v/0?c P.S. I'm only 14 years old. I'm working through a _Mathematica_ book, so that I may use _Mathematica_ to enter into the Intel or Semmes Science Fairs next year.


title: Graph does not evaluate some options when not displayed

text: **How can I force`Graph` to evaluate all its options without actually displaying the graph itself?** Evaluating the following code ignores the `Print` statements in `VertexShapeFunction`, `EdgeShapeFunction` and possibly in other options too meaning that these options are not evaluated and I assume that the graph is not built at all, until displayed (notice the `;` at the end):               g = Graph[{Print["entered Graph"]; 1 -> 2, 2 -> 3, 3 -> 1},        VertexShapeFunction -> (Disk[Print[#]; #, .1] &),        EdgeShapeFunction -> (Line[Print[#]; #] &),        ImageSize -> {Print["imagesize"]; 100, 100}];      > entered Graph > > imagesize I assume this is because of some kind of optimization going on in the background, like when dynamic objects are only updated when they are onscreen. However, this delayed behaviour is inconsistent with other functions' policy on options (see later) and is rather dangerous, as now calling for the presumed static object `g`, I do not expect extra evaluations:               g      > {-0.866025,-0.5} > > {0.866025,-0.5} > > {1.83697*10^-16,1.} ![enter image description here](http://i.stack.imgur.com/0xNCx.jpg) For comparison, a similar (partly dynamic) object is a chart, which behaves as expected (again, note `;`):               BubbleChart[{{1, 0, 1}, {0, 1, 2}, {1, 2, 3}},         ChartElementFunction -> (Disk[Print[#]; First@#, .1] &)];      > {{0.942265,1.05774},{-0.11547,0.11547}} > > {{-0.0816497,0.0816497},{0.836701,1.1633}} > > {{0.9,1.1},{1.8,2.2}} In general, I had the impression, that functions work like `BubbleChart` (i.e. `Plot`, `ListPlot`, etc.) so `Graph` is the odd one out. Is this delayed evaluation a feature or a bug?


title: Export plot to Excel

text: Very new to Mathematica. Used the code to solve for the response of a system of spring mass dampers but would like to export the data to Excel.               Dyn = NDSolve[{Response[[1]] == 0, Response[[2]] == 0,                     Response[[3]] == 0, Response[[4]] == 0, x[0] == 0.1, x'[0] == 0,                     phi[0] == 0, phi'[0] == 0, xf[0] == 0, xf'[0] == 0, xr[0] == 0,                     xr'[0] == 0}, {x, phi, xf, xr}, {t, 0, 1}];          Plot[Evaluate[{x[t], phi[t], xf[t], xr[t]} /. Dyn], {t, 0, 1}, PlotRange -> All]      Basically want `x`, `phi`, `xf` and `xr` against time, only in Excel. Thanks.


title: What's the simplest way to plot an ErrorListPlot with only y error bars?

text: Sometimes I get really tired of Preparing data for making an ErrorListPlot using `Thread` and friends. Is there a simpler way to plot an ErrorListPlot with only y error bars? Nothing is mentioned in the documentation.


title: Why doesn't my line match my barchart?

text: I'm trying to create a chart that has both a line and a bar chart representation of an expression. Because I'm using the same expression twice, I expect the line and the bar chart to match, but they are slightly off.               c = Plot[1000 (1 + 0.12/4)^(4 x), {x, 0, 12},        PlotRange -> {{0, 12}, {0, 7000}}]     d = BarChart[Table[1000 (1 + 0.12/4)^(4 x), {x, 0, 12, 1}]]     Show[c, d]      I can't figure out why this would be. Any help would be greatly appreciated.


title: How is AstronomicalData interpreting its date arguments?

text: It is easy to confirm that the `AstronomicalData` is not interpreting its arguments as UTC (or "GMT", which is, in any case, ambiguous) dates by verifying that the changes in the data it reports do not show a jump over a leap second:               ListPlot[         AstronomicalData["Pluto", {"Azimuth", #, {51.4773673, 0.00000000}}, TimeZone -> 0] &          /@ (DateList[{2012, 6, 30, 23, 59, N[58 + 2/3*#]}] & /@ Range[0, 6])]      ![enter image description here](http://i.stack.imgur.com/iBfEo.png) What timekeeping system is `AstronomicalData` assuming its date argument corresponds to? It could be any of the "smoothly flowing" timekeeping systems. Either one of the uniform ones, TAI, TT/TDT, or GPS, each of which differs from UTC by a different amount beyond the cumulative number of leap seconds to date (0s, 32.184s, and -19s, respectively); or, more likely, UT1.


title: How to save data using FileNameSetter or similar

text: I would like to export data to a file using a SaveAs type dialog, using something like `FileNameSetter[name,"Save"]` to give a browse button. Any help with this would be greatly appreciated. It is very possible that I have simply misunderstood the documentation. Many thanks, Christina


title: Displaying index as subscript on output: e.g. C[i] -> C_i with Notation[...] or Interpretation[..]?

text: You have all convinced me not to type in formulas with subscripts. However, in order to be able to match the subscripts in my whiteboard math, I figure a 2nd best solution is to want to display instances of `C[i]` with $C_i$ , only in the output, for a chosen set of $C$ and for any $i$               DisplaySubscripted[val_] :=       Format[val[args__]] := Interpretation[Subscript[val, args], val[args]]     SubscriptVariables[valueList_] := Scan[DisplaySubscripted, valueList];          (* Usage*)     SubscriptVariables[{a, b}]; (* Label the variables I want to display subscripted*)     Solve[a[1] + a[2] - 2 b[2] == c[1], b[2]]     (* This subscripts the a[1], a[2], b[2] and not the c[1], as I hoped.       It also doesn't seem to mess up the symbolics*)      Am I missing something, or is this a side-effect free approach to this problem? (it also works well with `Subsuperscript` and `a[1][2]` displaying as $a_1^2$ and it doesn't seem to mess up the superscript with powers) ALTERNATIVELY: I also thought that Notation may be a way to do this. Easy enough to do this for an arbitrary variable. e.g.               Needs["Notation`"];     DisplaySubscripted[var_] :=       Notation[ParsedBoxWrapper[         SubscriptBox[var, "1"]]\[DoubleLongLeftArrow]ParsedBoxWrapper[         RowBox[{var, "[", "1", "]"}]]];     DisplaySubscripted["f"];          f[1] (* Displays in output properly as f_1*)      However, I can't figure out how to match this for arbitrary subscript patterns. The obvious one does not work: `Notation[ParsedBoxWrapper[ SubscriptBox[var, "_"]]\\[DoubleLongLeftArrow]ParsedBoxWrapper[ RowBox[{var, "[", "_", "]"}]]]` I am also not entirely sure that passing `var_` as strings is the best way to do it, but if I use `DisplaySubscripted[f]` instead, it displays the namespace (i.e. `Global'f_1`). If the Format approach I gave first works, it seems much simpler.


title: How to make a 3D plot auto-rotate?

text: When doing presentation with _Mathematica_ , I often want a 3D plot to rotate automatically, so the 3D feeling is stronger. I don't want to drag the mouse very time. So, I want a general function like               autoRotate["3D graphics here"]      The out put is a rotating version, and I can stop/start the rotation by click a control. **Question: How can I implement this function efficiently so the rotation is as smooth as possible?** Here is my first try: Get viewpoint and compute the rotation matrix;               g = Plot3D[Sin[x y], {x, 0, 3}, {y, 0, 3}];     vc = AbsoluteOptions[g, ViewCenter][[1, 2]];     vp = AbsoluteOptions[g, ViewPoint][[1, 2]];     m = RotationMatrix[3 Degree, {0., 0., 1.}];     newvp = m.(vp - vc);      then manipulate:               Manipulate[If[start, newvp = m.newvp];       Show[g, ViewPoint -> Dynamic[newvp + vc],        SphericalRegion -> True ], {start, {False, True }}]      This seems slow and I lose the ability to zoom/rotate the plot manually. Second try:               DynamicModule[{},         Show[g, ViewPoint ->         Dynamic[newvp = m.newvp; newvp + vc, UpdateInterval -> 1.],        SphericalRegion -> True ]]      This seems faster, but I can't control the refreshrate. `UpdateInterval ->1` seems to lose effect and I also can't zoom/rotate the plot manually. **Update:** Based on Rojo's idea and Silvia's comment, here is what I currently use:               autoRotate[gr_Graphics3D, rate_: 7] :=       DynamicModule[{vp, va, vv, vc }, {vp, va, vv, vc} =         gr~AbsoluteOptions~#~OptionValue~# &@{ViewPoint, ViewAngle,           ViewVertical, ViewCenter};       Overlay[{Show[Graphics3D[], ViewPoint -> Dynamic[vp],          ViewAngle -> Dynamic[va], SphericalRegion -> True],          Show[gr, SphericalRegion -> True,           ViewPoint -> Dynamic[RotationMatrix[Clock[2 \[Pi], rate], vv].vp],          ViewAngle -> Dynamic[va], Boxed -> False , Axes -> False]}, All,         1]]


title: Pattern matching Q for rectangular data matrices

text: Given a List of rectangular nx3 arrays of data, each of the form {...,{x,y,z},...}, (the ellipses are not Mathematica pattern syntax, just for illustration). Some members of this list may be - by coincidence - square, ie 3x3. What's the appropriate method to match each {x,y,z} row regardless of whether n is 3 or not? For example, the following expression,               With[{n = 4},      Graphics@ Table[Random[], {i, 1, n}, {j, 1, 3}] /. {a_, b_, c_} :>         Line[{{1, a}, {2, b}, {3, c}}]      ]      Only works as intended for n!=3. When n==3, then "a" matches the 1st row, "b" matches the 2nd, "c" the 3rd row. I've tried Repeated, ie, {{a_,b_,c_}..}, but that results in a different error that I've not analyzed. This is a simplification of a more involved database problem. Any suggestions?


title: How can I set the background color to the Popupmenu?

text: I want to set the `Background` color of a `PopupMenu` to blue. I already searched in the documentation center, but I didn't find any option that seemed suitable.                PopupMenu[         Dynamic[x],          {"Country1", "Country2", "Country3"},          ImageSize -> {180, 60}, Background -> Blue,         Alignment -> {Center, Center},         MenuStyle ->Directive[Orange, 20, Bold]      ]      ![enter image description here](http://i.stack.imgur.com/X9TWH.png)


title: Set promotes Rule to RuleDelayed?

text: In mentally building a model of how Mathematica works, I naively expected `Set` to create a `Rule` in a symbol's `DownValues`, and `SetDelayed` to create a `RuleDelayed` in a symbol's `DownValues`. Therefore, I was a bit surprised when I tested               ClearAll[g];     Set[g[5], 0];     SetDelayed[g[x_], 1];     DownValues[g] // FullForm      and saw               List[RuleDelayed[HoldPattern[g[5]],0],RuleDelayed[HoldPattern[g[Pattern[x,Blank[]]]],1]]      I naively expected to see               List[Rule[HoldPattern[g[5]],0],RuleDelayed[HoldPattern[g[Pattern[x,Blank[]]]],1]]      or even               List[Rule[g[5],0],RuleDelayed[HoldPattern[g[Pattern[x,Blank[]]]],1]]      The extra `HoldPattern` and `RuleDelayed` seem semantically harmless -- at least I wasn't able to think of a breaking example before breakfast. Looking into the issue, I find the following remarks in the documentation for `HoldPattern` (emphases are mine) > The left-hand sides of rules are **usually** evaluated, as are **parts of** > the left-hand sides of assignments. You can use HoldPattern to stop any part > from being evaluated. The ambiguity of that statement signals that there is a whole lot more going on, here, meaning `Set` and `SetDelayed` aren't going to be exactly equivalent to the rules one would naively expect, and there must be special cases and exclusions in the works. I'd be grateful for hints, experiences, opinions, deeper knowledge, suggested experiments, and especially pointers to clarifying documentation.


title: Usage of plot results

text: Please consider the following examples for a `ListLinePlot` and `ListPlot`               data=Prime[Range[25]];     lstlinePlot=ListLinePlot[data];     lstPlot=ListPlot[Tooltip@data];      **Displaying plot-values** As I would like to give the user the chance to retrieve plot-values directly from the plot, I thought to overlay `lstlinePlot` with `lstPlot`, whereas for the latter the plot-values are displayed via `Tooltip`:               res=Show[{lstlinePlot,lstPlot}]      To evaluate two plots based on the same data seems to me rather time consuming. I wonder whether there is a more efficient way to make the plot- values available as via `Tooltip` (I thought of enabling a "display modus" within `Mesh` but this does not seem to exist.) **Retrieving plot-data directly from plot** It would be nice to be able to click on the line of `lstlinePlot`, press the copy shortcut (e.g. cmd+c) and paste the data into another notebook or into a txt-file (as plain text maybe). I know how to retrieve data from a plot (e.g. `lstlinePlot[[1, 1, 3, 2, 1, All, 2]]`) but I would like to make data available via copy-paste.


title: DynamicModule variables that retain values during code reloading

text: At times I'll find myself building a some interface component where I want to have some localized dynamic variables, and while testing I might realize that some bit of the code needs to change, which means I lose the current state of all the localized variables, some which might be bothersome to set once again. In such case my typical solution is something like:               DynamicModule[{       persistant = 21,       transient = 2},           Column[{               InputField[Dynamic[persistant]],               InputField[Dynamic[transient]],               Dynamic[persistant*transient],           }],       Deinitialization :> (saveVar = persistant),       Initialization :> (FinishDynamic[]; If[ValueQ[saveVar], persistant = saveVar])     ]      Which will retain the value of `persistant` even if I rerun the code. However if you have a bunch of variables that you want to retain it becomes bothersome to save each and everyoen and reload them, and what more you might want to save `DownValues` as well as `OwnValues` so I thought that I'd make a bit more general solution using `DumpSave` or `Save` to save definitions and load them in using `Get`:               Deinitialization :> (If[FileExistsQ["tempfile"], DeleteFile["tempfile"]];            Save["tempfile", {persistant}]),     Initialization :> (FinishDynamic[]; If[FileExistsQ["tempfile"], get["tempfile"]])      But when trying this I've run into problems since the names that are saved are the local temporary names eg. `FE`persistant$$161`instead of just`persistant` which means the values aren't loaded back again correctly. So my question is whether theres either another way to achieve a similar result or if the naming problem can be resolved


title: Procedural to functional style

text: The following code generates an iterative mapping of some trigonometric functions. I have a couple questions about it. The first question is how to optimize this iterative process using mathematica's language and the second is about the result. Do you think the flower looking structures that appear in these plots are a result of some numerical instability or a true part of the mathematics? Additionally, I was trying to get the different listplots to show up in different colors. thx               k = 100000;     m = 5;     For[l = 0, l <= m, l++,       dt = .0001 + .0005 l; t = 0; x = RandomReal[{0, 2 \[Pi]}];        y = RandomReal[{0, 2 \[Pi]}];       xs = Table[0 , {n, 1, k}]; ys = Table[0 , {n, 1, k}];       For[n = 1, n <= k,          n++, {xp = x, yp = y, x = Cos[4 yp] Cos[t], y = Sin[xp] Sin[t],           xs[[n]] = x, ys[[n]] = y, t = t + dt}]        data =          Partition[Flatten[Table[{xs[[n]], ys[[n]]}, {n, 1, k}]], 2] // N;       Subscript[p, l] =         ListPlot[data, AxesOrigin -> {0, 0},          PlotStyle -> {Hue[l], PointSize[.001]}, AspectRatio -> 1]];     Art = Table[Subscript[p, n], {n, 0, m}];     Show[Art]      ![enter image description here](http://i.stack.imgur.com/EelaT.jpg) If you consider the frequency of the cosine term as a parameter $x_{n+1} = \cos(ay_n)\cos(t_n)$ a bifurcation occurs at approx. $a=2.939$.


title: Using Solve Within Manipulate to Model Feedback Control System Problem

text: This post is extremely long and I do apologize - but please bear with me with all the explanation of the context of the question - due to how long the code is I have included a hyperlink where you can see the text as it looks in Mathematica to make everything easier to read and understand. It might help if you are familiar with Classical Control as that is what I am modelling. First let me explain what I am trying to do: I am writing a problem to automate solutions to a control systems assignment. I have had success with questions one and two, and am having some trouble in completing question three (I have code that works but not inside a manipulate [which is what I am trying to do]) - I will explain in more detail below. First it is worth looking at the assignment: ![This is question one](http://i.stack.imgur.com/OxWjD.png)                                 Question one has been succesfully modelled.      This is question two: ![enter image description here](http://i.stack.imgur.com/1imqp.png)                                 Question two has been succesfully modelled.      The problem lies here, with the first part of question three: ![enter image description here](http://i.stack.imgur.com/EmdUo.png)                                 Question three is where the problem lies.      Now I am going to include images of my hand-written solutions to these parts: This is my hand-written solution to question one: ![enter image description here](http://i.stack.imgur.com/tS6iO.png) This is my hand-written solution to question two: ![enter image description here](http://i.stack.imgur.com/QVzZI.png) This is my hand-written solution to the first bit of question three: ![enter image description here](http://i.stack.imgur.com/i4OSe.png) Now I have actually written Mathematica code which successfully calculates the value of k, but this code is not all embedded in a single manipulate -> let me start by introducing this previously written code (which is background to my actual code question) here: First let us create block a for the transfer function and block b for the gain, connect them in series to gain an OL expression I will call OLblockab, and then feed this back upon itself to gain CL expression Clblockab.               blocka = TransferFunctionModel[{5/((4 + s) (200 + s))}, s];          blockb = TransferFunctionModel[k, s];          OLblockab = SystemsModelSeriesConnect[blocka, blockb]          TransferFunctionModel[{{{5 k}}, {{5 k + (4 + s) (200 + s)}}}, s,      SystemsModelLabels -> {{None}, {None}}]      Now we feed this back upon itself to get a closed loop representation:               CLblockab = SystemsModelFeedbackConnect[OLblockab]          TransferFunctionModel[{{{5 k}}, {{5 k + (4 + s) (200 + s)}}}, s,      SystemsModelLabels -> {{None}, {None}}]      So we can see that thus far all is well, the old Mathematica code is consistent with the handwritten solution up to this point. Now what I did was I copied and pasted from within the Transfer Function to gain a normal Algebraic expression that I can use commands on in Mathematica, and I expanded the denominator:                (5 k)/(5 k + (4 + s) (200 + s)) // ExpandDenominator           (5 k)/(800 + 5 k + 204 s + s^2)      The reason I did this is that I need to compare the equation I have to a standard form of equation. This is the standard form of the equation: ![enter image description here](http://i.stack.imgur.com/M6fLh.png) So the assignment actually gives us a value of (1/Sqrt2) for zeta, hence I can set up two equations between the standard form of equation I need and the one I have. The two equations equate the numerator and denominators to solve the system for zeta and for Omegan (I think these are called the damping ratios and natural frequency of the system in Control Systems terms). This is the code that I wrote to do this:               N[Solve[Subscript[\[Omega], n]^2 == 800 + 5 k &&      204 == 2 (1/Sqrt[2]) Subscript[\[Omega], n]]] // FullSimplify          {{k -> 4001.6, Subscript[\[Omega], n] -> 144.25}}      So this matches with the handwritten solution, and all is well. So then this is when my question actually starts: Then I thought - why don't I put everything that I have done in a single Manipulate function? I can just input values for a, b, c, d and it will work everything out for me. I started programming this Manipulate - and it works until I get to question 3 part one. Here is a link to a page on the control website I am building where you can download the notebook http://www.controlmanchester.com/462-2/ And here is the code reformatted for this page:                   Manipulate[         Column[           {         "This is your student number",         "                           ",         Row[{a, b, c, d}]            ,         "                           ",         "                           ",         "This is your  G(s)",         "                           ",         Subscript[G, (s)] = (a + 1)/((s + (b + 1)/2) (s + 20 (c + 1))) ,         "                           ",         "                           ",         "This is your Subscript[C, PI](s) ",          Subscript[C, PI (s)] = 1 + (b + 1)/(2 s),         "                           ",         "                           ",         "This is your Subscript[C, PD](s) ",          Subscript[C, PD (s)] = 1 + (s/(4 (6 + d) (1 + c)))           "                           ",         "                           ",         " This is your tf for G(s)  ",          tf1 =  TransferFunctionModel[Subscript[G, (s)], s],         "                           ",         "                           ",         " This is your unit step time function for G(s)  ",         "                           ",         or1 = OutputResponse[tf1, UnitStep[t], t]   ,         "                           ",         "                           ",         " This is the step response of G(s)" ,         Plot[{or1}, {t, 0, 5}, ImageSize -> 300],         "                           ",         "                           ",         " This is the bode plot of G(s)" ,           BodePlot[tf1, ImageSize -> 300] ,         "                           ",         "                           ",         " This is the gain block k    ",          kblock = TransferFunctionModel[k],          "                           ",          "                           ",          " This is the open loop  G(s)k  combo"          GsOLblock = SystemsModelSeriesConnect[ tf1, kblock],          "                           ",          "                           ",          " This is the closed loop  G(s)k/1+kG(s)  combo ",          GsCLblock = SystemsModelFeedbackConnect[GsOLblock],          "                           ",          "                           ",          "The expressions to compare are  ",              Row[   "\!\(\*FractionBox[\(k \*SuperscriptBox[\((\*SubscriptBox[\(\            \[Omega]\), \(n\)])\), \(2\)]\), \(\*SuperscriptBox[\(s\), \(2\)] + 2 \            \[Zeta] \((\*SubscriptBox[\(\[Omega]\), \(n\)])\) s + \            \*SuperscriptBox[\((\*SubscriptBox[\(\[Omega]\), \(n\)])\), \(2\)]\)]\             \)"  ,                 denom = FullSimplify[ (Subscript[G, (s)]  k)/(             1 + Subscript[G, (s)] k)]    ]    ,           "                           ",           "                           ",             "Now we expand the denominator of our function",            denom2 = denom // ExpandDenominator            "                           ",           "                           ",             "Now we solve for k",           Row[{ nom = Numerator[denom2]   ,            "                  =    k(\!\(\*SubscriptBox[\(\[Omega]\), \(n\)]\)\           \!\(\*SuperscriptBox[\()\), \(2\)]\)" } ]             ,            Row[{ nom1 = nom/k  ,             "                  =     (\!\(\*SubscriptBox[\(\[Omega]\), \(n\)]\)\            \!\(\*SuperscriptBox[\()\), \(2\)]\)" } ]                             \            ,             res1 = Solve[  Sqrt[nom1] ==  Subscript[\[Omega], n] ,              Subscript[\[Omega], n]    ] ,                           Row[{spec1 = Subscript[\[Omega], n] /. res1    ,              "This is the specific value for \!\(\*SubscriptBox[\(\[Omega]\), \             \(n\)]\)"}, "               " ]      ,              Row[{"We are given a condition that \[Zeta] = 1/\!\(\*SqrtBox[\(2\)]\             \) "  ,       \[Stigma] = 1/Sqrt[2 ] ;}]            ,                  Row[{ denom3 = Denominator[denom2] ,              "     =     \!\(\*SuperscriptBox[\(s\), \             \(2\)]\)+2\[Zeta](\!\(\*SubscriptBox[\(\[Omega]\), \             \(n\)]\))s+(\!\(\*SubscriptBox[\(\[Omega]\), \             \(n\)]\)\!\(\*SuperscriptBox[\()\), \(2\)]\)"   }]          ,               Row[{ denom3 = Denominator[denom2] ,               "     =     \!\(\*SuperscriptBox[\(s\), \              \(2\)]\)+2(\!\(\*FractionBox[\(1\), \              SqrtBox[\(2\)]]\))\!\(\*SubscriptBox[\(\[Omega]\), \               \(n\)]\)s+(\!\(\*SubscriptBox[\(\[Omega]\), \               \(n\)]\)\!\(\*SuperscriptBox[\()\), \(2\)]\)"   }]      ,                     Row[{ denom3 = Denominator[denom2] ,                "     =     \!\(\*SuperscriptBox[\(s\), \               \(2\)]\)+\!\(\*SqrtBox[\(2\)]\)\!\(\*SubscriptBox[\(\[Omega]\), \               \(n\)]\)s+(\!\(\*SubscriptBox[\(\[Omega]\), \               \(n\)]\)\!\(\*SuperscriptBox[\()\), \(2\)]\)"   }]      ,              Row[{ denom3 = Denominator[denom2] ,                funct1    =                    s^2 + Sqrt[                2] (spec1) s + (spec1)^2   }, "       =          "]      ,               Row[{ denom3 = Denominator[denom2] - s^2 ,               funct2    =     funct1 - s^2  }, "       =          "]      ,              "                           ",              "                           ",               "Now we solve for k"                   }               ]              , {a, 1, 9, 1}, {b, 1, 9, 1}, {c, 1, 9, 1}, {d, 1, 9, 1}]      So now I guess my question is - how can I implement the method that I previously had for solving k in my current example? I am sorry that I have not made this shorter. When I just copied and pasted the code I reformatted into a fresh notebook it went into a crazy loop and I had to exit my kernel - so you can take a look at the notebook above but also I am going to provide screenshots of the output of the manipulate function here so you can see the state of play - the values for the variables a, b, c, d are the same as in the handwritten solutions. ![enter image description here](http://i.stack.imgur.com/jVBh0.png) ![enter image description here](http://i.stack.imgur.com/ja69y.png) ![enter image description here](http://i.stack.imgur.com/gzwQL.png) ![enter image description here](http://i.stack.imgur.com/WZ4r3.png)   ![enter image description here](http://i.stack.imgur.com/wcNsO.png) Again, apologies for the extremely long post - I find it hard myself getting my head around it all but I have got stuck at this point - I hope that someone knows how I can move forward. Many thanks if you made it reading this far! Cheers


title: How do I make an image "nearly" black and white?

text: Using the following code, I downloaded an image from the web and adjusted the image to obtain the "negation" of the image: > >     im1 = Import["http://www.furnituremaker.com/images/Craftsman.gif"] >   >     im2 = ColorConvert[ >      ImageAdjust[ >       ColorQuantize[ColorNegate[im1], 20, Dithering -> False], 1], >      "Grayscale" >      ] >   > > ![Furniture 1](http://i.stack.imgur.com/mNGxs.gif) > > ![Furniture 2](http://i.stack.imgur.com/OzCkU.gif) Now, I would like to convert this to an image that is "nearly" black and white. By "nearly," I mean that the resulting image may have a small amount of gray at the interface of the black and white, so as to keep the resulting image smooth. (It seems like simply rasterizing an image can sometimes look bad.) How can I accomplish this? I tried using `Darker`, but it just makes the background gray again: > >     im3 = Darker[im2] >   > > ![Furniture 3](http://i.stack.imgur.com/IVXLQ.gif) Instead I would like to somehow adjust the saturation so that the line art and text appears black. `ColorConvert` seems like a possibility, but in the documentation I do not see how to specify a black and white color space. Can you please help me?


title: Taking the time derivative of a function with more than one variable depending on t?

text: Yeah, I was wondering if it was possible ? I have a function which have different variables depending on time, like: $$\frac{d}{dt}mr^{2}\dot{\phi}$$ In this case both $r$, being a length, depends on time, and so does the time derived angle $\dot{\phi}$. I know this is an easy equation to solve in hand, but maybe sometime you get something a bit more difficult. So, can this be done in mathematica, and how ? :) Hope you understand what I mean. Thanks in advance.


title: Is there any function that creates an array from 1 to n, repeating each value m times?

text: I am trying to implement `SparseArray`, using the function `With` to give the condition for different matrix elements. I would need a function `f`, that instead of doing what `Mod` does,               Mod[{1, 2, 3, 4, 5, 6}, 3, 1]      > {1, 2, 3, 1, 2, 3} I would like to have:               f[{1, 2, 3, 4, 5, 6}, 3, 1]      > {1, 1, 1, 2, 2, 2} So that,               f[1,3,1]      > 1 and               f[4,3,1]      > 2 Does such a function `f` exist?


title: Using NotebookDirectory in batch-mode

text: I am running _Mathematica_ via the terminal (Linux) and my `.m`-script contains the command:               ClearAll["Global`*"]     SetDirectory[NotebookDirectory[]];      such that the directory is set to that of the notebook. When I run this with `math -noprompt -script test.m` I get two errors: > `FrontEndObject::notavail A front end is not available; certain operations > require a front end` and > `SetDirectory:fstr: File specification NotebookDirectory[$Failed] is not a > string of one or more characters` In Windows this works perfectly. Does this mean that setting the notebook directory is not supported in the Linux terminal as it is in Windows?


title: Loading Cell Option Definitions on Kernel Launch for Stylesheets

text: I have my own stylesheet that I like using so much I change all my documents to it almost immediately, but as I demo Mathematica to people I cannot use `DefaultStyleDefinitions` as it unnecessarily confuses people. I therefore have a function (typed verbatim, not loaded) in my init.m file that pastes the definitions from a stylesheet into the `EvaluationNotebook[]`               BeginPackage["PasteStyles`"]     pasteStyleSheet::usage="pasteStyleSheet[stylesheet, \"Admin\"] pastes the style definitions provided by stylesheet located in $BaseDirectory (etc)"; Begin["`Private`"]     pasteStyleSheet[stylesheet_String,"Admin"]:=SetOptions[EvaluationNotebook[],StyleDefinitions->Get[FileNameJoin[{$BaseDirectory,"FrontEnd","StyleSheets",stylesheet<>".nb"}]]]     pasteStyleSheet[stylesheet_String,"User"]:=SetOptions[EvaluationNotebook[],StyleDefinitions->Get[FileNameJoin[{$UserBaseDirectory,"FrontEnd","StyleSheets",stylesheet<>".nb"}]]]     pasteStyleSheet[stylesheet_String,"System"]:=SetOptions[EvaluationNotebook[],StyleDefinitions->Get[FileNameJoin[{$InstallationDirectory,"SystemFiles","FrontEnd","StyleSheets",stylesheet<>".nb"}]]]     End[]     EndPackage[]      I have an issue in that I use options for cells such as `WholeCellGroupOpener` and `ReturnCreatesNewCell` that Mathematica doesn't seem to know anything about when my function is evaluated. I found this out because I used to find `$CellContext` throughout my pasted style definitions. Currently, I have shoved the following lines into the package to make sure it works.               System`WholeCellGroupOpener;     System`ReturnCreatesNewCell;      My questions are:   * Why do I get `$CellContext` for some functions that should be on ``System`?   * How do I ensure my function works as intended? Does it need to live somewhere else? Justifications:   * I need to paste the styles, as I email the notebooks out.   * I spend most of my time making fun things in the front end, I'm expecting this stylesheet to eventually become something that no one else will ever want to use.


title: How to compile a function whose arguments are list?

text: I'm unsuccessfully trying to compile this function               check[argA_, argB_] := argA[[1]] == argB[[1]];      assuming that both arguments argA and argB are of the form               {Real, String, ....}      Neither               cf = Compile[     {     {x, {_Real, _String}, 1},     {y, {_Real, _String}, 1}     },     x[[1]] == y[[1]]     ];      nor               cf = Compile[     {     {x, {_Real, _String}, {1}},     {y, {_Real, _String}, {1}}     },     x[[1]] == y[[1]]     ];      work as expected, and I can't see the underlying rule. I'm grateful for any explaination.


title: Make a "ditch" function for electric field purpose

text: ![Test](http://i.stack.imgur.com/Z8psG.png) I'm trying to make a function to simulate a finite bar and get the electric field, i did it by put 22 funnels together but is too slow and is not very accurate; does anyone have any function to replace this thing? PD: this function is:               Total[Table[1/Sqrt[x^2 + (y + i)^2], {i, -5, 5, 0.5}]]      Final Result: ![enter image description here](http://i.stack.imgur.com/svVTh.jpg) Thanks!


title: Non linear equation phase space

text: As a supplementary to my question solution of differential equation I post a new question of how is it possible to make a Table that has elements the solutions of a non linear differential equation, so that to plot them. In a linear system you can do the following:               ss = DSolve[{x'[t] == 3 x[t], y'[t] == -y[t], x[0] == x0, y[0] == y0}, {x, y}, t];     toplot = Table[{x@t, y@t} /. ss, {x0, -0.5, 0.5, 0.25}, {y0, -0.5, 0.5, 0.25}];     ParametricPlot[Evaluate[toplot], {t, -1, 1}]      as @belisarius proposed. If I have to use `NDSolve` can I use variables as above in initial conditions? I first tried the following example.               Plot[r (1 - r^2), {r, 0, 1}, AxesLabel -> {r, r'}]      ssa = NDSolve[{r'[t] == r[t] (1 - r[t]^2), u'[t] == 1, r[0] == r0,                    u[0] == u0}, {r[t], u[t]}, {t, 0, 100}]      toplot = Table[{r@t Cos[u@t], r@t Sin[u@t]} /. ssa, {r0, -.5, .5, 0.25},                                                          {u0, -.5, .5, 0.25}];       ParametricPlot[toplot, {t, 0, 100}]        The solution is what I expected, but it opened a message that said that initial condition r0 is not a number or rectangular array of numbers. I then tried another example, it opened the same message but the solution was nearly what I wanted for some values of μ. For μ>0 the solution was OK except that it wasn't shown the second fixed point. For μ<=0 I didn't get any solution.               sol = NDSolve[{x'[t] == μ - x[t]^2, y'[t] == -y[t], x[0] == x0, y[0] == y0},                   {x[t], y[t]}, {t, 0, 100}]          toplot = Table[{x@t, y@t} /. sol, {x0, -.5, 2, .25}, {y0, -.5, .5, .25}];`          ParametricPlot[Evaluate[toplot], {t, 0, 100}, PlotRange -> All]      **if you copy-paste the code remember to manually treat μ** The expected plots are shown bellow: ![2d saddle node bifurcation](http://i.stack.imgur.com/ptqJD.jpg)


title: Connecting Mathematica to a SOCKS5 tunnel proxy

text: I have Mathematica setup normally and connections work. However, when I want to use it to connect through my SSH tunnel program (Tunnelier), it throws the error > PacletSiteUpdate::err: An error occurred attempting to update paclet > information from site http://pacletserver.wolfram.com. Server returned > nothing (no headers, no data) meanwhile I get the following error message in Tunnelier: > (unrecognized proxy protocol) connection from 127.0.0.1 failed: Unsupported > client protocol; the client may be expecting a regular HTTP proxy I have left the HTTP, HTTPS and FTP proxy fields blank, and only filled in the SOCKS IP (127.0.0.1) and the port (9494). Firefox and IE can successfully connect via the same SSH tunnel. I have also tried it with a similarly working Putty tunnel, with it throwing the exact same error, just with no output from the Putty client.


title: Plotting a 2D shape along a 3D parametric function curve

text: Say I have a 3D curve that is parametrically defined. How would I be able to plot shapes like figure 8s whose centers are aligned along the 3D curve? Say the curve was:               P[a_]:={-a,a,1/2 a (8-a)};     arch=ParametricPlot3D[P[a],{a,0,8},Axes->Automatic,AxesLabel->{"x","y","z"},PlotRange->All,Boxed->False,BoxRatios->Automatic]      Does anyone know how I might be able to do this?


title: Is it possible to give the closed-form of the stiffness matrix of triangular prism element?

text: Suppose the vertices of triangular prism are 1, 2, 3 (bottom triangle), 4, 5, 6 (top triangle), the coordinates of the vertices are $$ (x_i, y_i, z_i), i=1,2,3,4,5,6. $$ We can write the stiffness matrix of FEM of the triangular prism as follows: $$ K_{i,j} = \int_0^1\int_0^{1-\xi}\int_{-1}^1 \begin{pmatrix}\frac{\eth N_i}{\eth\xi} & \frac{\eth N_i}{\eth\eta} & \frac{\eth N_i}{\eth\zeta}\end{pmatrix} (\textbf{J}^{-1})^T\textbf{J}^{-1}\begin{pmatrix}\frac{\eth N_j}{\eth\xi} \\ \frac{\eth N_j}{\eth\eta} \\ \frac{\eth N_j}{\eth\zeta}\end{pmatrix}det(\mathbf{J})d\xi d\eta d\zeta\,\\ i,j=1,2,...,6. $$ where $$ \textbf{J}=\begin{pmatrix}\frac{\eth x}{\eth\xi} & \frac{\eth y}{\eth\xi} & \frac{\eth z}{\eth\xi} \\ \frac{\eth x}{\eth\eta} & \frac{\eth y}{\eth\eta} & \frac{\eth z}{\eth\eta} \\ \frac{\eth x}{\eth\zeta} & \frac{\eth y}{\eth\zeta} & \frac{\eth z}{\eth\zeta} \end{pmatrix} $$ and $$ \textbf{N}=\begin{pmatrix}N_1 & N_2 & N_3 & N_4 & N_5 & N_6\end{pmatrix}^T\\ \left\{\begin{array}{} N_1=\frac{1}{2}(1-\zeta)(1-\xi-\eta)\\ N_2=\frac{1}{2}\xi(1-\zeta)\\ N_3=\frac{1}{2}\eta(1-\zeta)\\ N_4=\frac{1}{2}(1+\zeta)(1-\xi-\eta)\\ N_5=\frac{1}{2}\xi(1+\zeta)\\ N_6=\frac{1}{2}\eta(1+\zeta) \end{array} \right.\ \\ \left\{\begin{array}{} x=\mathbf{N^T}\mathbf{x_e}\\ y=\mathbf{N^T}\mathbf{y_e}\\ z=\mathbf{N^T}\mathbf{z_e}\\ \end{array} \right.\ \\ \left\{\begin{array}{} \mathbf{x_e}=\begin{pmatrix}x_1 & x_2 & x_3 & x_4 & x_5 & x_6\end{pmatrix}^T\\ \mathbf{y_e}=\begin{pmatrix}y_1 & y_2 & y_3 & y_4 & y_5 & y_6\end{pmatrix}^T\\ \mathbf{z_e}=\begin{pmatrix}z_1 & z_2 & z_3 & z_4 & z_5 & z_6\end{pmatrix}^T \end{array} \right.\ $$ Is it possible to give the closed-form of the integration by the powerful mathematica? Thanks, Tang Laoya


title: How can I consistently get a good logistic regression fit?

text: I'm executing the command               NonlinearModelFit[data, c/(1 + a Exp[-b x]), {a, b, c}, x]      with the data being               data = { {0, 15576}, {10, 15935}, {20, 16326},      {30, 18235}, {40, 21680}, {50, 22927}, {60, 28667},      {70, 41674}, {80, 50020}, {90, 75979}, {100, 148700},      {110, 197200}, {120, 212801}, {130, 215499}, {140, 227511}}      and I'm getting a nonsensical result. It's a horrible fit. I've tried various `Method` options and I always get a bad fit. My goal is to try to replicate what a TI-84 would give. I don't know enough about this stuff to know why the TI-84 always seems to give reasonable fits but _Mathematica_ does not.


title: Replace "," in a list with "."

text: I have a list which consists of numbers which use comma (,) instead of dot (.) as their decimal point. I would like to replace the commas, but only those commas which are followed by more than five digits, with a dot. A little example:               {0, "", 0, 1, 3, 93345, 27, 763212, 3}      should be converted into:               {0, "", 0, 1, 3.93345`, 27.763212`, 3}


title: How to export large matrix from .nb file into .pdf

text: I have one technical problem with printing large matrix 50x50 with lot of data. Always when I want to export .nb to .pdf, I can see just part of matrix, never all. Is there solution for this? I need to present data, but not in a .nb file. It is easy to do scrolling left or right in a .nb file - but how to print the whole matrix to a .pdf file?


title: rule transformations for compositions of tensor products

text: The tensor product satisfies far commutativity: $(f \circ g) \otimes (h \circ k) =(f \otimes h) \circ (g \otimes k)$. I have some replacement rules I'd like to apply to an expression containing tensor products and compositions. For example, whenever $(a \otimes b) \circ (c \otimes d)$ appears, I might like to replace it with $l$. The problem is that applying far commutativity in an a prespecified way (for example, `lhs -> rhs`) cannot guarantee that $(a \otimes b) \circ (c \otimes d)$ appears as a subexpression of the result, even if it is implicitly present. I therefore need to search the space of far-commutativity-transformed expressions and apply certain replacement rules when I can. I know that the space of expressions far-commutativity-equivalent to a given one is finite, after all possible replacements are performed the process terminates, and the result does not depend on the order of the replacements. This seems like the sort of term-rewriting problem for which Mathematica might have an automatic capability. Is there a short, readable, and relatively efficient way to do it?


title: Fit implicit function

text: Can anyone help me with fitting an implicit function to data? The function is given by:               a*x^2 + 2*b*x*y + c*y^2 = e      under the condition               a*c-b^2=1      something like a least square fit with $\chi^2$ value would be really nice. Unfortunately I have no idea how to do a fit with an only implicitly given function. I tried the solutions according to this thread How to use FindFit to fit an implicit function?, but i got the following errors:               pts = {{0.943851, 0.0255852}, {-2.23615, 0.0255852}, {2.12656, -0.0845208}, {2.32489, -0.0354676}, {-0.284106, -0.0354676}, {-2.64798, 0.0415494},{1.41402,0.0415494}, {-0.114051, 0.0669646}, {-2.99405,0.0669646}, {-3.92389,0.0825293}, {-0.273894,0.0825293}, {-2.66303, 0.0877706}, {-1.76303,0.0877706}}          fitfunc[a_, b_, d_, x_] := y /. Solve[a*x^2 + 2*b*x*y + (1 + b^2)/a*y^2 == d, {y},InverseFunctions -> True]     FindFit[pts, fitfunc[a, b, d, x], {a, b, d}, x]     FindFit::eqineq: Constraints in {(-a b x+Sqrt[a d+a b^2 d-a^2 x^2])/(1+b^2)} are not all equality or inequality constraints. With the exception of integer domain constraints for linear programming, domain constraints or constraints with Unequal (!=) are not supported. >>      I also tried:               fitfunc2[a_?NumericQ, b_?NumericQ, d_?NumericQ, , x_?NumericQ] :=  y /. FindRoot[a*x^2 + 2*b*x*y + (1 + b^2)/a*y^2 == d, {y, 1.}]     FindFit[pts, fitfunc2[a, b, d, x], {a, b, d}, x]     FindFit::nrlnum: The function value {-0.0255852+fitfunc2[1.,1.,1.,0.943851],-0.0255852+fitfunc2[1.,1.,1.,-2.23615],0.0845208\[VeryThinSpace]+fitfunc2[1.,1.,1.,2.12656],0.0354676\[VeryThinSpace]+fitfunc2[1.,1.,1.,2.32489],0.0354676\[VeryThinSpace]+fitfunc2[1.,1.,1.,-0.284106],-0.0415494+fitfunc2[1.,1.,1.,-2.64798],-0.0415494+fitfunc2[1.,1.,1.,1.41402],-0.0669646+fitfunc2[1.,1.,1.,-0.114051],-0.0669646+fitfunc2[1.,1.,1.,-2.99405],-0.0825293+fitfunc2[1.,1.,1.,-3.92389],-0.0825293+fitfunc2[1.,1.,1.,-0.273894],-0.0877706+fitfunc2[1.,1.,1.,-2.66303],-0.0877706+fitfunc2[1.,1.,1.,-1.76303]}     is not a list of real numbers with dimensions {13} at {a,b,d} = {1.,1.,1.}. >>


title: Issue with scope of variables

text: For the definitions,               t = 1;     f[x_, y_] := t (x + y);     v[3] := {1, 1};     g[u_] := f[v[u][[1]], v[u][[2]]];      the following two expressions yield different results, despite the only difference being the name of the iterator.               Table[g[s], {s, 3, 3}]     Table[g[t], {t, 3, 3}]      I believe this is related to how `Table` applies the value of its variables, as mentioned in http://mathematica.stackexchange.com/a/23533. Are there other functions that behave similarly (albeit bizarrely)? Other than using a different variable name for the iterator, are there good ways to avoid this issue?


title: Combine two functions in mathematica to get one image with two elements

text: I am trying combine this two functions into one piece in grid.               RegionPlot[x^2+y^2<=1 \[And] y>x,{x,-2,2},{y,-2,2},PlotPoints->15]          Graphics[Disk[{1/2,-1/2}, 1/2]]      I tried put Disk[{},] inside first one but it doesn't work. I would appreciate for any help.


title: Simplify expression to Abs

text: FullSimplify[Sqrt[1/(a^2 b^2)], Element[{a, b}, Reals]]      gives               Abs[1/(a b)]      How do I simplify the following expression               FullSimplify[Sqrt[(1 + a + b)/(a^2 b^2)], Element[{a, b}, Reals]]      into $\frac{\sqrt{a+b+1}}{\left| a b\right| }$ ?


title: How to find the center of a circular pattern?

text: I am writing an algorithm that finds the center of 500 x 500 pixels images coming from a live feed from a camera at 50 Hz. So it has to be quick! The images are images of an optical field which looks like a "flower" (example below) which is somehow circular, so it does have a true center, but since it jiggles and it rotates, I have to calculate the true center for every frame. Here is an example of the field: ![example of kernel $K$](http://i.stack.imgur.com/i050B.png) **What I did so far:** Prior to the beginning of frame capture, I prepare in advance 10 matrices $M_i$ of size 600 x 600 like this:                    linepoints[a_] := {{Cos[a], Sin[a]}, {Cos[a + Pi], Sin[a + Pi]}}           img[l_, k_] := Graphics[{Table[Line[linepoints[a + k*Pi/(10l)]], {a, 0, 2Pi, Pi/l}],                               White, Disk[{0, 0}, .2]}, ImageSize -> {600, 600}]           M[l_, k_] := ImageData[ColorConvert[img[l, k], "Grayscale"], "Bit"]           masks = mask[l, Range[10]];      The matrices in `masks` have all $2l$ lines going out from the center, and they are rotated of $\frac{2\pi}{10l}k$ from one another, so that $M(l,1)=M(l,11)$. Here's one for $l=30$ (so 60 rays): ![Example of $M_k$ mtrix](http://i.stack.imgur.com/MMUi6.png) It is important that the number of "rays" in the $M_k$ matrices matches the number of "petals" in the true image from the camera, which is not a problem, as that number is fixed from the beginning. The algorithm calculates the discrete convolution of all 10 matrices $M_k$ with a kernel $K$ (the actual frame coming from the camera, cropped at 500 x 500 around a "guessed" center), so that I end up with a tensor $T$ made of 10 matrices of size 100 x 100.                   array = ImageData[image, "Real32"][[All, All, 2]] (*10 msec*)         T=ListCorrelate[array, 1 - #] & /@ masks          (*about 250 msec*)      (Here `image` is the image in 1, not yet a frame from the video feed.) With `Transpose[]` I turn $T$ into a 100 x 100 matrix `convol` of lists of length 10, on which I run a simple visibility test:                   visibility[list_]:=(Max[list]-Min[list])/(Max[list]+Min[list])         m = Map[visibility,convol,{2}];                   (*10 msec*)         {x,y}=Position[m,Max[m]];                         (*0.1 msec*)      Here `m` is nothing else than an map of where the visibility is highest, which corresponds to the true center of the pattern. Below, the corresponding `ArrayPlot[m]` and `ArrayPlot[Log[m]]` for the optical field in Fig. 1. ![m](http://i.stack.imgur.com/jn8n0.png)![Log\[m\]](http://i.stack.imgur.com/MlvDD.png) All this is fine, except that if I use `ListConvolve[]` it takes 300 milliseconds per frame, while if I use the convolution theorem with FFT it takes 150 milliseconds on my 8-core machine, and to run in real-time it should take no more than 20 milliseconds. As of now, the algorithm is an order of magnitude slower than I would like it to be. _**My question is the following:_** I have GTX 660 Ti, with 1344 CUDA cores. Is there a way I can use it to speedup the above algorithm (or a better version of it) and have it run in real-time? Or, is there a more clever version than the algorithm above? (I'm pretty sure that I am being a very naive programmer...) _**EDIT_** It is very important to find the center with high precision, because then by addressing the visibility curve (the plot of the 10 points calculated at the true center) I can detect rotations of the pattern with a precision even below $\pi/10l$. I tried `CUDAImageConvolve[]`, but it gives error messages for a too large kernel... Unfortunately a kernel is too large already around 60 x 60. **Other test images:** 40 petals: http://i.stack.imgur.com/ktps4.png 80 petals: http://i.stack.imgur.com/MUAAo.png 100 petals: http://i.stack.imgur.com/WBiZD.png 120 petals: http://i.stack.imgur.com/uFlBH.png 140 petals: http://i.stack.imgur.com/1B3P2.png 160 petals: http://i.stack.imgur.com/ZKyxa.png


title: Constraint on variables in summation

text: Is it possible to have a constraint on variables in summation of series just similar to pattern constraint e.g.               Sum[Binomial[i + 3, 3]*Binomial[2, j], {i, 0, Infinity}, {j, 0, Infinity} ]       with the condition that `i + j = 2`?


title: Site - Cell Correspondence in Voronoi Diagram obtained via VoronoiMesh

text: Consider the following:               pts = RandomReal[4, {10, 2}];     vor = VoronoiMesh[pts, {{0, 4}, {0, 4}}];          Graphics[{GraphicsComplex[        MeshCoordinates[vor], {Thick, Blue, MeshCells[vor, 1],          PointSize[0.02], Red, MeshCells[vor, 0], Opacity[0.2], Yellow,          MeshCells[vor, 2]}], PointSize[0.02], Point[pts[[1]]], Green,        MeshPrimitives[vor, 2][[1]]}]      ![Mathematica graphics](http://i.stack.imgur.com/2HLxl.png) Looking at the above, we see that the Voronoi sites (points that generate the Voronoi diagram) do not correspond to the Voronoi cells (in the order) generated by `VoronoiMesh`. Since `VoronoiMesh` discards the points used in generating the diagram, there's no obvious way I can see to align the Voronoi sites with their corresponding cells. This feels like an oversight to me, since one will have to do some complex post-processing to obtain such correspondence. **My question is:** is there an easy way to obtain a site - cell alignment of the Voronoi diagram obtained via `VoronoiMesh` other than using e.g. `RegionMember` which seems like an unnecessary overkill when this information should be available in the `Mesh` object. So e.g. with the points above, an output of the form shown below is desirable:               Transpose[{pts, MeshCells[vor, 2]}]      > >     {{{3.15429516, 1.68154241}, Polygon[{20, 11, 6, 15}]}, >      {{0.925806386, 3.57266721}, Polygon[{12, 3, 1, 13}]}, >      {{2.12535296, 3.88158116}, Polygon[{14, 5, 8, 18}]}, >      {{3.52419343, 0.689832144}, Polygon[{18, 8, 7, 17}]}, >      {{0.590442758, 1.53821808}, Polygon[{10, 4, 9, 6, 11}]}, >      {{2.70632597, 3.81614775}, Polygon[{19, 13, 1, 5, 14}]}, >      {{2.23994147, 1.5141697}, Polygon[{15, 6, 9, 2, 16}]}, >      {{3.68657472, 2.93505855}, Polygon[{16, 2, 3, 12, 21}]}, >      {{0.12127097, 2.63380289}, Polygon[{17, 7, 4, 10, 22}]}, >      {{2.21266451, 2.69765978}, Polygon[{1, 3, 2, 9, 4, 7, 8, 5}]}} >


title: How do I save a Unicode string?

text: I am having a problem saving a long complicated string with Unicode characters in it. I have boiled the problem down, I think, to this minimal example:               hw = {72, 101, 108, 108, 111, 32, 8594, 32,          87, 111, 114, 108, 100, 33};     str = FromCharacterCode[hw]      which assigns a _hello world_ string with a right arrow (the Unicode 8594 character) to `str`. If I then               ExportString[str, "Text"]      I get a different string, as the second line in ![right and wrong hello world strings](http://i.stack.imgur.com/Za1tj.png) instead of the first line. I have a program that reads cells from a Notebook and custom converts it to a LaTeX string. I just cannot save the string. What am I doing wrong?


title: Cell with no form using NotebookWrite

text: Is there a way to create a cell with no form? Usually a cell is either an input cell or an output cell, for example if you do `NotebookWrite[InputNotebook, "test"]` and hit Ctrl+E, the cell is in the input form `Cell["test", "Input"]`. However, if you do `CreateDocument["test"]`, there is no form related to the cell, i.e., `Cell["test"]`. Is there a way to create a cell with no form using `NotebookWrite[]`?


title: How can I prevent a polynomial from being simplified?

text: I'm having a problem with polynomials. Let's say I have a polynomial "2x^2 - 5x + 6 - 3x^2" .. How can I check that this expression is not simplified ? Additionally, I would like to locate the uncombined terms (2x^2 and -3x^2) and print them. I tried a lot of polynomial built-in functions, all of them simplify the expression before output.. For example,               MonomialList[2 x^2 - 5 x + 6 - 3 x^2]      > >     {-x^2, -5 x, 6} >   Is there any command to suppress automatic simplification ? Thanks.


title: Convenient string manipulation

text: With Mathematica I always feel that strings are "second class citizens." Compared to a language such as PERL one must juggle a lot of code to accomplish the same task. The available functionality is not bad but the syntax is uncomfortable. While there are a few shorthand forms such as `<>` for `StringJoin` and `~~` for `StringExpression`, most of the string functionality lacks such syntax, and uses clumsy names like: `StringReplace`, `StringDrop`, `StringReverse`, `Characters`, `CharacterRange`, `FromCharacterCode`, and `RegularExpression`. In Mathematica strings are handled like mathematical objects, allowing `5 "a" + "b"` where `"a"` and `"b"` act as symbols. This is a feature that I would not change, even if doing so would _not_ break stacks of code. Nevertheless it precludes certain terse string syntax wherein the expression `5 "a" + "b"` would be rendered `"aaaaab"` for example. * * * ### What is the best way to make string manipulation more convenient in Mathematica? Ideas that come to mind, either alone or in combination, are:   1. Overload existing functions to work on strings, e.g. `Take`, `Replace`, `Reverse`.     * This was the original topic of my question to which Sasha replied. It was seen as inadvisable. ****   2. Use shortened names for string functions, e.g. `StringReplace` >> `StrRpl`, `Characters` >> `Chrs`, `RegularExpression` >> `RegEx`   3. Create new infix syntax for string functions, and possibly new string operations.   4. Create a new container for strings, e.g. `str["string"]`, and then definitions for various functions. (This was suggested by Leonid Shifrin.)   5. A variation of (4), expand strings (automatically?) to characters, e.g. `"string"` >> `str["s","t","r","i","n","g"]` so that the characters can be seen by `Part`, `Take`, etc.   6. Call another language such as PERL from within Mathematica to handle string processing.   7. Create new string functions that conglomerate frequently used sequences of operations.


title: Context unique to each group at a specified level

text: Recent versions of Mathematica provide the option of having a unique `$Context` for each cell group, via:   * Evaluation > Notebook's Default Context > Unique to Each Cell Group This is an appealing concept, but I find it unusable, as my code spans multiple cell groups. I would like a way to specify a unique context for cell groups _of a certain level_ such as every `Section`, but _not_ a separate context for every `Subsection` or `Subsubsection`. A solution will need to affect new cell groups as they are created.


title: Why is slider not working properly in Manipulate?

text: This script is an abstraction from a script intended to plot errors in guiding a small telescope that is tracking a guide star. The data loosely imitate the kind of data one might get from the program PHD Guiding. The script should plot the data using slider control of dynamic starting points of moving windows on segments of data lists. The data are organized as lists of lists, e.g. `{{t, dx}, ...}`. Each sublist has two elements: (1) time, measured in seconds, and (2) tracking error measured in pixels on x or y coordinates on the screen of a guide camera. The starting time of a window is chosen with the slider. The length of the segment in the window is fixed. The script draws a panel with a slider and a plot. Each small movement of the slider should redraw the plot, giving a new six second window on a segment of the data, each successive window beginning one second later. The length of this imaginary guiding session and of each of the two lists, `dxList` and `dyList`, is 20. Hence, with windows of arbitrary length six, moving the slider from beginning to end should plot 15 windows on the data, each one replacing the previous. A very similar script using `Dynamic[]` rather than `Manipulate[]` works correctly and smoothly, but `Manipulate` makes a better looking plot with less code, so I would prefer to use it. The problem is that in this script using `Manipulate`, moving the slider draws only the first and the last window. It acts more like a setter than a slider. I would like to know where I have gone wrong and how to make the slider operate smoothly to plot all 17 windows.               Clear[dxList, dyList, window];          window = 6; (* arbitrary short segment length *)          (* Hypothetical list of error corrections dx by time t on x axis while guiding.  {{t, dx}, ...} *)     dxList = {{1, 1},   {2, 2},    {3, -1},   {4, -1.5}, {5, 0},  { 6, -.5}, {7, .5},                {8, 1.5}, {9, 1},    {10, -.5}, {11, 1},   {12, 2}, {13, -1},  {14, -2},                {15, 0},  {16, -.5}, {17, .5},  {18, 1.5}, {19, 1}, {20, -.5}};          (* Hypothetical list of error corrections dy by time on y axis while      guiding. {{t, dy}, ...} *)     (* Make list similar to dxList with random  elements. *)     dyList = {#[[1]], -#[[2]] + Random[Real, 1]} & /@ dxList;          (* select[] gets a window of data from dxList or dyList starting at      time t and ending at t + segLen. *)          select[t_, window_, list_] :=        Cases[If[ (#[[1]] >= t) && (#[[1]] < (t + window)), #] & /@ list, Except[Null]];          (* Check to see how select[] is working. *)     Print["Selected segment of dxList from record 5 = ", select[5, window, xList]]     Print["Selected segment of dyList from record 5 = ", select[5, window, yList]]          Manipulate[ (* The Slider variable is "start". *)           ListPlot[ (* Plots two lists, dxList, dyList. *)            {select[start, window, dxList], select[start, window, dyList]},              Joined     -> True,         PlotLabel  ->  Style["Telescope guiding errors, dx (Blue) dy (Red)",          FontSize  -> 8],        PlotStyle   -> {{Blue}, {Red}},       Background  -> White,       AxesLabel   -> {"Time", "Pixels"}       ],      {start, {1, Length[dxList] - window + 1, 1}, Slider}      ]


title: Implementing discrete and continuous Hilbert transforms

text: What is an efficient and accurate _Mathematica_ implementation of the Hilbert transform, for both continuous and especially discretely sampled functions? This transform relates phase and amplitude in minimum phase systems.


title: Partitioning with varying partition size

text: How can I partition a list into partitions whose sizes vary? The length of the $k$'th partition is a function $f(k)$. For example: if $l = \{1, 2, 3, 4, 5, 6\}$ and $f(k) = k$. Then the partitioning $p$ would look like $p = \{\{1\},\{2, 3\},\{4,5,6\}\}$


title: On coloring the faces of a surface differently with parameter-dependent colors

text: Old versions of _Mathematica_ (`$VersionNumber < 6`) supported a particular syntax of `ParametricPlot3D[]` that allowed for graphics specifications to be supplied as a fourth component of a vector-valued function; e.g. `ParametricPlot3D[{f[u, v], g[u, v], h[u, v], Hue[w[u, v]]}, {u, umin, umax}, {v, vmin, vmax}]`. Nowadays, this functionality has been superseded by the options `ColorFunction`, `PlotStyle`, and other related functions. Unfortunately, some flexibility seems to have been lost with these changes. For instance, the old implementation of `ParametricPlot3D[]` allowed me to use `FaceForm[]` to color the two faces of a polygon differently, with the stuff within `FaceForm[]` depending on the parameters. This allowed me to do things like this:               <<Version5`Graphics` (* simulates old-school graphics *)          ParametricPlot3D[{(3 + Cos[u]) Cos[v], (3 + Cos[u]) Sin[v], Sin[u],      {EdgeForm[], FaceForm[ColorData["DarkRainbow"][Rescale[v, {0, Pi/2}]],        ColorData["BrightBands"][Rescale[v, {0, Pi/2}]]]}},      {u, -7 Pi/6, 7 Pi/12}, {v, Pi/6, Pi/2},        Axes -> False, Boxed -> False, Lighting -> False, PlotPoints -> 41]      ![torus section with differently-colored faces](http://i.stack.imgur.com/ilxj5.png) Unfortunately, as can be seen through close inspection, I miss out on the adaptive plotting capability that is provided by the current implementation of `ParametricPlot3D[]`. I know that in the current version, the output is a `GraphicsComplex[]` object, with the colors assigned through the option `VertexColors`, which doesn't interact at all with directives like `FaceForm[]`. It has been suggested to me that I do two plots with the different colorings, with one a perturbed version of the other, and then combining these two into one `Graphics3D[]` object. This seems rather wasteful to me, however. In short: how can I do parameter-dependent coloring of a surface plotted with `ParametricPlot3D[]`, with the faces colored differently? * * * **(added 1/21/2011)** Both of the answers given so far rely on the fact that color gradients in _Mathematica_ can be turned into images that can subsequently be used as textures. Unfortunately, this doesn't seem to be applicable to general coloring schemes. Consider for instance the following twisted cylinders:               <<Version6`Graphics` (* restore default graphics *)          With[{a = 1, p = 2/3},      GraphicsGrid[{        {ParametricPlot3D[{a Cos[u] Cos[p Pi v] - a Sin[u] Sin[p Pi v],            a Cos[p Pi v] Sin[u] + a Cos[u] Sin[p Pi v], v},          {u, 0, 3 Pi/2}, {v, -1, 1}, Axes -> None, Boxed -> False,           ColorFunction -> (Hue[(1 - Cos[3 Pi #5] Sin[4 #4])/2] &),           ColorFunctionScaling -> False, Mesh -> False, PlotPoints -> 85],              ParametricPlot3D[{a Cos[u] Cos[p Pi v] - a Sin[u] Sin[p Pi v],            a Cos[p Pi v] Sin[u] + a Cos[u] Sin[p Pi v], v},           {u, 0, 3 Pi/2}, {v, -1, 1}, Axes -> None, Boxed -> False,           ColorFunction -> (Hue[(1 + Cos[3 #4] Cos[4 Pi #5])/2] &),           ColorFunctionScaling -> False, Mesh -> False, PlotPoints -> 85]}        }]]      ![colored twisted cylinders](http://i.stack.imgur.com/s4Ltu.png) where the cylinder on the left is colored with `Hue[(1 - Cos[3 Pi v] Sin[4 u])/2` and the one on the right is colored with `Hue[(1 + Cos[3 u] Cos[4 Pi v])/2]`. I want to be able to use something like `FaceForm[Hue[(1 + Cos[3 u] Cos[4 Pi v])/2], Hue[(1 - Cos[3 Pi v] Sin[4 u])/2]]`, as with the following image:               << Version5`Graphics`          With[{a = 1, p = 2/3},       ParametricPlot3D[{a Cos[u] Cos[p Pi v] - a Sin[u] Sin[p Pi v],         a Cos[p Pi v] Sin[u] + a Cos[u] Sin[p Pi v], v, {EdgeForm[],        FaceForm[Hue[(1 + Cos[3 u] Cos[4 Pi v])/2],                 Hue[(1 - Cos[3 Pi v] Sin[4 u])/2]]}},       {u, 0, 3 Pi/2}, {v, -1, 1},        Axes -> None, Boxed -> False, Lighting -> False, PlotPoints -> 85]]      ![two-faced colored cylinder](http://i.stack.imgur.com/WJCAd.png) and it looks to me that the current solutions don't apply to this situation. What can be done here?


title: Disable rounding up of PolarAxesOrigin

text: How to disable rounding up the radius which is used to calculate the origin of the polar axes with the option `PolarAxesOrigin`? Example:               PolarPlot[Sqrt[n], {n, 0, 20}, PolarAxes -> True,     PolarAxesOrigin -> {0, 7}, PolarTicks -> {"Degrees", Automatic}]      ![polar plot](http://i.stack.imgur.com/5Dc3f.png) It rounds `7` to `8`, `13` to `15` and `521` to `600`.


title: Keep palette visible when Mathematica application loses focus

text: When the Mathematica application loses focus, palette windows disappear (normal notebooks and dialogs (`CreateDialog`) stay). This is usually convenient because the small palette windows would clutter the screen. I would like to use a palette as a drag-and-drop target. For this I need to keep it visible even when another application is focused. Which notebook property needs to be changed to prevent one particular palette from disappearing when Mathematica loses focus? (Why I want to keep this drop target as a palette: it's easy to open from the Palettes menu and it has a small frame.) **Note:** Per the comments below, this does not seem to happen on all systems. **Update:** It seems that this is an OS-wide behaviour for this window type, at least on OS X. The answers suggest changing the window type (`WindowFrame` option). * * * Here are two screenshots to demonstrate. The only difference is switching the focus to the browser. ![Mathematica graphics](http://i.stack.imgur.com/ZIvDZ.png) ![Mathematica graphics](http://i.stack.imgur.com/KF60z.png)


title: How to create custom Graphics primitive?

text: How to create custom `Graphics primitive`? It should have the following properties, resembling properties of built-in geometric figures, like `Circle` etc:   1. Has constant head, say `RoundedRectangle`. It should not evaluate to the list of lines, so as normal `Rectangle`.   2. Can serve as a subject for `GeometricTransformation`


title: Using less memory to store and manipulate specific types

text: Is there a simple way to use Integer types (in particular, a table of Integer types) that require only 4 or 8 bytes (reps. 32 and 64 bits) representation? It seems that integers in _Mathematica_ have a 192 bits representation:               ByteCount[RandomInteger[]]      > >     24 >   Using a 64 bits representation would save up lots of memory in problems where you know you don't require too large integers and memory is an issue. Note that this question applies to other types.


title: Dealing with Empty Brackets in a List

text: I have a large list with varying constituent parts. Some of these are like this: i.e. `graphlist[[34]]`               {{{33, 0.0115084}}, {{33, 0.00539003}}, {{33, 0.0158185}},       {{33, 0.0136278}}, {{33, 0.00756737}}, {{33, 0.0017506}},       {{33, 0.038599}}, {{33, 0.00538894}}, {{33, 0.00656522}},      {{33, 0.00310004}}, {{33, 0.00151645}}, {{33, 7.75*10^-7}},      {{33, 0.00205609}}, {{33, 0.00125328}}}      Whereas others are like this: `graphlist[[1]]`               {{}, {{0, 0.00342769}}, {{0, 0.00503465}}, {},       {{0, 0.000187}}, {}, {}, {}, {}, {}, {}, {}, {}, {}}      Because they are all part of a long list, I'm trying to find a command that can do the following. On a list without any null values, I am running this command to get the second part:               graphlist[[34]][[All, 1]][[All, 2]]          > {0.0115084, 0.00539003, 0.0158185, 0.0136278, 0.00756737, 0.0017506,      > 0.038599, 0.00538894, 0.00656522, 0.00310004, 0.00151645,      >  7.75*10^-7, 0.00205609, 0.00125328}      But if I run a similar command on the list with nulls, the error message: "Part::partw: Part 1 of {} does not exist. >>" ensues. My goal is to similarly get output that would look like this: > {0,0.00342769,0.00503465,0,0.000187,0,0,0,0,0,0,0,0,0} Is there a way to construct a command that simply returns a 'zero' value for empty brackets? Thanks in advance.


title: Better way to make a certain list with palindromic sublists

text: Here is my code, which works, but seems a little too long, I think might be a more refined version.               Range[Ceiling[#/2]] ~ Join ~        If[OddQ[#], Rest, Identity] @ Reverse @ Range[Ceiling[#/2]] & /@ Range[9]          Range[Ceiling[#/2]] ~ Join ~ Range[Floor[#/2], 1, -1] & /@ Range[9]      > >     {{1}, {1, 1}, {1, 2, 1}, {1, 2, 2, 1}, {1, 2, 3, 2, 1}, {1, 2, 3, 3,  2, > 1}, >      {1, 2, 3, 4, 3, 2, 1}, {1, 2, 3, 4, 4, 3, 2, 1}, {1, 2, 3, 4, 5, 4, 3, > 2, 1}} >


title: Problem in units convertion when multipliying Boltzmann constant and a temperature

text: When define the temperature of a variable in Celsius, Mathematica 9.0 does not calculate the right answer when multiplying by boltzmann constant. Example:               Temperature1 = Quantity[100, "Celsius"];          Temperature2 = Quantity[373.15, "Kelvins"];          Temperature1 * Quantity["BoltzmannConstant"]          Temperature2 * Quantity["BoltzmannConstant"]      > >     Quantity[1.38065*10^-21, "Joules"] <-- WRONG Answer >   >     Quantity[5.15189*10^-21, "Joules"] <-- CORRECT Answer >   _Mathematica_ should be able to manage this units conversion, or there is something I'm doing wrong?


title: Problems with PropertyValue when Graph's vertices are Lists

text: I create a `Graph` which vertices are lists (points in n-dimensional space)               v1 = {{1, 2} -> {3, 4}, {5, 6} -> {7, 8}};     g1 = Graph[v1];     PropertyValue[{g1, VertexList[g1][[1]]}, VertexWeight] = 10      and I get a message error: > >     Set::write: Tag PropertyValue in PropertyValue[...] is protected >   Now, if I do               v2 = {1 -> 2, 3 -> 4};     g2 = Graph[v2];     PropertyValue[{g2, VertexList[g2][[1]]}, VertexWeight] = 10      everything is fine. `g1` and `g2` are structurally indentical, the difference is only in vertices type: list(`g1`) and scalar(`g2`). What's the problem here?


title: Finding an index with certain conditions

text: EDIT: I need to find out an index `i` which depends on certain conditions and I'm not able to implement it. I have a list (time points) $t_i$ and two constants $a,c$ the length of the list $t_i$ is $n$. So now I want to find the index $1 \leq i < n$, which can be found according to $t_{n-i}+a<c<t_{n-(i+1)}$ where $t_0:=\infty$. For example I know that `i=5`in this example, but I would like to have a function which tells me that:               c = 0.07875`     a = 0.01125`     ti = {0.056249999999999994`, 0.045`, 0.03375`, 0.0225`, 0.01125`, 0.`}     n=6      Do you have any tips how to implement it?


title: Applying rules with functions to expressions with derivatives

text: I have a function that I want to see applied, potentially within a derivative. The use of delayed vs. non-delayed rules seems irrelevant. See the following:               f$sub = {f[c_] :> a c};          f[c] //. f$sub;          q (f[c])^2 //. f$sub;          D[f[c], c] //. f$sub;          D[f[c] //. f$sub, c] //. f$sub;          (*The following is a rough reason of why I wanted rules *)     g$sub = {g[a] :> a + f[c] }          g2$sub = {g2[a] :> a + D[f[c], c] }          g[a] //. g$sub (* Don't want f sub'd, want to see it left with the function *)          g[a] //. Union[g$sub, f$sub] (* Want f$sub used to simplify things *)          f$alt$sub = {f[c_] :> 2 a c};          g2[a] //. Union[g2$sub, f$alt$sub ](* What does it look like with the alternative *)      Ideally, I would want to see the output as `a c`, `q (a c)^2`, `a`. The last doesn't work, presumably becomes `FullForm@D[f[c],c]` is `Derivative[1][f][c]` which doesn't match the pattern. Are there any easy tricks to get the substitution to respect derivatives? My first attempt of changing the rule to `fsub = {f[c_] :> a c, Derivative[1][f][c_] :> D[f[c], c]}` didn't seem to do anything (delayed or not).


title: Mathematica User Interface Tutorial

text: There I am looking for Mathematica User Interface Tutorial if anyone know Please provide the Link or description UserInface like Importing file using Buttons poping dialog boxes etc. Any help will be appriciated


title: Loop until convergence of two variables

text: I have the following program which i need to repeat steps until until two variables converge and I want this to be printed with the number of iterations: What I have : Input variables:               xTensionLaminate = 1325     SigmaFail = xTensionLaminate*VF     σApplied = xTensionLaminate*0.25     VF = 0.6      then the program is steps: 1.Apply tension part of the cycle. The applied stress on the fibers is               σAppliedFibers = σApplied/VF      2.All fibers with strength less than SigmaAppliedFibers fail. The fraction of fibers that have failed are:[%][7]               FibersTensionFail1 = CDF[NormalDistribution[795, 50 ], σAppliedFibers]      3.Fraction of fibers that remain[%][8]               FibersTensionRemaining1 = 1 - FibersTensionFail1      4.The remaining fibers now are equally loaded by the new stress[Mpa]               σAppliedFibersNew = σAppliedFibers/(1 - FibersTensionFail1)      5.Repeat steps corresponding to equations [7][8] until either convergence of (FibersTensionFail1 = FibersTensionRemaining1)<1 or all fibers fail FibersTensionFail1=1 This iteration needs to be done until `FibersTensionRemaining` and `FibersTensionFail` are equal or either one equal to unity. So I try to put this in a `While` loop.               While[FibersTensionRemaining <= FibersTensionFail,      FibersTensionFail = CDF[NormalDistribution[795, 50 ], σAppliedFibers];      FibersTensionRemaining = 1 - FibersTensionFail;      σAppliedFibersNew = σAppliedFibers/(1 - FibersTensionFail)      My question here is that in the NormalDistribution the `σAppliedFibers` variable changes at each iteration according to the formula `σAppliedFibersNew = σAppliedFibers/(1 - FibersTensionFail)` so the new `σAppliedFibers` comes back into `FibersTensionFail = CDF[NormalDistribution[795, 50 ], σAppliedFibers];` where after doing this n number of times there should be a converge in `FibersTensionRemaining` and `FibersTensionFail` Please help on this as i cannot find the way Thanks, Nick **EDIT: Note: The name of the Variables are slightly changed here but are the same.** What I do as a code manually and I stop the calculation: 1st iteration:               AccountingForm[     FibersFailed1 =      CDF[NormalDistribution[795, 50  ], StressAppliedFibers1] , 30] = 0.0000005919095091896093     AccountingForm[FibersRemaining1 = 1 - FibersFailed1, 31] = 0.999999408090491     StressAppliedFibers2 = StressAppliedFibers/(1 - FibersFailed1) = 552.084      2nd iteration:               AccountingForm[     FibersFailed2 =      CDF[NormalDistribution[795, 50  ], StressAppliedFibers2], 30] = 0.000000591909509834259     AccountingForm[FibersRemaining2 = 1 - FibersFailed2, 30]=0.99999940809049     StressAppliedFibers3 = StressAppliedFibers/(1 - FibersFailed2)=552.084      3rd Iteration:               AccountingForm[     FibersFailed3 =      CDF[NormalDistribution[795, 50 ], StressAppliedFibers3] , 30]=0.0000005919095098342807     AccountingForm[FibersRemaining3 = 1 - FibersFailed3, 30]= 0.99999940809049     StressAppliedFibers4 = StressAppliedFibers/(1 - FibersFailed3)=552.084      4th Iteration:               AccountingForm[     FibersFailed4 =      CDF[NormalDistribution[795, 50 ], StressAppliedFibers4] , 30]=0.0000005919095098342807     AccountingForm[FibersRemaining4 = 1 - FibersFailed4, 30]= 0.99999940809049     StressAppliedFibers5 = StressAppliedFibers/(1 - FibersFailed4)=552.084      So what we can see here is that after the 3rd iteration the values remain the same no matter how many iterations are made again. What I need to figure how to make the loop which will take these variables and change them until the values converge and then print the number of iterations and also the final value of The `FibersRemaining` and `StressAppliedFibers`. Simple yes but I do not know how to add to a loop changeable variables. thanks N


title: How to find lattice points on a line segment?

text: How do I find points on the line segment joining `{-4, 11}` and `{16, -1}` whose coordinates are positive integers?


title: Is there something like DensityPlot3D to visualize atomic orbitals?

text: I'm visualizing some hydrogen like atomic orbitals. For looking at plane slices of the probability density, the `DensityPlot` function works well, and with something like:               Manipulate[      DensityPlot[ psi1XYsq[u, v, z], {u, -w, w}, {v, -w, w} ,       Mesh -> False, Frame -> False, PlotPoints -> 45,       ColorFunctionScaling -> True, ColorFunction -> "SunsetColors"]      , {{w, 10}, 1, 20}      , {z, 1, 20, 1}      ]      I can get a nice plot ![hybrid orbital sample plot in x y plane](http://i.stack.imgur.com/nHtMY.png) I was hoping that there was something like a `DensityPlot3D` so that I could visualize these in 3D, but I don't see such a function. I was wondering how `DensityPlot` be simulated using other plot functions, so that the same idea could be applied to a 3D plot to construct a `DensityPlot3D` like function?


title: Sum of two functions, list processing

text: I am creating some simple graphs of functions defined by ordered pairs. Students are learning about "operations on functions", in this case, adding functions. If I have two functions defined by ordered pairs, how do I add them? I know this must be a simple list processing thing, I would appreciate any help. I.E.               functiong = {{-5, -5}, {-3, -3}, {1, 1}, {2, 2},  {5, 5}};     functionf = {{-5, 4}, {-3, 2}, {1, 2}, {2, 5}, {5, 5}};      I want to have the sum....               sum = {{-5, -1}, {-3, -1}, {1, 3}, {2, 7}, {5, 10}};      Easy to do manually, but if I modify the lists to create new examples, I'd like to have _Mathematica_ "add" those lists for me.... **Edit** Below, an example of the kind of question I see in the textbooks the students are using. They are told that what they see is function $f$ (red) and function $g$ (blue) and asked to draw $(f+g)(x)$ ![enter image description here](http://i.stack.imgur.com/hSUjq.png) My question is answered, but now that the context is clear, I would of course welcome any further suggestions on ways to easily create similar (and perhaps more interesting , but not harder!) problems.


title: Why FindFit could not exactly fulfill condition?

text: I tried to fit some data with boundary conditions, but `FindFit` just could not work. Does anyone know the reason? **Details** : The function to be fitted is `A*Tanh[x+a]+B`. Data is provided from `x=0` to some positive number. I set the requirement that the fitted function should be same as `Tanh[x]` at `x=0` both for its value and its first derivative. I realized such a condition in `FindFit` through a direct setting; however, it does not seems to work, i.e. the function is NOT exactly connected to the expected one. There is still about 10^-7 to 10^-10 difference between the two. Following is my code and result                tL = Transpose[{Range[0, 5, .5], Tanh[#] & /@ Range[0, 5, .5] + RandomReal[.2, 11]}];     f = Tanh[x]; fD = D[tf, {x, 1}];     fitf = A*Tanh[x + a] + B; fitfD = D[fitf, {x, 1}];     fitf0 = fitf /. x -> 0; fitfD0 = fitfD /. x -> 0;     fit = FindFit[tL, {fitf, {fitf0 == 0, fitfD0 == 1}}, {{a, 0}, {A, 1}, {B, 0}}, x];     fitf=fitf/.fit;     F = Piecewise[{{f, x < 0}, {fitf, x >= 0}}]     FD = D[F, {x, 1}]     Show[Plot[F, {x, -6, 6}, PlotStyle -> Red, AxesLabel -> {x, "f(x)"}],ListPlot[tL], PlotRange -> All]     Limit[F, x -> 0, Direction -> -1]     Plot[FD, {x, -1, 1}, AxesLabel -> {x, "f'(x)"}]      ![enter image description here](http://i.stack.imgur.com/1VeLZ.png) ![enter image description here](http://i.stack.imgur.com/WB6jD.png)


title: Formatted text in a Dynamic or Manipulate control

text: I am using a `Manipulate` control to show different calculations for the same user-specified parameters. I would like to show the results for the calculation the user selected and also provide some formatted text to describe how I arrived at the result. So as a test I placed the formatted text in a `Cell` set as `Text` and assigned that cell to a variable. I then show in a `Table` the results of the calculation and the text cell. What I'm finding is that the text displays the _Mathematica_ functions which are used to format the text instead of just displaying the formatted text. If I use `CellPrint` for this text variable I can get the cell to display properly in the notebook. `CellPrint` however returns `Null` so I can't pass it's value to my `Dynamic` or `Manipulate` controls. Let me show an example of my code:               testText1 :=       Cell[TextData[{Cell[          BoxData[FormBox[SuperscriptBox["R", "*"], TraditionalForm]],           FormatType -> "TraditionalForm"], " = Rate of star formation = 10 "}],        "Text", CellChangeTimes -> {{3.547210260347546*^9, 3.547210296541616*^9}}]          CellPrint[testText1]          Manipulate[      Switch[testStatChoice, 1,        testText1], {{testStatChoice, 1,         "Select Calculation"}, {1 -> "1: First Calculation Example"},        ControlType -> PopupMenu}]      I have hunted around for other methods or properties that will allow me to display my paragraphs of text with equations within an `Manipulate` but haven't yet found a solution. Edit: So I am now headed in the right direction. So a trimmed down version of what I have so far is the following: [Code sample deleted. Look at final solution below.] My issue is with the 2nd, 3rd and 4th paragraphs. The text continues onto the next line but it gets indented. Edit2: I solved the line indenting issue with RowBoxes that continue onto another line by wrapping the RowBox with a StyleBox and setting the LineIndent property to 0.0 for that StyleBox. You may have also noticed that I was using spaces for my indenting of my code lines. That was ugly and I replaced that with AdjustmentBoxes that have BoxMargins set so that the line was indented to my preference. I am going to delete my large code insert above and replace it below with my fixed end result. I still have an issue with my last paragraph but I think I should be able to solve it.               stat1TestText :=        DisplayForm[        Column[{Cell[           "This statistic is calculated by adding up from the beginning \     of the Milky Way the time it took for the first Sun-like stars to \     come into existence, the time that elapsed on Earth for life to start \     on Earth once the Sun had formed and the time it takes for new life \     to come into existence based on the given set of Drake Equation \     Parameters."],           StyleBox[           RowBox[{"The last number to calculate is the amount of time (on \     average) that it would take for life to come into existence given the \     first 4 parameters of the Drake Equation", " (",              SuperscriptBox["R", "*"], " = rate of star formation, ",              SubscriptBox["f", "p"], " = fraction of stars with planets, ",              SubscriptBox["n", "e"],              " = # of planets that could support life, and ",              SubscriptBox["f", "l"],              " = fraction that develop life).  So Frank Drake\     \[CloseCurlyQuote]s original values for these parameters were:"}],            LineIndent -> 0.0],           AdjustmentBox[           RowBox[{SuperscriptBox["R", "*"], "= 10 new stars per year  "}],            BoxMargins -> {{4, 0}, {0, 0}}],           AdjustmentBox[           RowBox[{SubscriptBox["f", "p"],              "= 0.50 fraction of stars with planets", " = ",              RowBox[{"50", "%"}]}], BoxMargins -> {{4, 0}, {0, 0}}],           AdjustmentBox[           RowBox[{SubscriptBox["n", "e"],              "= 2 planets that could support life for each star"}],            BoxMargins -> {{4, 0}, {0, 0}}],           AdjustmentBox[           RowBox[{SubscriptBox["f", "l"],              "= 1.00 fraction of stars that develop life = ",              RowBox[{"100", "%"}]}], BoxMargins -> {{4, 0}, {0, 0}}],           Cell["Using the above parameters,every year, the number of stars \     to have the genesis of life in the Milky Way can be calculated by \     mulitplying those 4 numbers together."],           AdjustmentBox[           RowBox[{SuperscriptBox["R", "*"], "\[Times]",              SubscriptBox["f", "p"], "\[Times]", SubscriptBox["n", "e"],              "\[Times]", SubscriptBox["f", "l"], "=",              RowBox[{"10", "\[Times]", "0.50", "\[Times]", "2.0",                "\[Times]", "1.00"}],              " = 10 stars in the Milky Way have life begin on a habitable \     planet in their solar system each year."}],            BoxMargins -> {{4, 0}, {0, 0}}],           AdjustmentBox[           StyleBox[            RowBox[{"This means that every ", FractionBox[1, 10], "th",               Cell["of a year new life will show up in the galaxy. For \     Drake Equation Parameters that are not so optimistic, such as the \     numbers I label More Reserved, you can estimate life coming into \     existence in the galaxy once every 150 years up to 28000 years. \     Really this number is small enough that it doesn't play a significant \     role in our calculation of microbial life first began in the Milky \     Way but I will use it anyway."]}], LineIndent -> 0.0],            BoxMargins -> {{0, 0}, {0, 0}}],           Cell["This means that every 1/10th of a year new life will show \     up in the galaxy. For Drake Equation Parameters that are not so \     optimistic, such as the numbers I label More Reserved, you can \     estimate life coming into existence in the galaxy once every 150 \     years up to 28000 years. Really this number is small enough that it \     doesn't play a significant role in our calculation of microbial life \     first began in the Milky Way but I will use it anyway."],}, Left,          1.5]];


title: How do I obtain the correct double limit?

text: The command               Limit[(Sin[x^2] + Sin[y^2])/ (x - y) /. x -> 0, y -> 0]     (*        0     *)      I think that _Mathematica_ finds the iterated limit instead of the double limit. It should be noted that WolframAlpha produces the correct answer, when asking for > "limit (sin(x^2)+sin(y^2))/(x-y) as x->0 and y->0" ![enter image description here](http://i.stack.imgur.com/9zjRo.png)


title: How to write aligned equations and export them HTML/TeX

text: This question is mainly about exporting to HTML/TeX. For those of you who do not know how to write aligned equations in _Mathematica_ please see this answer. Lets assume that you modified your stylesheet as I mentioned in my answer. In my notebook this is the cell expression I have:               Cell[BoxData[         FormBox[GridBox[{         {         RowBox[{         RowBox[{"a", "+", "b", "+", "c"}], "\[AlignmentMarker]", "=", "d"}]},         {         RowBox[{"c", "\[AlignmentMarker]", "=",          RowBox[{"d", "-", "a", "-", "b"}]}]}     }], TraditionalForm]], "DisplayMath"]      Now I want to export this expression to TeX, we can do this with:               cell = Cell[BoxData[             FormBox[GridBox[{             {             RowBox[{             RowBox[{"a", "+", "b", "+", "c"}], "\[AlignmentMarker]", "=", "d"}]},             {             RowBox[{"c", "\[AlignmentMarker]", "=",              RowBox[{"d", "-", "a", "-", "b"}]}]}         }], TraditionalForm]], "DisplayMath"];     Convert`TeX`BoxesToTeX[cell]      The output is:               \begin{array}{c}      a+b+c=d \\      c=d-a-b     \end{array}      The function `Convert`TeX`BoxesToTeX` is undocumented but the documentation does show how to use it under examples. It seems that the function doesn't do anything with the `\\[AligmentMarker]`, but I'm sure we could make good use of them. What we want to do is find any appearances of the `\\[AligmentMarker]` and substitute them with "&". And if we did find some `\\[AligmentMaker]`s then we use StringReplace to change "array" for "aligned". This is the output that I would like to end up with:               \begin{aligned}      a+b+c&=d \\      c&=d-a-b     \end{aligned}      Does anyone know how to create a wrapper function that does this? The main problem I'm having is replacing things in `cell`.


title: Geographic background containing both outlines and contours: how?

text: I would like to create a map which will show lakes and rivers together with elevation contours and contour labels. What is the simplest way to do this with `GeoGraphics` in version 10? The solution I have (below) looks much too convoluted. * * * I need to plot this point on the map:               pos = WeatherData["KP60", "Coordinates"]      This is good, except the background is not what I need:               g = GeoGraphics[{PointSize[Large], Darker@Red, Point[pos]}]      ![enter image description here](http://i.stack.imgur.com/8BHhV.png) Since I can't seem to mix two `GeoStyle`s, I tried overlaying a polygon that contains the contours. This lead to the following:               {range, projection} = {GeoRange, GeoProjection} /. Options[g, {GeoRange, GeoProjection}]          {a, b, d, c} = Tuples[Reverse@range]          GeoGraphics[{{GeoStyling["ContourMap", ContourShading -> None,  ContourLabels -> True], Polygon[{a, b, c, d}]}, {PointSize@Large, Darker@Red, Point[pos]}}, GeoRange -> range]      ![enter image description here](http://i.stack.imgur.com/XNRp5.png) However, now the projection has changed, and adding `GeoProjection -> projection` causes the polygon not to show. Is there a fix for this?