Histogram: Bars not stacked, not overlapped, but side by side?

I would like to make a histogram with multiple datasets. Then Mathematica allows to either overlap or stack the data from the different data sets. However, I would like to have the bars side by side, but could not find a way how to do this. To illustrate what I mean: ![Mathematica graphics](http://i.stack.imgur.com/VXqw3.png) I want the thing on the right, but Mathematica does the thing on the left. Thanks! Obviously I should have supplied the data. Thanks for the answers so far - I couldn't figure out how to apply these to my data. Here they are:               {{1.25268, 0.944003, 0.508123, 0.835465, 1.08849, 0.730729, 0.539924,        0.458693, 0.62392, 1.14587, 0.69167, 0.969927, 0.627031, 0.371587,        0.477359, 0.844106, 0.414103, 1.03941, 0.95057, 0.448324, 0.419288,        0.362599, 0.482544, 0.129278, 0.39682, 0.838922, 0.870031, 0.566886,        0.522641, 0.472174, 0.447978, 0.558935, 1.19184, 0.807466,        0.621846, 0.765641, 0.701002, 0.998617, 0.536467, 0.602834, 1.04632,        0.563083, 0.629105, 0.493605, 0.421362, 0.716212, 0.520913,        0.653301, 0.688559, 0.612859, 0.21673, 0.683028, 0.381265, 0.638092,        0.671275, 0.710335, 0.301763, 0.860698, 0.621846, 0.460767,        0.716212, 0.719323, 0.642931, 0.665745, 0.628759, 0.383339, 1.0999,        0.713446, 0.564466, 0.65261, 0.494988}, {0.698237, 0.699274,        0.649499, 0.673349, 0.626339, 0.576218, 0.692707, 0.626339, 0.65261,        0.63982, 0.544418, 0.535085, 0.67888, 0.660906, 0.675769, 0.676115,        0.665399, 0.573453, 0.450743, 0.650881, 0.643623, 0.647425,        0.64777, 0.645005, 0.643968, 0.69962, 0.62945, 0.55375, 0.670584,        0.671621, 0.659523, 0.642586, 0.330107, 0.362254, 0.63982, 0.699274,        0.680954, 0.668856, 0.638438, 0.703768, 0.690633, 0.610785,        0.681991, 0.557898, 0.666091, 0.674732, 0.646388, 0.633253, 0.58486,        0.690978, 0.605254, 0.716212, 0.659523, 0.619772, 0.672312,        0.688213, 0.640857, 0.679226, 0.587625, 0.591773, 0.596613,        0.640857, 0.624611, 0.658832, 0.640166, 0.670584, 0.64466, 0.66056,        0.646388, 0.528517}, {0.237815, 0.238161, 0.251988, 0.211891,        0.222606, 0.197373, 0.220878, 0.193571, 0.248185, 0.226409,        0.206015, 0.225026, 0.234013, 0.26132, 0.222952, 0.252333, 0.187003,        0.243692, 0.211545, 0.273764, 0.193225, 0.236433, 0.238161,        0.230211, 0.258209, 0.246803, 0.203941, 0.254062, 0.272382,        0.244037, 0.231594, 0.155894, 0.23505, 0.24542, 0.208434, 0.1673,        0.230557, 0.248877, 0.176979, 0.218804, 0.213619, 0.272382,        0.253025, 0.203249, 0.227791, 0.259246, 0.212582, 0.237124,        0.197373, 0.221915, 0.258209, 0.277221, 0.286899, 0.17214, 0.216384,        0.207397, 0.241618, 0.252333, 0.208434, 0.206706, 0.238852,        0.256827, 0.200138, 0.237124, 0.244037, 0.239889, 0.215347,        0.215002, 0.119945, 0.196336, 0.196336, 0.208434, 0.247148}}      Which with Histogram gives: ![enter image description here](http://i.stack.imgur.com/FW2vD.png)


Find elements in a decay chain using IsotopeData

I am trying to write a program using the _Mathematica_ function `IsotopeData`, but am finding the code troublesome. Due to my (relative) familiarity with Python, I am puzzled as to how _Mathematica_ works, as they are very different. $\require{mhchem}$ What I am trying to do, is to find the elements in a decay chain which end with either $\ce{^{191}_{77}Ir}$ or $\ce{^{193}_{77}Ir}$. In Python syntax, what I'm trying to do would look a bit like this:               #A would be the Atomic Mass and Z the Atomic Number     #DaughterNuclide(Z,A) would return the Daughter Nuclides of the isotope          def IsoCheck(z,a):         try:             x = DaughterNuclide(z,a)             if x in Isotopes:                  return [z,a]             else:                  return [0,0]         except:             return [0,0]          L=[]     Isotopes = [[76,191],[78,191]]     for a in xrange(1,295):         for z in xrange(1,119):             if IsoCheck(z,a) != [0,0]:                 L.append(IsoCheck(z,a))          repeat = 1     #Then, repeat until all chains are over     while repeat == 1:          repeat = 0          for x in L:              if IsoCheck(x) != [0,0] #Lets just pretend it isn't a list                  L.append(x)                  repeat = 1      Now, my question is this: what would the equivalent code to perform this task in _Mathematica_ look like?


FindFit returns worse result when putting constraints on parameters

I want to fit some data to a model of exponential decay using the `FindFit` function:               data = {{0, 78}, {24, 64.5}, {48, 70.5}, {96, 54}, {144, 64.5}, {216, 3}, {336, 0}, {696, 0}};     model = data[[1, 2]]*Exp[-k1*t];          fit1 = FindFit[data, model, k1, t]     fit2 = FindFit[data, {model, k1 > 0}, k1, t]          modelf1 = Function[{t}, Evaluate[model /. fit1]];     modelf2 = Function[{t}, Evaluate[model /. fit2]];          Plot[#[t], {t, 0, 696}, Epilog -> Map[Point, data], PlotRange -> All] & /@ {modelf1, modelf2}      Interestingly, the model with no specified constraint on _k1_ finds a much better solution than the constrained model, but the solution of the unconstrained problem falls within the range of the constrained one. Here is the output: * * *               {k1 -> 0.00512571}     {k1 -> 1.01979}      ![Result of the Plot](http://i.stack.imgur.com/bB51j.png) Why isn't the solution to the constrained problem at least as good as the solution of the unconstrained one?


Assigning weights to edges of a hypercube based on the Gray code labels for vertices being connected

Say I want to construct an $n$-dimensional hypercube graph $G$ using the command: `G = HypercubeGraph[n]`. I'd like to assign edge weights to the $2^{(n-1)}n$ edges in $G$, $(e_1,e_2,...)$, with something like a function `assignWeights[G,weightList]` where `weightList` is of the form:               weightList = {{grayCodeA, grayCodeB, w1},{grayCode..., grayCode..., w2}, ...};      Here, each entry in `weightList` specifies a weight $w_i$ for an edge between vertices in the hypercube correspond to specific Gray codes (e.g. between "0010" and "0110" codes for the $n = 4$ dimensional hypercube in this picture: http://en.wikipedia.org/wiki/File:Hamming_distance_4_bit_binary.svg). Nothing's better than an example, so let's construct one for the $n = 3$ dimensional hypercube, where our edgeweights are just random real numbers over the interval $[0,1]$:               n = 3;          tupleSet = Tuples[{0, 1}, n];     weightList = Array[{} &, 2^(n - 1)*n];          counter = 0;     For[a = 1, a <= Length[tupleSet], a++,       For[b = a + 1, b <= Length[tupleSet], b++,         If[HammingDistance[tupleSet[[a]], tupleSet[[b]]] == 1,           counter += 1;           weightList[[counter]] = {tupleSet[[a]], tupleSet[[b]], RandomReal[{0, 1}]};           ];         ];       ];          weightList      (Please let me know if you there's a nice built-in way to generate these tuple pairs without nested loops...) How would we write something like `assignWeights[G,weightList]`? Once we assign the weights, can we color code the edges to visually represent the weight assignments?


Differentiating an unknown solution to a PDE

Sorry if this question is too basic -- I'm not very familiar with Mathematica. I am interested in a way to systematically address the following sort of problem: Suppose that $u=u(x,y)$ is a function of two variables on $\mathbb{R}^2$ that satisfies a Liouville type equation: $$\Delta u= e^{-2u}$$. I can check by hand that the function $$v=\partial^2_{xy} u+\partial_x u \cdot \partial_y u$$ is harmonic, i.e. $$\Delta v=0.$$ My question is how can I make Mathematica verify this? I'm interested in more complicated examples I don't want to check by hand, but the principle is the same.


How to avoid plotting lines not defined in a Which function?               fa1[x_] := Which[x >= 15, 1, x >= 10, 0.55, x >= 5, 0.1]     Plot[fa1[x], {x, -1, 20}, BaseStyle -> AbsoluteThickness[4],       PlotLegends ->        LineLegend["Expressions", BaseStyle -> AbsoluteThickness[4]]]      ![enter image description here](http://i.stack.imgur.com/beNmg.png)


Mathematica Solve Hangs Indefinitely

The following code hangs               Clear[S, Ext, k, α, β, γ, δ, f, a, b, c];     S[k_] := α β^(f - k) γ^(f - k)^2 δ^(f - k)^3;     Ext[k_] := a + b k + c k^2;     Solve[{S'[km] == Ext'[km], S''[km] == Ext''[km], Ext[km] == S[km]}, {a, b, c}, Reals];      This sort of algebra was going to get really ugly and I was really hoping Mathematica could handle it... any ideas on how what might be causing Mathematica to get stuck in the "Running..." state? My goal is is a solution for {a,b,c} in terms of {α, β, γ, δ, f, km}.


How does Mathematica determine that an evaluation should be terminated?

How **exactly** does _Mathematica_ determine that evaluation of particular expression should be finished and the result should be returned? Here are some examples of unclear behavior which have arisen, when I tried to understand deeper Todd Gayley's `Block` trick:               x := Block[{tried = True}, x + 1] /; ! TrueQ[tried]         x + y         (* 1 + x + y *)          x + 1      > During evaluation of In[3]:= $IterationLimit::itlim: Iteration limit of 4096 > exceeded. >>               (* Hold[4096 + x] *)      Why did the evaluation stop at `1 + x + y` in the first case and the second go into an infinite loop? The other interesting side of the trick is that when we evaluate just `x`, the infinite loop does not begin. The reason is that evaluation in this case does not go outside of the `Block` scope:               Clear[x];     x := Block[{tried = True}, x + 1] /; ! TrueQ[tried]     x /; ! TrueQ[tried] := x + 1     x     x /; TrueQ[tried] := x + 1     x          (* 1 + x *)      > During evaluation of In[1]:= $RecursionLimit::reclim: Recursion depth of 256 > exceeded. >>               (* 254 + Hold[RuleCondition[$ConditionHold[$ConditionHold[          Block[{tried = True}, x + 1]]], ! TrueQ[tried]]] *)      But if we try to use `Set` instead of `SetDelayed` we get a couple of infinite loops:               x = Block[{tried = True}, x + 1] /; ! TrueQ[tried];      ![](http://i.stack.imgur.com/j6XYg.png) What happens in this case?


Is it possible to obtain explicit symbolic solutions to such linear ordinary differential equations?

The ordinary differential equations to solve have symbolic parameters $k_1,k_2,k_3,k_4,k_5,k_6 \in \mathbb{R}$. $$ \left\\{ \begin{array}{l} {y_1}'(t)=-{k_1} {y_1}(t)-{k_2} {y_1}(t),\\\ {y_2}'(t)={k_2} {y_1}(t)-{k_3} {y_2}(t),\\\ {y_3}'(t)={k_1} {y_1}(t)+{k_3} {y_2}(t)-{k_4} {y_3}(t),\\\ {y_4}'(t)={k_4} {y_3}(t)-{k_5} {y_2}(t) {y_4}(t)+{k_6} {y_5}(t),\\\ {y_5}'(t)={k_5} {y_2}(t) {y_4}(t)-{k_6} {y_5}(t)\\\ \end{array} \right.$$ The ODE system itself seems simple when all $k_i$ are numerical numbers. How to solve it symbolically ? Is it possible to obtain explicit solutions? Update: Expressions in MMA:(DSolve does not work for such nonlinear ODE system)                 DSolve[{D[y1[t], t] == -k1*y1[t] - k2*y1[t],       D[y2[t], t] == k2*y1[t] - k3*y2[t],       D[y3[t], t] == k1*y1[t] + k3*y2[t] - k4*y3[t],       D[y4[t], t] == k4*y3[t] - k5*y2[t]*y4[t] + k6*y5[t],       D[y5[t], t] == k5*y2[t]*y4[t] - k6*y5[t]}, {y1[t], y2[t], y3[t],        y4[t], y5[t]}, t]


On using DiracDelta[t] in OutputResposne in version 10. Different result from version 9

I am baffled by this. I was trying to run same example I had working in version 9.01 and found now I get empty plots. The example is here . Here is a simplified version of the above. The same exact example produces a plot in version 9.01. But in Version 10, it is empty. ![enter image description here](http://i.stack.imgur.com/t6ajQ.png)               w = 1; z = 0.07;     sys = TransferFunctionModel[w^2/(s^2 + 2 z*w*s + w^2), s];     fun = First@OutputResponse[sys, DiracDelta[t], {t, 0, 20}];     Plot[Evaluate[%], {t, 0, 20}]      I tried to find what is going on, so I asked for analytical solution, in version 10 it says:               w = 1; z = 0.07;     sys = TransferFunctionModel[w^2/(s^2 + 2 z*w*s + w^2), s];     fun = First@OutputResponse[sys, DiracDelta[t], t] // ComplexExpand // Simplify // Chop      ![Mathematica graphics](http://i.stack.imgur.com/E8C68.png) In version 9.01:               w = 1; z = 0.07;     sys = TransferFunctionModel[w^2/(s^2 + 2 z*w*s + w^2), s];     fun = First@OutputResponse[sys, DiracDelta[t], t] // ComplexExpand // Simplify // Chop      ![Mathematica graphics](http://i.stack.imgur.com/jF5Vi.png) So in version 10 the solution seems to be reversed. going back in time !                Plot[Evaluate[fun], {t, -20, 0}]      ![Mathematica graphics](http://i.stack.imgur.com/xD0uO.png) Any idea what is going on? What changes could have caused this?


Rectangles of the Same Size Aren't Shown the Same!

I've written a mathematia code which arranges $n$ unit squares in columns of length $m$ (of course, when $n$ is not divisible to $m$, then the last column is not full). This is the code:               n = 60;     m = 1;     l = {};     For[i = 0, i <= n - 1,       l = Append[l,         Rectangle[{Quotient[i, m], Mod[i, m]}, {Quotient[i, m] + .9,           Mod[i, m] + .9}]]; i++]     Graphics[{Red, l}]      **Here's my problem:** For a fixed value for $n$ (say, $60$), if you change $m$ then you get squares of smaller or larger sizes, as shown below. I want all the squares for different $m$'s be of the same size. What should I do? Thanks in advance. for $n = 60$ and $m = 1$: ![enter image description here](http://i.stack.imgur.com/H9P67.gif) for $n = 60$ and $m = 13$: ![enter image description here](http://i.stack.imgur.com/55UOW.gif)


Changing line thickness without changing line length

Is there any way to change the thickness of line without changing the width? For instance, the following example shows that as thickness increases, the white gap decreases. Is there any way to maintain the gap?               Show[         ListPlot[{{0, 2}, {13.4, 2}}, PlotRange -> All, Joined -> True,                  Mesh -> None, PlotStyle -> {Gray, Thickness[0.01]}],         ListPlot[{{14.7, 2}, {24, 2}}, Joined -> True, Mesh -> None,                  PlotStyle -> {Gray, Thickness[0.01]}]     ]      ![thin lines with gap](http://i.stack.imgur.com/UTdOv.png)               Show[         ListPlot[{{0, 2}, {13.4, 2}}, PlotRange -> All, Joined -> True,                  Mesh -> None, PlotStyle -> {Gray, Thickness[0.05]}],         ListPlot[{{14.7, 2}, {24, 2}}, Joined -> True, Mesh -> None,                  PlotStyle -> {Gray, Thickness[0.05]}]     ]      ![thick lines without gap](http://i.stack.imgur.com/TVtxR.png)


Factor inside argument

How do you use Factor so that it will factor expressions inside the arguments of some bigger expression. For example                Factor[ Cos[t w - t z]]      gives                Cos[t w - t z]      but i would like it to give:                Cos[t(w - z)]


Mathematica command for type checking?

I have a program where users can enter mathematica commands that can evaluate to any of the standard numeric types (complex, real, int, etc.), or to boolean values. Moreover the users can enter functions that depend on variables. (For the sake of this post let's assume the variables are all of type complex.) I want to know if there's a mathematica command that can type-check an _arbitrary_ string. Specifically, I'd want something like               ReturnsComplex[string, assumptions]      that would return true for "1/x + 7x^2 + Sin[x]" but false for "E^x == 5", say. Does anyone know of such a command, or a way to implement one without a huge quantity of work? (Assume that I can identify all the variables in the string and substitute in if necessary.)


Why Solve and Simplify give different results?

I want to solve the following equation               y == (1/(1/4 + y) - 1/(3/4 - y))/((1/4 + y) + 1/(3/4 - y))      I tried               Simplify[y == (1/(1/4 + y) - 1/(3/4 - y))/((1/4 + y) + 1/(3/4 - y)), y]      which gave me > Solve[0.166667] Then I tried               Solve[y == (1/(1/4 + y) - 1/(3/4 - y))/((1/4 + y) + 1/(3/4 - y)), y]      which gave me > {{y -> 1.70683179538858`}, {y -> -0.82623525169495` \+ 0.902601424800742`I},   >  {y -> -0.82623525169495` \- 0.902601424800742`I}, {y -> > 0.195638708001323`}} I guess `Simplify` deletes potential roots, but `Solve` and `Simplify` didn't even have an overlap in the roots. Any idea?


Strange behaviour of OutputResponse

I am having some trouble when using OutputResponse. For instance consider the following command               Simplify[Chop[OutputResponse[       TransferFunctionModel[           {             {{12265.875860667435 + 15863.964729950849*s + 5000.*s^2}},              12265.875860667435 + 15986.623488557521*s + 5132.222766045224*s^2 +             81.0807167110999*s^3 + 16.908502769264427*s^4 + 1.*s^5           },           s,           SystemsModelLabels -> {{None}, {None}}           ],       UnitStep[t],       t]]]      The output is zero on version 9.0.1-mac. It can't be zero. The above transfer function is a result of the feedback connection of a series connection between two transfer functions. What am I missing? Many thanks Ed


How can I return a Sequence?

Recently I had the need to redefine a certain symbol in my init.m so it would be automatically omitted from any lists it appears in. I decided to redefine it to an empty sequence, e.g. `Locked = Sequence[]`, but that got me thinking. What if I wanted to return a sequence (not necessarily an empty one) in a `:=` definition? `Return` doesn't have the `SequenceHold` attribute, and adding it in a package might cause problems, so what would I do? **EDIT:** I think I've figured out what exactly causes me to have the problem. I've defined it to display a `Message` first to let me know whenever a package I'm importing attempts to attack my computer. (It _is_ trying to cause my computer to behave in a manner not consistent with my wishes, after all.) So I defined it as `Locked := (Message[Locked::nope]; Sequence[])`, but strangely it just returns Null. (It doesn't show a return value, but if I do `{Locked}`, it returns `{Null}`, and if I try to set it as an attribute it says that Null is not a valid attribute and doesn't set any of them.)


float output left in CDF

I'm experimenting with embedding a CDF on a Wordpress site and while it mostly works, the plots are running out of room along the right edge. It seems like if the images were floated left they would fit and look like the output does in MMA. This might have a simple answer, yet how to force the plot output to float left? See http://nomtbf.com/2013/04/weibull-vs-exponential-pdfs/ for an example of the issue.


How can one find undocumented options or option values in Mathematica?

_Mathematica_ has a lot of undocumented or poorly documented options.   1. How does one go about working out if there is an undocumented option that might solve a particular problem?   2. How does one work out what the universe of possible values the option might take are? (This also applies to options whose existence is documented, but where the range of valid values isn't.) * * * As background, here is a collection of ones I and others have found so far: **Graphics** The `Method` option is an option for `Graphics` and related commands like `BarChart`. It is mentioned in the notes in the documentation and turns up in `Options[Graphics]` but is not listed as an option in the documentation with any examples. There are many sub-options, none of which are explicitly documented.   * `Method -> {"ShrinkWrap" -> True}` removes whitespace that _Mathematica_ adds as a tiny rim to each plot. (pointed out by Sjoerd)   * `Method -> {"GridLinesInFront" -> True}` does what it says (see Brett Champion's answer to this question and this MathGroup thread). `Dynamic` `GridLines` using this option are present in much of the graphical Wolfram|Alpha output (See, e.g. the edited number line code).   * `Method -> {"AxesInFront" -> True}` also does what it says. (see TomD's comment on Brett's answer)   * `Method -> {Refinement -> {ControlValue -> angle}}` sets the angle that decides when two points in a plot are not further subdivided - default is `5\[Degree]`. (see Yaro's answer here and the relevant page in Stan Wagon's book. Also, a `Plot` version comparison by Alexey)   * The option `"MessagesHead"` is used to track the origin of calls to `Plot`, etc., made by dependent plot functions such as `LogPlot`, `LogLinearPlot`, and `DateListLogPlot`. This allows the correct options and messages to be passed to and from the general function. An example of its use can be seen in this question.   * `ImageSizeRaw` option for various plotting and graphics functions is not documented, but turns out to be important for embedding CDFs into web pages.   * `PrivateFontOptions -> {"OperatorSubstitution" -> False}`, as documented here, stops minus signs, parentheses and the like from being in _Mathematica_ 's special fonts rather than the selected text font.   * s0rce discovered that the `ScalingFunctions` option works for line plots (`ListPlot`, `Plot`, etc). Possible values include `"Reverse"`, `"Log"` `"Log10"` – the last of these being itself undocumented.   * Not strictly a graphics function, but often used to create nice-looking ticks, `FindDivisions` has an undocumented `Method` option: for example, `FindDivisions[{-1.8,8.9}, 6, Method -> "ExtendRange"]` gives the encompassing divisions `{-2, 0, 2, 4, 6, 8, 10}`, as does `Method -> Automatic`; any other setting for `Method` gives the _inner_ divisions: `{0, 2, 4, 6, 8}`.    * You can control the amount a `PieChart` segment pops out of the chart when you click it using `SetOptions[Charting'iSectorChart, {PopoutSpacing -> n}]`, where `n` is numeric. The default is 0.2; for fun, try a negative number. You can suppress this behaviour altogether using `SetOptions[Charting'SectorChart, {Popout -> False}]` (in both these examples, change the quote mark to a backquote). **Panels** As noted in an earlier question, these options pop up in some graphics/panels, but are unrecognised when one uses them explicitly in `Panel`, `Graphics` or related structures:   * `LineColor`   * `FrontFaceColor`   * `BackFaceColor`   * `GraphicsColor` **Legends** There seem to be a lot of undocumented options here:   * `AssembleLegendContainer`   * `BubbleScaleLegend`   * `ColorGradientLegend`   * `ContourLegend`   * `CurveLegend`   * `GridLegend`   * `Legend`   * `LegendContainer`: `SetOptions[Legending`GridLegend, Legending`LegendContainer -> Identity]` removes the border from legends (thanks to Mr.Wizard)   * `LegendHeading`   * `LegendImage`   * `LegendItemLayout`   * `LegendLayout`   * `LegendPane`   * `LegendPosition`   * `LegendReap`   * `Legends`   * `LegendSize`   * `LegendSow` **Equation-solving and minimisation/optimisation**   * `Evaluated -> False` option of `FindRoot` (TomD in comments)  **System options for evaluation** Per acl's answer below, `SystemOptions[]` reveals many hidden options using the following syntax. These can be set using `SetSystemOptions[]`.   * `"PackedArrayOptions" /. SystemOptions[]`   * `"CompileOptions" /. SystemOptions[]` Although this book by Nancy Blachman has been written for Version 2, it is still not a bad starting point: http://www.amazon.com/Mathematica-Quick- Reference-Version-Spiral/dp/0201628805


Geomarker Scaling

Struggling to get a 3d cylinder to scale properly on a street map. I want to use the stacked cylinder as a custom pin.               mypin = Graphics3D[     Table[Cylinder[{{0, 0, h}, {0, 0, h + 0.95}}, 0.25], {h, 1, 19}],      ImageSize -> Automatic];          GeoGraphics[{GeoPosition[{51.5144, -0.08028}],      GeoMarker[GeoPosition[{51.5144, -0.08028}], mypin,      "Scale" -> Automatic, "Alignment" -> Bottom]},      GeoRange -> Quantity[0.05, "Miles"]]      I know automatic doesn't work on its own but I've been replacing it with various values and all that happens is the marker vanishes. I should add that the reason for doing this is that the cylinder represents a building of x floors, and once I get the cylinder scaled properly the intention is to use each cylinder to display various feature of the building. E.g. Red cylinder if a floor is over capacity, cylinder radius proportional to the number of desks it contains.


How to create a group action table with Mathematica?

Background: I want to explain the Sylow Theorems as detailed as possible, therefore I am rewriting the proof using concrete examples. Since the answers to my questions ( about Mathematica ) have often, if not always, exceeded my expectations, and I lack the tools to adequately show a table, I start with a compact description of my question. I can elaborate if required, of course. Question: **Is it possible to create a group action table with Mathematica?** For example: Let $G = \left\\{ 1,a,a^2, b, ba, ba^2 \right \\}$, where $a^3=b^2=1, ab=ba^2 (D3) $ . Let $S$ be the set of subsets of size $3$ of $G$: $\left\\{ \left\\{ 1,a,a^2 \right \\}, \left\\{1,a,b \right \\}, ..., \left\\{b,ba,ba^2 \right \\} \right \\} $ . Define the map $f: G \times S \rightarrow S \ $ by $(g,s) \mapsto gs$. **The group action table, illustrating the map $f$ would be of size 20 X 6 with each cell containing an element of $S$.** I have ( experience with ) the Mathematica AbstractAlgebra package. I'll accept answers in GAP also.


Flatten at a certain level

In an earlier question the brainteasing fourth syntax variant of `Flatten` was discussed. I see that with               Flatten[{{{1, 2, 3}, {4, 5}}, {{6, 7}, {8, 9, 10}}}, {{1}, {2, 3}}]      I can `Flatten` the lists at level 2 (i.e., Merge `{1, 2, 3}` with `{4, 5}`, and `{6, 7}` with `{8, 9, 10}`) to `{{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}}`, something that I expected `Flatten` to be able to do with the usual level specification. But that convention doesn't work here. `Flatten[{{{1, 2, 3}, {4, 5}}, {{6, 7}, {8, 9, 10}}}, {2}]` returns `{{{1, 2, 3}, {6, 7}}, {{4, 5}, {8, 9, 10}}}` With that introduction, now to my question: How would I use `Flatten` to flatten the slightly differing               {{{1, 2, 3}, {4, 5}, 11}, {{6, 7}, {8, 9, 10}, 12}}      to               {{1, 2, 3, 4, 5, 11}, {6, 7, 8, 9, 10, 12}}?      If that's not possible I'd have to resort to using an additionally `Map`, but I really would like to avoid that, as I just feel that `Flatten` or another single function ought to be able to do this on its own. In this case, a simple               Flatten /@ {{{1, 2, 3}, {4, 5}, 11}, {{6, 7}, {8, 9, 10}, 12}}      would do, and since `Map` does follow the level specification conventions I can use it to `Flatten` other depths in more complex constructions.


Celebration: How to golf a marriage with a prefix free code

We all know a conspicuous member of our community got hitched recently. As most of us are not in Malta, and weren't able to fly there, I thought of a celebration question. Sort of. The challenge is golfing a function (Mma only) that finds a prefix free encoding for the letters of two sentences. The trick is that both sentences (given as parameters) must share **the same encoding** , with one of them written backwards. The number of available symbols for the encoding is also a parameter for the function (always less than 10), and the function should attempt to find the shortest encoding for that number of symbols. There is no a-priori guarantee that a solution exists for every parameter set. As an example, related to our celebration:               we wish you the best      and               sz is the handsomest groom      Inspiration was taken from this question (which does not require a prefix free code), but is a good explanation of what is required. Happy wedding and golfing! Shortest code wins! **PS:** A bounty of 100, a wedding garter and the party leftovers to the winner **EDIT** Clarifications. To be updated as comments and answers arise   1. No caps. Only lowercase.   2. No need to encode whitespaces, special chars or punctuation (skip them and consider only lowercase letters)    3. Your solution _should_ be able to show up results before they are back from the honeymoon.


What are some useful, undocumented Mathematica functions?

There have already been some questions about some undocumented functionality in Mathematica. Such as ( _please add to these lists!_ )   * How can one find undocumented options or option values in Mathematica?   * What do these undocumented Style options in Mathematica do?   * Undocumented command-line options Also, other questions and answers that contained undocumented functions   * `Internal`InheritedBlock` (also in Exposing Symbols to $ContextPath)   * `Internal`Bag` (in Implementing a Quadtree in Mathematica) (also here)   * `RuleCondition` (in Replace inside Held expression) Along with the "Undocumented (or scarcely documented) Features" segment of the What is in your Mathematica tool bag? question. Szabolcs also maintains a list of Mathematica tricks which contains a list of "undocumented stuff". * * * **So, what undocumented functions do you know and how do you use them?** (Added useful information is maybe how you discovered the functions and any version dependence.)


CUDALink Error: A CUDALink kernel timed out?

I'm following the CUDALink tutorial [ http://reference.wolfram.com/language/CUDALink/tutorial/Introduction.html ] and everything is going fine until I get to the part that calls CUDADot on the matrices. At this part I get a time out error but the Out line returns almost immediately. I've included the commands and some other CUDA and system information bits. I'm running Windows 8.1 with Mathematica 10 Home. There is an on-board intel graphics chip and the Nvidia GPU. I can see that the Nvidia GPU registers that Mathematica is using it when I execute the CUDAQ[] command (Nvida taskbar icon shows GPU is active and that Mathematica is using it). What is odd is that I can execute a few of the CUDA examples in the help. I've tried a few of the image ones (the tiger and the moon, for example) but I can't seem to get the CUDADot to work. Everything seems to be installed fine.               Needs["CUDALink`"]          CUDAQ[]     True          CUDAInformation[]     {1 -> {"Name" -> "GeForce GTX 860M", "Clock Rate" -> 1019500,      "Compute Capabilities" -> 5., "GPU Overlap" -> 1,      "Maximum Block Dimensions" -> {1024, 1024, 64},      "Maximum Grid Dimensions" -> {2147483647, 65535, 65535},      "Maximum Threads Per Block" -> 1024,      "Maximum Shared Memory Per Block" -> 49152,      "Total Constant Memory" -> 65536, "Warp Size" -> 32,      "Maximum Pitch" -> 2147483647,      "Maximum Registers Per Block" -> 65536, "Texture Alignment" -> 512,     "Multiprocessor Count" -> 5, "Core Count" -> 160,      "Execution Timeout" -> 1, "Integrated" -> False,      "Can Map Host Memory" -> True, "Compute Mode" -> "Default",      "Texture1D Width" -> 65536, "Texture2D Width" -> 65536,      "Texture2D Height" -> 65536, "Texture3D Width" -> 4096,      "Texture3D Height" -> 4096, "Texture3D Depth" -> 4096,      "Texture2D Array Width" -> 16384,      "Texture2D Array Height" -> 16384,      "Texture2D Array Slices" -> 2048, "Surface Alignment" -> 512,      "Concurrent Kernels" -> True, "ECC Enabled" -> False,      "TCC Enabled" -> False, "Total Memory" -> 4294967296}}          randM = RandomReal[1, {4000, 4000}];          AbsoluteTiming[randM.randM;]     {1.276902, Null}          randMG = CUDAMemoryLoad[randM]     CUDAMemory["<22093>", "Double"]          AbsoluteTiming[res = CUDADot[randMG, randMG]]     CUDADot::lnchtout: A CUDALink kernel timed out. >>     {0.071061, CUDADot[CUDAMemory["<22093>", "Double"], CUDAMemory["<22093>", "Double"]]}          CUDADriverVersion[]     "340.52"          CUDAResourcesInformation[]     {{"Name" -> "CUDAResources", "Version" -> "10.0.0.1",      "BuildNumber" -> "", "Qualifier" -> "Win64",      "WolframVersion" -> "10+", "SystemID" -> {"Windows-x86-64"},      "Description" -> "{ToolkitVersion -> 6.0, MinimumDriver -> 270.0}",      "Category" -> "", "Creator" -> "", "Publisher" -> "",      "Support" -> "", "Internal" -> False,      "Location" ->      "C:\\Users\\Edmund\\AppData\\Roaming\\Mathematica\\Paclets\\\     Repository\\CUDAResources-Win64-10.0.0.1", "Context" -> {},      "Enabled" -> True, "Loading" -> Manual,      "Hash" -> "8cd86e25825c095afcb781fa82d3cf73"}}          CUDAResourcesInstall[]     {     PacletManager`Paclet[     "Name" -> "CUDAResources", "Version" -> "10.0.0.1",      "MathematicaVersion" -> "10.*",      "Description" -> "{ToolkitVersion -> 6.0, MinimumDriver -> 270.0}",      "SystemID" -> {"Windows-x86-64"}, "Qualifier" -> "Win64",      "Extensions" -> {{     "Resource",      "Resources" -> {     "CUDAToolkit", "ExampleData", "LibraryResources", "CUDALink",      "OpenCLLink"}}},      "Location" -> "C:\\Users\\Edmund\\AppData\\Roaming\\Mathematica\\\     Paclets\\Repository\\CUDAResources-Win64-10.0.0.1"]}      Any ideas? Thanks, Edmund


Ploting legends in contourplot

In Mathematica 8. Given this:               f[x_, y_, z_] := z - x^2 - y^2 (*relation among the variable f[x,y,z]==0*)     parameter = Range[0.1, 1, 0.1];(*choice of parameter values*)      I'm trying to plot the level curves               ContourPlot[Evaluate@Table[f[x, y, z] == 0, {z, parameter}], {x, -1, 1}, {y, -1,1}, PlotLegends -> parameter]      I have the next error message: > ContourPlot::optx: "Unknown option PlotLegends in ContourPlot[{0.1 > -x^2-y^2==0,0.2 -x^2-y^2==0,0.3 -x^2-y^2==0,0.4 -x^2-y^2==0,0.5 > -x^2-y^2==0,0.6 -x^2-y^2==0,0.7 -x^2-y^2==0,0.8 -x^2-y^2==0,0.9 > -x^2-y^2==0,1. -x^2-y^2==0},{x,-1,1},{y,-1,1},PlotLegends->parameter]" I tried using:               Needs["PlotLegends`"]          ShowLegend[        ContourPlot[Evaluate@Table[f[x, y, z] == 0,         {z, parameter}], {x, -1, 1}, {y, -1,1}, PlotLegends -> parameter] ]      what I should do?


Edit Automatic PlotRange

if I have a plot let us say               Plot[x^2 - 5 x - 10, {x, 0, 8}]      I want o check if there is a way to know the automatic plot range and to add or subtract from that range as I need. I will assume something fictitious like this:               Plot[x^2 - 5 x - 10, {x, 0, 8}, PlotRange -> (Automatic + {0, 10})]      is there a way to do something like this?


Problem with infinite sum

I am facing a problem in evaluating infinite sums of the following form. As a first thing define the following function               Z[n_] := Product[1/(1 - t^i), {i, 1, n}]          P[list_] := (num = Union[list]; Product[Z[Count[list, num[[i]]]], {i, 1, Length[num]}])      Then consider a sum of the following kind               Sum[P[{i, j}]*t^(-i - j), {i, 0, \[Infinity]}, {j, 0, \[Infinity]}]      Now, Mathematica behaves in a strange way: it considers the P[{i,j}] factor as if i is always different than j. This does not make sense, since for example I am summing over the couples (2,2) and (3,3). I believe the problem relies in the way the infinity is considered, since everything works fine with arbitrary high finite sums. What could I do?


How to typeset a system of equations

Is it possible to typeset systems of equations in _Mathematica_ , and if so, how can I do it using a big left bracket as one could in LaTeX with `\left\{ ... \.`? I know this is possible using the `Piecewise`, but is there a special command for this?


The following code doesn't seem to work finding Chomatic Number of Undirected Graph in Mathematica(MathKernel)

In[37]:= g = Graph[{4->3, 5->3, 5->4, 6->1, 6->2, 6->4, 6->5}]          Out[37]= Graph[{4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2, 6 -> 4, 6 -> 5}]      I created a graph as show above and while trying to import combinatorica package, I get the following error               In[38]:= << Combinatorica`;          General::compat:         Combinatorica Graph and Permutations functionality has been superseded by         preloaded functionaliy. The package now being loaded may conflict with         this. Please see the Compatibility Guide for details.      I don't know what's going on here, but while trying to find the chromatic number using the following command, it gives the subsequent following error.               In[43]:= CN = ChromaticNumber[g]          First::normal: Nonatomic expression expected at position 1 in First[All].          First::normal: Nonatomic expression expected at position 1 in First[All].          Part::partw: Part 2 of First[All] does not exist.          First::normal: Nonatomic expression expected at position 1 in First[All].          General::stop: Further output of First::normal          will be suppressed during this calculation.          Part::partw: Part 2 of First[All] does not exist.          Part::partw: Part 2 of First[All] does not exist.          General::stop: Further output of Part::partw          will be suppressed during this calculation.          Range::range: Range specification in          Range[V[Graph[{4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2, 6 -> 4, 6 -> 5}]]]          does not have appropriate bounds.          Table::iterb: Iterator {Combinatorica`Private`i$318,           V[Graph[{4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2, 6 -> 4, 6 -> 5}]]} does          not have appropriate bounds.          Join::heads: Heads Combinatorica`Private`Double and Table at positions 1 and 2          are expected to be the same.          Join::heads: Heads Combinatorica`Private`Double and Table at positions 1 and 2          are expected to be the same.          Join::heads: Heads Combinatorica`Private`Double and List at positions 1 and 2          are expected to be the same.          General::stop: Further output of Join::heads          will be suppressed during this calculation.          Table::iterb: Iterator {V[Graph[{4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2,              6 -> 4, 6 -> 5}]]} does not have appropriate bounds.          Transpose::nmtx:         The first two levels of the one-dimensional list {} cannot be transposed.          Transpose::nmtx:         The first two levels of the one-dimensional list {} cannot be transposed.          Part::pspec: Part specification          {4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2, 6 -> 4, 6 -> 5}          is neither an integer nor a list of integers.          Part::pspec: Part specification          Graph[{4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2, 6 -> 4, 6 -> 5}][[2]]          is neither an integer nor a list of integers.          Table::iterb: Iterator {V[Graph[{4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2,              6 -> 4, 6 -> 5}]]} does not have appropriate bounds.          General::stop: Further output of Table::iterb          will be suppressed during this calculation.          Part::pspec: Part specification Combinatorica`Private`Double[]          is neither an integer nor a list of integers.          General::stop: Further output of Part::pspec          will be suppressed during this calculation.          Range::range: Range specification in          Range[1 + Table[0, {V[Graph[{4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2,                  6 -> 4, 6 -> 5}]]}][[Combinatorica`Private`Double[],0]]] does not          have appropriate bounds.          Complement::heads:         Heads Part and Range at positions 2 and 1 are expected to be the same.          Out[43]= Table[Complement[Range[1 +           >       Table[0, {V[Graph[{4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2, 6 -> 4,           >             6 -> 5}]]}][[Combinatorica`Private`Double[],0]]],           >     Table[0, {V[Graph[{4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2, 6 -> 4,           >           6 -> 5}]]}][[Combinatorica`Private`Double[],0]]],           >    {V[Graph[{4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2, 6 -> 4, 6 -> 5}]]}]      Did I go wrong somewhere ? please help.


Is it possible to find a CellularAutomaton behind a sequence of 2D Tables

Maybe this is a hard question, maybe not. Whoever knows the answer can help me a lot starting working on CA theory. Let's suppose I have a sequence               a[n_] := Table[f[i, j], {i, -n, n}, {j, -n, n}]      for some known function $f$. And let's make it simple: $f$ takes only the values $0$ and $1$. Is there a way to find a cellular automaton that will create the same table-- that is, to generalize the approach demonstrated by Michael E2 in his answer to the question about how to generate a certain type of nested array? For reference, the code he presented was the following:               Grid[CellularAutomaton[{     670410854876259114171370389518449844628889143930760386943729872789478228151265\     8462491554691453382697921609151728673186802143641955019044568101339107753983,     2, {1, 1}}, {{{0}}, 1}, {{{9}}}] /. 1 -> "*"]


How to use many global assumptions

I would like to use many global assumptions. Say I have two global assumptions.               $Assumptions = 0 < a < 1          $Assumptions = 0 < b < 1      Then I would like to print `Yes` if `a b > 1` holds and print `No` otherwise. For this I have               Refine[If[a*b > 1, Print[Yes], Print[No]], $Assumptions]      My result is just a repetition of `If` term as follows:               If[a q > 1, Print[Yes], Print[No]]      Can anyone help?


Image Restoration

I want to degrade the image, and then execute the restoration, such as a lena.jpg. I tried this:               lena = ExampleData[{"TestImage", "Lena"}];     lena1 = GaussianFilter[lena, 5]       With these get stained image lena1.jpg is stained image from lena this image use for recognition in folow step                ImageDeconvolve[lena1, GaussianMatrix[5.10]]      only parameter 5.10 gives beter picture then lena1.jpg Then this I have three pictures "lena.jpg"-original image, "lena1.jpg"-degraded image and Image after deconvolve - Restoration image. Problem: 1) I do not know which settings (filters) to apply during restoration pictures and 2) Which function to use when degradation and restoration during which, as you know? Whether we can write a concrete example of an image degradation and restoration so obtained images? Sorry for my English... :)


Calling Mathematica from Lazarus/Freepascal

I will appreciate if anyone can give me an hint about freepascal and mathematica mathlink communication. I'd like to build a Form using Lazarus/freepascal that call mathkernel. I'm trying to move away from ExcelLink-component to a home made Form.


Function that displays set of integers fulfilling constrictions

I would like to make a function of three parameters $i$, $j$ and $k$ that displays a list of integers fulfilling some criteria. Specifically the set of integers is: $\zeta_{ijk} = \Big\\{p\in\\{2j+2,2j+3,\ldots,2k+2\\}\ |\ $ $p=2i+1,\ \text{or}\ p\leq i+j,\ \text{or}\ p\geq i+k+3 \Big\\}$ for $k\in\\{0,1,\ldots\\}$, $\ j \in \\{0,1,\ldots,k\\}$ and $i\in\\{j,j+1,\ldots,k+1\\}$. where $|$ denotes that constrictions on $p$ follows. To clarify, some examples are: $\zeta_{000}=\zeta_{100}=\emptyset$ $\zeta_{001}=\\{4\\}$, $\ \zeta_{101}=\\{3\\}$, $\ \zeta_{201}=\\{2\\}$ $\zeta_{111}=\zeta_{211}=\emptyset$ $\zeta_{002}=\\{5,6\\}$, $\ \zeta_{102}=\\{3,6\\}$, $\ \zeta_{202}=\\{2,5\\}$, $\ \zeta_{302}=\\{2,3\\}$ And so on. I have problems implementing the logical constrictions in e.g. the Table-function, inside my user-defined function. Any ideas?


TimeSeriesForecast Forecasts

I am trying to make sure I understand how `TimeSeriesForecast` works. I apologize in advance for the basic nature of this question. I am using Mathematica 10. I create a `TimeSeries` in a stock like GE, containing O/H/L/C prices and from there estimate a vector autoregression (ARMA) model using some in-sample data. I now want to produce 1-step ahead forecasts, period by period, for the out of sample data. The code I have listed below does this and produces the results as shown. I want to make 100% sure that the forecast produced for period n are the forecast OHLC prices for period n, and not the forecast prices produced at period n for period n+1. So below, is the first set of forecast prices the forecast for period 8325, or the forecasts produced in period 8325 for period 8326? Whats confusing me is the with ISend = 8325, I get:               GE["Path"][[ISend + 1]]         (* {8325, {20.4819, 20.5104, 20.1867, 20.32}} *)      i.e it seems that the TimeSeries variable GE somehow "lags" by 1 period. _Forecasting code_               ISend         (* 8325 *)          n = 1;          forecasts =        Flatten[Table[         TimeSeriesForecast[eproc,            TimeSeriesWindow[GE, {ISend - 3 + i, ISend - 2 + i}], {n},            Method -> "Covariance"]["Path"], {i, 1, 386}], 1];          Take[forecasts, 5]          (* {{8325, {19.8498, 19.8257, 19.3094,         19.6899}}, {8326, {20.711, 20.7849, 20.3424,         21.2416}}, {8327, {20.142, 20.4853, 20.1133,         20.2042}}, {8328, {20.1565, 20.2824, 20.009,         20.0737}}, {8329, {20.0761, 20.1621, 19.96, 20.0177}}} *)


Associate the elements of a table

I have a table form as:               table = {{a, 6}, {b, ff}, {c, 2}}      I want to associate the first element of each pair from the table to the second element of the pair as in:               a=6, b=ff, c=2.      I want the parameters a,b,c to be recognized throughout the program with assigned values. Doing as below, everything is perfect:               a := 6;     a^2 + 5     Clear[a]     Out[2] 41      But in the example below, I failed:               Clear[table, a, b, c]     table = {{a, 6}, {b, ff}, {c, 2}}     z = table[[1, 1]]     z := table[[1, 2]]     a^2 + 5          Out[4]  {{a, 6}, {b, ff}, {c, 2}}     Out[5]  a     Out[6]  5 + a^2      Why this fail?


Differential equation with random variable

How can I derive analytically or compute numerically the solution to following differential equation $$ dy/dt = y\cdot X\cdot (y\cdot X - g(y,X))\cdot X $$ where X is a random variable (e.g. from a normal distribution) and g is a known function of y and X, e.g. $g=E[(y\cdot X)^2]$ ?


Web Browsing Automation with Mathematica

I want to build a bot to automate web browsing, this mean something like:   * filling forms   * press "submit" buttons   * find certain text inside pages   * and so on... How can I do this with Mathematica? The `Import` function just make you download a single web page but it doesn't support cookies and similar things to build a complete automated bot, does Mathematica have some useful packet to do so?


Question about modifying a Slider2D control

Background: I want to develop a custom control, based on a 2D slider. I currently have this ( working ) example.                 Manipulate[        If[(iOld != i || jOld != j),         lata[[1]] = i; lata[[2]] = j];         i = lata[[1]];         j = lata[[2]];         iOld = i;         jOld = j;         lata,         Row[{            Column[{            Control[{{i, i, "i"}, -5, 5, 0.25}],            Control[{{j, j, "j"}, -5, 5, 0.25}]}]            ,            Control[{{lata, lata, "lata"}, {-5, -5}, {5, 5}, {0.25, 0.25}}]         }],         Initialization -> {           lata = {1, 0},           i = lata[[1]],           j = lata[[2]],           jOld = j,           iOld = i         }]      This control is a 2D Slider and two normal sliders in sync. Clearly the two sliders are not necessary but I like the built-in functionality of the slider's drop down precision- entry ( and auto play ). **Question: Is there an easy way to build a 2D Slider with the drop down precision provided for a normal slider, thus in x and y direction? Or do I have to build it from scratch?** ( Update: Basically remove the two sliders =itself= but remain all other functionality in the example. )


About number truncation of ticks display in ListPlot

In my problem, I need to plot a figure in a relatively small region of the $x$ axis, e.g.,                ListPlot[{RandomReal[#] + 10^4,         RandomReal[#]} & /@ (Range[100] 10^-10), Frame -> True, Axes -> False]      and the figure is displayed properly, but all the tick marks have the same label: ![Mathematica graphics](http://i.stack.imgur.com/ujeYw.png) Is there any clever way to get rid of this problem?


Where can I take a pool of words from?

Dear Community members, I am thinking about an interactive machine to teach a school child to write difficult words correctly. As a first step I need a collection of words. I will select a pool of words from this collection. Then I will use the pool to make the machine. My question is: is there a way to get the words with _Mathematica_? A constraint is that I need German words.


Doing a chi-square independence test in Mathematica

I have a matrix consisting of the following data:               Needs["HypothesisTesting`"]     data = {{11, 206}, {32, 1374}}      How would I make a chi-square independence test with a level of 5% of significance out of this? When I try the following:               In[9]:= ChiSquarePValue[data, 0.05]      I get this a very little value out of it.               Out[9]= OneSidedPValue -> 1.89247*10^-303      However, the correct answer would be something around `0.017` or `1.7%`.


Convert Locator (x,y) values to Lat/Lon as per GetCoordinates on Map

I want to convert the (x,y) coordinates you get from using a locator on a map to Lat/Lon coordinates - exactly like the GetCoordinates tool does when you right click on a map.               Manipulate[GeoGraphics[GeoPosition[{51.5164090, -0.0943590}],     GeoRange -> Quantity[0.20, "Miles"]], {u, Locator}, {u}]      ie if I create a simple map and use use right click -> GetCoordinates it will give me 3 pairs of values   1. Lat Lon   2. Lat Lon in degrees   3. (x,y) <\-- this is the one Locator returns. Simple demo map               GeoGraphics[GeoPosition[{51.5164090, -0.0943590}],      GeoRange -> Quantity[10, "Miles"]]      Im presuming its related to GeoPositionENU somehow but the starting point seems to change for each instance of the map.


Neural Network and New Mathematica version

do you think that Wolfram would integrate the Neural Networks package in the new version of Mathematica? Also because the Neural Networks package is not compatible with ListPlot in Mathematica 9.0. Thanks!


Why do I get an error message when for this type of recursion?

When I type the following code:               mus[] = 0;      mus[x__] := First[List[x]] + mus[Rest[List[x]]]      What one would think would happen is that if, `mus[1,2,3,4]` is input, the number 10 would be output. However, I get the error message, > $RecursionLimit::reclim: Recursion depth of 1024 exceeded However if I use the following code:               lsum[{}] := 0;      lsum[L_] := First[L] + lsum[Rest[L]];      sum[x__] := lsum[List[x]]      It works as I thought it should, namely if input lsum[x1,x2,x3,...,xn], the output is the sum of the xi's.


Limit of a complex function

Can someone show me how to find the limit of a complex function? Example:               z1 = 3 + 4*I          some_function[z] = z * z1      Set-up:               Limit[some_function[z],z->z1]      The result should be > >     (4*I + 3)*z >   but I get > >     Limit[some_function[z], z -> 3 + 4 I] >   What am I doing wrong? I tried to search in google and in the help files in the section about complex analysis. Thank you for your attention.


Generating social network graph from a CSV file

I am new to Mathematica and wanted to generate undirected graph for data sets that show the relationships of organizations with each other. The data is in a square matrix. The cells of the matrix provide information about the relationships between each pair of organization (0 if no relationship exists; 1 if there is some relationship; 2 if the organizations work as partners; 3 if any of the board members serve in the paired organization). There are 81 organizations in the study, so the matrix is 81x81. The data data structure in CSV looks like the following. ![example of data structure](http://i.stack.imgur.com/6IlMw.jpg) I would very much appreciate if anyone would provide me the steps for generating the social network graph for the stated scenario using Mathematica 9. Thanks! -Brian


Solving for any one variable in a formula given values for all the others

Consider the formula for the area of a rectangle. I can write the formula as `area[length_, width_] := length*width` and plug in numbers for the dimensions and get the area. Also, I could write a formula for finding each specific dimension in terms of the remaining two. My question is this: Is there a way to write a single expression which will do the whole job, that is I can plug in any two of the components of the area formula and have _Mathematica_ return the third?


Searching linked lists that contain lists?

Following the advice I've read here and other sites, I've been trying to use the Mathematica equivalent of a linked lists...               testList = {{a, b}, {{c, d}, {{e, f}, {}}}}      Now, I want to see if `{c,d}` is a member of `testList`. How do I do that? MemeberQ doesn't transverse the list recursively and Flatten also nukes the sub lists. The following seems to work but I would expect there to be a cleaner simpler way...               memberInLinkedList[{}, _] = False;     memberInLinkedList[l_List, v_] := True /; First[l] == v;     memberInLinkedList[l_List, v_] := memberInLinkedList[Last[l], v];      Is there a more eloquent or built-in way to do this? Perhaps a general idiom or package that handles this transparently?


Generating a random tree of given cardinality, depth, and labeling

For demo, exploration and teaching purposes, I would like to be able (and asking you for help) to generate these special instances of trees: For given:   * **N** \- number of nodes in the tree   * **D** \- depth of the tree (largest distance root-leaf) I need to generate a random tree with all nodes labeled so that:   * Root is labeled _"Lorem"_   * First or other prominent child of the root is labeled _"ipsum"_.   * All other children are labeled randomly from words from following paragraph: _"dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."_ * * * Example from related question: (but this solution doesn't care about depth limitations)               vtx[] := Table[i <-> RandomInteger[{0, i - 1}], {i, 1, 50}];     Graph@vtx[]      ![](http://i.stack.imgur.com/TkBHq.png) * * * Tree should look like this: (just imagine words instead of numbers) ![enter image description here](http://i.stack.imgur.com/bNcCn.jpg)


PDE plotting assistance needed

![enter image description here](http://i.stack.imgur.com/Dn4o5.png)               ClearAll["Global`*"];     pdeset = {Derivative[1, 0][U][t, x] == Derivative[0, 2][U][t, x],      Derivative[1, 0][T][t, x] == Derivative[0, 2][T][t, x] + E Derivative[0, 1][U][t, x]^2}     ics = {U[0, x] == 0, T[0, x] == 0};     bcs = {U[t, 0] == cos[t], T[t, 0] == 1, U[t, 10] == 0, T[t, 10] == 0 };     bcAll = Flatten[{ics, bcs}, 1];        * For `E=0.1`, when I try to solve `sol = NDSolve[{pdeset, bcAll}, {U, T}, {t, 0, 5}, {x, 0, 4 Pi}]` I get this error NDSolve::bcedge: "Boundary condition U[t,10]==0 is not specified on a single edge of the boundary of the computational domain"   * **How to plot`Derivative[0, 1][T][t, x] as x->0 vs t (0...Pi)` for `E=0.1,0.2,0.3`?**


How to define and compute various properties of a variable size matrix

I have a rather simple question, but I have not been able to figure out how to implement a solution in _Mathematica_. I would like to define a variable size square matrix, say an N x N matrix A, whose entries A_ij are of the form Kroneceker-delta_ij (N+1-2k)/2. (In fact, the matrices I want to deal with are N dimensional irreducible representations of SU(2)). Eventually, I would like to compute traces of products of certain matrices, but I can not even get tr(IdentityMatrix[N] = N) to work. How should I approach this problem?


StreamPlot Label for General Parameter

I have a simple DEQ: $$y'(t) = y + C$$ for a constant $C$. It turns out that the equilibrium point of this DEQ is $-C$. I can use the `StreamPlot` command to plot the direction field for 'any' value of $C$, for example, for $C = 2$:                StreamPlot[{1, y + 2}, {t, -4, 4}, {y, -8,  4}]      The `StreamPlot` is: ![enter image description here](http://i.stack.imgur.com/QnvRf.png) This `StreamPlot` would look exactly like this for any value of $C$. is there some way to show the y-axis as a $C$ instead of $-2$ and to show the other values as $C \pm <\rm{offset}>$. That is, the point $-4$ is shown as $C-2$, the point $-2$ is shown as $C$, the point 0 is shown as $C+2$, etc. In other words, the y-axis values are shown as a function of the general equilibrium point?


How to speed up given code for evaluating the tensor product of matrix elements?

ρ[n_, L_]:=       FixedPoint[         ArrayFlatten,TensorProduct@@Table[Subscript[ρ, l,m][k],{k,n},{l,L},{m,L}]];          list2[n_, L_]:=       ParallelTable[ρ[n,L][[i,j]]->a[i,j],{i,L^n},{j,L^n}]/.        {a[i_,j_]:>ToExpression["a"<>ToString[i]]}//Flatten;          p1[n_, L_] :=        Sum[         Subscript[ρ, L, L][k]*         Product[          If[k == k1, 1,               ParallelSum[Subscript[ρ, l, l][k1], {l, L - 1}]], {k1, n}], {k, n}]//Expand;          P1[n_, L_]:= P1[n,L]= p1[n,L] /. list2[n,L];          p0[n_, L_]:=       ParallelProduct[         Sum[Subscript[ρ, l, l][k], {l, L - 1}], {k, n}] // Expand;          P0[n_, L_]:=P0[n,L]= p0[n,L] /. list2[n,L];      Easy to evaluate...               P0[4, 3]-P0[3, 3]     P1[4, 3]-P1[3, 3]      What kind of changes are needed to speed up this calculation...               P0[5, 3]-P0[4, 3]     P1[5, 3]-P1[4, 3]


How to create a Hyperlink within the current Notebook?

Using “Create Hyperlink” dialog window I can create a link to a tagged cell in my notebook (it's “Destination notebook: Current notebook” radio button). Now, I can't figure it out how to create such links with `Hyperlink[]` command. I tried               Hyperlink["label", {"", "tag"}]     Hyperlink["label", {None, "tag"}]     Hyperlink["label", {Automatic, "tag"}]      etc., but nothing works.


PDE syntax question

I am trying to solve a PDE of a reaction diffusion equation, and while I'm getting a decent looking solution, I am also getting inconsistent BC / initial conditions warnings and wanted to check if my logic and coding was ok, or whether it's utterly wrong. I set up the equation like so;               Do2 = 2*10^-9;     a = 7.5*10^-7;     ko = 1;     omega = 3.0318*10^7;     ro = 150*10^-6;          eqn2 = D[P[r, t], t] - Do2*(D[P[r, t], r, r])  + a*omega*((P[r, t])/(P[r, t] + ko));      I then specify my boundary and initial conditions; so initially, in the region from 0 to $r_{o}$, $p = 0$ all across. So I write;               iv = P[r, 0] == 0;      Now, the boundary conditions - at $r = 0$, then is a steady concentration of oxygen diffusing into the region towards $r_{o}$ which is slowly being consumed at the rate $\frac{ap}{p + k_{o}}$, being reduced to zero at $r_{o}$. So I give my boundary conditions (which I believe are Dirichlet BCs) as;               bcs = {P[0, t] == 100, P[ro, t] == 0};      To solve and plot this I write               s11 = NDSolve[{eqn2 == 0, iv, bcs}, {P[r, t]}, {r, 0, ro}, {t, 0, 500}]     Plot3D[P[r, t] /. s11, {r, 0, ro}, {t, 0, 1000}]      Which plots something that looks relatively like what I'd expect - however, it warns me that the boundary conditions are inconsistent - am I plotting what I think I'm plotting, or is there something remiss is my code or logic? I should also add that my guess of $r_{o}$ is likely an underestimate - however, if I increase it to say, $r_{o} = 200*10^{-6}$, I get an error stating * _"Warning: scaled local spatial error estimate of 17.41130212282342`at t = 500.` in the direction of independent variable r is much greater than the prescribed error tolerance. Grid spacing with 25 points may be too large to achieve the desired accuracy or precision. A singularity may have formed or a smaller grid spacing can be specified using the MaxStepSize or MinPoints method options"_ I wonder if this is because the condition is unrealistic (ie: all the oxygen would be consumed by the point and is couldn't be a true boundary) or something more subtle I'm missing?


Symbolic Jacobian computation

I have an equation for which I would like to compute the Jacobian symbolically. $$f(x)=Ax-diag(x)(Ax+b)$$, where $x\in \mathbb{R}^n$, $A\in \mathbb{R}^{n\times n}$ and $b\in \mathbb{R}^n$. I am new to Mathematica, and I have seen this relevant question, but I am not aware of how to automatically ensure Mathematica recognises the different dimensions. Can someone help me how to code that in Mathematica?


Can Button[] generate output without using Print[]?

`Button[]` beguiles me. A simple example follows:               b1 = Button["Evaluate", Cos[Pi/6], Method -> "Queued"]     b2 = Button["Evaluate", Print[Cos[Pi/6]], Method -> "Queued"]      Both of the above statements produce buttons. When one clicks on `b1`, it appears to evaluate something, but does not output or display anything. Clicking on `b2` displays the expected output. But clicking a second time on `b2` prints the expected result a second time. Continuing to click on `b2` just increases the list of printed results. This uselessly clutters the notebook I want to distribute. I want a `Button[]` to execute a function and simply display its results as near as possible to what pressing **`Shift + Return`** in an input cell would do. I further want it to overwrite previous output. Ideally I would place the `Button[]` expression in a hidden initialization cell so only the actual button appears in the deployed notebook. Does anyway exist to get a Button to do what I've described? How?


Nested list to graph

The following nested list can be regarded as a representation of a (tree) graph:               li = {"fig", {"date", {"kumquat"}, {"papaya", {"peach"}, {"apple"}}},                  {"mango", {"orange", {"pear"}, {"avocado"}}},                   {"banana"}}      In the above, a string is a node in the tree, and any lists that follow it are subtrees rooted at that node. What are some of the ways by which this can be converted into a graph (or more concretely, a list of `DirectedEdge`s)? I've come up with one way, listed below. But I wanted to learn about other interesting approaches - for instance, pattern replacements might be used? This is what I came up with:               h[{str_String}] := Sequence[];     h[{str_String, ls__List}] := {DirectedEdge[str, #[[1]]], h@#} & /@ {ls};          edges = Flatten@h@li          (*      {"fig" \[DirectedEdge] "date", "date" \[DirectedEdge] "kumquat",       "date" \[DirectedEdge] "papaya", "papaya" \[DirectedEdge] "peach",       "papaya" \[DirectedEdge] "apple", "fig" \[DirectedEdge] "mango",       "mango" \[DirectedEdge] "orange", "orange" \[DirectedEdge] "pear",       "orange" \[DirectedEdge] "avocado", "fig" \[DirectedEdge] "banana"}     *)          TreePlot[Rule @@@ edges, Automatic, "fig", DirectedEdges -> True,       VertexLabeling -> True]      ![Don't you wish this were an actual tree?](http://i.stack.imgur.com/qF7wN.png)


Mma 10: Half the parallel power (Macs)?

Here is a comparison of the parallel kernels launched under _Mathematica_ under v9 and v10, on the same identical current 2014 R2-D2 Mac Pro ... [ Update: Valerio has commented that the same issue arises on the Macbook Air.] # Under v9.01               $ProcessorCount       > 12 Issuing:                LaunchKernels[]      ... launches 12 kernels, and actually uses them ... notice that the `ParallelTable` is 12 times the speed of `Table[]` for this construct:               In[5]:= Table[Pause[1]; f[i], {i, 12}] // AbsoluteTiming      > Out[5]= {12.003106, {f[1], f[2], f[3], f[4], f[5], f[6], f[7], f[8], f[9], > f[10], f[11], f[12]}}               In[6]:= ParallelTable[Pause[1]; f[i], {i, 12}] // AbsoluteTiming      > Out[6]= {1.010648, {f[1], f[2], f[3], f[4], f[5], f[6], f[7], f[8], f[9], > f[10], f[11], f[12]}} So, to perform the same operation, the parallel result under v9 is 12 times the speed of the single kernel result. # Under v10 -- half my potential processing power has gone               $ProcessorCount      > 6 ... down from 12 - even though I am running on the identical machine. Now, I know that my Mac Pro actually has 6 processors, and each runs 2 threads ... and under v9, that yielded 12 processor kernels for Mma 9 ... but under v10, it is only yielding 6 kernels ... ON THE SAME MACHINE. And this has real effects ... it effectively reduces by 50% the maximum potential power of my Mac:                LaunchKernels[]      ... launches 6 kernels (not 12 kernels as under v9). Compare the performance:                In[3]:= ParallelTable[Pause[1]; f[i], {i, 12}] // AbsoluteTiming      > Out[3]= {2.009933, {f[1], f[2], f[3], f[4], f[5], f[6], f[7], f[8], f[9], > f[10], f[11], f[12]}} So, under the new v10, I am getting half the parallel performance here and half the kernels that I got under v9. Even more perplexing is that this worked fine in an earlier pre-release version of v10. I am very confused. Anyone have any ideas how I can get my missing kernels back? Or why a decision may have been made to hobble the performance of the Mac Pro under v10? # Addendum Just noticed that if I go to:   * `Evaluation Menu -> Parallel Kernel Configuration` ... the automatic setting for:   * `Number of kernels to use: is set to: Automatic` (which Mma sets to 6) If I change this to:   * `Manual setting` and set it to 12 ... then it seems to use 12. But I am still confused as to why, if _Mathematica_ 10 can actually support 12 kernels on the machine, ... why would Wolfram set it to use only half of them by default, when v9 supported all of them by default? # Reply to Szabolcs: real-world test Szabolcs suggests below that _Mathematica_ may not practically use more kernels than physical cores, even if your processor supports virtual cores ... so there is no real difference. In reply, here is a quick timing test of a real-world application (kernel density estimation) from the _mathStatica_ benchmarking test suite. The task is to plot 12 kernel density estimates, corresponding to 12 different bandwidths.               bandwidths = {.2, .35, .45, .55, .65, 1, 1.5, 2, 2.2, 2.5, 3, 3.2};      ![](http://www.tri.org.au/se/kerneldensitytiming.png) Here are the results running under:   * v9 (default: 12 kernels): 3.38 seconds   * v10 (default: 6 kernels): 9.53 seconds   * v10 (manual overide to 12 kernels): 7.46 seconds I don't know what has changed to cause such a performance hit under v10 ... but even so, that is not the point. The point is that the v10 default kernel setting fails to take advantage of the power of the Mac Pro ... and results in worse performance in a typical parallel-processing application. # More extensive real-world test: _Update: 1 August 2014_ I have now had the opportunity to run the full _mathStatica_ (primarily symbolic) benchmark suite under both:   * the default v10 parallel setting (6 kernels)   * the manual override v10 setting (12 kernels) Here are the results: ![](http://www.tri.org.au/se/v10with6versus12kernels.png) The results fall into 2 categories:   * _For problems that have more than 6 separate components to them_ : ... For such problems, using 12 kernels is ALWAYS unambiguously faster, and significantly so.    * _For problems that have 6 or less separate components_ : ...For instance, Examples 7 and 9 can only be broken down into 2 symbolic components, so the benefits of parallelism max out with 2 kernels. In these cases, the 6 automatic kernels case is sometimes marginally faster than the 12 kernel case (presumably due to running overheads etc) ... but the difference is tiny, and essentially unnoticeable. **In summary:** for problems that CAN benefit from more than 6 kernels, the default Mma 10 (automatic) setting of 6 kernels on a Mac Pro appears to be sub-optimal, and fails to take advantage of the full capability of the machine. This problem is new to v10, and does not occur under v9.


How do you multiply out integer powers in a symbolic expression?

I have the following problem: I want to transform integer powers into a series of multiplications within symbolic expressions. E.g. `x^3` should be written as `x*x*x`. I tried applying the rule `a_^b_ -> a a^b-1` with a `ReplaceRepeated`, but Mathematica "simplifies" this again to `x^3`. Any suggestions?


Mathematica equivalent of regex '\w{2,3}'

It beats me to write the Mathematica pattern equivalent to the regex:               \w{2,3}      Any ideas?


How to present a Graphic and a Table in close proximity to each other

Often, with a `Plot` or within `Manipulate` I want to display a graph and, in close proximity to it, a table showing the results of relevant computations. The quickest way to do this is with `GraphicsColumn`, but that always seems to create cells of identical height and width, which is usually not what I want. Here is a trivial example:               Manipulate[      GraphicsColumn[{Plot[Sin[x + c], {x, 0, 2*Pi}],         TableForm[{{c}}, TableHeadings -> {{"c"}, {"value"}}]}], {c, 0, 3}]      ![GraphicsColumn makes me sad](http://i.stack.imgur.com/Tgeha.jpg) Is there some other convenient way to place the table below the graph without an ocean of whitespace, or a way to specify that GraphicsColumn can use cells of differing size?


Q-Multinomial Coefficient

How can one compute the q-Multinomial Coefficient as a function of q,m and a list {n1,n2,n3,...} in Mathematica? See http://mathworld.wolfram.com/q-MultinomialCoefficient.html for the definition.


How to evaluate the sum over a hyperplane

I have difficulties in evaluating the following expression: $$\sum_{\small n_1+...+n_{k}=m-k}\; \prod_{i=1}^{k}\frac{1}{(n_i+1)(n_i+2)}$$ I have tried the function `RootSum`, but it doesn't work and gives the following warning:               RootSum[Sum[Subscript[n, j], {j, 1, k}] - m + k,                  Product[1/((Subscript[n, i] + 2) (Subscript[n, i] + 1)), {i, 1, k}]]       > "RootSum::pfn - m + k + $\sum\limits_{j=1}^{k} n_j$ is not a pure function". I will really appreciate it if someone could give me some hints. Thanks!


How can locators be added to the points on a 3D grid?

Here is a pared down example of some 3D data that I want to make dynamic and add locators to each set of points. Is that possible?               dimension1 = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},                   {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},                   {4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},                   {5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5},                   {6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6},                   {7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7},                   {8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},                   {9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9},                   {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}};          dimension2 = {{2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}};          dimension3 = {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},                   {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},                   {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},                   {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},                   {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},                   {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},                   {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},                   {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},                   {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},                   {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},                   {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}};          firstDimension = ListPlot3D[dimension1, BoxRatios -> {1, 1, 1},        PlotStyle -> {Cyan, Opacity[0.2]}, Background -> White];          secondDimension = ListPlot3D[dimension2, BoxRatios -> {1, 1, 1},        PlotStyle -> {Magenta, Opacity[0.2]}, Background -> White];          thirdDimension = ListPlot3D[dimension3, BoxRatios -> {1, 1, 1},        PlotStyle -> {Yellow, Opacity[0.2]}, Background -> White];          Show[firstDimension, secondDimension, thirdDimension]      ![Mathematica graphics](http://i.stack.imgur.com/Vq0Yd.png) The locators should move the points on the grid, and affect the other surrounding points depending on a variable.


How can I set constraints on parameters in NelderMeadMinimize package?

I read about NelderMeadMinimize package. How can I set constraints on the parameters? For example I want to minimize an equation with $10$ parameters such as ${a_1, a_2, ....}$. I want to put the condition $a_1 > 0$. How can I do that? **EDIT 1:** As an example I have $10$ equations and $10$ unknown parameters which I want to find them by minimizing `problem1`:               problem1 = (-30 + A3/A1)^2 + (4 e3a α1 α3 + 2 d2 β1)^2        + (-2 A3 - 2 c2 α3 + 4 c4a α3^3 + 8 e3a α1 β1)^2 + (4 e3a α1^2 + 2 d2 β3)^2        + (-3.13995 - 2 c2 + 2 d2 + 12 c4a α1^2 - 4 e3a β3)^2        + (-1.49499 - 2 c2 + 2 d2 + 4 c4a α1^2 + 4 e3a β3)^2        + (-2.10157 - 4 c2 d2 + 24 c4a d2 α1^2 - 16 e3a^2 α3^2 - 8 d2 e3a β3)^2        + (-0.0277073 - 4 c2 d2 + 8 c4a d2 α1^2 - 16 e3a^2 α3^2 + 8 d2 e3a β3)^2        + (-2 A1 - 2 c2 α1 + 4 c4a α1^3 + 4 e3a α3 β1 + 4 e3a α1 β3)^2        + (0.00429025 α1^2)/((β1 Sqrt[1 - (2 c2 + 2 d2 - 4 c4a α1^2 - 4 e3a β3)/Sqrt[ 64               e3a^2 α3^2 + (2 c2 + 2 d2 - 4 c4a α1^2 - 4 e3a β3)^2]])/(Sqrt[2] α1)        + Sqrt[1 + (2 c2 + 2 d2 - 4 c4a α1^2 - 4 e3a β3)/Sqrt[64 e3a^2 α3^2                             + (2 c2 + 2 d2 - 4 c4a α1^2 - 4 e3a β3)^2]]/Sqrt[2])^2;                  parameters1 = {c2, d2, e3a, c4a, α1, α3, β1, β3, A1, A3};              function1 = Function @@ {parameters1, problem1};              minimizer =        With[{nelderMead = NelderMeadMinimize`Dump`CompiledNelderMead[function1, parameters1],              bounds = {-1, 1}, dimension = Length[parameters1],              tolerance = Sqrt[$MachineEpsilon]},                   Compile[{{dummy, _Integer, 0}},                 nelderMead[RandomReal[bounds, {dimension + 1, dimension}], tolerance, -1],                 CompilationOptions -> {"ExpressionOptimization" -> True,                                        "InlineCompiledFunctions" -> True},                 RuntimeOptions -> {"CompareWithTolerance" -> False,                                    "EvaluateSymbolically" -> False},                 RuntimeAttributes -> Listable(*"Parallelization"->True*),                 CompilationTarget -> "C"]];                   ans = {First[#], Thread[parameters1 -> Rest[#]]} & /@                      Take[minimizer@Range[3000] // Sort, 10]           I know that $\alpha_1$, $\alpha_3$, $\beta_1$, $\beta_3$, $A_1$, and $A_3$ should be positive. How can I put these constraints on these parameters when applying NelderMead minimization? Is it possible? **EDIT 2** First one should download the package and also needs to run:               Needs["CCompilerDriver`"]


Position of First nonzero number

I want to know is there any one line code to find position of first nonzero number without calculating position of all non zero numbers. For example,               A = {0, 0, 0, 1, -2, -1, 0};     First[Flatten[Position[A, _?(# != 0 &)], 1]]      will give me position of first non zero number. But first it calculate position of all non zero number. Is there any way to stop position function when it found first non zero number?


How to parallel the computation tasks according to machines instead of kernels

On a HPC, there are many computation nodes, each node corresponds to an independent machine. Every node has several cores, for example 8 per node. _Mathematica_ can launch remote kernels on different nodes (see method here). After all the kernels were launched, _Mathematica_ seems to regard all the kernels as the same thing. We can use `ParallelMap` and different options `"FinestGrained"` or `"CoarsestGrained"` to distribute computation tasks to different kernels regardless of which node a kernel belongs to. But I am in a case where I want to distribute my computation task according to machines instead of kernels, because my computation involves matrix eigenvalues. When the matrix is large, the memory usage is considerable while each node has limited memory resources. So I can not parallelize the computation to `"FinestGrained"` to kernels, as that will exhaust the memory and probably would cause the node to break down. One way to solve this is to launch a limited number of kernels on each node, for example, only launch one kernel per node, and the one kernel on each node won't eat up all the memory. But in this way, I will lose the **multi-thread feature** of `Eigenvalues` computation (see here), because memory usage is determined by the dimension of the matrix. Using 1 core or 8 cores to compute the same matrix needs the same amount of memory, but obviously 8 cores will be faster. So if I launch only one kernel on each node I am wasting the remaining 7 cores on each node. So here is the question. **How to distribute the computation tasks according to machines instead of kernels, and preserve multi-thread feature of built-in functions**? I mean to create a new option `"FinestGrainedToNodes"` which will distribute computation tasks evenly to different node.


How do I make the color of arrowheads in a graph different from the colors of the arrows?

I'm graphing a Markov process               mp = DiscreteMarkovProcess[{1, 0, 0}, ({          {0.6, 0.1, 0.3},          {0.2, 0.7, 0.1},          {0.3, 0.3, 0.4}         })];      and would like to have arrows whose thicknesses corresponds to the transition probabilities, with arrowheads of a different color in the exact center of each edge. But all my attempts end up a mess.               g = Graph[mp];     Scan[(PropertyValue[{g, #}, EdgeLabels] =           PropertyValue[{g, #}, "Probability"]) &, EdgeList[g]];     Scan[(PropertyValue[{g, #}, EdgeStyle] =          Directive[Arrowheads[{{.045, .575}}], GrayLevel[.7],            Thickness[PropertyValue[{g, #}, "Probability"]/20]]) &,        EdgeList[g]];     g      ![](http://i.stack.imgur.com/wdQaA.png) ![enter image description here][1] The thick edges leave gaps between their ends and the nodes of the graph, and I can't figure out how to change the color of the arrow heads so that they stand out against the color of the edges. How can I change the color of the arrowheads in my figure. How can I avoid the gaps that appear between nodes and the ends of the edges?


How to fix Ticks in Gauges?

Ticks is an option for Gauges. I fail, however, to apply custom Ticks to Gauges. For instance, compare these two:                {ThermometerGauge[50, {0, 100}, Ticks -> Automatic],       ThermometerGauge[50, {0, 100}, Ticks -> {0, 50, 100}]}      What you see is this: ![enter image description here](http://i.stack.imgur.com/D2vDP.jpg) _No difference!_ I also tried with the Horizontal- and VerticalGauge with the same success. _Do you know a workaround?_ EDIT 11.07.13: I have seen the answers to my question. They all are good and fascinating, and in another case I will certainly use them. They do not answer my question though. For this reason I would like to give some more explanation of what I am really after. I will give it within an example of a different problem, where it is easy to obtain such a result. So let us consider two simple plots. First is this               Plot[x, {x, -0.3, 0.3}, ImageSize -> 250]      second is this:                Plot[x, {x, -0.3, 0.3}, Ticks -> {{0, 3/16, 1/4}, Automatic},       ImageSize -> 250]      ![enter image description here](http://i.stack.imgur.com/VBURg.jpg) Here you can see it. The y axis in both plots is automatic - do not look at it. The x axis of the first plot is automatic for comparison, while the x axis of the second plot is what I am after. I would like to achieve the same on the ThermometerGauge, if possible by easy means. The easy means are here important, since looking at programs below I feel that it is easier to draw such a Gauge from scratch. For example, like this:                 thermo[x_] := Show[{        Graphics3D[{Text[Style["-0.3", 12], {-0.15, 0, -0.3}],           Text[Style["0", 12], {-0.15, 0, 0}],          Text[Style["3/16", 12], {0.14, 0, 3/16}] ,           Text[Style["1/4", 12], {0.15, 0, 0.25}] ,           Text[Style["0.3", 12], {-0.13, 0, 0.3}]},          ViewPoint -> {0, -1.5, 0}, Boxed -> False,          ImageSize -> {120, 300}],        Graphics3D[{LightBlue, Specularity[White, 20], Opacity[0.5],           Sphere[{0, 0, -0.4}, 0.11]}],        Graphics3D[{Red, Specularity[White, 20],           Sphere[{0, 0, -0.4}, 0.1]}],        Graphics3D[{LightBlue, Opacity[0.5],           Tube[{{0, 0, -0.4}, {0, 0, 0.35}}, 0.05]}],        Graphics3D[{Red, Specularity[White, 20],           Cylinder[{{0, 0, -0.45}, {0, 0, x}}, 0.04]}],             Graphics3D[{Thickness[0.015],           Line[{{-0.07, 0, #}, {-0.09, 0, #}}] & /@            Table[i, {i, -0.3, 0.3, 0.1}]}],        Graphics3D[{Red, Thickness[0.015],           Arrow[{{0.09, 0, 3/16}, {0.03, 0, 3/16}}],           Arrow[{{0.09, 0, 0.25}, {0.03, 0, 0.25}}]}]        }]      Try it:               Manipulate[      thermo[x], {{x, 0}, -0.3, 0.3}]      It looks as shown here: ![enter image description here](http://i.stack.imgur.com/2MjjY.jpg)


Computing derivatives of a moment generating function

Dear Mathematica users, I'm trying to compute higher order derivatives of a moment generating function and then evalutate them in 0 (in order to get some moment conditions for a GMM estimation). Although I try to declare constants at the beginning of my script, which follows:               % Declaring constants         Constants -> {kappa, theta, sigma, gamma, b, dt, Uy, J, phi, lambda}          %     A[Uv_] = (-(kappa *theta)/(sigma^2))*((gamma + b)*dt +        2*Log[1 - ((gamma + b + (sigma^(2))*Uv)/(2*gamma))*(1 -              exp[-gamma*dt])]) + (exp[Uy*J] - 1 - Uy*phi*J)*lambda*dt;          %     B[Uv_] = -(a*(1 - exp[-gamma*dt]) -        Uv*(2*gamma - (gamma - b)*(1 - exp[-gamma*dt])))/(2*       gamma - (gamma + b)*(1 - exp[-gamma*dt]) -       Uv*(sigma^(2))*(1 - exp[-gamma*dt]));          % My moment generating function     EVPsi[Uv_] = exp[A[Uv]]*(1 - B[Uv]/omega)^(-v)      My problem is due to the fact that when I compute the first order derivative by using               EVPsi'[Uv] /. Uv -> 0      I get the following expression               % First derivative of the mgf evalueated in Uv=0     -v (1 + (a (1 - exp[-dt gamma]))/(     omega (2 gamma - (b + gamma) (1 - exp[-dt gamma]))))^(-1 -       v) (-((2 gamma - (-b + gamma) (1 - exp[-dt gamma]))/(      omega (2 gamma - (b + gamma) (1 - exp[-dt gamma])))) + (     a sigma^2 (1 - exp[-dt gamma])^2)/(     omega (2 gamma - (b + gamma) (1 - exp[-dt gamma]))^2)) exp[     dt lambda (-1 - J phi Uy + exp[J Uy]) - (     kappa theta (dt (b + gamma) +         2 Log[1 - ((b + gamma) (1 - exp[-dt gamma]))/(2 gamma)]))/     sigma^2] + (     kappa theta (1 + (a (1 - exp[-dt gamma]))/(     omega (2 gamma - (b + gamma) (1 - exp[-dt gamma]))))^-v (1 -      exp[-dt gamma]) Derivative[1][exp][     dt lambda (-1 - J phi Uy + exp[J Uy]) - (     kappa theta (dt (b + gamma) +         2 Log[1 - ((b + gamma) (1 - exp[-dt gamma]))/(2 gamma)]))/     sigma^2])/(     gamma (1 - ((b + gamma) (1 - exp[-dt gamma]))/(2 gamma)))      What I'm missing here is why I get in the last lines an expression such as               Derivative[1][exp][product of constants!!]      instead of a 0. I would be thankful if you could shed some light on this. Thank you.


Extracting RHS from Rule

In an example from another question, the rhs of a list of rules can be simply extracted:               In[1]:= rules1 = Solve[x + y == 3 && x - y == 6, {x, y}][[1]]                        9         3     Out[1]= {x -> -, y -> -(-)}                   2         2          In[2]:= rules1 /. Rule -> (#2 & )                    9    3      Out[2]= {-, -(-)}               2    2      However, when I try the same replacement with a list of rules where the RHS is a pure function, it does not result in a list of the RHS.               In[3]:= rules2 = {MySum -> Total[#1] & , MyProd -> Times[#1] & }          Out[3]= {MySum -> Total[#1] & , MyProd -> Times[#1] & }          In[4]:= rules2 /. Rule -> (#2 & )          Out[4]= {(#2 & )[MySum, Total[#1]] & , (#2 & )[MyProd, Times[#1]] & }      How do I correct this?


Multiple instrument chord

I would like to create a chord using multiple instruments. This started as an attempt to explain music to a friend but my curiosity has taken over. I am familiar with the SoundNote function. I know that SoundNote can create a chord using the same instrument:               Sound[SoundNote[{"C4", "G3"}, 1, "Harpsichord"]]      And it can create a series of notes with different respective instruments:               Sound[{SoundNote["C", 0.5`, "Oboe"], SoundNote["G", 0.5`, "SynthVoice"], SoundNote["C5", 0.5`, "Organ"]}]      What I'm wondering is if there is a way to play more than one sound with specific notes at the same time.


Using a compiled function inside NIntegrate gives "CompiledFunction::cfsa" message

The following function is defined for Real input:               FFc = Compile[{{x, _Real}, {EF, _Real}},If[x > EF, 0., If[x == EF, 0.5, 1.]]]      FFc is now used in the function called foo:               EBoundary = 6.5;     foo[Ef_?NumericQ] := NIntegrate[FFc[x, Ef] , {x, -EBoundary, EBoundary}]      When I call foo like               foo[3.2]      I get an error message:               CompiledFunction::cfsa: "Argument x at position 1 should be a \!\(\"machine-size real number\"\)."      Since I'm using real numbers I have no idea why I get this message. What is the problem? Is it, because If[] can return 0?


PrintTemporary in ParallelTable

I thought of a possible answer to Monitor doesn't work with ParallelTable but it doesn't work as I hoped it would. This accumulates print cells instead of deleting them as intended. Can it be fixed?               ParallelTable[       NotebookDelete[x]; x = PrintTemporary[i];       Pause[1]; i,       {i, 1, 15}     ]      I thought that `x` would be local to each kernel, and this would print four cells (for four cores) that would be deleted and replaced with each iteration. I then thought that the value of `x` was lost between iterations, but this also fails to delete the print cells:               ParallelTable[       x = PrintTemporary[i]; NotebookDelete[x];       Pause[1]; i,       {i, 1, 15}     ]


Plotting a floor function with endpoints?

Would someone mind showing me how to plot a floor function with the appropriate endpoints? I tried Google, but the best I could find was something posted from 2004 that no longer appears to work. Sorry if this is overly basic, I've only got a couple of weeks of experience with Mathematica and no one to work with on it. Edit: I'm looking to create a graph similar to the one shown on the wiki page for floor/ceiling functions. I'm not too concerned with the frame or the tick marks.


Prevent Cell Deletion

How might I be able to prevent a `Cell` form being deleted when you press the Delete key? Maybe there is a way to display some type of `Dialog` when you attempt to delete(or cut) a cell?


How to add FindDivisions to the plot commands?

I used these instructions to make a legend bar next to my plot (I can't comment there) But I'm lost to where and how can I add FindDivisions to the DensityPlot under "Edit: illustrating additional options"?               {densityPlot, densityColors, densityRange} =        reportColorRange[        ListStreamDensityPlot[data, VectorScale -> Small,          DataRange -> {{0, 2 Pi}, {-0.5, 0.5}},          ColorFunction -> ColorData["Rainbow"]]];           With[{plotWidth = .85, aspectRatio = .9},       density =       display[{densityPlot // at[{0, 0}, plotWidth],        colorLegend[densityColors, densityRange, LabelStyle -> LightGray,         FrameStyle -> Orange, "ColorBarFrameStyle" -> LightGray,         Background -> Darker@Darker@Darker@Blue, "ColorSwathes" -> None,        Contours -> 10, RoundingRadius -> 0, BoxFrame -> 3,         "Digits" -> 2] //        at[{plotWidth, 0}, {1 - plotWidth, plotWidth/aspectRatio}]},        AspectRatio -> aspectRatio, ImageSize -> 400]]      Also how can I add another plot to the existing one? I would need to draw a sinusoid on it. Show command ruins it. It's obvious where sinusoid should be. This is my plot: ![](http://i.stack.imgur.com/sICZ2.jpg) I would like my numbers in a bar legend rounded. Thanks in advance. P.S. Just in case you need data I used for my plot.               a = 0.05     z = -1     data =      Table[With[{x = 0 + 2 Pi/5 (i - 1),        y = -0.5 + 0.2 (j - 1)}, {{NIntegrate[        a*z*Cos[t]/((t^2 - 2 t x + x^2 + y^2 + z^2)^(3/2) -            3 (y Sqrt[t^2 - 2 t x + x^2 + y^2 + z^2] Sin[               t]) a), {t, -Infinity, Infinity},        Method -> {"GlobalAdaptive", "MaxErrorIncreases" -> 800,          Method -> "GaussKronrodRule"}, AccuracyGoal -> 20,        MaxRecursion -> 20],       NIntegrate[-z/((t^2 - 2 t x + x^2 + y^2 + z^2)^(3/2) -           3 (y Sqrt[t^2 - 2 t x + x^2 + y^2 + z^2] Sin[              t]) a), {t, -Infinity, Infinity},        Method -> {"GlobalAdaptive", "MaxErrorIncreases" -> 800,          Method -> "GaussKronrodRule"}, AccuracyGoal -> 20,        MaxRecursion -> 20]},       NIntegrate[(y +          a*(t*Cos[t] - x*Cos[t] - Sin[t]))/((t^2 - 2 t x + x^2 + y^2 +             z^2)^(3/2) -          3 (y Sqrt[t^2 - 2 t x + x^2 + y^2 + z^2] Sin[             t]) a), {t, -Infinity, Infinity},       Method -> {"GlobalAdaptive", "MaxErrorIncreases" -> 800,         Method -> "GaussKronrodRule"}, AccuracyGoal -> 20,       MaxRecursion -> 40]}], {i, 1, 6}, {j, 1, 6}]


Is there a way to hide or toggle the visibility of code?

Many of my notebooks have a similar repeating structure, which is very convenient and reliable for my workflow: a chunk of code defining a `Manipulate` for exploring some phenomenon, the output of the `Manipulate`, where the phenomenon can be explored, and then some notes or observations about the phenomenon. When I'm focused on coding, this is fine, but as my focus shifts to the phenomenon itself, the code is distracting and takes up a lot of space, so I'd like to be able to hide or collapse it. Is there a way to hide or toggle the visibility of code, independently of the results it produces? In effect, what I'm seeking is there _reverse_ of the default behavior, in which code and results that are grouped together can be collapsed to show just the code. Note that I'm not seeking a way to move the code elsewhere: the point is the be able to easily move back and forth between having the code behind some data or visualization visible, and associated with the output, and having it hidden or collapsed.


Organizing similar datasets using DownValues instead of Contexts

In his answer to this question, Leonid helped me find a way to programmatically generate contexts for holding sets of symbols with the same names. Perhaps a simpler way is to use `DownValues` so:               dataRaw["Paris"] = Import["Paris.csv"];     data["Paris"] = Differences[dataRaw["Paris"]];     dataMax["Paris"] = Max[dataRaw["Paris"]];          dataRaw["Madrid"] = Import["Madrid.csv"];     data["Madrid"] = Differences[dataRaw["Madrid"]];     dataMax["Madrid"] = Max[dataRaw["Madrid"]];      lets me make a plot using               ListLinePlot[data /@ {"Paris", "Madrid"}]      and can be implemented with a simple function               importCity[cityName_String] := (         dataRaw[cityName] = Import[cityName ~~ ".csv"];         data[cityName] = Differences[dataRaw[cityName]];         dataMax[cityName] = Max[dataRaw[cityName]];     )      Other than cluttering everything with a lot of `[cityName]`, are there hidden perils to using `DownValues` in this way? Is there some disadvantage to storing every `dataRaw` as `DownValues` of the same symbol instead of individually in multiple contexts?


Ubuntu 12.10 no window focus on help browser

The help browser is not getting window focus when clicked on it. Clicking links or buttons in the help browser works without window focus, but copying code or typing in it doesn't. I can get window focus on the help browser by using the alt+tab or the Window menu. I'm running Mathematica 8.0.4.0 on Ubuntu 12.10. Mathematica is the only software that has this behavior, that's why i post this question here. Has anyone else experienced this behavior or know a solution to it? edit: switching focus between notebooks behaves normally.


CDF and MediaWiki

Recently there was a handful of CDF embedding-related topics. However I would like to ask whether anyone has succeeded in embedding CDF into MediaWiki page? I've attempted to do so with the Widget extension but it fails to load fully. Is there any way to fix this?


Tool to locate bloat in a notebook?

In developing a notebook, I often find I have created a very boated file that takes a long time to save. I would like to slim it down. It is usually the result of graphics and images, but they may be hidden deep in the hierarchy of the notebook. Finding the wasted space is a pain. A very useful tool would be something that graphically indicated (perhaps in the cell marker) the number of bytes (or similar) that are within a cell. Anyone know of such a thing, or have a pointer on how to create?


Light Weight Grid and core limitation

I am trying to figure out what would be best for running some simulations using multiple computers where **each has it's own mma 8 licence**. The main part of the computation involves a parallelized table which runs the algorithm for different values. The computers are :   * intel i7 quad core PC   * intel core duo laptop (from where I will be controlling the PC) Looking around I found two basic options :   * using ssh on Mathematica to run parallel computations   * using remote desktop to control the PC I am leaning towards the second for two main reasons. First, I assume that I can only use a total of 4 cores in the whole grid given the home licensing (am I wrong or does this only apply to a single license for the whole grid). Given this limitation, if I use remote desktop, I can run two simulations. This would allow me to fully benefit from the quad core PC, while still running stuff on my laptop or even work on some more code. Is my thinking flawed? Did I miss something in the ssh options/licencing limitations that would make me lean more towards this option? ## EDIT : So it turns out that with multiple licences you can have more than 4 kernels running. Quoting Jagra : > each license will typically grant access to a minimum of 4 parallel kernels > + a control kernel So in my case, I would have 4 kernels on the quad core and 2 on my core duo, plus one control kernel. So I could really see the benefits of running the Grid for parallel kernels, even though I would only be able to use one instance of Mathematica, and not work on code while the algorithm is running. The positive side of LW Grid, as Jagra pointed out, is that you don't need to be sending input/output files between the remote PC and your control PC which can be very time and resource consuming if they are very large. ## EDIT 2: After contacting Wolfram support, they informed me that Trial licences also provide 4 kernels to the grid. (I was thinking of adding a PC which only has a trial licence for MMA9)


Can plot a function, NSolve takes too long

I'm new to Mathematica, so maybe mine is an easy to solve issue, but I haven't been able to figure it out. I have a series of linear ODEs I solve using for:               sol = ConstantArray[0, 1];     For[i = 2, i < 20, i++,           sol = Append[sol,                  First[y[t] /.                  DSolve[{y''[t] == -121/150*y'[t] - 1/10*y[t] -                       3 + (2/3)*D[sol[[i - 1]], t] + 1/10*sol[[i - 1]],                       y'[0] == 25, y''[0] == 0}, y, t]]]]      It runs fast and fine (takes a couple of seconds). I get the first derivative of every solution:               vels = D[sol, t];      Again, everything OK... Then I plot all of them:               Plot[vels, {t, 0, 80}]      ![plot of vels](http://i.stack.imgur.com/Odo0c.png) Pretty fast. I want to know the value of t for which each solution crosses a numeric boundary:               For[i = 2, i < 15, i++,       t10 = AppendTo[t10,         First[t /. NSolve[{vels[[i]] == 10, t < 40, t > 5}, t]]]]      It takes like a second or two for, say, the first 8 terms, but the 9th won't end after like an hour. It's funny because I can 'see' the result, and with a zoom large enough I could estimate the value by myself from the plot. Am I missing something important? Does it have anything to do with the methods used? Do I have to use some other command? Thanks in advance.


Build a refined grid based on intersecting line

I honestly have no idea where to begin with this problem. In summary, I have a 2D coarse grid with an intersecting line. For an easy example, let's assume it's a 4x4 grid. ![Coarse Grid with intersect.](http://i.stack.imgur.com/nOJ7L.png) I wish to pass through each grid block multiple times and subsequently divide each grid block in half that either has the line passing through it (or possibly through one of its vertices). ![1st pass](http://i.stack.imgur.com/UKWAk.png) ![3rd pass](http://i.stack.imgur.com/zrkKl.png) ![4th pass](http://i.stack.imgur.com/Mz2AE.png) ...etc. After a set number of passes, I want to assign a property to each grid block that is intersected. (example, set color to blue). ![Assign properties](http://i.stack.imgur.com/9qWON.png) The only requirement is the algorithm provide the final set of refined grid blocks have at least one shared side until the termination points. The final output would be a list of vertices and their cartesian coordinates. Thanks in advance. **UPDATE:** The grid blocks (which will eventually total in the millions) will have CPU intensive calculations performed on them. So the ideal solution will only refine the grid block size close to the line while leaving the areas away from the line in their "coarse" state.