Relational joining of tables

A common thing to want to do with data is to combine it (at least I thought this was a common thing). In SQL there is the idea of table joins "select id,v1,v2 from A,B where A.id=B.id" kind of thing. I'm trying to do a join like this using Mathematica, i.e. retrieve table A from the Internet, retrieve table B from the Internet, combine, do stuff with the resulting joined columns. My First effort was this:               (* Simulate tables *)     a = Table[{x, RandomReal[]}, {x, 1, 1000}];     b = Table[{x, RandomReal[]}, {x, 1, 1000}];     (* Use this simple match function for now *)     RMatch[x_] := x[[1]] == x[[3]];     Length[Part[        Select[Flatten[Outer[Function[{x, y}, Join[x, y]], a, b, 1], 1],          RMatch], All, {1, 2, 4}]] // Timing      > >     {1.906250, 1000} >   This works, but is way too slow. Imagine if it was 100,000 rows each; the program may never finish. Also this will take up a lot of memory; creating a temporary list of rows that is NxM in size. So I tried an iterative approach instead:               (* Simulate tables *)     a = Table[{x, RandomReal[]}, {x, 1, 1000}];     b = Table[{x, RandomReal[]}, {x, 1, 1000}];     (* Use this simple match function for now *)     RMatch[x_, y_] := x[[1]] == y[[1]];     RJoin[a_, b_, match_] := Block[       {lena = Length[a], lenb = Length[b], arow, brow, i, j},       Flatten[Reap[          For[i = 1, i <= lena, ++i,           arow = a[[i]];           For[j = 1, j <= lenb, ++j,            brow = b[[j]];            If[match[arow, brow], Sow[Join[arow, brow]]             ]            ]           ]          ][[2]], 1        ]       ]     Length[Select[RJoin[a, b, RMatch],         Function[{x}, x[[1]] == x[[3]]]]] // Timing      > >     {2.562500, 1000} >   This will use much less memory, but is even slower. Is this something that just isn't appropriate for _Mathematica_ i.e. do this using a different tool, output the table and work with that instead? That would be a shame, but it seems that it may be necessary. # Update: Thanks to the great answers below I decided to give up on the general case and focus on unique ID matching, which is the situation that arises the most. Following Verbeia and Michael E2's examples I came up with a version that is fast and readable.               (* Simulate tables *)     a = Table[{x, RandomReal[]}, {x, 1, 1000000, 2}];     b = Table[{x, RandomReal[]}, {x, 1, 1000000, 3}];          RJoin[a_, b_] := Block[{f},       Do[         f[x[[1]]] = x[[2]],         {x, a}         ];        Cases[b /. {x_, y_} -> {x, y, f[x]}, {_, _, _Real}]       ]          (* Use and time *)     Length[RJoin[a, b]] // Timing      > >     {1.750000, 166667} >   That's 1.75 seconds to join two tables with almost a million rows total. This is mildly faster than Michael E's version which took 4.2 seconds on my computer. When I need a more general case I plan to use Java to process the data, but this should handle most of my cases. # Update 2 I managed to simplify and speed up the arbitrary matching case a little bit               (*Simulate tables*)     a = Table[{x, RandomReal[]}, {x, 1, 1000, 1}];     b = Table[{x, RandomReal[]}, {x, 1, 1000, 1}];          (*Use this simple match function for now*)     RMatch[x_, y_] := x[[1]] == y[[1]];          RJoin[a_, b_, match_] :=      Flatten[       Reap[Do[           If[match[x, y],            Sow[{x[[1]], x[[2]], y[[2]]}];            ],           {x, a}, {y, b}           ];         ][[2]]       , 1]     Length[RJoin[a, b, RMatch]] // Timing      > >     {1.359375, 1000} >


Using MapThread on list of lists

Just a light weight question for learning. If you think this was asked before, please feel free to close it. I am trying to learn `MapThread` more, and wanted to use it to generate `Rule` from a list like this               lst = {{1, 2},{a, b}}      in order to obtain               (* {1 -> a, 2 -> b}  *)      Using `MapThread` works nice:               MapThread[Rule, lst]     (* {1 -> a, 2 -> b}  *)      But when the list contain more than one list in it, like this               lst = {{{1, 2}, {a, b}}, {{3, 4}, {c, d}}}      Then I could not find a way to use `MapThread` on its own on the whole list. It needs help to iterate over all the lists. So what I do now is `Map` the function `MapThread` on each list in the list. Like this               Map[ MapThread[Rule, #] &,  lst]     (*  {{1 -> a, 2 -> b}, {3 -> c, 4 -> d}}  *)      I did not want to do this:               MapThread[Rule, ArrayFlatten[{lst}]]     (* {1 -> a, 2 -> b, 3 -> c, 4 -> d} *)      because it loses the structure I had at the start, even though I can correct things with               Partition[%, 2]     (* {{1 -> a, 2 -> b}, {3 -> c, 4 -> d}} *)      But it seems not a good way to do it. Question is: What is the recommended way to do this type of operation? Can `MapThread` be told to do this on its own without the help of `Map`? Are there other commands to do the above that you think are better? I used `Rule` above, but you can replace that with any function `f` that takes 2 arguments. **Update 12/26/12** Fyi, I made a small addition to the solution so that it can be also used for 2D matrix, in addition to the 3D matrix (since this was not part of what I was asking originally). Here is my changes. I found that the trick is to tell `Apply` the level to use. For 2D matrix, use level 0 or {}. But for 3D matrix, use {1}. This assumes the input is either 2D or 3D. So this is how it looks now:               f[lst_List] :=Apply[Thread[Rule[#1, #2]] &, lst,If[MatrixQ[lst], Sequence @@ {}, {1}]]     f[ {{1, 2}, {a, b}} ]     (* {1 -> a, 2 -> b} *)      and               f[ {{{1, 2}, {a, b}}, {{3, 4}, {c, d}}}]     (*  {{1 -> a, 2 -> b}, {3 -> c, 4 -> d}} *)      Another way I could have done this, is by making 2 function definitions               f[lst_?(MatrixQ[#] &)] := Apply[Thread[Rule[#1, #2]] &, lst]     f[lst_List] := Apply[Thread[Rule[#1, #2]] &, lst, {1}]      But I personally never liked this type of coding much. Because now the logic is spread around, instead of all being contained in one place that is easier to see and maintain, So I normally like to have one function, and inside it, add the different logic needs for different values and types of the input, rather than define many different functions.


Why does using ReplaceAll twice produce a different result?

Why does this:               Solve[a x^4 + b x^3 + c x^2 + d x + e == 0,  x] /.         {2 c^3 - 9 b c d + 27 a d^2 + 27 b^2 e - 72 a c e -> F}      produce a different result from this?               Solve[a x^4 + b x^3 + c x^2 + d x + e == 0,  x] /.         {2 c^3 - 9 b c d + 27 a d^2 + 27 b^2 e - 72 a c e -> F} /.         {2 c^3 - 9 b c d + 27 a d^2 + 27 b^2 e - 72 a c e -> F}


Make Sinc'[0] return 0 instead of Indeterminate

I want Sinc'[0] to return 0, but instead it returns Indeterminate. I've tried               Unprotect[Sinc]     Unprotect[Derivative]     Derivative[1][Sinc][0] ^= 0      But it doesn't work. Maybe this needs to be similar to this (from the help files for Derivative)               f'[x_] := If[PossibleZeroQ[x], N[0, Precision[x]], (x Cos[x] - Sin[x])/x^2];


How to create a ListLinePlot with a layout analogous to ChartLayout -> "Stacked"?

I am using 3 checkboxes as desktops, portables and ipods in such a way that when I click to desktops it should shows `ListLinePlot` of `p1`, when I click to portables, it should show `ListLinePlot` of `p2` and in the same way, when I click to ipods, it shows `ListLinePlot` of `p3`.               p1 = {.955, .914, .956, 1.516, 1.355};      p2 = {1.462, 1.357, 1.577, 1.917, 2.054};     p3 = {0,0, 1.57, 1.619, 3.997};          Column[{CheckboxBar[        Dynamic[z], {ListLinePlot[p1, Filling -> Axis,            FillingStyle -> Blue] -> Desktop,          ListLinePlot[p2, Filling -> Axis, FillingStyle -> LightBlue] ->           Portables,          ListLinePlot[p3, Filling -> Axis, FillingStyle -> Green] -> Ipods}], Spacer[5], Dynamic[z]}]      This is working correctly. But I want when I click both desktops and portables on, it should show the plots of `p1` and `p2` in a stacked way. Here I am explaining it with the help of `BarChart` because I have no idea whether 'ListLinePlot`can do this .               BarChart[Table[{p1[[i]], p2[[i]]}, {i, 1, 5, 1}], ChartLayout -> "Stacked"]      If I click Desktops, Portables and ipods, then it should dynamically take data of p1, p2 and p3 in stacked order as               BarChart[Table[{p1[[i]],p2[[i]], p3[[i]]}, {i, 1, 5, 1}], ChartLayout -> "Stacked"]      and so on. But I want stacked `ListLinePlot` and I don't know any function like `ChartLayout` in `BarChart`. I have seen the `Accumulate` function but it does not work as I wanted. For more clarification, just have a look at http://graphics.thomsonreuters.com/12/01/US_APPLEBREAK0112_VT.html I want to do as it is, as in the product button of this link. Please help me.


How can I give input to an ArrayPlot

I would like to create a dynamic ArrayPlot so that the squares, when clicked, provide input. Can I use ArrayPlot for this? Or is there something else I should have to use.


How to create a notebook element that can replace itself?

I would like to create a notebook element that can replace itself. Here's an example to illustrate:               Panel[Column[       {Style["This is a panel", Bold],        Button["Press me!",         SelectionMove[EvaluationNotebook[], All, EvaluationCell];          NotebookWrite[EvaluationNotebook[],           "\"Now I'm just a piece of static text.\""]]}]]      This code will create a little panel: ![Mathematica graphics](http://i.stack.imgur.com/AUxce.png) If we press the button, the panel will get replaced by a piece of static text (i.e. not a dynamic expression that's shown as text, but just plain old non- dynamic text). ![Mathematica graphics](http://i.stack.imgur.com/KFkrB.png) Well, in this implementation actually it's not the panel that gets replaced, but the complete cell containing the panel, and that's my problem: I need _only the panel_ to be replaced, so this will work even if the panel is just a subexpression in a larger expression. **How can we create an UI control that is able to replace itself with an arbitrary expression in the notebook?**


Memory Leak while running Animate/Manipulate/Export

While looking into building a simulation for an ant colony, I started encountering some memory leakage issues.                ymax = 1000; xmax = 1000;      nest = {500, 500};      maxAnts = 30;      steps = 200;      maxSpeed = 20;      maxAngle = π/6;           orientation =         RandomVariate[UniformDistribution[{0, 2 π}], maxAnts];     ant = Table[        agent[∞, nest, orientation[[i]], #] & /@ Range[i], {i,          maxAnts}];          update[agent[symbol_, location_, direction_, t_]] :=      Module[{dir, speed, loc},        dir = First@         RandomVariate[          UniformDistribution[{direction - maxAngle,             direction + maxAngle}], 1];        speed = RandomVariate[UniformDistribution[{1, maxSpeed}], 1];       loc = Flatten[location + Round[{speed*Cos[dir], speed*Sin[dir]}]];       loc = Min[#] & /@ Transpose[{loc, {xmax, ymax}}];       loc = Max[#] & /@ Transpose[{loc, {0, 0}}];       agent[symbol, loc, dir, t + 1]]          display[agent[symbol_, location_, direction_, t_]] :=      Text[Rotate[symbol, direction], location]     display[list_] := Module[{lst = display[#] & /@ list}, Graphics[lst]]          history =        Join[ant[[#]],           NestList[update, Last@ant[[#]], steps - Length[ant[[#]]]]] & /@         Range[maxAnts];          Animate[Show[Graphics[display[history[[All, i]]]],        Graphics[{Red, PointSize[Large], Point[nest]}],        PlotRange -> {{0, xmax}, {0, ymax}}], {i, 1, steps, 1}]      ![Animation](http://i.stack.imgur.com/XfjZd.gif) The issue I have is that Mathematica seems to have a memory leak, as the Animate, or manipulate, or exporting to gif runs, the amount of memory allocated to Mathematica keeps growing until it just stops working. Below is a gif in which I turn the animation on and off to show that the memory keeps growing as Animate (or Manipulate) runs. A bummer because this limits the number of ants and steps to use. ![Memory Leakage](http://i.stack.imgur.com/NZJm4.gif)


Locator with Integer value coordinates

I want to get the Pixel value of an image.and here is my code               DynamicModule[{p = {50, 50}},       {Show[img, Graphics[Locator[Dynamic[p]]]],                       ImageValue[img, Dynamic[p]]}]      and it came up with a warning that p is with a non integer value, to solve the problem ,I used `Floor` to get an integer value               DynamicModule[{p = {50, 50}},       {Show[img, Graphics[Locator[Dynamic[p]]]],                       ImageValue[img,Floor/@Dynamic[p]]}]      this time it still doesnt work, with a warning:                   ImageValue::imgrng: The specified argument Floor[p$20303] should be a pair of real or      integer numbers or a list of those.      My question is ,can I strict the loactor to Integer Domain?or is there any more elegent way to deal with this problem?


Importing a Canon Raw file (.CR2)

This is a very top level question with no code examples attached. I have an interest in using Mathematica to read raw files coming from a Canon camera, before they are converted into jpg's, where data is lost. Are there any existing non proprietary mathematica scripts, which can read a CR2 file from a Canon camera and display its image as it would if a jpeg were imported. At the very least a script that can display data about the image stored in the CR2 file to include intensity, size, pixel value, LRGB histograms, etc...


Padding and formatting within BaseForm

I find using BaseForm to be a little tricky. For example, if you use BaseForm and then do some additional operation all the numbers turn back into base 10, so you have do BaseForm as the "last step". This creates the problem of how you then format the BaseForm if it is the last step. For example, given the following:               BaseForm[Grid[Partition[Map[FromDigits[#,16]&,RealDigits[FractionalPart[CubeRoot[Table[Prime[n],{n,64}]]],16,8,-1][[All,1]]],8],Alignment->Right],16]      ![enter image description here](http://i.stack.imgur.com/GO1Qa.png) Formatting problems are: (1) how to get leading zeroes for those values that are less than 8 hex digits? (2) how to get rid of the 16's (I don't want to display them) Please do not answer with copy and paste from the doc center, unless you can you show how the command in question works in the above expression inside of BaseForm. PaddedForm and other similar commands DO NOT WORK as far as I can tell. For example if you write:               BaseForm[Grid[Partition[Map[PaddedForm[FromDigits[#,16],8]&,... etc      It does NOT work.


Ulam's Spiral with Opperman's diagonals (quarter-squares)

First we craft a function to return the quadrant boundary based on Oppermann's Conjecture               a[n_] := (Mod[n, 2] + n^2 + 2 n)/4      Then we create a few lists               r = 10;     q = 1;     q1 = Table[a[q + 4 (n - 1)] <-> a[q + 4 (n)], {n, 1, r}];     q = 2;     q2 = Table[a[q + 4 (n - 1)] <-> a[q + 4 (n)], {n, 1, r}];     q = 3;     q3 = Table[a[q + 4 (n - 1)] <-> a[q + 4 (n)], {n, 1, r}];     q = 4;     q4 = Table[a[q + 4 (n - 1)] <-> a[q + 4 (n)], {n, 1, r}];     u = Flatten[Table[{(n - 1) <-> n}, {n, 2, a[4 + 4 r] + 1}]];      We produce the normal Ulam's Spiral               Graph[u]      ![Ulam's Spiral](http://i.stack.imgur.com/eDqsa.png) We don't get the spiral when we attempt to combine the diagonal lists by using this               Graph[Union[u, q1, q2, q3, q4]]      ![Ulam Bad Spiral](http://i.stack.imgur.com/RaRF3.png) How can we overlay the diagonals onto the spiral?


Specifying non-conflicting PlotTheme options

I am trying out Mathematica 10 on https://programming.wolframcloud.com. `$PlotTheme` interested me a lot because it finally produces nice plots (probably) without the need of fine tuning of every plot. However, the options are conflicting each other and there seems to be some hiding options. For example (figures available at https://www.wolframcloud.com/objects/0caeabc9-81ba-4c6c-a51d-64f06c644a40),               (* This get thick lines *)     LogPlot[{1/x, x,2x, E^x},{x,1,10},PlotTheme->{"ThickLines"}]          (* This get monochrome *)     LogPlot[{1/x, x,2x, E^x},{x,1,10},PlotTheme->{"Monochrome"}]          (* There is no monochrome or thick lines here *)     LogPlot[{1/x, x,2x, E^x},{x,1,10},PlotTheme->{"Monochrome","ThickLines"}]      As another example,               (* Didn't get open markers or monochrome, but at least get thick *)     ListPlot[{{{1,2},{2,4},{3,7},{4,9}},{{1,3},{2,4}}},PlotTheme->{"Monochrome","OpenMarkersThick"}]          (* After adding frame, markers completely changed *)     ListPlot[{{{1,2},{2,4},{3,7},{4,9}},{{1,3},{2,4}}},PlotTheme->{"Monochrome","Frame","OpenMarkersThick"}]      Is it possible to make those themes non-conflicting with each other? The theme seems perfect for me is as follows: (1) The lines are solid, dashed, dotted, ... ("Monochrome") (2) The lines are colored. (e.g. "VibrantColor") (3) Framed ("Frame"). (4) Larger labels ("LargeLabels"). At best thicker lines ("ThickLines"). (5) Setting apply both to `Plot` and `ListPlot` (to put in $PlotTheme instead of tuning every plot). But I am not able to get all of them satisfied -- once `Plot` looks fine, `ListPlot` looks ugly. Is it possible to get some non-conflicting fine tunings once and apply everywhere?


Error Using Sow in DensityHistogram with ColorFunction

To find the color values used in a plot, I was using `Sow` as shown here:               Short@Reap[Histogram3D[RandomVariate[BinormalDistribution[.5], 500],        ColorFunction -> (ColorData["Rainbow"][Sow[#1]] &)]      ]      ![Sow/Reap OK](http://i.stack.imgur.com/bcs6D.png) But I get an error if I simply replace `Histogram3D` by               Short@Reap[       DensityHistogram[RandomVariate[BinormalDistribution[.5], 500],         ColorFunction -> (ColorData["Rainbow"][Sow[#1]] &)]       ]      Now I get the following message:               Transpose::nmtx :  "The first two levels of the one-dimensional list"         {{{-3.5,3.},{-3.5,3.},{0.,24.}},0, ... , 1} cannot be transposed.          Transpose::argt :  "Transpose called with 0 arguments; 1 or 2      arguments are    expected."      ![error](http://i.stack.imgur.com/kK5Qz.png) It's possible to work around this problem by doing without `Sow` and `Reap` as follows:               l = {};     {DensityHistogram[RandomVariate[BinormalDistribution[.5], 500],        ColorFunction -> (ColorData["Rainbow"][AppendTo[l, #1]; #1] &)],       N@l}      But it would be nice to know **if there is an explanation** for why `Sow` doesn't work in the `DensityHistogram` example whereas it works in `Histogram3D`. The same error appears if I leave out the `Reap`. From the message it seems clear that a list of all `PlotRange` tuples is being _sown_ at some point before the `ColorFunction` actually is put to use. I tried to suppress passing that kind of argument to `Sow` by modifying the `ColorFunction` to               ColorFunction -> (If[ListQ[#1], White,       ColorData["Rainbow"][Sow[#1]]] &)      but it had no effect. As Leonid pointed out in his answer, there must therefore be a _different_ invocation of `Sow` outside the color function. Maybe someone knows another way to suppress the invalid `ColorFunction` call that seems to trip up `Sow`. However, it doesn't seem to be obvious because when I _don't_ use `Sow` as in my work-around based on `AppendTo` with a list `l`, there is no entry in the resulting list `l` that corresponds to the `PlotRange` tuples. **Edit** It seems that this is a problem specifically with `DensityHistogram`. I also noticed that the setting for `FrameTicks` is _ignored_ by `DensityHistogram`. It can be restored by wrapping the plot in `Show` with the desired `FrameTicks` option. None of these issues arise with the related function `SmoothDensityHistogram`. Leonid pointed out what the probable cause for the `Sow` error is, but since wrapping the result in another `Show`, I would for now stick with the workaround I mentioned above: ditch `Sow` and `Reap`, and use `AppendTo` to collect the desired values in a list `l` using a `CompoundExpression` of the type `AppendTo[l, #]; #`.


What is an "INTERNAL SELF-TEST ERROR"?

I got this all the time after updating to 9.0 (OS 10.8.2): !["Internal self-test error" message](http://i.stack.imgur.com/Cq6Vv.png) That's **Clipboard|c|3015** for the benefit of anyone searching. The error went away with 9.0.1, but a version has reappeared (multiple times at each launch) since updating my OS (to 10.9): ![enter image description here](http://i.stack.imgur.com/SmUdq.png) That's **SpanBox|c|2178** for the benefit of anyone searching. What does an "Internal self-test error" mean?


Using Boole to integrate over region

I have a complex and long piecewise function to integrate, so I have written a Mathematica script that cuts the whole range of integration, evaluates the integrand in each region and then integrates it. In order to integrate the evaluated function on the right range, I set the integration on the whole original range and I use Boole to define the appropriate region. Now, it happens that both the integrand and the region depends on other parameters, say `a` and `b`, so I should get an integral which depends on these, as in the following WORKING example               Assuming[0 < 2 a < 1,       Integrate[       Exp[-t] Boole[(b < 0.5 && a < t < 2 a) || (b > 0.5 &&             0 < t < a)], {t, 0, 1}]]      which gives $\begin{cases} e^{-2. a} \left(e^a-1.\right) & 0.<a<0.5\land b<0.5 \\\ e^{-1. a} \left(e^a-1.\right) & 0.<a<0.5\land b>0.5 \\\ 0\. & \text{True} \end{cases}$ However, when the range of integration becomes too complex, Mathematica stops to evaluate the integral and give me back an implicit solution. For example, consider the following code               r = (0 < b < 1/          2 && ((0 < a < b &&              b + a < z <               1 && ((z - b < x <= z - a && 0 < y < a) || (z - a < x < z &&                  0 < y < z - x))) || (a == b && b + a < z < 1 &&              z - a < x < z && 0 < y < z - x) || (b < a < 1 - b &&              b + a < z < 1 && z - b < x < z && 0 < y < z - x))) || (1/2 <=           b < 1 && 0 < a < 1 - b &&          b + a < z <           1 && ((z - b < x <= z - a && 0 < y < a) || (z - a < x < z &&              0 < y < z - x)))     int = Exp[-0.5 y1^2 y -          2 (y2^2 (z - b - a) + y1^2 (-z + b + x + a))] y1^2 Boole[r]     Integrate[int, {z, a, 1}, {x, a, z}, {y, 0, a}]      The last line gives me $\text{y1}^2 \int _a^1\int _a^z\int _0^a\exp \left(-2 \text{y1}^2 (a+b+x-z)+2 \text{y2}^2 (a+b-z)-0.5 y \text{y1}^2\right) \text{Boole}[...]dydxdz$ The same happens if I isolate intervals with respect to `a,b` , as in               r = LogicalExpand[(0 < b <            1/2 && ((0 < a < b &&               b + a < z <                1 && ((z - b < x <= z - a && 0 < y < a) || (z - a < x < z &&                   0 < y < z - x))) || (a == b && b + a < z < 1 &&               z - a < x < z && 0 < y < z - x) || (b < a < 1 - b &&               b + a < z < 1 && z - b < x < z && 0 < y < z - x))) || (1/2 <=            b < 1 && 0 < a < 1 - b &&           b + a < z <            1 && ((z - b < x <= z - a && 0 < y < a) || (z - a < x < z &&               0 < y < z - x)))]     s = Reduce[r[[2]], {x, y}]     int = Exp[-0.5 y1^2 y -          2 (y2^2 (z - b - a) + y1^2 (-z + b + x + a))] y1^2 Boole[s]     Integrate[int, {z, a, 1}, {x, a, z}, {y, 0, a}]      or if I split the `Integrate` function               Integrate[      Integrate[Integrate[int, {y, 0, a}], {x, a, z}], {z, a, 1}]      Why Mathematica cannot evaluate the integral?


How to enter chemical equations?

When I want to take chemistry notes and write down a formula such as H_2O or C_2H_5OH it enters "Math mode" which changes the font size and italicizes the letters. Is there an easy way to properly enter chemical formulas and equations in text? I'm new to Mathematica 10 and I'm really boggled by all the styles and how to change them so please keep it simple.


BSplineCurve Interpolation

Can I get interpolated values from this B-spline, (shown in red)?               points = {{-2, 2}, {2, 2}, {6, 6}, {10, 7}, {14, 11},        {18, 2}, {22, 1}, {26, 2}, {30, 1}, {34, 1}};          fn1 = Interpolation[points, Method -> "Spline"];     fn2 = Interpolation[points];          Show[ListPlot[points],      Graphics[{Red, BSplineCurve[points]}],      Plot[fn1[x], {x, -2, 36}],      Plot[fn2[x], {x, -2, 36}],      AxesOrigin -> {-2, 0}]      ![enter image description here](http://i.stack.imgur.com/kpMjw.png)


Plotting the solution of a vector stochastic differential equation

I have a vector stochastic differential equation, $$\mathrm dq = p\,\mathrm dt\qquad q(0)=0$$ $$\mathrm dp = (-q -p)\mathrm dt+\mathrm dW\qquad p(0)=10$$ This can be entered to give me the process describing **either** p or q, using               proc = ItoProcess[         {{p[t], -p[t]-q[t]}, {{0}, {1}}, XXX[t]},         {{q, p}, {0, 10}},         {t,0}     ]      where `XXX` is either `q` or `p`. The solution can be plotted using the usual method (here for `p`) of               ListLinePlot@RandomFunction[proc, {0, 10, .02}, 10]      > ![enter image description here](http://i.stack.imgur.com/bBTbp.png) However, the situation is more difficult if I want to extract **both** `q` and `p`, as for each simulation it will give me a list of the type (obtained using `Normal`, and by setting `XXX[t]` to `{q[t], p[t]}` in the `ItoProcess`)               {{{t0, {q[t0], p[t0]}}, {t1, {q[t1], p[t1]}}, ...}      i.e. the times aren't properly distributed over the p/q, and as a consequence I'm having a hard time finding a good way of getting this into a plottable form. So the questions are:   1. Is there a nice way of getting all components out of a vector stochastic differential equation to plot them alongside each other?   2. If there's none, what's the right hacky approach? Fiddling with `Transpose` and `Flatten`?


How to manipulate 2D plots?

When it comes to visual analysis, large datasets or data with intricate internal details often makes plotting in 2D useless, as the outcome is either just a fraction of the full dataset, or no details can be observed in the mess of datapoints. **How can one make the process of changing the plot range and/or zooming, panning, etc. less tedious** than doing it programmatically and iteratively, from time to time? I often meet with this issue, and developed various methods to deal with it (like this). Though I have now a working solution that I would like to share (see below), I also am highly interested in what kind of methods and tricks others invented to visualize and manipulate complex 2D data with ease.


Is there any simple way to zoom/magnify a selected portion of a plot (like gnuplot or xmgrace)?

Is there any simple way to zoom a particular portion of a plot (similar to what you can do with gnuplot or xmgrace using the magnifier and selecting a region)? Usually I do it by varying the `PlotRange[]` manually or by putting the `PlotRange[]` under `Manipulate[]`, but that is not very convenient option for heavy plotting (which involve complicated functions or large data). Is there anything like a magnifier tool or something similar?


Using MatrixPlot, how can I dynamically zoom in and out with my mouse?

I have a MatrixPlot output which I would like to zoom around in, drawing boxes that define a zoom region with my mouse. These things are all fairly standard in Labview... surely Mathematica must have a similar set of abilities? For an example matrix, we can write:               TestArray = Array[RandomInteger[{0, 1}] &, {100, 100}];     MatrixPlot[TestArray]


Singular integral: NIntegrate fails to converge

I need to calculate the following singular integral:               NIntegrate[Log[1 + y^2]/Cos[Pi y], {y, 0, 1}]      However, it is failing to converge. I have tried to specify `MaxRecursion`, `PrecisionGoal`, and `Exclusions` but neither helped. How does one calculate singular integrals in Mathematica?


Citation and Bibliography mac with Mathematica 9

Insert bibliographical note doesn't appear on the insert menu for Mac. However if I right click the mouse this option does appear: i tried to use a standard bibtex file with it, but it doesn't seem to compile and gives a strange error message. Any idea if this feature is indeed useable?


Why animator smoothes dynamic updates, or how to make pacman drink beer

How could I make a pacman drink beer in Mathematica? This is what I have so far               pacman[xposFun_, angleFun_] := {Yellow,         Disk[{Dynamic@xposFun[Clock[{0, Infinity}]], 0`}, 1`,          Dynamic[{Pi/6 Abs@Sin[2 Pi Clock[]],             angleFun[Clock[{0, Infinity}]]} /. {val_, ang_} :> {val + ang,              2 Pi - val}]]};          burp := Quiet@EmitSound@ListPlay@Upsample[ConstantArray[1, 80], 200]          xpos[t_] := \[Piecewise] {         {5 t, 0 < t < 3},         {15, t >= 3},         {0, True}        };          angle[t_] := \[Piecewise] {        {0, 0 < t < 3},        {Pi/4 (t - 3), 3 < t < 4.8},        {Pi/4 (4.8 - 3), t > 4.8}       }          angleBeer[t_] := \[Piecewise] {        {0, 0 < t < 3.5},        {Pi/4 (t - 3.5), 3.5 < t < 5.3},        {Pi/4 (5.3 - 3.5), t > 5.3}       }          beer[filling_] := {{Opacity[0.2], EdgeForm[Directive[Thick, Gray]],          Polygon[{{0`, 0`}, {1`, 0`}, {1.2, 1.5}, {-0.2, 1.5}}]},        Opacity[0.8], filling, EdgeForm[Directive[White, Thickness[0.01]]],         Scale[{Polygon[{{0`, 0`}, {1`, 0`}, {1.2, 1.3}, {-0.2, 1.3}}],          White,           Polygon[{{-0.2, 1.3}, {1.2, 1.3}, {1.3, 1.6}, {-0.3, 1.6}}]},          0.9],        {Opacity[0.], EdgeForm[Directive[Gray, Thickness[0.01]]],          Disk[{1.1`, 0.7`}, 0.3, {-Pi/2 - 0.2, Pi/2 - 0.2}]}};          Graphics[{pacman[xpos, angle],        Translate[        Rotate[beer[          Dynamic[If[Clock[{0, 5.4}, 5.4, 1] < 5.4, Darker@Yellow,             If[Clock[{0, 7.4, 1}, 7.4, 1] == 7.4, Refresh[burp, None]];             Opacity[0.]]]],          Dynamic@angleBeer[Clock[{0, Infinity}]]], {16, -0.2}]},       PlotRange -> {{0, 20}, {-1.2, 2}}, Background -> Black]           Animator@Dynamic@anything      ![enter image description here](http://i.stack.imgur.com/xbDcN.gif) Now, this serves as an excuse to ask the real question. This is an issue I've also had with version 8 but that I didn't have a reproducible small code for it. I see the dynamic animation is choppy but it gets fixed while any `Animator` is running on display dynamically updating something, like the `Animator@Dynamic@anything` that the code above displays after the pacman. For testing, you can get the animation to restart, by copying and pasting the cell in the same place. Once the pacman is moving, try starting and stopping the animator to see the difference in choppiness. Furthermore, changing the `DynamicUpdateInterval` in the `SystemOption`s can make this improve but it's always choppier without the animator, as if without it it always missed some frames... Do you see this behaviour too? How could I tell the front end "heyy, an animation is happening even if I'm not using an animator"?


How to "ReplaceAll" using a set of conditional expressions instead of a list of rules

Suppose that I have two linear functions               f[x_] := f0 + f1 x     g[x_] := g0 + g1 x      and a (possibly rather complicated) set of conditional expressions, obtained through Reduce. For example, we might have something like this:               conditions = (f0 == f1 && g0 == 0) || (f0 == g1 && g0 == f1)      What I would like to do is write something like               {f[x],g[x]} /. conditions      and receive as output the set of pairs of $f$ and $g$ adhering to that formula. In this case we'd have               {{a + ax, bx}, {a + bx, b + ax}}      (or maybe `{{f0 + f0x, g1x}, {f0 + f1x, f1 + f0x}}` to stick with original variable names). How can I do this?


Find the slope between adjacent points in a list

I have a list of two dimensional points that are ordered by their x-coordinate. I would like to calculate the slope between all adjacent points. I'm familiar with the use of pure functions in Sort for example that can compare adjacent elements. Is there a way to perform a function on all adjacent elements in a list?


Style markers in strings

I'm dealing with strings in _Mathematica_ and I would love to handle their stylling in the most cenvenient way. Without loss of generality, let's assume I want to make some parts of string `Bold`. Example of desired output: > to **be** or **not** to be I know I can achieve that by for example:               StringForm["to `` or `` to be", ##] & @@ (Style[#, Bold]& /@ {"be", "not"})       but I want single function `bold` and some kind of markers (here `#`):               bold @ "to #be# or #not# to be"      > to **be** or **not** to be * * * It is **my approach** :               bold = Module[{x},                    With[{patt = "#" ~~ x : Except["#"] .. ~~ "#"},            StringForm @@ ({                           StringReplace[#, patt :> "``"],                           Sequence @@ StringCases[#, patt :> Style[x, Bold]]                           })]                  ] &      and I have **couple of questions** about it:   * do you feel that `#` is not the best choice too? :)   * is this: `{patt = "#"~~...}` a proper way of storing patterns?   * maybe some other ideas? I like this way but I'm not sure if it is bulletproof. It is quite handy because `StringCases` etc do not look for overlaps by default. Notice that _mixed-style-string-form_ tends to produce some kind of error If you want to edit that cell. This is also what I to want to ask about: > >     INTERNAL SELF-TEST ERROR: MathEditCells2|c|1384 >     Click here to find out if this problem is known, and to help improve >     Mathematica by reporting it to Wolfram Research >


How to output an expression as a Dot[] product

How to force _Mathematica_ to **output** an expression such as $a1u1+a2u2+a3u3$ as a `Dot` product like this one:               {a1,a2,a3}.{u1,u2,u3}       or A.U


A palette of accumulated expertise

I've been trying to put together a palette of useful functionality garnered from this site. There is useful stuff scattered all over the place, for example:   * Post an image   * Copy code   * Duplicate a notebook   * Paste a table As an ugly, yet functional, way of putting them together, I have something like:               CreatePalette[Column[{         OpenerView[{"Duplicate Active Notebook", duplicating}, True],         OpenerView[{"Pasting a table", pasting}, True],         OpenerView[{"Copy for StackExchange", copyForStackExchange}, True]         (* etc *)         }],       WindowTitle -> "mathematica.stackexchange.com"];      where the definitions inside each `OpenerView` are slight modifications of the code from the above links. (Usually just stripping off any existing palette stuff is all that is required. I did find that a single button seemed to require `ImageSize -> Automatic` so it would display properly.) So the question is, what else can I add to this? **Are there any procedures _you_ use regularly that are suitable for a palette?** Things that have made your mathematica experience easier and more productive?   **Is there any enlightening information that could be continually displayed on a palette?** E.g. progress bars, memory usage, cursor position?   **Are there any tips and hints for beginners that could be nicely presented on a palette?**


How to scale edge length and keep layout of edge-weighted Graph?

I love using `Graph` as structure to store and visualize my data in _Mathematica_. Consider the following simple example for creating a `Graph` object with weighted directed edges. I already laid out the graph in a tree structure using the options `{"LayeredEmbedding", "Orientation" -> Top, "RootVertex" -> 1}` I found in the documentation of `GraphLayout`, since this representation is useful for my particular needs.               vertices={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100};     edges={1\[DirectedEdge]2,3\[DirectedEdge]4,5\[DirectedEdge]6,7\[DirectedEdge]8,9\[DirectedEdge]10,11\[DirectedEdge]12,13\[DirectedEdge]14,15\[DirectedEdge]16,17\[DirectedEdge]18,19\[DirectedEdge]20,21\[DirectedEdge]22,23\[DirectedEdge]24,25\[DirectedEdge]26,27\[DirectedEdge]28,29\[DirectedEdge]30,31\[DirectedEdge]32,33\[DirectedEdge]34,35\[DirectedEdge]36,37\[DirectedEdge]38,39\[DirectedEdge]40,41\[DirectedEdge]42,43\[DirectedEdge]44,45\[DirectedEdge]46,47\[DirectedEdge]48,49\[DirectedEdge]50,51\[DirectedEdge]52,53\[DirectedEdge]54,57\[DirectedEdge]58,59\[DirectedEdge]60,61\[DirectedEdge]62,63\[DirectedEdge]64,65\[DirectedEdge]66,67\[DirectedEdge]68,69\[DirectedEdge]70,71\[DirectedEdge]72,73\[DirectedEdge]74,75\[DirectedEdge]76,77\[DirectedEdge]78,79\[DirectedEdge]80,81\[DirectedEdge]82,83\[DirectedEdge]84,85\[DirectedEdge]86,87\[DirectedEdge]88,89\[DirectedEdge]90,91\[DirectedEdge]92,93\[DirectedEdge]94,95\[DirectedEdge]96,97\[DirectedEdge]98,99\[DirectedEdge]100,2\[DirectedEdge]3,2\[DirectedEdge]5,6\[DirectedEdge]7,6\[DirectedEdge]9,10\[DirectedEdge]11,10\[DirectedEdge]13,14\[DirectedEdge]15,14\[DirectedEdge]17,4\[DirectedEdge]19,4\[DirectedEdge]21,22\[DirectedEdge]23,22\[DirectedEdge]25,20\[DirectedEdge]27,20\[DirectedEdge]29,28\[DirectedEdge]31,28\[DirectedEdge]33,34\[DirectedEdge]35,34\[DirectedEdge]37,30\[DirectedEdge]39,30\[DirectedEdge]41,42\[DirectedEdge]43,42\[DirectedEdge]45,40\[DirectedEdge]47,40\[DirectedEdge]49,24\[DirectedEdge]51,24\[DirectedEdge]53,54\[DirectedEdge]55,54\[DirectedEdge]56,26\[DirectedEdge]57,26\[DirectedEdge]59,60\[DirectedEdge]61,60\[DirectedEdge]63,58\[DirectedEdge]65,58\[DirectedEdge]67,8\[DirectedEdge]69,8\[DirectedEdge]71,72\[DirectedEdge]73,72\[DirectedEdge]75,76\[DirectedEdge]77,76\[DirectedEdge]79,74\[DirectedEdge]81,74\[DirectedEdge]83,70\[DirectedEdge]85,70\[DirectedEdge]87,88\[DirectedEdge]89,88\[DirectedEdge]91,86\[DirectedEdge]93,86\[DirectedEdge]95,12\[DirectedEdge]97,12\[DirectedEdge]99};     weights={18,53,50,53,51,96,129,47,47,55,68,75,74,82,65,87,76,10,10,57,99,4,4,46,46,81,81,64,74,7,7,17,17,61,86,64,70,17,17,23,23,64,104,8,8,48,48,80,80,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};          Graph[vertices, edges, EdgeWeight -> weights,        EdgeLabels -> MapThread[Rule, {edges, weights}],        GraphLayout -> {"LayeredEmbedding", "Orientation" -> Top,          "RootVertex" -> 1}, EdgeLabelStyle -> Directive[Blue, 20]]      The graph that I get with these options looks like the following: ![enter image description here](http://i.stack.imgur.com/VwaHH.png) Edge weights are put as labels but all edges have the same length due to the options specified. What I would like to obtain now is a `Graph` object with edges scaled according to the edge weight while keeping the tree-like layout of the graph. I have read the documentation of `GraphLayout` and several other documentation pages on `EdgeWeight`, `TreeGraph`, _etc_. The only possibility I found so far is to use the options `{"SpringElectricalEmbedding", "EdgeWeighted"->True}` for the `Graph` object. However this destroys the tree- like layout I want to keep:                Graph[vertices, edges, EdgeWeight -> weights,       EdgeLabels -> MapThread[Rule, {edges, weights}],       GraphLayout -> {"SpringElectricalEmbedding", "EdgeWeighted" -> True},EdgeLabelStyle -> Directive[Blue, 20]]      And the `Graph` object looks like this: ![enter image description here](http://i.stack.imgur.com/yEtuS.png) **Question: Is there a way to combine the tree-like layout of`Graph` with weight-scaled edges in Mathematica?** I think one would have to change the `VertexCoordinates` that are embedded in the `Graph`. It is easy to access the current `VertexCoordinates` using `GraphEmbedding` but I can't figure out how to change them appropriately.


How to simplify the following trigonometry expression such that the number of used characters is minimal?               (13*Cos[t] - 5*Cos[2*t] - 2*Cos[3*t] - Cos[4*t])/4      The question sounds weird because I ask for the minimal number of used characters, but it is not a typo. The number of used characters must be minimal because the plotter needs short expression. Please ignore the computation performance for this case.


Please explain this code (contains Append, Do, Coefficient)

I am a graduate student using a past student's Mathematica program. Will someone please explain to me exactly what this piece of code is doing? Specifically the `Do[c[j] = {}, {j, 0, k}]`, `Append` command, and the `Coefficient` command. Thanks in advance.               inttstar[1] = (1/8)*(tstar[2] - tstar[0]);     (* Eq 2.31 *)          inttstar[i_] := inttstar[i] = (tstar[i + 1]/(i + 1) - tstar[i - 1]/(i - 1))/         4 - (-1)^i*tstar[0]/(2 (i^2 - 1));    (* Eq 2.30 *)     inttstar[k];          Do[c[j] = {}, {j, 0, k}]     Do[Do[c[j] = Append[c[j], Coefficient[inttstar[j], tstar[i], 1]], {i,         0, k}], {j, 0, k}]          r = {};          Do[r = Append[r, c[i]], {i, 0, 15}]          r


Connect to Windows kernel from Linux computer

I've seen many questions regarding the connection to a Linux machine from a Windows one, but I need to do the opposite. **Situation:** I have Mathematica on my Linux laptop (`A`) and I want to run a remote kernel on my Windows desktop (`B`) (which also has Mathematica) **Current solution:** On `A` I have a kernel that opens in `LinkMode` so when I execute something it gives me a port and IP address of my machine. Then on `B` I use the `LinkConnect` function that allows me to run my computations on `B`'s kernel. **Things to improve:** I want to be able to do this automatically. One annoying part of this solution is that the numbers `N,M` that I use in the `LinkConnect` function (`LinkConnect["N@IP-address,M@IP- address",LinkProtocol->"TCPIP"`) always change, so I have to retype them every time. The other problem is that sometimes I use parallel functions e.g. `ParallelTable[]` but using this solution doesn't allow me to execute multiple kernels on `B`. **Questions:** I think Mathematica comes with a way to do this connection in the background using Remote Kernels, but I don't know how to connect `A` with `B` using that.   * Is it possible to connect from Linux to Windows using Remote Kernels? if so, how?   * Will this allow me to execute parallel kernels in `B`?


Why does DominantColors keep shuffling the order of the results?

This graphic is produced by running `DominantColors` (new in _Mathematica_ 9) with different values, using the Lena image as the source: ![lenna strips](http://i.stack.imgur.com/7qAoA.png) Each row is a list of the dominant colours in an image, when asking for between 2 and 60. However I'm surprised that the order of the colors keeps changing: why would the order depend on how many you asked for? Have I done something daft in my code? Or I have failed to grasp something obvious in the online documentation? (Either is likely.)               With[{l = ExampleData[{"TestImage", "Lena"}]},         Graphics[          Table[{colorList = DominantColors[l, d];            {Table[{                 colorList[[x]],                  Rectangle[{x - 1, 10 - d},{x, 10 - (d + 0.7)}]                   },                 {x, 1, Length@colorList}]}},           {d, 2, 60}]]     ]


How to plot rectangles aligned by their center?

Supose I have a rectangle which area is $x^2$. In some cases I may not know what is the size of each side, for $x=12,$ we have several possibilites:               {{144, 1}, {72, 2}, {48, 3}, {36, 4}, {24, 6}, {18, 8}, {16, 9}, {12,        12}, {9, 16}, {8, 18}, {6, 24}, {4, 36}, {3, 48}, {2, 72}, {1, 144}}      I want to plot each one of these rectangles, all them aligned by their center. Until now, I did this:               n = 144;     a = Select[n/Range[1, n], IntegerQ];     b = Reverse[a];     c = Table[{a[[x]], b[[x]]}, {x, 1, Length[a]}]      Which finds all the sizes of the sizes which satisfy $a\cdot b=x^2$. But I can't figure out how to do the next part, can you help me?


How do I add a color bar to a 3D plot?

I tried               Plot3D[Exp[-x^2 - y^2], {x, -2, 2}, {y, -2, 2},      ColorFunction -> (ColorData["TemperatureMap"][#3] &),      PlotLegends -> Automatic]      in an attempt to add a colorbar legend to the plot, but this did not work. It did work here:               DensityPlot[Exp[-x^2 - y^2], {x, -2, 2}, {y, -2, 2},      ColorFunction -> "SunsetColors",      PlotLegends -> Automatic]      Any suggestions in how I can get it to work in the first bit of code? Thanks.


Why does my matrix lose rank?

I want to check the rank of a matrix for observability, but _Mathematica_ loses a rank if the matrix contains very large numbers. Let's say my matrix is               myM = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {5.4 10^0, 1, 1, 1}};      with this matrix I get a rank of 4               MatrixRank[myM]      but if I change the matrix to               myM = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {5.4 10^12, 1, 1, 1}};      (first entry in the last row) the rank of my matrix is only 3. Can somebody explain it to me please?


Use of Manipulate in CDF documents

I am trying to publish a cdf document, but I'm having some problems with the function `Manipulate` with this code:               Manipulate[x + 1, {x}]      In _Mathematica_ , when I set `x = d + d^3` in the input field, I get this output: > `Manipulate[x + 1, {{x, d + d^3}}]` This is what I want. However, it seems that the cdf player is only able to evaluate the expression `x + 1` when `x` is a number and not a more complicated expression. Is this true or I am doing something wrong?


How to stop Manipulate changing view point

When using the following manipulate I can rotate the plot and manipulate the value without my view point changing;               Manipulate[Plot3D[Sin[a*x + y^2], {x, -3, 3}, {y, -2, 2}], {a, 1, 5}]      If I rotate one of these plot in the following manipulate the value the view point changes back to the default.               Manipulate[GraphicsRow     [{Plot3D[Sin[a*x + y^2], {x, -3, 3}, {y, -2, 2}],     Plot3D[Sin[a*x + y^2], {x, -3, 3}, {y, -2, 2}]}],      {a, 1, 5}]      I have a much more complex plot that contains a GraphgicsRow and a Column and I want it to keep the view point of the plot while I manipulate it. Is there a simple way to do this? Is the problem the GraphicsRow or is that just a coincidence? Thanks.


intersection between two curves in Mathematica

I have two curves (drawn from points) in a plane, one is drawn with `ListLinePlot` and the other drawn with `ParametricPlot`. How can I determine the intersection between both curves? I cannot use (don't know how to) interpolation directly, since the curves are not graphs. Let's say we have                r[\[Phi]_] = 1 + 1/20 Sin[20 \[Phi]];       tb = Table[{r[\[Phi]] Cos[\[Phi]], r[\[Phi]] Sin[\[Phi]]}, {\[Phi], 0, 2 \[Pi], 0.1}];      ListLinePlot[tb]       and we interpolate data stored in `tb`. E.g. at `x = 0.95` there are 4 (or 5) different values for `y`. How can I plot interpolating function? I am sure I am missing something. Theoretically, I could use interpolation across segments of points on a curve but this is something I want to avoid. Any ideas?


How to run Mathematica using Mac Terminal

My question is so trivial and I'm sure most people in here know exactly how to do this, however I still don't know how to run Mathematica in Mac terminal! I need to use all the cores of my computer in order to get faster results. I open Mathematica in terminal using this command:               /Applications/Mathematica.app/Contents/MacOS/MathKernel      Then when I type `math -run "<<test.m"` (test is my file's name), nothing happens! Can anybody guide me what to do or refer me to a good refrence with some examples at this?


Using DSolve to solve for x[t,parameter]

I'm trying to solve an ODE with two independent variables (a cannon firing from a cliff incorporating wind resistance dependent on velocity). I've tried the following for the x-component:               NDSolve[{x''[t, θ] == -0.2*x'[t, θ]/2.30, x'[0, θ] == 10.8*Cos[θ], x[0, θ] == 0},       x[t, θ], t]      Assuming my algebra is correct, how do I properly phrase this input to give me `x[t, θ]`?


Why does Plot3D omit parts of the surface at kinks?

When doing               Plot3D[Max[p^2-q^2,0],{p,0,1},{q,-1,1},PlotStyle->White]      the result looks like this (with Mathematica 8.0.0.0): ![enter image description here](http://i.stack.imgur.com/uhghv.png) As you can easily see, at the "kink" where the function starts going above 0, Mathematica leaves a gap in the surface. Why does it do that, and more importantly, what can I do about it?


How do I eliminate the breaks in a 3D plot with a Max or Min function?

Whenever I make a 3D plot using the `Max` or `Min` functions, I get breaks in the plot when it switches from one expression in `Max` or `Min` to the other. How can I eliminate these breaks to get one continuous surface? The particular example I want to make work is this:               ParametricPlot3D[{r Cos[t], r Sin[t],       Max[r^2 Cos[t]^2 - 1.06^2, 0] + Max[r^2 Sin[t]^2 - 1.92^2, 0]},       {t, 0, 2 \[Pi]}, {r, 0, 3.4}, Mesh->None, Boxed->False, Axes->None]      which produces this: ![surface showing breaks in plot](http://i.stack.imgur.com/QTZ9H.png) but it is possible to reproduce the effect with simpler expressions like `Plot3D[Max[x, 1], {x, 0, 2}, {y, 0, 2}]`. * * * I've checked that occurs with Mathematica 7 and 8 on Windows and Linux.


Exporting Mathematica expression as SVG

I was thinking it would be nice if I could export Mathematica expressions as svg, but I am having some issues. At first blush everything seems to work fine. This piece of code does produce a svg file:               res = Solve[x^2 + a x + 1 == 0, x]     Export["res.svg", res]      The problem with the svg file are the fonts. If I try to open the file in Adobe Illustrator I get this message:               SVGMathematica2Mono:          Font not found on the system; missing font has been substituted.     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -           SVGCourier:          Font not found on the system; missing font has been substituted.     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -      The end result looks like this: ![SVG issues](http://i.stack.imgur.com/DpEev.png) It looks bad in several other svg viewers as well. Is there some way to either embed the needed fonts in the svg file or convert the expression to a graphic and export it as such?


How can this image (optical illusion) be created with Mathematica?

I came across this image the other day: ![enter image description here](http://i.stack.imgur.com/ttcii.jpg) and liked the sensation of it pulsing. I was wondering if anyone would know how to create something similar with Mathematica (without the Pink Floyd Dark Side of the Moon logo). **Edit** Very nice work from @halirutan, @Silvia, and @J.M -- you've given me headaches -- literally :)


Possible to use Manipulate in GUIRunModal?

Is it possible to use the widget created by `Manipulate` within `GUIRunModal`? I intend to run the file using `MathematicaScript -script <filename>`.


Better use of Mathematica's PolynomialReduce[]?

I've been using               scPhiDecomp[expr_]:= PolynomialReduce[expr, {x^2-y^2,2 x y}, {x,y}]      which works great on               scPhiDecomp[a x^2 + 2c x y -a y^2]     >> {{a,c},0}      but doesn't do what I want on               scPhiDecomp[y (a x^2 + 2c x y -a y^2)]     >> {{0,(a x)/2+c y},-a y^3}      How do I use `PolynomialReduce[]` to produce `{{a y, c y}, 0}` on the second expression, while still producing the desired result on the 1st? Thanks, Keith


Strange message appearing when using Wolfram Alpha in Mathematica

I have Mathematica 9.0.1.0 and I've recently noticed that whenever I press the equals sign and type something like Sech[x]^2, I get the message: ![enter image description here](http://i.stack.imgur.com/dFYfV.png) I then tried other search queries, such as p^2, Hamiltonian, and 40 degrees 39'44''. I keep getting the same message, though. What's strange is that, regardless of the search query, Mathematica still correctly interprets the input. Does anyone know why this message appears? I only started seeing it a week or two ago. Thanks.


Graphics elements in a 2D lattice

I'm trying to write a small piece of code that will take the RHS of a first order linear ODE and return a slope field sampled at a few points. I have written:               (* Direction fields for 1st order linear equations y' = f(y,t) *)          grid = 10;          supt = 2; inft = -2; supy = 2; infy = -2;          tlist = Table[inft + n (supt - inft)/grid, {n, 0, grid}];     ylist = Table[infy + n (supy - infy)/grid, {n, 0, grid}];          Ggrid = Partition[Flatten[Outer[{#1, #2} &, tlist, ylist]], 2];          f = #1 + Exp[-2 #1] - 3 #2 &;          slopes = f[#[[1]], #[[2]]] & /@ Ggrid // N;       slopes is a `Table` of function values evaluated on the 2 dimensional array `Ggrid`. I would like to plot a small line with the given slope at the corresponding point in `Ggrid`.


How to stack matrices: one on top of another?

I have over 10 thousands matrices each with n by 3 size. For example, M[1]={{1,2,3},{4,5,6},{7,8,9}}, M[5]={{10,11,12},{13,14,15}} and M[20]={{16,17,18},{19,20,21},{22,23,24},{25,26,27}}. I want to form Mfinal={{1,2,3},{4,5,6},{7,8,9},{10,11,12},{13,14,15},{16,17,18},{19,20,21},{22,23,24},{25,26,27}}. I have tried like this mylist={5,20}; Do [Mfinal=Join[M[1],M[i],1],{i,mylist}]. It does not give me the results I desire.


non-linear trend reduction using thresholds

Doing some mappings of the earth magnetic field results in the left-hand figure below (which consists of 181 profiles): ![Non-linear trend reduction without threshold](http://i.stack.imgur.com/oKzCe.jpg) To improve this I tried a non-linear trend reduction using, for example,               lm = LinearModelFit[data, {a, a^2,a^3,a^4,a^5,a^6,a^7,a^8,a^9},a];      (middle figure) and               lm = LinearModelFit[data, {a, a^2,a^3}, a];      (right-hand figure), respectively. Data was defined as `data = Import[#1, "Table"];` within a `Scan` environment. Because of the occurrence of artifacts I feel that I have to consider something like thresholds, so that the reduction will be only considered within a threshold (for example -20 <= t <= 20) and the data outside of this range should not be affected by these calculations. I have no idea how to handle this effectively. My idea first was to use a lot of `IF`'s and to separate each profile into several parts. But this will be ineffective and time-consuming... I would like to handle all those 181 profiles separately before combining them. * * * @R.M.: This is the code I used so far:               SetDirectory[SystemDialogInput["Directory"]]     listOfFileNames = ReadList["listing.txt", Word];          Scan[      (data = Import[#1, "Table"];        newfile = StringReplace[#1, ".dat" -> "-red.dat"];        wfile = OpenWrite[newfile, FormatType -> StandardForm];        Clear[lm]; Clear[a]; Clear[neu]; Clear[aha];         start = First[First[data]]; mdim = Length[data];        lm = LinearModelFit[          data, {a, a^2, a^3, a^4, a^5, a^6, a^7, a^8, a^9}, a];        Do[aha = Last[Take[data, {m, m}]]; ywert = Last[aha];          xwert = First[aha]; neu[m] = ywert - lm[xwert], {m, mdim}];        Do[WriteString[newfile, start + (m - 1)*0.05  , "  "];          Write[newfile,    neu[m]], {m, mdim}];        Close[wfile];        Clear;        ) &,      listOfFileNames      ]      With listing.txt: 09500.dat 09525.dat 09550.dat 09575.dat 09600.dat 09625.dat 09650.dat 09675.dat etc * * * @belisarius: ![example 2](http://i.stack.imgur.com/Ij5Ru.jpg) This shows the quality of data outside of the pipeline I want to achieve @Mr.Wizard: With VSNR there is no effect on the data: ![enter image description here](http://i.stack.imgur.com/X7RyQ.png)


Creating a table/Matrix during a For loop

I have a `For` loop (with `i` as a counter), which calculates different values (`y1`, `y2`, `y3`,...) as a function of the variable `x`. How can I create a table/matrix which contains `i` lines, each line containing the variable `x_i` and the values (`y1_i`, `y2_i`, `y3_i`,...)?


Create a (maybe nested) list of nminimize solutions in a loop

I'm a total newbie in mathematica, so need some help. I understand that my question is about basics, but i couldn't find the answer in docs, google and here. Here is what i'm trying to do.               For[i = 1, i < 10, i++,      Quiet[s =          NMinimize[{Abs[x1] + Abs[x2] + Abs[x3] + Abs[x4] + Abs[x5],            Abs[0.055*(x1 + 11) + 0.065*(x2 - 13) + 0.068*(x3 - 47) +                0.071*(x4 - 50) + 0.07*(x5 - 43) + 0.852] <= 0.30 * i &&             Abs[-8.567*(x1 + 11) - 9.057*(x2 - 13) - 9.154*(x3 - 47) -                8.937*(x4 - 50) - 8.608*(x5 - 43) - 1359.469] <= 6 &&             Abs[55.818*(x1 + 11) + 62.22*(x2 - 13) + 64.286*(x3 - 47) +                64.945*(x4 - 50) + 63.306*(x5 - 43) + 4747.69] <=              1650}, {x1, x2, x3, x4, x5},           Method -> "DifferentialEvolution"]]            AppendTo[sols_nested_list, s]???      ]      Here AppendTo is wrond, but i need something like {{f,x1,x2,x3,x4,x5},{f,x1,x2,x3,x4,x5}...} How can i do this? Thanks in andvance.


Specifying an array that may have an unknown number of entries

Say I'm running some process of unknown duration, and during the process, I need to periodically record the state of some variable. If we knew exactly how long the process took, we could simply specify an array of appropriate size, and know that when the array is filled, we'll be finished. However, if this is not the case, it seems one has to resort to operations like:               testArray = Append[testArray,dataPoint];      Which becomes both computationally intensive and memory intensive at the limit of large array sizes. Is there a better way to proceed? Or should I simply specify a very large version of `testArray` and then chop it down after I've finished my procedure and filled it to some limited extent? Let me provide an example of the kind of process I'm thinking of (using the horrible `Append` strategy just to make things clear):               randVar=0;     storage={};          While[randVar<=0.99,     randVar=RandomReal[];     storage = Append[storage,randVar];     ];     Length[storage];      How do we use e.g. Sow/Reap to deal with the array updates?


get while loop output into a list

I would like to get the output from this while loop and use it as a list so I can count the frequency of the various tuples..               n = 1;     While[n < 10,       Print[RandomSample[Join[Table["a", {2}], Table["b", {2}]], 2]]; n++]      I'm thinking it should be easy but I haven't been able to do it? Thanks in advance for any suggestions!


Assign the output of a loop

> **Possible Duplicate:**   >  Creating a table/Matrix during a For loop Yet another simple question.               For[i = 1, i < 3, i++,      For[j = 1, j < 3, j++,        Print[{i, j}]      ]     ]      I want to assign the output to a list, for example like:               tts = {{1, 1}, {1, 2}, {2, 1}, {2, 2}}      All my efforts did not gave me the desired result, but I am sure it is possible. Any suggestions are welcome.


Dispatch displays rules incorrectly and evaluates when displaying

Consider this               a = 3;     disp = Dispatch[Unevaluated[{a -> 2}]]      > ![enter image description here](http://i.stack.imgur.com/E8Eg8.png) We see the rule `3 -> 2`, rather than `a -> 2`. However, we have               Unevaluated[a] /. disp      > >     2 (*not 3*) >   So that indeed the rule in the dispatch table was `a -> 2`. Note however that               Unevaluated[a] /. Normal[disp]      > >     3 >   As `Normal[disp]` intermediately evaluates to `a -> 2` which evaluates to `3 -> 2`. `a` does not match 3, so there is no replacement. So at first sight it may seem reasonable that `Dispatch` displays the table this way. However, this may lead to side effects **Side effects** Consider the following example. First we just set `disp2`, without displaying it.               disp2 = Dispatch[Unevaluated[{Print["hello"] -> 2}]];      > >      Null (*prints nothing, note the semicolon*) >   but when we do display the `Dispatch` table, the message is printed. ![enter image description here](http://i.stack.imgur.com/7fUqK.png) Note that we can still use the `Dispatch` table however.               Unevaluated[Print["hello"]] /. disp2      > >     2 >   This seems quite weird to me. To me it seems reasonable to put any expression in a `Dispatch` table. But it is not nice at all that such expressions would be evaluated when we display the `Dispatch` table. I suppose the way around this is to use `HoldPattern`, but that is disappointing to me, because really this should not be necessary. **Comparison with Association** To see why this is disappointing, consider `Association`. Here it is crucial that we use `Unevaluated`, as it is not an option to use `HoldPattern`, as the following does not work.               (*b has no value*)     Association[HoldPattern[b] -> 2][b]      > >     Missing["KeyAbsent", b] >   For `a`, which does have a value, we would have to do               Association[Unevaluated[a -> 2]][Unevaluated[a]]      > >     2 >   **Quick fix** Note that evaluating the following will prevent this issue.               Unprotect[Dispatch];     Clear@Dispatch;     Protect[Dispatch];      This only clears the rules that determine how `Dispatch` tables are displayed. **Question** So all in all it's nothing too major, I just wanted to share this. It is not nice that `Dispatch` can have side effects when used in this reasonable way. Is this a bug? A perfect answer would "spelunk" to where to code is evaluated.


How to set the initial condition? (to make IC and BC consistent)

I want to find the initial condition which fits mixed boundary condition of Phi[r, Theta, t]. The original initial condition in text is               Phi[r, Theta, 0] == 1      . I heard the information that the initial condition doesn't have to be strictly consistent (the value 1). It can be bigger or smaller than 1, or can vary. The mixed boundary condition which should be consistent with initial condition and shouldn't be changed is               Derivative[1, 0, 0][Phi][s, Theta, t] == k/rc Phi[s, Theta, t]      I tried five kinds of initial conditions. At first, as information in text               Phi[r, Theta, 0] == 1      At second, (using exponential function in small section)               Phi[r, Theta, 0] == If[r < (1 + a) s, Exp[k/rc (r - s)], If[r < (1 + 2 a) s,      Exp[-(k/rc) (r - (1 + 2 a) s)], 1]]      At third, (using linear function in small section)               Phi[r, Theta, 0] == If[r < (1 + b) s, k/rc (r - s) + 1, If[r < (1 + 2 b) s,      -(k/rc) (r - (1 + 2 b) s) + 1, 1]]      At fourth, (using exponential function again but some different from second)               Phi[r, Theta, 0] == If[r < (1 + c) s, 2 - Exp[-(k/rc) (r - s)], If[r < (1 + 2 c) s,      2 - Exp[k/rc (r - (1 + 2 c) s)], 1]]      At fifth, (same function with second, but using Piecewise than If statement)               Phi[r, Theta, 0] == Piecewise[{{Exp[k/rc (r - s)], r < (1 + a) s}, {Exp[-(k/       rc) (r - (1 + 2 a) s)], r < (1 + 2 a) s}, {1, r >= (1 + 2 a) s}}]      All five trial gave me 'ibcinc boundary and initial conditions are inconsistent' error message. How can I set ' **initial condition** ' to fit 'mixed boundary condition'? Thanks in advance! * * * * * * _From here, it is the before-shortened question. (How to get over NDSolve ibcinc error message? (Inconsistent initial condition and mixed boundary condition))_ I have a question about the error message which includes ibcinc. The problem is that I tried to adjust initial condition to satisfy the Mixed boundary condition, but I was still given ibcinc inconsistent message. The original initial condition is               Phi[r, Theta, 0] == 1      . I tried to make new initial condition (Fun1[r],Fun2[r],and Fun3[r] instead of 1) using this original initial condition. However, this gave same ibcinc inconsistent IC and BC error message. The hole code is following.               Clear["Global`*"]     Dif = 1.33 10^11;     s = 8 ;     rc = s/0.0713;     k = 10^4;     a = 10^-3;     Fun1[r_] =      If[r < (1 + a) s, Exp[k/rc (r - s)],      If[r < (1 + 2 a) s,      Exp[-(k/rc) (r - (1 + 2 a) s)], 1]]     b = 10^-3;     Fun2[r_] =      If[r < (1 + b) s, k/rc (r - s) + 1,      If[r < (1 + 2 b) s, -(k/        rc) (r - (1 + 2 b) s) + 1, 1]]     c = 10^-3;     Fun3[r_] =      If[r < (1 + c) s, 2 - Exp[-(k/rc) (r - s)],      If[r < (1 + 2 c) s,      2 - Exp[k/rc (r - (1 + 2 c) s)], 1]]     Fun11[r_] = Piecewise[{{Exp[k/rc (r - s)],      r < (1 + a) s}, {Exp[-(k/rc) (r - (1 + 2 a) s)], r < (1 + 2 a) s}, {1,      r >= (1 + 2 a) s}}]     Plot[Fun1[r],{r,s,(1+3 a)s}]     Plot[Fun2[r],{r,s,(1+3 b)s}]     Plot[Fun3[r],{r,s,(1+3 c)s}]     Plot[Fun11[r],{r,s,(1+3 a)s}]     t0 = 10^-3;     tmax = 10;     rmax = 1.5 s     e = 1.602 10^-19     Ef = 10^6     kB = 1.381 10^-23     T = 298     Const = (e Ef)/(kB T) /10^10 (* 1/(angstrom)*)     sol = NDSolve[{D[Phi[r, Theta, t], {t, 1}] ==      Dif (D[Phi[r, Theta, t], {r, 2}] +         1/r^2 D[Phi[r, Theta, t], {Theta, 2}] + (2/r -            rc/r^2 + Const Cos[Theta]) D[Phi[r, Theta,            t], {r, 1}] + (1/r^2 Cos[Theta]/Sin[Theta] -            Const/r Sin[Theta]) D[Phi[r, Theta,            t], {Theta, 1}]), Phi[r, Theta, 0] ==      Fun3[r], Phi[rmax, Theta, t] ==      1, ( Derivative[1, 0, 0][Phi][s, Theta,        t]) == k/rc (Phi[s, Theta, t]), (       D[Phi[r, Theta, t], {Theta, 1}] /. Theta ->         10^-3) ==      0, ( D[Phi[r, Theta, t], {Theta,          1}] /. Theta -> (\[Pi] - 10^-3)) ==      0}, Phi, {r, s, rmax}, {Theta,      10^-3, \[Pi] - 10^-3}, {t, 0, tmax}, PrecisionGoal -> 4,      StartingStepSize -> 0.0001,      Method -> {"MethodOfLines",      "SpatialDiscretization" -> {"TensorProductGrid",        "MinPoints" -> 100, "MaxPoints" -> 200}}]          (*BCtest1*)Plot3D[      First[(Phi[rmax, Theta, t] - 1) /. sol], {Theta,       10^-3, \[Pi] - 10^-3}, {t, 0, tmax}]     (*BCtest2-1*)Plot3D[      First[((( D[Phi[r, Theta, t], {r, 1}]) - k/         rc Phi[r, Theta, t]) /. sol) /.       r -> s], {Theta, 10^-3, \[Pi] - 10^-3}, {t, 0, tmax}]     (*BCtest2-1-1*)Plot3D[      First[((( D[Phi[r, Theta, t], {r, 1}])) /. sol) /.       r -> s], {Theta, 10^-3, \[Pi] - 10^-3}, {t, 0, tmax}]     (*BCtest2-1-1-1*)Plot3D[      First[((( D[Phi[r, Theta, t], {r, 1}])) /.       r -> s) /. sol], {Theta, 10^-3, \[Pi] - 10^-3}, {t, 0,       tmax}]     (*BCtest2-2*)Plot3D[      First[((( D[Phi[r, Theta, t], {r, 1}]) - k/          rc Phi[r, Theta, t]) /. sol) /.       r -> s] + k/rc, {Theta,       10^-3, \[Pi] - 10^-3}, {t, 0, tmax}]     (*BCtest2-3*)Plot3D[      First[((( D[Phi[r, Theta, t], {r, 1}]) - k/         rc (Phi[r, Theta, t] - 1)) /. sol) /.       r -> s], {Theta, 10^-3, \[Pi] - 10^-3}, {t, 0, tmax}]     (*BCtest3*)Plot3D[      First[( D[Phi[r, Theta, t], {Theta, 1}] /. Theta ->        10^-3) /. sol], {r, s, rmax}, {t, 0, tmax}]     (*BCtest4*)Plot3D[      First[( D[Phi[r, Theta, t], {Theta,         1}] /. Theta -> (\[Pi] - 10^-3)) /. sol], {r, s,       rmax}, {t, 0, tmax}]          Phin = First[Phi /. sol]     Plot3D[Phin[s, Theta, t], {Theta,      10^-3, \[Pi] - 10^-3}, {t, 0, tmax}]     Plot3D[Phin[r, 10^-3, t], {r, s, rmax}, {t, 0, tmax}]      If solution is well investigated, boundary conditions should have consistency so that the boudary condition test gives the value nearly zero ( _BCtest 1~4_ ) using Plot3D, but the second boundary condition               ( Derivative[1, 0, 0][Phi][s, Theta, t]) == k/rc (Phi[s, Theta, t])      is not satisfied (That is, in boundary condition test ( _BCtest2-1_ ) using Plot3D, (Derivative[1,0,0][Phi][s, Theta, t]- (k/rc) Phi[s, Theta, t]) should give nearly zero, but k/rc ), and is expected to have conflicts with initial condition               Phi[r, Theta, 0] == Fun1[r]      ,               Phi[r, Theta, 0] == Fun2[r]      , or               Phi[r, Theta, 0] == Fun3[r]      Could I get a suggestion for adjust the initial condition to new one which doesn't deviate much from the original initial condition               Phi[r, Theta, 0] == 1      ? Or can I receive new insights to get over inconsistent IC and BC error message? Thanks in advance!


Changing "Block[]" to a Manipulation

I have a graph here and I want to be able to manipulate the 4 parameters that are in the Block command. I want to watch the graph change as I change the parameters. I've done this before, but the Block command that Mathematica suggested throws me off a little bit. Here is the code:                test = Block[{ε = 3, ω0 = 1, ωf = 1.788,       A = 5}, Reap[      NDSolve[{x''[t] == ε (1 - x[t]^2) x'[t] - ω0^2*x[t] +           A*Sin[ωf*t], x[0] == 1, x'[0] == 0,         WhenEvent[Mod[t, 2 π/ωf] == 0,          Sow[{x[t], x'[t]}]]}, {}, {t, 0, 10000},        MaxSteps -> ∞]]][[-1, 1]];          ListPlot[test, ImageSize -> Medium, PlotRange -> All,       PlotStyle -> PointSize[0.0035]]


ListPlot under conditions Part II

I have a data file containing several columns and thousands lines of data. Below I present a small portion of it, in order to express my issue:               -6.00000000          -0.50000000   0.2012925952067529E+01   -.1354335628382003E+01   -.1226489717949115E+01   0.3971000000000000E+02   0.3563073636222663E-02    8     -6.00000000          -0.40000000   -.1667709017102080E+01   0.1996988297249126E+01   -.8819770483714856E+00   0.2608000000000000E+02   0.7532864609099250E-05    6     -6.00000000          -0.30000000   -.1790107106742991E+01   -.1663230917261907E+01   0.1128076001589623E+01   0.2088000000000000E+02   0.3177221419972102E-02    3     -6.00000000          -0.20000000   -.1705528943436493E+01   -.1416493048162809E+01   -.1473371717762452E+01   0.1974000000000000E+02   0.1287464426169665E-04    7     -6.00000000          -0.10000000   -.1438853964633666E+01   0.8237153975034051E+00   0.2328464291089728E+01   0.1852000000000000E+02   0.4189535638506170E-02    2     -6.00000000           0.00000000   -.7656851229280424E+00   -.1226763235452721E+01   -.2690993457287972E+01   0.4270000000000000E+02   0.1253249246603346E-11    7     -6.00000000           0.10000000   0.2359731627744364E+01   -.1081845089584134E+01   -.1195510444527736E+01   0.3603000000000000E+02   0.3777453269309895E-06    8      The first two columns correspond to the coordinates $x$ and $y$. I have a MMA code (is given below) for plotting the coordinates $(x,y)$ and assign to each point a color according to the value of the sixth column. The last column has an integer which takes values inside the interval [0,8].               input = ReadList["data18.out", Number, RecordLists -> True];     input2 = ReadList["data0.out", Number, RecordLists -> True];          data = Table[{input[[i, 1]], input[[i, 2]], Log10[input[[i, 6]]]}, {i,1, Length[input]}];     data2 = Table[{input2[[i, 1]], input2[[i, 3]]}, {i, 1, Length[input2]}];          Clear[colorbar]     colorbar[{min_, max_}, colorFunction_: Automatic, divs_: 150] :=      DensityPlot[y, {x, 0, 0.1}, {y, min, max}, AspectRatio -> 10,      PlotRangePadding -> 0, PlotPoints -> {2, divs}, MaxRecursion -> 0,      Frame -> True,      FrameLabel -> {{None,       Row[{Subscript["log", "10"], "(", Subscript["t", "esc"],         ")"}]}, {None, None}},      LabelStyle -> Directive[FontFamily -> "Helvetica", 17],      FrameTicks -> {{None, All}, {None, None}},      FrameTicksStyle -> Directive[FontFamily -> "Helvetica", 15, Plain],      ColorFunction -> colorFunction]          V = ω^2/2*(x^2 + y^2 + z^2) + ϵ*(x^2*y^2 + x^2*z^2 +        y^2*z^2 - x^2*y^2*z^2);     Vxy = V /. {z -> 0};     ω = ϵ = 1;     E0 = 8.5;     z0 = 0.1;     xmin = 4.5;          f[x_, px_] := 1/2*px^2 + V /. {y -> 0, z -> z0};          plrange = {{-xmin, xmin}, {-xmin, xmin}};     valrange = {0, 5};          C0 = ContourPlot[Evaluate[f[x, px]], {x, -5, 5}, {px, -5, 5},      Contours -> {E0}, ContourStyle -> {{Black, Thickness[0.003]}},      AspectRatio -> 1, ContourShading -> False, PlotPoints -> 200,      PerformanceGoal -> "Speed", PlotRange -> plrange];          L0 = ListPlot[data2, PlotStyle -> {Black, PointSize[0.011]}];          With[{opts = {ImageSize -> {Automatic, 550}}, cf = "Rainbow"},      Row[{Show[     ListPlot[List /@ data[[All, {1, 2}]],       PlotStyle -> ({PointSize[0.01], ColorData[cf][1 - #]} & /@          Rescale[data[[All, 3]], valrange]), PlotRange -> plrange,       AspectRatio -> 1, Frame -> True, RotateLabel -> False,       Axes -> None, FrameTicks -> True,       FrameLabel -> {Subscript["x", "0"],         OverDot[Subscript["x", "0"]]},       LabelStyle -> Directive[FontFamily -> "Helvetica", 17],       ImagePadding -> {{60, 20}, {60, 20}}, opts], C0, L0],      Show[colorbar[valrange, ColorData[cf][1 - #] &],      ImagePadding -> {{20, 60}, {60, 20}}, opts]}]]      The `data18.out` file contains all the data. However, if there is a zero at the last column I want the corresponding points to be plotted in black; only when 1-8 the rainbow colors should apply. So, in order plot with in black these points, I extracted them in a separate file `data0.out`. What I want is instead of using two files, to use only the original `data_all.out` file. I suppose that and `IF` condition is possible inside the `ListPlot` Here is the final output ![grid](http://i.stack.imgur.com/8518J.jpg) Many thanks in advance. **EDIT** The complete data file can be found here: data **EDIT 2** A revised working MMA notebook can be downloaded from here: code


Set Frame Margin for Exporting Video File (.avi)

I have a question regarding setting the frame margins of exporting .avi file. I want to make a short video of some pictures I import using Table:               table1 = Table[     [Show[Import[ToString[i] <> ".eps"], ImageSize -> Large], {i, 1, 100, 1}];      These pictures are all fine with 0 image padding, but when I try exporting them to video:               Export["1.avi", table1, ImageSize -> Large,      "FrameRate" -> 4],      And the video cuts them off, as if only showing a thin stripe of the whole pictures. I tried messing with ImagePadding, but that only puts the pictures in the video in the bottom left corner. Is there a way to show the pictures in the video at the center of the screen, when playing? Thank you very much.


Converting other C++ classes to MTensor in LibraryLink

Hopefully this will be a quick question + a quick answer: Say I have a C++ (or C) code using LibraryLink. I am using a library that defines a specific matrix class, as many numerical libraries commonly do. So during the computations I am using this class and, at the very end, I want to convert it to an MTensor to be used as output. What is the simplest way to do that? Hopefully, one that does not require reallocating the entire matrix? [Not sure it helps, but the matrix elements are assumed to be stored sequentially.] Thank you in advance for the support. Gabriel **Edit:** Two examples are the NVector class in SUNDIALS and the Matrix class in numerical recipes (3rd Edition in C++). Here is a quote from Numerical Recipes ($n$,$m$ are integers): let               MatDoub a(n,m);     Doub *b &a[0][0];      Then $a[i][j]$ and $b[m*i+j]$ are equivalent.


Complex Numbers: need to find $\left | H(\omega ) \right |$ and the arg $\left | H(\omega) \right |$ of the following equation

> Let $H(\omega)$ be a complex-valued function of the real variable $\omega$. > Find $\left | H(\omega ) \right |$ and arg $\left | H(\omega ) \right |$. > > $\quad \quad H(\omega) = \frac{-2-j\omega}{(3 + j\omega)^{2}}$ I'm pretty cobfused with what I'm supposed to be looking for. Am I looking for the principle argument of $H(\omega)$? and just calculate the absolute value of the function?


NSolve cannot solve system of equations in Mathematica

I have the following two equations:               Ieq1=-1 - (0.763546 I1 (1/(-(-8 + 10/I2)^2 + (1 - 9/I1 + 10/I2)^2) - (     18 (1 - 9/I1 + 10/I2))/(     I1 (-(-8 + 10/I2)^2 + (1 - 9/I1 + 10/I2)^2)^2)) X^1.3)/((1.36-      I1) (I1/(-(-8 + 10/I2)^2 + (1 - 9/I1 + 10/I2)^2))^2.3) + (     0.587343 X^1.3)/((1.36-      I1) (I1/(-(-8 + 10/I2)^2 + (1 - 9/I1 + 10/I2)^2))^1.3) + (     0.587343 I1 X^1.3)/((1.36-      I1)^2 (I1/(-(-8 + 10/I2)^2 + (1 - 9/I1 + 10/I2)^2))^1.3);          Ieq2=1 + (0.763546 I1^2 ((20 (-8 + 10/I2))/I2^2 - (20 (1 - 9/I1 + 10/I2))/     I2^2) (-8 + (1 - 9/I1 + 10/I2)^2) X^1.3)/((1.36-      I1) (I1/(-(-8 + 10/I2)^2 + (1 - 9/I1 + 10/       I2)^2))^2.3 (-(-8 + 10/I2)^2 + (1 - 9/I1 + 10/I2)^2)^3) - (      0.587343 I1 ((20 (-8 + 10/I2))/I2^2 - (20 (1 - 9/I1 + 10/I2))/     I2^2) (-8 + (1 - 9/I1 + 10/I2)^2) X^1.3)/((1.36-      I1) (I1/(-(-8 + 10/I2)^2 + (1 - 9/I1 + 10/       I2)^2))^1.3 (-(-8 + 10/I2)^2 + (1 - 9/I1 + 10/I2)^2)^2);      and then I use the NSolve function:                NSolve[{Ieq1 == 0, Ieq2 == 0}, {I1, I2}]      because I want to solve each one as a function of X. But unfortunately it just gets stuck while running. Do you have any suggestions to overcome this problem?


Packing squares into a circle

I am currently trying to solve and understand a problem about packing the maximum of squares into a circle. What I am trying to do, is to calculate the maximum number of variable sized squares (with fixed side) into a circle of variable diameter. For example the result you get at WolframAlpha typing 'pack squares of side 50mm into a circle of diameter 300mm': Densest known packing: ![enter image description here](http://i.stack.imgur.com/D26ua.gif) Furthermore, I would like to be able to add a variable for horizontal and vertical spacing between each square. I have found this to be exactly what I am trying to understand and build.


some confusion about ReplaceRepeated

This is Right.               NestWhile[Log, 100, # > 1 &]     {100} //. {x_} /; x > 1 :> {Log[x]}     100. //. x_ /; x > 1 :> Log[x]      This is wrong,why?               100 //. x_ /; x > 1 :> Log[x]      ![enter image description here](http://i.stack.imgur.com/0BFpO.jpg)


Simple Solve example fails: why?

`Solve` is an amazing tool, but sometimes it doesn't work in the way I expect it to. The particular instance that is confusing me right now is this:               Solve[a==b&&c==d,a]      I expect it to tell me that `a->b`, but instead it gives no solutions. I am using version 9, if this makes a difference. To be clear, my question is _not_ how do I fix this example (e.g. "Ian, just do `Solve[a==b&&c==d,{a,c}]`"), but rather, _why_ does it think there are no solutions. Bonus if you can provide a tool that does think `a->b` is a solution. **Update:** Thanks to @MichaelE2 in the comments for the illustrative example -- it made obvious what was not obvious to me before; `Solve` performs a task which is only an approximation to the everyday meaning of the word "solve". When I think of the expression `Solve[expr,vars]`, what I want it to do is treat every symbol not in the list `vars` as "known" and solve for the "unknown" symbols in `vars`. What it actually does is try to find a set of replacements for the symbols in `vars` such that `expr/.soln` is `True`. This slight difference in meaning is usually not an issue, but for examples like the one above, and also ones like               Solve[{a==b,b==c},c]      these two meanings give very different, but respectively correct, answers. I guess the updated question is just the bonus: is there a function which does a better job of approximating the "usual" definition of solve.


How can I make a stylesheet where inline cells have are styled like input cells? By "similar", I mean the same font and syntax highlighting. I have even tried copying all settings from `Input` cell of `Core.nb` to a private style definition for `InlineCell`, but had no luck.


How do I find the intersection of a closed 3D curve given by numerical data with a specified plane?

I have a list of 3D data points which form a closed curve. My own data can't be easily generated analytically, but the qualitative behaviour is well represented by a parametric curve families such as `{Sin[a1 t] Cos[a2 t], Sin[a3 t] Sin[a4 t], Sin[a5 t]}` where the `aN` are constants. Sample data is given by:               dt = Table[{Sin[3 t] Cos[1 t], Sin[t] Sin[5 t], Sin[2 t]}, {t, -10, 10, 0.005}];     p1 = ListPointPlot3D[dt]      ![points from a closed curve](http://i.stack.imgur.com/nqFrN.png) I want to solve for the points where this closed 3D curve cuts a plane I specify but I'm am unable to do it. For example a plane at `z = 0.5` as shown here:               p2 = Plot3D[-0.5, {x, -1, 1}, {y, -1, 1}]     Show[p1, p2]      ![cutting plane](http://i.stack.imgur.com/24FqM.png) No approach I've tried so far has worked e.g. `Interpolation`, `Nearest` to -0.5, use of `Select` and `Drop`. The data does wrap around itself multiple times and getting slightly different solution points on each pass due to differences in the stepsize or something like that is not a problem. Related I think to this question In brief: How can I find where a closed curve given by numerical data points cuts a specified plane? Any help you can give is much appreciated.


Plotting series solution to the heat equation

I am trying to plot a solution to the heat equation $u(x,t) = \sum_1^\infty \frac{8(-1)^(n+1)}{\pi^2 n^2} \sin(n \pi x) \exp(-n^2 \pi^2) $ I am using the following from another answer here on Mathematica. I am trying to plot it from x=[0,1]. I am trying the following, but it does not seem to produce a plot               f[x_, t_, nm_] := SUM[(8 (-1)^(n + 1)/(Pi^2*n^2))*Sin[n* Pi *x]*Exp[-n^2 Pi^2*t], {n, 1, nm}];          Plot[Table[f[x, t, 150], {t, {0, 0.01, 0.1, 0.5, 1, 10}}] // Release, {x, 0, 1, 0.05}]


Why do certain values in ArcSin not fully evaluate?

This is a continuation of: Why do certain fractional values in TriangleWave not evaluate?   The analysis by R.M and rasher revealed that problem to reduce to the behavior of:               ArcSin[Sin[π / 10]]      > >     ArcSin[1/4 (-1 + Sqrt[5])] >   Every other denominator besides ten, at least up to 500,000, automatically evaluates to a simpler form:                Position[ArcSin[Sin[π / Range[500000]]], _ArcSin]  (* slow *)      > >     {{10}} >   All other coefficient of π with a denominator of ten appear to exhibit the same problem:               ArcSin[Sin[{1, 3, 7, 9, 11} π/10]]      > >     {ArcSin[1/4 (-1 + Sqrt[5])], ArcSin[1/4 (1 + Sqrt[5])], ArcSin[1/4 (1 + > Sqrt[5])], >      ArcSin[1/4 (-1 + Sqrt[5])], ArcSin[1/4 (1 - Sqrt[5])]} >   `FullSimplify` reduces the expression:                ArcSin[Sin[{1, 3, 7, 9, 11} π/10]] // FullSimplify      > >     {π/10, (3 π)/10, (3 π)/10, π/10, -(π/10)} >   Is this a bug? Is there some explanation for it? * * * **Before someone points out the obvious** : I see that `Sin[π/10]` evaluates to `1/4 (-1 + Sqrt[5])`. But why isn't `ArcSin` "smart" enough to recognize this value, when it recognizes others? For example `Sin[π/12]` evaluates to `(-1 + Sqrt[3])/(2 Sqrt[2])` but `ArcSin` correctly recognizes this and outputs `π/12`.


Return struct from function (with DownValues)

In Mathematica there is a way to create struct-like data type:               struct[myField]=value      I want to return myStruct from a function:               getStruct[input_List] := Module[{struct},        (*populate struct[key]=value from input*)        Return[struct];        ];      But when I do:               st = getStruct[myInput];     DownValues[st]      it returns nothing, because it references symbol that was created inside function (like struct$1299885). I can still access this struct with st["field"], but it's not very usefully without field list. Basically, I want to pass structs between functions, easily get field list AND easily access values inside those fields. And no, I don't want to do this with global symbols - I want to keep everything in local scope. Is it possible with Mathematica? I tried this approach because you can easily nest structs within each other and easily access nested fields, like st["field1"]["field2"]. I can also do this with list of rules, but nested access requires a lot of code and looks ugly for something so simple. Edit: it seems I was missing something very simple. To get list of fields I just needed to run:               DownValues[Evaluate[st]]      Thanks, Leonid.


Showing result of derivative and other functions

I have a problem with my _Mathematica_ 7.0 When I write:               Derivative[x^2, x]      Mathematica returns as result :               Derivative[x^2, x]      not `2x` Why is that? Am I doing something wrong with `Derivative`?


Animated Vector plot

I'm trying to make an animation of a time-varying 2D vector field. However, I'm got a difficulty in that _Mathematica_ normalises the length of the vectors with each call to `VectorPlot`. A (very simple) example:               myField = {Cos[2 π t], 0};          Animate[             VectorPlot[myField /. t -> TT, {x, -1, 1}, {y, -1, 1}],             {TT, 0, 1}]      Expected result: The arrows grow and shrink in time The actual result: The arrows remain the same size, but flick direction Is there some way to fix the length of the arrows relative to the field value?


Conditional solution for system of linear equations

I have a linear equation system `Q.m = t`, with `m` unkown and where `Q` has dimensions `{(n-1)²,n²}`, `t` has dimensions `{(n-1)²}` and `m` dimensions `{n²}`. I'm trying to find a way to find a (possible) solution `m1` such that `Norm[Partition[m1,n]]` is less or equal to 1. My idea goes something like this: Somehow optimizing using the solution given by `LinearSolve[Q,t]` and `NullSpace[Q]`. I got some help with the code from a friend, he gave this suggestion:               ns = NullSpace[Q];     vars = Array[p, {Length@ns}];     sol = Partition[m + vars.ns, n];     NumericMatrixOnly[f_][args_?(MatrixQ[#, NumericQ] &)] := f[args]     AbsoluteTiming[     res = FindMinimum[Max[NumericMatrixOnly[Norm][sol], 1], vars];]     m1 = sol /. Last@res;      This solution isn't as fast or accurate as I would want, in what other ways could I optimize this? I could do it with alternating projections, but I wanted to see if Mathematica have any nice built-in methods.


Long run time for older code that ran fast in older versions

The following code block is in Trott's Guidebook for Programming. The associated notebook says that this and a few other routines ran in a matter of seconds. I killed it after half an hour.   I am curious to know what might be the issue. My guess is that `$MaxMachineNumber` is much bigger on my new laptop.               Module[{cp, cls, L = 0.02},       (* an initial contour plot *)       cp = ContourPlot[Im[Exp[1/(x + I y)]], {x, -L, L}, {y, -L, L},                         PlotPoints -> 400, DisplayFunction -> Identity] /.       (* replace large high-precision numbers by biiig machine numbers *)          z_?(Abs[#] > $MaxMachineNumber&) :> Sign[z] $MaxMachineNumber/2;       (* homogeneously distributed contour lines *)                        cls = #[[100]]& /@ Partition[Sort[Flatten[cp[[1]]]], 800];          (* the final contour plot *)            ListContourPlot[cp[[1]], MeshRange -> {{-L, L}, {-L, L}},                       Contours -> cls, ContourLines -> False,                       ColorFunction -> (Hue[Random[]]&),                        AspectRatio -> Automatic, FrameTicks -> None]]


Mathematica Manipulate with macros AND variable number of controls (persistence desired)

This post about avoiding code duplication in `Manipulate` helped a lot getting as far as I did. The method of "macros" outlined there works excellent, but when the number of controls is again controlled by yet another manipulate control, things get difficult. I got two closely related problems in that area: **Problem 1:** The following works like a charm:               With[{rows = 3, cols = 3, fieldSize = 5},       Manipulate[         Column[{           TableForm@mat,           Row[{"det = ", Det[mat]}]         }]         , {mat, None}, {initialized, None}         , Evaluate@With[{makeRow = Function[{rowIndex},             Map[Function[{colIndex}                 ,InputField[Dynamic[mat[[rowIndex, colIndex]]], Number, FieldSize -> fieldSize]]               , Range[cols]]             , HoldAll]}         , Grid[Map[makeRow, Range[rows]]]]         , Initialization :> (           If[Not[initialized === True], mat = Table[0, {rows}, {cols}]];           initialized = True         )         , SaveDefinitions -> True     ]]      ![Mathematica graphics](http://i.stack.imgur.com/rAd1T.png) I can enter a matrix, and Manipulate will calculate the determinant. If I start a new session, the values from the last session will still be there (important). But now suppose, I want to specify the matrix size with a setter bar. This can be done by wrapping a manipulate around it.               Manipulate[       With[{rows = size, cols = size, fieldSize = 5},         Manipulate[           Column[{TableForm@mat, Row[{"det = ", Det[mat]}]}]           , {mat, None}, {initialized, None}           , Evaluate@With[{makeRow = Function[{rowIndex},               Map[Function[{colIndex}, InputField[Dynamic[mat[[rowIndex, colIndex]]], Number, FieldSize -> fieldSize]], Range[cols]]               , HoldAll]}             , Grid[Map[makeRow, Range[rows]]]]           , Initialization :> (             If[Not[initialized === True], mat = Table[0, {rows}, {cols}]];             initialized = True           ), SaveDefinitions -> True]]         , {{size, 3}, Range[7], ControlType -> SetterBar}     ]      But this breaks the persistence over sessions. I tried to put the variable mat into the outer `Manipulate`, but that broke the whole thing. ![Mathematica graphics](http://i.stack.imgur.com/4K1IH.png) **Problem 2:** Kind of the same thing, with sliders instead of input fields.   I want to use a combination of setter bars and sliders to input a discrete probability istribution, and then do stuff with it within a manipulate.   IMPORTANT: The values should be persistent over sessions. ![Mathematica graphics](http://i.stack.imgur.com/8hP3N.png) Via the setter bar, I indicate that I want, for example, a prob dist for the integers from 2 through 5. That should then bring up 4 sliders that I can use to define the prob dist, one for each number. So the number of sliders should be variable. As you can see, I solved the problem of writing a macro for the slider generation, but I failed to make the number of sliders dependent on the inputs from the setter bars. It's clear from the code how I tried to solve the problem: The code, as it is, does everything I want, except that the number of sliders is always the same; and if you change one of the "lifeIsEasy" variables, it will seize to work.               With[{slidersPerRow = 3, lifeIsEasy1 = False, lifeIsEasy2 = False,        length = 8       , normalize = Function[{pd, from, to}         , With[{total = Total[pd[[Range[from, to]]]], len = to - from + 1}          , If[total == 0, Table[1/len, {len}],            pd[[Range[from, to]]]/total]]]},      Manipulate[       If[max < min, max = min];       Column[{         Row[{"min ", min, "   max ", max}]         , Row[{"=== slider values ==="}]         , TableForm[{sliderVals}, TableHeadings -> {None, Range[length]}]         , Row[{"=== prob dist ==="}]         , TableForm[{normalize[sliderVals, min, max]},           TableHeadings -> {None, Range[min, max]}]         , Row[{"expectation: ",            normalize[sliderVals, min, max] . Range[min, max]}]         }]       , {initialized, None}       , {sliderVals, None}       , Row[{         Control[{{min, 1}, Range[4], ControlType -> SetterBar}]         , Spacer[25]         , Control[{{max, min + 3}, Range[min, min + 4],            ControlType -> SetterBar}]         }]       , Row[{"I want ", Dynamic[max - min + 1], " sliders in ",          Dynamic@Ceiling[(max - min + 1)/slidersPerRow], " rows, "         , slidersPerRow, " per Row, and ",          Dynamic@Mod[max - min + 1, slidersPerRow, 1], " in the last" }]       , Evaluate@With[{makeSl = Function[{index}            , Dynamic@             Row[{ToString[index] <> " ",                Manipulator[Dynamic[sliderVals[[index]]]]}]            , HoldAll]}         , With[{           makeSliderRow = Function[{startIndex, endIndex}             , Row[Map[makeSl, Range[startIndex, endIndex]], Spacer[10]]]           }          , Sequence @@ Table[            makeSliderRow[             min + slidersPerRow*sliderRow(*=startIndex*)             , Min[Join[{min + slidersPerRow - 1 + slidersPerRow*sliderRow}, If[lifeIsEasy1, max, {}]]]](*=endIndex*)               , {sliderRow, 0, If[lifeIsEasy2, Ceiling[(max - min + 1)/slidersPerRow] - 1, 1]}             ](*seqtab*)          ](*with*)         ](*evalwith*)       , Initialization :> (         If[Not[initialized === True], sliderVals = Table[0, {length}]];         initialized = True         )       , SaveDefinitions -> True       ](*manip*)      ](*with*)      Another approach I had for the problem was to use an inner Manipulate, but that didn't work either; I didn't get that even to the point where everything except persistence works, as in problem 1. **UPDATE** Although it is possible to do all this with Manipulate (see my 3 answers below), jVincent has convinced me that it is better and easier to do with DynamicModule instead. I want to show how to make reusable components with this method. Here is a slightly improved version of jVincent's solution.               makeInputGrid = Function[{mat},         Grid@Table[With[{x = x, y = y},             InputField[Dynamic[mat[[x, y]]], ImageSize -> 50]],             {x, 1, Dimensions[mat][[1]]},             {y, 1, Dimensions[mat][[2]]}],         HoldAll];     DynamicModule[{mymat = Table[0, {2}, {2}]},         Column[{             Slider[Dynamic[Dimensions[mymat][[1]], (mymat = Table[0, {#}, {#}]) &], {2, 8, 1}],             Dynamic@makeInputGrid[mymat],              Dynamic@MatrixForm@mymat,             Dynamic@Det@mymat         }]     ]      Now, the function makeInputGrid can be used elsewhere. Note the HoldAll attribute, it won't work without that. Here is how to do the slider problem with this approach. (I tried to make it look a little towards the way Manipulate makes things look.)               sliderGrid = Function[         {sliderValues, slidersPerRow, minVal, maxVal, which},         Panel@Grid[Partition[             Table[With[{index = which[[i]]},                 Row[{index, Spacer[7], Manipulator[Dynamic[sliderValues[[index]]], {minVal, maxVal}]}]             ], {i, Length[which]}],             slidersPerRow, slidersPerRow, 1, {}]],        HoldFirst     ];     checkboxRow = Function[{flags},         Panel@Row[Table[With[{i = i},            Row[{i, Spacer[5], Checkbox[Dynamic[flags[[i]]]], Spacer[7]}]         ], {i, Length[flags]}]],        HoldAll     ];     With[{len = 10, min = -1, max = 1},         DynamicModule[{             flags = Table[True, {len}],             vals = RandomReal[{min, max}, len]         },         Panel[Column[{             Panel@Column[{                 checkboxRow[flags],                 Dynamic@sliderGrid[vals, 3, min, max, Select[Range[10], flags[[#]]&]]             }],             Dynamic@Grid[{Range[len], vals}]         }],         Background -> GrayLevel[0.9]         ]     ]]      ![variable number of sliders using dynamicmodule](http://i.stack.imgur.com/tO2Uc.jpg)


Attaching functions to movable locators

I'm trying to create a manipulate plot showing the electric field due to a collection of point charges. At the moment I've created such a plot which allows the x and y positions of each charge to be manipulated using sliders, however what I would particularly like to do is to be able to click and drag the points on the plot. I have created locators which can be manipulated like so, however I can't work out how to attach a function to them. Any help would be greatly appreciated.


Logarithmic scale in BarChart3D

I want to display my data in a logarithmic way in a 3d diagram. I found BarChart3D, which seems to be nearly what i need. I tried:               BarChart3D[data2, ChartLayout -> "Grid"]     BarChart3D[(Log[10, data2] - 2)/5.0568, ChartLayout -> "Grid"]      and got this figures: ![non-logarithmic data](http://i.stack.imgur.com/7sC8B.png) ![logarithmic data \(wrong scale\)](http://i.stack.imgur.com/2j3ir.png) What I need now is a way to fix the horizontal scale. Would be glad to get some hints! THANKS A LOT! Andreas EDIT: Just found the very simple answer               ScalingFunctions -> "Log"      sorry for waste of bits.


Change the height of a function being plotted

How do I alter the height of any function plot using the `Plot` function? Mathematica seems to limit the height of the plot up to the range of a function and distort the ratio of the Plot ![](http://i.stack.imgur.com/UWYIZ.png) Here in the above example the plot has a distorted axes ratio. How do I correct it?


Forcing unifom axis scaling on a list plot

I'm trying to draw a `ListPlot` where the x and y axis have the same scale. My data is               {{100, 500}, {461/5, 473}, {548/5, 452}, {1459/10, 437}, {974/5, 428}, {250, 425},       {1526/5, 428}, {3541/10, 437}, {1952/5, 452}, {2039/5, 473}, {400, 500}}      A simple `ListPlot` will result in: ![Listplot no scale](http://i.stack.imgur.com/wMjwD.png) where the x and y axis have a different scales. I want them to force them to have the same scale. So far I've been able to achieve this only by explicitly setting `PlotRange` to the same value for x and y, and using `AspectRation->1`. Example:               range := {Min[Flatten[x]], Max[Flatten[x]]}     ListPlot[x, PlotRange -> {range, range}, AspectRatio -> 1]      The result is: ![List plot scaled](http://i.stack.imgur.com/9zevu.png) Questions:   * Is there a `Plot` option to force the scale to be uniform? Do I always have to set the same range and `AspectRatio` to 1?   * From the second image there is satisfying y ∈ [400, 500] and x < 100 with an x value that is lying outside of the drawing range. I thought by using the `Min` of all x and y this could not happen. What am I doing wrong?


How to plot an ellipse?

I'm new to _Mathematica_ , and I'm finding it difficult to plot an ellipse. I tried using               Plot[(x/5)^2 + (y/3)^2 == 1, {x, -5, 5}, {y, -3, 3}]      but I'm getting some errors. Is there something wrong with the syntax? Or do I need to rewrite the equation and plot?


Coloring a shape according to a function

I would like to create a $2D$ shape, say an ellipse, where each point in the ellipse is colored according a `RGB` function, so at point `x` and `y` the color would be:               RGBColor[ u[x,y], v[x,y], w[x,y]]      I am sure there has to be an easy way to do this, but I have not had much luck.