title: Setting label in DendrogramPlot

text: I want to create a dendrogram with the labels being a visual representation of the data. Something like this: ![What I wanna do](http://i.stack.imgur.com/slJvH.png) How can I do that in _Mathematica_? My attempt so far hasn't been very successful. The labels are all messed up.               Needs["HierarchicalClustering`"]     SeedRandom@2;     data = RandomVariate[NormalDistribution[], {10, 20}];     label = ListPlot[#, Axes -> False, Joined -> True] & /@ data;     DendrogramPlot[data, Orientation -> Right, LeafLabels -> label]      This is what I get from the code above: ![enter image description here](http://i.stack.imgur.com/2cexk.png)


title: Converting truth tables to boolean expressions

text: I have a truth table for a Boolean expression represented like this               table={{0, 0, 0, 0} -> 0, {0, 0, 0, 1} -> 0, {0, 0, 1, 0} ->      0, {0, 0, 1, 1} -> 0, {0, 1, 0, 0} -> 0, {0, 1, 0, 1} ->      0, {0, 1, 1, 0} -> 0, {0, 1, 1, 1} -> 1, {1, 0, 0, 0} ->      1, {1, 0, 0, 1} -> 1, {1, 0, 1, 0} -> 1, {1, 0, 1, 1} ->      1, {1, 1, 0, 0} -> 1, {1, 1, 0, 1} -> 1, {1, 1, 1, 0} ->      1, {1, 1, 1, 1} -> 0}      (all on one line) The table contains the values I want at the output given y4,y3,y2,y1 at the input, i.e.               {y4,y3,y2,y1} -> desiredOutput      What is the best way to transform this data into a form that can be then processed in terms of y with functions such as BooleanMinimize?


title: Trace of intersecting planes

text: I have a set of curved planes that intersect each other. I only want all the parts of all planes displayed that are above the intersecting traces. Further, I would like to highlight the intersecting traces. It sounds like a simple enough problem (maybe it is), but I couldn't finde any routine to do this. So, any help is welcome. Here is an example:                   inputData = {            {{0, .5, .5, 1200}, {0, 1, 0, 1500}, {.5, .5, 0, 1150}, {1/3, 1/3,               1/3, 1100}}            , {{0, 0, 0, 1650}, {0, .5, .5, 1200}, {1/3, 1/3, 1/3, 1100}, {.5,               0, .5, 1300}}            , {{1, 0, 0, 1650}, {1/3, 1/3, 1/3, 1100}, {.5, 0, .5,               1300}, {.5, .5, 0, 1150}}            };          coords[{A_, B_, C_}] := {A/2 + B, A Tan[Pi/3]/2};     newCoordinates[data_] := Table[        Join[coords[{data[[i, #, 1]], data[[i, #, 2]],              data[[i, #, 3]]}], {data[[i, #, 4]]}] & /@          Range@Length@data[[i]]        , {i, 1, Length[inputData]}        ];         data = newCoordinates[inputData];         quad = Fit[data[[#]], {1, x, y, x^2, x y, y^2}, {x, y}] & /@             Range@Length@data;              Plot3D[quad, {x, 0, 1}, {y, 0, 1}          , MeshFunctions -> {#3 &}          , RegionFunction ->            Function[{x, y, z},             0 < Sqrt[3] x - y && 1.72 > Sqrt[3] x + y && z > 1100]          , PlotStyle -> {Directive[Orange, Opacity[.5]],             Directive[Green, Opacity[.5]]}          , PlotRange -> {{0, 1}, {0, 1}, {0, 2000}}          , BoundaryStyle -> Thick          , BoxRatios -> {1.2, 1.2, 2}          , Boxed -> False          , Axes -> None          , ImageSize -> 500          ]


title: In a manipulatable graph, display x values of all intersections with one of the lines?

text: I'm doing a project about Moore's law, I'm trying to create a graph that which you can manipulate, but I want the x-values of the intersections with one the lines to be displayed; how would I go about doing this? This is what I have (the first formula is 'real', the rest are placeholders for the sake of having intersections):               j0=1980;     Manipulate[LogPlot[{tj0*2^((j - j0)/2), -(b*2^((j - j0)/1.5) - 1000),          -a*j + c}, {j, 1980, 2000},Frame -> True, PlotRange -> All, LabelStyle ->      {FontFamily -> "Helvetica", FontSize -> 15}, FrameLabel -> {"Year", "Transistor Count"}],     {{tj0, 100, "Transistor Count First Year"}, 100, 200}, {{b, 100, "b-Value"}, 100, 200},      {{a, 100, "a-Value"}, 80,  120}, {{c, 250000, "c-Value"}, 250000, 300000}]      ![enter image description here](http://i.stack.imgur.com/6nvgH.png) What I would like is something like this:               Manipulate[ If[(-M + M p + Ls z - Ls p z)/(-1 + z) <= M, Plot[{If[G <= M, (-G + M + G z - Ls z)/z], If[(-M + M p + Ls z - Ls p z)/(-1 + z) <= M, Exp[((1 - p)*Log[G] - p*Log[((M p - Ls p z)/z)] - (1 - p)* Log[((-M + M p + Ls z - Ls p z)/(-1 + z))])/-p]]}, {G, 0, 2000}, AxesLabel -> {" SubscriptBox[\"W\", \"G\"] ", " SubscriptBox[\"W\", \"B\"] "}, PlotRange -> {{0, 2500}, {0, 2500}}, AxesStyle -> Directive[Bold], LabelStyle -> Bold, Epilog -> {Thick, Dashed, Line[{{(-M + M p + Ls z - Ls p z)/(-1 + z), 0}, {(-M + M p + Ls z - Ls p z)/(-1 + z), (M p - Ls p z)/ z}}]}, Prolog -> {Thick, Black, Line[{{0, 0}, {2500, 2500}}]}, PlotStyle -> {{Thick, Blue}, {Thick, Purple}}, PlotLabel -> "Optimal Insurance Contract"], Plot[{If[G <= M, (-G + M + G z - Ls z)/z], G}, {G, 0, 2500}, AxesStyle -> Directive[Bold], AxesLabel -> {" SubscriptBox[\"W\", \"G\"] ", " SubscriptBox[\"W\", \"B\"] "}, PlotStyle -> {{Thick, Blue}, {Thick, Black}}, AxesOrigin -> {0, 0}, PlotRange -> {{0, 2500}, {0, 2500}}, AxesStyle -> Directive[Bold], Epilog -> {PointSize[Large], Red, Point[{M, M - Ls}]}, PlotLabel -> "Optimal Insurance Contract", LabelStyle -> Bold]], {{p, .5, "Probability of Bad State"}, .1, .9}, {{M, 1000, "Original Wealth"}, 500, 1250}, {{z, .52, "Insurance Premium"}, .3, .9}, {{Ls, 200, "Loss"}, 50, 900}, Text[Style[ "Wealth in the Good State = " Dynamic[ If[(-M + M p + Ls z - Ls p z)/(-1 + z) <= M, Dynamic[(-M + M p + Ls z - Ls p z)/(-1 + z)], M]], 12, "Label"]], Text[Style[ "Wealth in the Bad State = " Dynamic[ If[(-M + M p + Ls z - Ls p z)/(-1 + z) <= M, Dynamic[(M p - Ls p z)/z], M - Ls]], 12, "Label"]], Text[Style[ "Premium = " Dynamic[ If[(-M + M p + Ls z - Ls p z)/(-1 + z) <= M, Dynamic[M - (-M + M p + Ls z - Ls p z)/(-1 + z)], 0]], 12, "Label"]]]      ![enter image description here](http://i.stack.imgur.com/QWoTD.png) I'd like thick dashed lines to go down to the x-axes from the intersections of any of the lines with the first blue line and the x (or j value here) to be displayed like in the second example.


title: Creating a C++ project with Visual Studio 2010

text: I am trying to create a GUI using Microsoft Visual Studio C++ 2010 by calling _Mathematica_ in my codes. I have done everything step by step as mentioned here Then I wrote this code as mentioned in here The code is as below               #include <mathlink.h>     #include <stdio.h>          int main(int argc, char *argv[]) {          MLENV env;          MLINK link;          int errno;               env = MLInitialize(0);               link = MLOpenArgcArgv(env, argc, argv, &errno);               MLActivate(link);               return 0;     }      The error I get is:               1>------ Build started: Project: mathematica_link_attempt1, Configuration: Debug Win32 ------     1>main.obj : error LNK2019: unresolved external symbol _MLOpenArgcArgv@16 referenced in function _main     1>main.obj : error LNK2019: unresolved external symbol _MLActivate@4 referenced in function _main     1>C:\Users\arvindrajan\documents\visual studio 2013\Projects\mathematica_link_attempt1\Debug\mathematica_link_attempt1.exe : fatal error LNK1120: 2 unresolved externals      Any advice please?


title: Why does Rotate in PlotMarkers behave strangely?

text: While answering Change the inner color of markers I came across a behavior that may be a bug.   I would like to know if there is another explanation. First a basic example of normal behavior:               ListLinePlot[{Prime~Array~12, Fibonacci~Array~12},      PlotMarkers -> Graphics[{Brown, Rectangle[]}, ImageSize -> 13],      PlotLegends -> Automatic     ]      ![enter image description here](http://i.stack.imgur.com/RZv2d.png) Note that the markers are included in the legend. But now if I `Rotate` the `Rectangle`:               ListLinePlot[{Prime~Array~12, Fibonacci~Array~12},      PlotMarkers -> Graphics[{Brown, Rectangle[] ~Rotate~ (Pi/4)}, ImageSize -> 13],      PlotLegends -> Automatic     ]      ![enter image description here](http://i.stack.imgur.com/sEarW.png) The markers disappear from the legend. They do appear if I `Rotate` the entire `Graphics`, however the markers are not scaled as before and they clip:               ListLinePlot[{Prime~Array~12, Fibonacci~Array~12},      PlotMarkers -> Graphics[{Brown, Rectangle[]}, ImageSize -> 13] ~Rotate~ (Pi/4),      PlotLegends -> Automatic     ]      ![enter image description here](http://i.stack.imgur.com/D8Yxl.png)   1. Is use of `Rotate` in plot markers simply unsupported or is this a bug?   2. Is there a way to use rotated primitives for markers and not break the legend?


title: Piecewise function with a function as argument

text: I want to define a piecewise function, which has two arguments, one of which is a function of the other's piecewise argument. I am giving an example               X0 = 1.7635;     X1 = 4.4855;     γ[En_] := En/0.13957     β[En_] := Sqrt[γ[En]^2 - 1]/γ[En]     X[En_] := Log[10, β[En]*γ[En]]     f[En_, Evaluate[X[En_] _]] :=Piecewise[{{0, X[En] < X0}, {4*X[En], X[En] > X0}}]     PLot[f[En, Evaluate[X[En]]], {En, 0.001, 1000}]      Is it possible?


title: Why is `Cell` > `Convert To` > `InputForm` not invertible?

text: I sometimes post code to PhysicsSE, and I usually convert it to `InputForm` first before posting, in order to avoid pages and pages of `RowBox` and `Offset` fluff. I usually instruct the user to copy/paste it into a new notebook, and use `Cell` > `Convert To` > `StandardForm` in order to get everything properly formatted. Unfortunately, this does not always work. For example, consider the following `StandardForm` code:               Q = Sum[Array[a[10 k], {3}], {k, 4}] // MatrixForm // TeXForm      It looks fine, and in this case there isn't any need to convert to `InputForm`, but that's just because this is meant to be a minimal example. Now let's convert it to `InputForm` (on Mac OSX, this is performed via `Command`+`Shift`+`I`):               Q = \text {MatrixForm}\left[\sum _k^4 \text {Array}[           a (10 k), \{3\}] \r ight]      This is, of course, completely un-runnable, and executing `Cell`>`Convert To`>`StandardForm` fails to produce the original expression, let alone anything which is syntactically correct. Why is this? Is this a glitch with the front end's implementation of `Convert To`? Or am I doing something wrong? The very similar expression               Q = Sum[Array[a[10 k], {3}], {k, 4}] // MatrixForm      gets converted via `InputForm` to               Q = MatrixForm[Sum[charge[[k]]*f[position[[k]]], {k, 4}]]      which is, of course, correct; this makes me suspect that the front-end is getting tripped up by the sequence of two `//` operators. More generally, what do you recommend is the best way to copy and paste Mathematica code to StackExchange sites?


title: Why does Mathematica stop when run in the background in command line mode?

text: If I try to start a Mathematica script in the background from the command line, like this:               math -script someFile.m &      then the process gets automatically suspended. Here's a terminal transcript for clarifications: ![](http://i.stack.imgur.com/TvE9z.png) This happens both on Linux and OS X. Other programs don't typically stop when run in the background.   * Why does this happen?   * What can I do to prevent this?


title: How can define a set of nested parameters

text: I would like to know how I to define a function with a nested set of parameters (or whatever you would like to call it). For example, how would I get the following function `A`,               M = m1 + m2;     \[Eta] = m1*m2/(m1 + m2)^2     A[t_]:= M (\[Eta] / M * t)^(1/4);      Such that if I just evaluated `A[5.0]` for example it would return,               1.49535 M Power[\[Eta]/M, (4)^-1]      (i.e. a function of `M` and `\[Eta]`) or something similar, but not `A` as a function of `m1`, `m2`,               1.49535 Power[(m1 m2)/(m1+m2)^2, (4)^-1] (m1+m2)      But, at the same time, maintain a form that I could replace either `m1` and `m2` or `M` and `\[Eta]`, such that both               A[5.0] /. m1 -> 1 /. m2 -> 1     A[5.0] /. M -> 2 /. \[Eta] -> 1/4      would return `1.77828`.


title: Pathological behaviour when evaluating a sum

text: When I declare the function $f$ as follows:               f[n_] := Sum[x/Sum[Sqrt[y], {y, 1, x}], {x, 1, n}]/n      the input               Limit[f[n],n -> Infinity]      does not yield an answer, in fact the evaluation is terminated after a few seconds. If I now write               Limit[f[x], x -> Infinity]      I get an answer of $0$. Why is that, according to the manual entry of "Sum" we have > The iteration variable i is treated as local, effectively using Block. If it matters, I use the version 9.0.


title: How to order lexicographically the monomers of a parametrized polynomial?

text: I want to order lexicographically the monomials in a "parametrized polynomial", i.e. polynomials whose "symbolic bits" may be either "variables" or "parameters". For example:               In[1]:= Expand[(x + a y + a^2 z)^3] /. a^n_ -> a^Mod[n, 3]          Out[1]= x^3 + y^3 + 6 x y z + z^3 + 3 x^2 y a + 3 y^2 z a + 3 x z^2 a +  3 x y^2 a^2 +      3 x^2 z a^2 + 3 y z^2 a^2      In the polynomial above `x`, `y`, and `z` are intended as "variables", whereas `a` is intended as a "parameter". The documentation for _Mathematica_ states that monomials in a polynomial are ordered lexicographically by default, but if so, I don't understand why the two terms with `x^2` come after the `y^3` term in the polynomial above, for example. So my question is: how can I force a lexicographic ordering of the monomials with respect to the "variables" (i.e. `x`, `y`, and `z`). (In particular, for the polynomial above, the symbol `a` should be disregarded for the ordering.) For example, the desired ordering for the polynomial above would be               x^3 + 3 x^2 y a + 3 x^2 z a^2 + 3 x y^2 a^2 + 3 x z^2 a + 6 x y z + y^3 + 3 y^2 z a + 3 y z^2 a^2 + z^3


title: Mathematica won't simplify the expression with obvious common factor of a fraction

text: I have an expression obtain from an integral, which is:               Integrate[ϵ^2/Sqrt[(ϵ - u)^2 + Δ^2], ϵ] // FullSimplify      The denominator and numerator of the result have an obvious common factor:               Sqrt[Δ^2 + (u - ϵ)^2]      How can I let mathematica to cancel this common factor? I have tried `Cancel` and `Refine` all the variables to be positive.


title: Populating an array with outputs of a function

text: I have searched, but didn't find much help on my issue. I have an optical physics problem that I'm working on ..               apeture = 1*10^-6;     r = Range[100];     k = Range[100];     λ = 632.8 * 10^-9;     pal = Pi*(apeture/λ);     θr = (r - 50)*(Pi/90);     field = Array[0 &, {k, r}];     Intensity = 1*(Sin[pal*Sin[θr]]/pal*Sin[θr])^2      admittedly I am a newcomer to Mathematica but not to programming. I operate mainly in embedded C but "speak" Python, Java, and Ada as well. So please understand that my question is mostly about using Mathematica. What I need is a n x m matrix 100 entries square that the Intensity function maps onto down each row. When the matrix is populated, I create a copy of it, rotate it by pi/2 and add the two. Once done, I plot the result. This is to study the interference patterns of orthogonal single-slit diffraction (Mill's Cross effects). An Edit for Clarity: Once the initial conditions are set, I need to place a function output in each row of the matrix. The columns are identical (at first). Then, I perform a 90 degree rotation of the matrix (CW or CCW.. doesn't matter as long as the results are orthogonal) and add the two. The resultant is an interference matrix that can be plotted. My questions in this regard:   1. Do I need to write a loop to do this, or can I write a compound statement like I have seen in other programs (MathCAD and MATLAB) that will automatically propagate the values in the matrix?   2. After reading the various posts on matrix rotation, I'm not entirely convinced of the best method. Suggestions are appreciated. Thanks for your help!


title: Something is rotten in ... my function writing

text: Juju3[expr_] :=     (Solve[expr[[1]] == 0, expr[[2]] == 0, expr[[3]] == 0, {r, x, y}];     a = %[[1]];     b = %%[[2]];     c = %%%[[3]];     Which[a[[2, 2]] == 0 || a[[3, 2]] == 0, Speak["MOO"],a[[2, 2]] != 0 && a[[3, 2]] != 0, Speak["PEACE AND LOVE"]]     j = D[expr, {{r, x, y}}];     j     FullSimplify[j /.Solve[expr[[1]] == 0, expr[[2]] == 0,expr[[3]] == 0, {r, x, y}]] ;     FullSimplify[Eigenvalues[%[[1]]]]     FullSimplify[Eigenvalues[%%[[2]]]]     FullSimplify[Eigenvalues[%%%[[3]]]])      Then I tried:               Juju3[{i - l*r - ux*r*x - uy*r*y, -mx*x + ex*ux*r*x, -my*y + ey*uy*r*y}]      ,and it did not work whereas when I just use my code without creating a function it works very well. I am reading about building functions with Mathematica right now but I still want to post this because I do not know what I am doing wrong. Everything? Maybe! Because I am a noob ^^ But I am reading tutorials so please do not get angry :) Specifically I have been told by a user that one should put semicolon for things that one do not want the output of, and also that one should put parentheses when having a function with multiple lines, so I did do that here. PS: I shortened the function because I use **b** and **c** also in the same way as **a** but no need for it here I guess.


title: Creating Mathematica packages

text: I'm building a package to help me write packages and their documentation. In this post I explained how to make a package and its documentation. In the answer I provided I describe how to build a very simple package. However, I have been looking around the extra packages that come with _Mathematica_ and in some packages I see many .m files. I see this as a good way of dividing the application. Can someone describe the structure of a package? To do this lets try to make a package out of the next simple functions. Suppose that we have the following in a notebook:               AddTwo::usage = "AddTwo[a, b] returns a+b";     AddThree::usage = "AddTwo[a, b, c] returns a+b+c";     DotTwo::usage = "DotTwo[a, b] returns a*b";     DotThree::usage = "DotTwo[a, b, c] returns a*b*c";     AddTwo[a_, b_] := a + b;     AddThree[a_, b_, c_] := a + b + c;     DotTwo[a_, b_] := a*b;     DotThree[a_, b_, c_] := a*b*c;      I would like to put these functions in a package. They all seem to be very simple arithmetic operations so let us make a package named `SimpleArithmetic`. This package is perfect to be divided into sections. One for additions and one for products, so we can make "subpackages" `Addition` and `Product`. If we follow some of the examples in the _Mathematica_ installation we can create a folder called `SimpleArithmetic` in say `$UserBaseDirectory`. Inside `SimpleArithmetic` we can create two other files `Addition.m` and `Product.m`. The code for the additions would be placed in `Addition.m` and the code for multiplications would be placed in `Product.m`. The question now is, how would these files look like? There is also a folder called `Kernel` which contains `Init.m`. Could someone please just explain the best practices to create packages? I've read over the documentation and the whole "context" and "packages" keywords have already confused me. The code in the files I have described would be very appreciated.


title: Custom package development: Basic steps

text: Every once in a while, I write a generic function that I use quite often for months to come. However, package development in Mathematica is not very well documented from what I can tell, and I was not able to find a coherent description online (most of them deal with tiny issues and bits). In the end, I usually give up and copy+paste the function in every new notebook, which isn't really the way to go. Does anyone here develop packages himself and could walk me from "open Mathematica" to "save as something that can be included via `<<Package``" or give me a good reference?


title: How to get the current index during a Scan iteration?

text: Is there a special keyword to get the current index in `Scan` ?   For example, let say I have the following code :               Scan[Print[#] &, {2, 5, 7}]      It print the content of the list :               2     5     7      How to modify the code to print the current index also ?               1,2     2,5     3,7


title: Approximate a function of four variables with a rational polynomial

text: I have a function that consists of four variables. Currently, I want to view it as function of one variable over the interval (0, 1) with the other three variables as parameters. I will plug values into those three parameters (and those values will not stay fixed). I want to see how the function changes with as the parameters vary. The function is very complicated, so I want to approximate it in a rational form. I have tried using the `MiniMaxApproximation`. However, it is only good for a single variable. Does _Mathematica_ offer any function that is suitable to my needs?


title: Maintaining postfix convention for directives in notebooks

text: It seems to be a fairly common convention to write certain 'meta' functions in postfix form like               f[x] // Simplify      to keep the the mathematical content at the front separate from the various directives. However converting expressions to `StandardForm` or `InputForm` converts everything to prefix. Is there a way to get `StandardForm` to use this convention or alternatively is there a form like `StandardForm`, but that uses this convention. I find myself often switching between`StandardForm` and `InputForm` while editing since I prefer to just edit textually using `InputForm` and then convert to `StandardForm` for display, but this makes it impossible to use the above convention. Reading the documentation I came across `Format` which seems one possible way to do this, but the following does not work:               Format[Simplify[x_], StandardForm] := Postfix[Simplify[x_]]      Apparently `Simplify` gets evaluated out before this rule is set up. I tried using `Hold` and `Unevaluated` to fix this without luck. This approach would also have the downside of having to define this rule for every function separately and I also do not yet know how I would set up such rules as a default for all my notebooks. So maybe there is a better way.


title: How to efficiently mask an image?

text: I want to extract/cut out a part of an image. Since my mask is not rectangular I want to set pixels that are not masked to zero (black). My current approach is something like this:               img = Import["path/to/image/image.jpg"];     {x, y, temp} = Dimensions@ImageData[img];     center = {100, 100};     radius = 30;     pixels =        Select[Flatten[Table[{i, j}, {i, 0, x}, {j, 0, y}], 1],         (center[[1]] - #[[1]])^2 + (center[[1]] - #[[2]])^2 > radius^2 &];     ReplaceImageValue[img, Map[# -> 0 &, pixels]]      Even though this works, it is extremely slow for large images. Is there any way to speed this up?


title: Draw grid lines at multiples of k

text: Here is a beginner's question: when creating plots with mathematica, I want the grid lines to be at multiples of a constant value. E.g. in the following plot, the vertical grid lines are at multiple of 2 $\pi$. ![enter image description here](http://i.stack.imgur.com/Vq3Fu.png) This is the corresponding Mathematica code:               Manipulate[      Plot[Sin[x], {x, 0, n*2*\[Pi]},        GridLines -> {2*\[Pi]*# & /@ Range[n], None},        GridLinesStyle -> Dashed], {n, 1, 50, 1}]      Since equidistant grid lines are very common, I wonder if there is an easier way than to use such complicated expressions like `2*\[Pi]*# & /@ Range[n]` to generate equidistant grid lines. Does Mathematica provide anything simpler?


title: Returning ancillary computation results from a function

text: Suppose I want to implement a function to solve a very basic Elliptic problem using Finite Element of some degree (It's just an example). Normally the user of my function is only interested to the numerical solution of the Elliptic problem, i.e. the values of the solution on a proper grid. So, the user call something like               u = EllipticDirichlet[..., range, ...];      Sometimes the caller of my function may be interested to some internal detail of the computation, for example the linear system formulation of the problem, i.e. the stiffness matrix K and the load vector F. Ideally my function should return these ancillary data tagged in some way, so the user of my function can get these data simply and in a roubust. I don't want my fuction return everytime the solution and all ancillary data in a list like in the following pseudocode.               {u, K, F} = EllipticDirichlet[..., range, ...];      What are the way to handle this situation? I can think to the following way.   1. Using Options or Arguments to tell to the function what to return. Not clean in my opinion, not because of the options, but because it would be preferable to keep main result distinct from other ancillary intermediate computation data.   2. Returning an "object" with "properties" like `LinearModelFit` for example. Probably the best idea but make the function result more difficult to use and to understand for a casual reader.   3. Using `Sow`. But I'm not sure if this this a use-case for `Sow`? For example it's legal to `Sow` from a function if no one `Reap`? Documentation say nothing about this.  There are other way to accomplish this task? ### Update I'm anything but a _MATLAB_ fan, but what I'm asking it's a very common scenario under _MATLAB_ , and it's very simple to consume and provide functions that returns differently "shaped" answer with different "levels" of details. For example in _MATLAB_ I can call a function with syntax like this               [x, u] = EllipticSolve[...]      if I'm only interested to the x grid used and solution u on grid vertices; or I can call               [x, u, K] = EllipticSolve[...]      if I'm occasionally also interested to the stiffness matrix K of the linear system used to solve the problem; I can also call               [~, ~, K] = EllipticSolve[...]      if I'm interested only to the stiffness matrix K. I think the function EllipticSolve can also do some optimization of the computation recognizing the output requested. Basically I whish to be able to do something like this.


title: Extract the generating curves from a Graphics3d returned from RevolutionPlot3D

text: I have a plot               g = RevolutionPlot3D[{Sin[t], t}, {t, 0, π}, {θ, -π, π + 3 π/4}];      Is it possible to extract the generatrices (generating curves) from `g`? Sometimes, I want to concentrate on plotting the surface in different ways, and what I need is the all the generating curves. Can I obtain these curves from `g`?. * * * For example, this is what I need (the data could be plot by `Line /@ curves` and could be exported elsewhere).               curves = Table[RotationMatrix[θ, {0, 0, 1}]. {Sin[t], 0, t}, {θ, 0, 2π, .3}, {t, 0, π, .3}];      The example result, `curves`, is what I want, but I obtain that by re-think about generating method and `{Sin[t], 0, t}`. Seems defining `g` was a waste of time. But in the plot of `g`, such lines/meshes are really shown by _Mathematica_ , so I would like to extract them.


title: How can I plot f(x) with respect to 1/x?

text: How can I plot f(x) on {y axis} with respect to 1/x on {x axis}?


title: Take[] and other Mathematica functions with live streams

text: I have a live video feed that I would like to convert into raw numbers that could be used for a variety of different things. I would also like to do simple operations on these numbers live with as little latency as possible. So essentially, I get a Dynamic matrix of numbers that, are in byte form (0 to 255). To make it easier, I greyscaled it, so that there is only one data point per pixel. Assuming the matrix is 360 X 240, whenever I try to `Take[]` from this dynamic matrix, I get an error message. How do I use specified pieces of the matrix to define some output on this data? In other words, lets say I want to cut the video up into 18X12 blocks so that I can operate on just just that section of the live matrix video feed, how can I use `Take[]` to do this? I assume there is some function that is not `Take[]` for this. For my specific project, I need to divide each pixel in this raw matrix data by 2 so that the data fits in the parameters 0 to 127 instead of 0 to 255, what is the most efficient way to calculate this live stream so that there is as little latency as possible? Would I use `TrackSymbols`? Or is there some other way to operate on a dynamic matrix? Any help on solutions to these two problems is greatly appreciated. And a warm smile goes to you for helping out a lone wolf amateur programmer like myself. EDIT: Sample data can be generated from any webcam with the following code, thanks to help from Andy:               img = Dynamic[ColorConvert[CurrentImage[], "Grayscale"]];     rawimg = Dynamic[Flatten[ImageData[img[[1]], "Byte"][[1 ;; 18, 1 ;; 12]]]]      I then want to turn this information into one DYNAMIC digit that is between 0 and 126. by dynamically taking the Mean of all the numbers in the list and dividing this number by two (and using the floor of the answer). So the input is a large matrix and the output is just a single number like "122".


title: Poor (network) performance of Interpreter["Time"]

text: I was surprised to see that `Interpreter` requires external WR resources as this is not documented, at least not here. On a 3Ghz iMac, took ~half a minute to process n=68 time strings:               timeData = {"0:12:15", "0:13:00", "0:17:00", "0:00:39", "0:00:25", "0:00:38",      "0:00:48", "0:05:50", "0:03:34", "0:05:50", "0:00:22", "0:04:05",      "0:00:07", "0:00:07", "0:00:46", "0:00:02", "0:00:32", "0:00:11",      "0:00:31", "0:09:55", "0:00:07", "0:00:34", "0:00:36", "0:07:44",      "0:00:11", "0:00:20", "0:02:29", "0:04:30", "0:00:56", "0:01:23",      "0:00:05", "0:00:05", "0:00:18", "0:00:13", "0:00:21", "0:00:21",      "0:00:06", "0:00:13", "0:00:56", "0:00:05", "0:00:15", "0:00:05",      "0:01:38", "0:00:22", "0:01:43", "0:00:14", "0:09:06", "0:01:39",      "0:03:17", "0:03:08", "0:00:45", "0:00:36", "0:00:38", "0:00:06",      "0:00:08", "0:01:07", "0:00:08", "0:01:06", "0:00:11", "0:00:17",      "0:00:08", "0:00:17", "0:00:09", "0:00:34", "0:00:25", "0:00:31",      "0:00:07", "0:01:29"};          AbsoluteTiming [Interpreter["Time"][#] & /@ timeData ] // First          26.633811      Timing is much lower, ~3 seconds, though once I ran it and got: "Interpreter::timeout : "A network operation for Interpreter timed out. Please try again later." Users can define their own interpreters, but curious if it's possible to make at least part of the functionality available locally? I can't imagine a simpler test case than time strings.


title: Numerical vs Symbolic Integration: Loss of precision

text: I am trying to integrate the following expression over the time interval $0\leq t \leq \text{period}$.               (Cl - Cn)/Cl*(b Sin[2 Pi/peroid*t] f[t] - 2 (wl/peroid) Pi^2 b^2/wl^2)      where               f[t_] := ((Cl - Cn)^2/Cl 2 Pi^2 b^2/wl - Cn wl) b (wl/peroid)                  Sin[2 Pi (wl/peroid)*t/wl]/((Cl - Cn)^2/Cl*b^2*                 wl*(Sin[2*Pi*(wl/peroid)*t/wl]^2) + (Cn - Cl) wl b^2/2*                 Cos[4 Pi (wl/peroid) t/wl] - Cl b^2 wl/2 - Cn wl^3/12)      $Cl, Cn, b, period, wl$ are all parameters and $t$ is the only variable. I tried to perform the integration symbolically and _Mathematica_ gave me the following result: > >     -(((Cl - Cn) (2 b^2 (Cl - Cn) \[Pi]^2 + Cn wl^2))/((2 Cl^2 - 3 Cl Cn + > Cn^2) wl)) >   To further verify that this symbolical expression is correct, I performed the above integration again but numerically with both _Mathematica_ and _Matlab_ with the following parameter values:               Cn = 0.001903418147340     Cl = 8.265172296997836/10000     b = 10/1000000     wl = 1000/1000000     peroid = 0.5      and I also evaluated the symbolic expression with the above set of values. The numerical integration performed by _Mathematica_ and _Matlab_ agrees with each other. However, both numerical integration performed by _Mathematica_ and _Matlab_ are 4 orders of magnitude different from the result obtained by evaluating the symbolic expression with the same set of parameter values. There's something going on, but I don't know what. Any suggestions ? So far, I have checked that the function that I want to evaluate is smooth. Any suggestions are greatly appreciated.


title: Importing .txt or .csv financial data

text: I am trying to import some financial data exported from Excel. You can find the relevant file here : Text File or CSV File This is what the data looks like in Excel : ![enter image description here](http://i.stack.imgur.com/W1prV.png) Using the following code to import :               BankShadowFed =        Import[FileNameJoin[{NotebookDirectory[], "BankShadowFed.txt"}],         "Table"];      I have the following problem: ![enter image description here](http://i.stack.imgur.com/YKwoW.png) While I can Change to expression each element, ![enter image description here](http://i.stack.imgur.com/1uGUb.png) I can't get it all right including the dates... What is the right way to `Import[]` those files ? Or `Export[]` them in the first place?


title: Exporting a plot inside Manipulate - Update first, then Export

text: I want Mathematica to excute the first action inside the `Button` fully before executing the second action. In particular, look at the following plot which I want to `Export` to a pdf.               Manipulate[myFigure=Show[Plot[x^2+a,{x,-1,1},PlotRange->{-1,4}]],{{a,2,"a"},-1,3},Button["Export a=0",{a=0,Export["Figure1.pdf",myFigure];}],Button["Export a=1",{a=1,Export["Figure2.pdf",myFigure];}]]      If I click `Export`, Mathematica seems to `Export` the plot before `Updating` the `Manipulate` to the new value for 'a'. However, I obviously want it to change to the new 'a' first, showing the new plot, and then `Export` this plot to a pdf. Any thoughts on how to make `Manipulate` `Dynamically Update` itself before the `Export`? Or other solutions?


title: Plotting columns of two separate data lists

text: I have two data lists with names data1 and data2. data1 has 8 columns and data2 has two columns. How can I plot 3rd column of data1 verses 1st column of data2?


title: ListLinePlot problem

text: OK, so here I got the solution of a numerically-solved PDE. I wish to plot in a graph, for a given time, the point x where the solution reaches 1/2. So here's the relevant string of code:               eps=5/9;     phi6m = NDSolveValue[{         D[u[t, x], t, t] - D[u[t, x], x, x] ==                 -6 u[t, x]^5 + (8 + 4 eps) u[t, x]^3 - (2 + 4 eps) u[t, x],         u[0, x] == Tanh[x],          Derivative[1, 0][u][0, x] == 0,          u[t, -7] == -1, u[t, 7] == 1                          }, u, {t, 0, 6}, {x, -7, 7}];     Do[         phi62 = phi6m[k/10, x];         phi6plus[[k]] = FindRoot[phi62 == 1/2, {x, k/10}],      {k, 1, 55}]     ListLinePlot[phi6plus, PlotRange -> All]      But when I run that code, I get all the values of x where the solution is worth 1/2 for the sampled time points instead of a plot. It also says that ListLinePlot is called with no argument. How am I to make a graph with the values of phi6plus for the given values of k? If possible, I'd also like to interpolate the data contained in the phi6plus array.


title: Plotting a time delay in mathematica?

text: I'm having some difficulty plotting a phase space of a function `f` that exhibits time delay. i.e.               s = NDSolve[{x'[t] == f[x[t - \[Tau]]], x[0] == 1 }, {x}, {t, 100}];     ParametricPlot[{x[t] /. s, x[t-\[Tau]] /. s}, PlotRange -> All]      i.e. how do I plot `x(t-\[Tau])` vs `x(t)` ?


title: Overlay two images

text: I have a series of endoscopic images taken by two cameras at the same time. A color image: ![enter image description here](http://i.stack.imgur.com/n74Fl.jpg) and a fluorescent image indicating cancerous cells ![enter image description here](http://i.stack.imgur.com/porNw.jpg) I now want to overlay the two images to indicate the cancer in the color image.               ImageCompose[img1, {img2, 0.35}]      ![enter image description here](http://i.stack.imgur.com/KKuzq.jpg) you can see that it does not match exactly. I need a way to match both images. Another problem is, sometimes the color camera zoomed a little in while the fluorescent image does not. In the fluorescent image everything but the bright area should be omitted. The color image is the basis and the fluoro image should be fitted to it, preferably in some false coloring. Here are two corresponding images: pair 1               im1col=Import["http://i.imgur.com/shzDETI.jpg"]     im1fluo=Import["http://i.imgur.com/Yh9iAXH.jpg"]      pair2               im2col=Import["http://i.imgur.com/ZnUJFrv.jpg"]     im2fluo=Import["http://imgur.com/VHlrpNj.jpg"]


title: Approximately Fit Data Without FindFit

text: I have some noisy data, and I'd like to analyze the derivative of the function the data approximately matches. `Interpolation` is normally great, but doesn't work very well at all here.               data = Table[{x, Sin[x] + RandomReal[{-.15, .15}]}, {x, 0, 2 \[Pi], .05}];      ![Almost sin\(x\)](http://i.stack.imgur.com/WR6Um.png)               xi = Interpolation[data];     Plot[xi'[t], {t, 0, 6.25}];      ![Not cos\(x\)](http://i.stack.imgur.com/MaOVG.png) As you can see, the derivative (as expected when you think of how interpolation works) is not at all `Cos[x]`. In this case, because it is so obvious that the curve is of the `Sin[x]` family, it would be trivial to fit it and take the derivative of the fit. In the data I actually collected, I do not know the function, and assuming some high-order polynomial, while it may fit well, is almost certainly an incorrect assumption. Is there a way to plot the derivative cleanly without requiring other knowledge about the function? Is it possible to tell `Interpolation` that it doesn't need to hit every point exactly?


title: How can I change the CDF which imports the data and uses it, without execution of code

text: I am making an application which first imports the data from the Excel file and then uses it in the deployment of a CDF. But is it possible to change the data of the Excel file and see its corresponding CDF without executing the code in the notebook? I have imported y1 and y2 from an excel file. Here is the code.               CDFDeploy[     ToFileName["C:\\Users\\murali\\Desktop","demo2thomson.cdf"],     {DynamicModule[{y =      Import["C:\\Users\\murali\\Desktop\\demo.xlsx"], y1 = y[[1, 1]],   y2 = y[[1, 2]], q1, q2},      Panel@Column[{Spacer[70] Text[         Style["iPhone and iPad quarterly sales- units, million", Bold,           18]], Column[{Spacer[70],          Text[Style["Click on/off:", Bold, 14]], q1 = True; q2 = True;          Row[{Labeled[            Button["     ", q1 = ! q1, Background -> Blue,              Appearance -> "Frameless"], "iPhone", {Right}],            Spacer[19],            Labeled[Button["     ", q2 = ! q2, Background -> Orange,              Appearance -> "Frameless"], "iPad", {Right}]}],          Column[{Dynamic@            BarChart[             Table[{If[q1, y1[[i]], 0], If[q2, y2[[i]], 0]}, {i, 1, 22,                1}], BarSpacing -> 0.8, ChartStyle -> {Blue, Orange},              ImageSize -> {600, 280},              GridLines -> {None, Automatic}]}]}]}]]}]      I am importing these values just as default and want that the end user can change these values. i.e. I don't want the end user to go to the code and execute again and again if he wants to change some of the values of y1 and y2. Is it possible that he can change value and see the difference in the CDF itself?


title: How to deal with complicated gaussian integrals in Mathematica?

text: As we know, for most Gaussian integrals, we can get the analytical result. Now I have many Gaussian integrals to treat, which have the following general form,               Integrate[        x1^n1 x2^n2 x3^n3 ... xd^          nd Exp[-{x1, x2, x3 ... xd}.matrix.{x1, x2, x3 ... xd} + c1 x1 +              c2 x2 ... cd xd], {x1, -Infinity, Infinity},          {x2, -Infinity, Infinity} ... {xd, -Infinity, Infinity}].       The matrix is a symmetrical positive definite matrix. We can get the analytical integral result for this general form. However, it is a difficult task for Mathematica to deal with the similiar expressions, which takes so much time. I have written a package for treating this problem. But, it is still not sufficient because I need to deal with lots of these kinds of integral expressions. So the computation time is important. So have you ever seen the package for doing this kind of Gaussian integral? Or can you give me some suggestions about this problem? Thank you very much! Thanks all of you. For the concept MultinormalDistribution, it is very helpful for me. By the way, How can I transform the following integral expression to the standard form of MultinormalDistribution in a simple way?               vec1 := {r1x, r1y, r1z};     vec2 := {r2x, r2y, r2z};     vect := {r1x, r1y, r1z, r2x, r2y, r2z};     vcof := {c1, c2, c3, c4, c5, c6};     Integrate[Exp[-vect.mat.vect + vcof.vect] (vec1.vec2)^n (vec1.vec1)^     l (vec2.vec2)^m, {r1x, -Infinity, Infinity}, {r1y, -Infinity,      Infinity}, {r1z, -Infinity, Infinity}, {r2x, -Infinity,      Infinity}, {r2y, -Infinity, Infinity}, {r2z, -Infinity, Infinity}];      The mat is a symmetrical positive definite sparse matrix. And n, l, m are integers.   Thanks!


title: Awkward output of TeXForm

text: When I try to format a number that has a big exponent with TeXForm the following happens:               In[1]:= TeXForm[1.543*10^-10 ]          Out[1]//TeXForm=         \text{1.543$\grave{ }$*${}^{\wedge}$-10}      But I would like to get something like `1.543 \cdot 10^{-10}`. Is there any workaround for this?


title: PDE with Stefan Conditions, a.k.a variable boundary

text: I want to solve the one-dimensional one-phase Stefan problem, but I don't know how to make Mathematica understand the conditions. If you are not familiar with what I'm asking please refer to this wikipedia article: http://en.wikipedia.org/wiki/Stefan_problem#Mathematical_formulation This is what I have so far. Clearly, it doesn't work.               NDSolve[      {D[u[x, t], t] == D[u[x, t], {x, 2}],       (-D[u[x, t], x] /. x -> 0) == 1,       u[s[t], t] == 0,       D[s[t]] == (-D[u[x, t], x] /. x -> s[t]),       u[x, 0] == 0,       s[0] == 0       },     {u, s}, {x, 0, s[t]}, {t, 0, 10}]      I hope there is someone out there with a magical code I'm using Mathematica 10. Thanks!


title: Symbolic derivatives are being calculated numerically

text: Just found the following while debugging a problem. _Mathematica_ is calculating the derivative of `IntegerPart[x]` in some odd way:               Plot[{IntegerPart@u, D[IntegerPart[x], x] /.x -> u}, {u, 0, 3},PlotRange -> Full]      ![enter image description here](http://i.stack.imgur.com/SJRtd.png) Do you know what is the violet curve in the plot above, and why _Mathematica_ thinks it is the derivative of `IntegerPart[x]`? **Edit** Or consider for example the following:               f[x_] := Sin[x] + IntegerPart[x];     Plot[{f[x], Derivative[1][f][x]}, {x, 0, Pi/2}]      ![enter image description here](http://i.stack.imgur.com/BB7zW.png) Or similarly               Plot[{FractionalPart[x], Derivative[1][FractionalPart][x]}, {x, 0, 3}]      ![enter image description here](http://i.stack.imgur.com/Jb8Ws.png) What is happening here?


title: Sum equation with equation and get an equation

text: I am trying to get an equation from summing other equations but it doesn't result in a correct answer. Is there another way of doing this?               n = 4; xList = {1, 2, 3, 4, 5}; yList = {4, 5, 6, 8, 7};     equation[x_] = a*(x^4) + b*(x^3) + c*(x^2) + d*(x^1) + e*(x^0);     eqSummer = 0;          Do[       eqSummer = eqSummer +  equation[xList[[i]]];       , {i, 1, Length[xList]}     ];          eqSum     36768/25 + (512 c)/5 + 10 e


title: Unexpected Setter Bar Behavior when Manipulate Nested in Dynamic Module

text: Consider this code:               DynamicModule[{x, y},     x[t_] := t^2 + 5;     y[t_] := t^3 + 5;          Manipulate[Plot[fcn[t], {t, -5, 5}],     {fcn, {x -> "Square", y -> "Cubic"}}]]      ![SetterBar not working properly](http://i.stack.imgur.com/zQemy.png) Why does the SetterBar created by Manipulate not highlight properly when either option is selected? The same problem exists for other user interface elements, like a RadioButtonBar:               DynamicModule[{x, y},     x[t_] := t^2 + 5;     y[t_] := t^3 + 5;          Manipulate[Plot[fcn[t], {t, -5, 5}],     {{fcn, x, "Graph Type"}, {x -> "Square", y -> "Cubic"}, RadioButtonBar}]]      ![enter image description here](http://i.stack.imgur.com/IZSfz.png) However, if you remove the DynamicModule, everything works as expected:               x[t_] := t^2 + 5;     y[t_] := t^3 + 5;          Manipulate[Plot[fcn[t], {t, -5, 5}],     {{fcn, x, "Graph Type"}, {x -> "Square", y -> "Cubic"}}]      ![enter image description here](http://i.stack.imgur.com/pZUlD.png) Also if you were to replace DynamicModule with Block or Module, everything works as expected:               Module[{x, y},     x[t_] := t^2 + 5;     y[t_] := t^3 + 5;          Manipulate[Plot[fcn[t], {t, -5, 5}],     {{fcn, x, "Graph Type"}, {x -> "Square", y -> "Cubic"}}]]      Can anyone explain why this is, and how to fix it?


title: How to set the slider width inside Manipulate

text: I use the code below to visualise the connection between a sine curve and the unit circle, but would like to make the slider wider, so it has at least almost the same with as the image. I have tried to replace ControlType->Slider[] with ControlType -> Slider[ImageSize->800], but this seems to have no effect at all och the resulting graphics. The question is thus how to set the width of the slider inside Manipulate?               Manipulate[      With[{ar = 1/(2*Pi), o = v - Cos[v]},        Show[Plot[Sin[x], {x, -6*Pi, 6*Pi},          PlotRange -> {{-2*Pi, 2*Pi}, {-1, 1}}, PlotStyle -> {Black},          AxesLabel -> {"v", Sin["v"]}, AspectRatio -> ar],        ListLinePlot[{{o + Cos[v], 0}, {o + Cos[v], Sin[v]}},          PlotStyle -> {Thick, Black}, AspectRatio -> ar],        ListLinePlot[{{o + Cos[v], Sin[v]}, {o, 0}},          PlotStyle -> {Dashed, Black}, AspectRatio -> ar],        Graphics[{AbsolutePointSize[8], Point[{o, 0}]}, AspectRatio -> ar],        Plot[{-Sqrt[1 - (x - o)^2], Sqrt[1 - (x - o)^2]}, {x, o - 1,           o + 1}, PlotRange -> {{-2*Pi, 2*Pi}, {-1, 1}},          PlotStyle -> {{Thick, Orange}, {Thick, Orange}},          AspectRatio -> ar], ImageSize -> 800]], {v, -3/2*Pi, 3/2*Pi},       ControlType -> Slider[]]      ![The resulting graphics](http://i.stack.imgur.com/zTgCy.png)


title: Finding the time at which an Ito process satisfies a constraint

text: I want to run an Ito stochastic process. I have the following parameters               b1b = 0.9;     b3b = .8;     a1b = 0.1;     a3b = 0.2;     eps = 0.1;     G = (1/eps^2)*b1b ; a1 = (1/eps^2)*a1b; a3 = (1/eps^2)*a3b;     xc = Sqrt[a1/a3];     Uc = a1*xc^2/2 - a3*xc^4/4      I want to stop the process when `U[x[t]]=U[xc]` and `y[t]=0` (or at least very close for each of these parameters: say in the vicinity of `10^-4*U[xc]` for `U[x[t]]` and `10^-8` for `y[t]`). Please note `U[x]` is the integral of `U'[x]`. I am trying to write code that simulates `dz[t]` for many realisations (say 100) and calculates the average of times at which the aforementioned constraint is satisfied (i.e., average of 100 times). However, I have no idea how to incorporate the constraints and extract the time at which the constraints are satisfied. I tried to use the `ItoProcess[]` function, but had no fruitful outcome. Any help would be much appreciated.


title: Log-scale histogram bug

text: Not really a question, more a solution to what I call a bug in mathematica v8(.0.0.4). I already sent a bug report to Wolfram. ### Problem The documentation for the _Histogram_ -function explains the following option.               {"Log",bspec}       apply binning bspec on log-transformed data.      When specifying the bins in the format `{xMin, xMax, dx}`, these values are not processed corretly which leads to insatisfying results. In detail, the lower and upper bounds are transformed to the logarithmic scale using the natural logarithm. From there on, the bin widths are determined using `dx` and these bin coordinates are transformed back using the common logarithm. One would expect that the routine uses either the natural or the common logarithm for both operations, but not a mixture of the two. ### Example Imagine, that `data` is a list of real values.               (* binning settings *)     binMin = 0.01;     binMax = 100;     binWidthLog = 1;     Histogram[data, {"Log", {binMin, binMax, binWidthLog}}]      ![Standard histogram](http://i.stack.imgur.com/PE32X.png) The minimum and maximum `x` values clearly don't follow the wanted behaviour. Using custom bin limits, this result can be reproduced as follows with a mixture of common and natural logarithms.               bins = {10^Range[Log[E, binMin], Log[E, binMax], binWidthLog]};     Histogram[data, {"Log", bins}]      ![Reproduced standard histogram](http://i.stack.imgur.com/JzVDp.png)


title: How do I plot cities on a Map?

text: Right now, I have the 20 cities with the most population in the world, given by the lines of code               numberofpeople = Map[{#, CityData[#, "Population"]} &, CityData[All]];     datapoints =       Reverse[SortBy[DeleteCases[numberofpeople, {_, _Missing}],          Last]][[1 ;; 20]]      Now, I am going to plot these cities on a World Map, so that there is a point for each city in the dataset. However, I am stuck on what to do from there. As of now, I have the line of code               Graphics[{EdgeForm[Black], , CountryData[#, "SchematicPolygon"]} & /@        CountryData[]]      I am unsure on what goes between the commas. The other two arguments give a black border for each country's border and then displays the world as a SchematicPolygon. Any help is much appreciated.


title: Derivative of a spline approximation

text: To approximate an experimental data function $f(t)$ with $t \in (t_{min},t_{max})$ I used a cubic spline $s(p)=(t(p),f(p))$ with the parameter $p \in (0,1)$ and $p = t/(t_{max}-t_{min})$ by using the command BSplineFunction. To take the time derivative I use the chain rule $s'=ds/dt = ds/dp \cdot dp/dt = s'(p)/(t_{max}-t_{min})$. When I try plotting the derivative $df/dt = s'[[2]]$ by               Show[ParametricPlot[{93*p, 1/93 s'[p][[2]]}, {p, 0, 1}], AspectRatio -> 1]      it shows me the error warning > Part::partw: Part 2 of BSplineFunction[{{0.,1.}},<>][t] does not exist. >> but still shows the correct graph. What went wrong?               data = {{3.107, 0.997}, {6.851, 1.008}, {10.594, 1.011}, {14.338,      1.007}, {18.081, 0.977}, {21.825, 0.967}, {25.568, 0.917}, {29.311,       0.852}, {33.055, 0.736}, {36.798, 0.533}, {40.542, 0.336}, {44.285,      0.205}, {48.029, 0.111}, {51.772, 0.074}, {55.516, 0.044}, {59.259,      0.032}, {63.003, 0.034}, {66.746, 0.01}, {70.49, 0.026}, {74.233,      0.01}, {77.977, 0.016}, {81.72, 0.002}, {85.464, -0.002}, {89.207,      0.01}, {92.951, 0.01}}     s = BSplineFunction[data, SplineDegree -> 3];      There is a caveat to the method. When fitting a spline to data p is not necessarily proportional to the independent variable. In my case the relationship between $p$ and $t(p)$ deviates substantially from linearity outside the range $p \in (0.025, 0.975)$. Is there a better way to get the derivative?


title: Why does the PlotStyle not apply globaly when I plot multiple data files

text: I have several data files which contain columns of data. All my files follow the same format data001.out, data002.out, ... , data00n.out. I want to import and plot all of them simultaneously. In particular, I use only the first two columns of the data files for my plot. I wrote this simple Mathematica code:               SetDirectory["..."];          dataAll = {};          Do[        data = ReadList["data00" <> ToString[NumberForm[i, 2, NumberPadding         -> {"0", ""}]] <> ".out", Number,         RecordLists -> True];        pdata = Table[{data[[j, 1]], data[[j, 2]]}, {j, 1, Length[data]}];        AppendTo[dataAll, Flatten[pdata]];       , {i, 1, 50}     ]             S0 = ListPlot[dataAll, Frame -> True, FrameLabel -> {"x", "y"},      RotateLabel -> False, PlotStyle -> {Black, PointSize[0.01]},      PlotRange -> All, ImageSize -> 500]      I am wondering, if there is a simpler or even more correct way to perform this task. Perhaps, the `Do` loop needs improvement. I noticed that the `PlotStyle` in `ListPlot` does not apply to all points of the dataAll list. Even if I determine the color (black) and the size, the output contains several colors ans sizes. Where is the mistake? Many thanks in advance!


title: What algorithm does Plot use to determine abscissas?

text: (I'm hoping this question is not hopelessly naive...) My understanding is that `Plot`'s strategy is to generate a list of abscissas, evaluate the argument expression at those abscissas, and from that point on behave pretty much like ListPlot with the list of abscissa-ordinate pairs as input. (More or less.) Assuming that the sketch above is not fantastically off-base, what algorithm does `Plot` use to compute the list of abscissas to use?


title: Getting InputStream errors when including a call to ElementData within an Import definition

text: So I am writing an `ImportExport` converter for a common chemistry file format, and I've run up against a problem that seems to be about shared streams and whatnot. I followed the directions on this page. To work the example, create a random text file whose contents do not matter.               Export["testfile.txt", "hello"];      The definition for the `Import` converter is as follows               ImportExport`RegisterImport["TestFormat", TestFormat`TestFormatImport];     TestFormat`TestFormatImport[filename_String, options___] :=       Module[{temp},       (*Do some stuff, all works just fine*)       temp = ElementData["C", "AtomicNumber"];       {"Test" -> temp}];      All this does is call for the atomic number associated with the symbol C. If you test it out it seems to work just fine:               In[3]:= Import["testfile.txt",{"TestFormat","Test"}]     Out[3]= 6      But any subsequent call to `ElementData` gives a stream error:               In[4]:= ElementData["F","AtomicNumber"]     During evaluation of In[4]:= General::openx: InputStream[C:\Users\myusername\AppData\Roaming\Mathematica\Paclets\Repository\ElementData-7.0.28\Data\ElementData.wdx,122] is not open. >>     During evaluation of In[4]:= BinaryRead::openx: InputStream[C:\Users\myusername\AppData\Roaming\Mathematica\Paclets\Repository\ElementData-7.0.28\Data\ElementData.wdx,122] is not open. >>     Out[4]= $Failed      But, if I make a call to `ElementData` _before_ I make the `Import` command, then the errors go away.               In[1]:= ImportExport`RegisterImport["TestFormat",                  TestFormat`TestFormatImport];             TestFormat`TestFormatImport[filename_String, options___] :=                  Module[{temp},                (*Do some stuff, all works just fine*)                temp = ElementData["C", "AtomicNumber"];                {"Test" -> temp}];             ElementData["H", "AtomicNumber"]             Import["testfile.txt", {"TestFormat", "Test"}]             ElementData["F", "AtomicNumber"]          Out[3]= 1          Out[4]= 6          Out[5]= 9      This is all well and good, but I don't want to have to randomly make a call to `ElementData` before I do an `Import` command every time. What is going on here and how can I fix it? Thanks


title: How to translate interactive graphics from Mathematica to standard HTML+SVG?

text: I have a simple interactive plot in _Mathematica_ , with controls for various parameters. The point the plot is simply that, by manipulating these controls users can explore how the plot changes as the parameters change. IOW, this is `Dynamic`-101 stuff (which is my level at the moment). I would like to convert this to (non-proprietary) HTML + SVG (+ CSS, JavaScript, etc., as needed). Is there a straightforward path for doing this? I know that one can export _Mathematica_ graphics to SVG, but I'm not sure how one would export the dynamic behavior described above. (BTW, I've looked for ways to do this starting from JavaScript to begin with, but I have found that JavaScript support for plotting is rather primitive. JavaScript graphics seem to be mostly about Illustrator-type stuff, and more recently, "data visualization". In comparison there's almost nothing in the JavaScript graphics universe for plotting functions, the way `Plot` et al. do.)


title: integral, explicit form

text: I want to estimate the ratio of integrals: $$ \frac{\int \frac{4 a T^3}{\frac{4 a T^4}{3}+\Lambda_1 \left(\frac{4}{T^3}+1\right)}}{\int \frac{4 a T^3}{\frac{4 a T^4}{3}+\Lambda_0 \left(\frac{4}{T^3}+1\right)}} $$ where $\Lambda_1$=$\Lambda$ (constant) and $\Lambda_1$=0 for some temperature $T_0$ (arbitrary constants are set to zero). When I try to integrate the function:               f[T_] := (4 a T^3)/(4/3 a T^4 + Λ (1 + 4/T^3))     Integrate[ f[T], T]       I get the result like this (with `#` and `&`) :               12a RootSum[ 12 Λ + 3 Λ #1^3 + 4 a #1^7 &, (Log[T - #1] #1^4)/(9 Λ + 28 a #1^4) &]      What am I doing wrong? How do I get an explicit expression for the integral? How do I solve this problem ?


title: Plotting multivariable integration

text: If I have a multivariable integration like               NIntegrate[x^2 + y^2, {x, 1, 5}, {y, 6, 10}]      But I need to plot its result in terms of `x` . Then how to do it ?


title: difficulty abstracting the OptionValue pattern

text: I am building lots of functions that use `Options` and `OptionValue` and wanted to reduce the redundancy in the expressions that define the functions. I will show a tiny example, here, but please imagine that instead of a couple of options with names like `a` and `b`, my real examples have dozens of options with names like               blancmangeWithRaisinsAndPartiallyHydrogenatedChocolateSauce      and you will easily understand why I want to do what I want to do. What do I want to do? My functions fit the following pattern: The following defines the acceptable optional parameters for `foo`: they are `a` and `b`, and they have default values 1 and 2, respectively. The acceptable options are defined separately from the body of the function. A caller may supply values for `a` or `b` or both or neither, using option syntax below.               ClearAll[foo];     Options[foo] = {"a" -> 1, "b" -> 2};      The following defines the body of the function. This function produces an association object with attributes corresponding to the values of the optional parameters.               foo[OptionsPattern[]] :=       <|"a" -> OptionValue["a"],        "b" -> OptionValue["b"]|>;      The following is a call that supplies only the optional value for a.               foo["a" -> 42]      > >     <|"a" -> 42, "b" -> 2|> >   The following is a call that supplies both a and b; notice that the order does not matter.               foo["b" -> 43, "a" -> 42]      > >     <|"a" -> 42, "b" -> 43|> >   The following is a call that supplies neither a nor b.               foo[]      > >     <|"a" -> 1, "b" -> 2|> >   I want to reduce the redundancy in the definition expression for `foo`. I define a helper:               ClearAll[opt];     opt[nym_] := Rule[nym, OptionValue[nym]];      Hoping for a new style of definition for `foo`:               foo[OptionsPattern[]] = <|opt["a"], opt["b"]|>      Notice that I used `Set` and not `SetDelayed` because I wanted the right-hand side to be evaluated at definition time, not at call time. But still no dice: `foo` doesn't work any more               foo[]      > >     <|"a" -> OptionValue["a"], "b" -> OptionValue["b"]|> >   Its options are still in-force               Options[foo]      > >     {a -> 1, b -> 2} >   Why doesn't my little trick work? Why doesn't `opt` rewrite in the context of the definiing expression for `foo`?


title: Remove redundant dependencies from a directed acyclic graph

text: Given a directed acyclic graph, I want to remove all the edges $v_i \rightarrow v_j$ if $v_j$ is reachable from $v_i$ by some other path. Given the rich set of graph algorithms in _Mathematica_ , what is the best way to achive this? The background of the problem is this. I have a list of jobs and their dependencies, e.g., $a \rightarrow b$ means job $b$ can start only when job $a$ finishes. A list $\\{a \rightarrow b, b \rightarrow c, a \rightarrow c\\}$ is redundant because $a \rightarrow c$ is implied. I want to reduce the dependencies to a bare minimum.


title: Possible to include additional styles in context menu?

text: I am using Mathematica 9 on Windows 8, and I regularly want to use cell styles such as _Section_ , _SubSection_ and so on. If I click the `+` button before creating a new cell, a context menu with a number of style options is displayed: ![enter image description here](http://i.stack.imgur.com/2W4HX.png) Is there a way to configure this menu to contain some of the styles that I regularly use?


title: What is Mathematica's equivalent to MATLAB's Simulink?

text: MATLAB has Simulink and Simscape, Maple has MapleSim and Scilab has Xcos. What is the equivalent product for _Mathematica_?


title: Time differences between code using user-defined probability distribution and code using built-in distribution

text: Why is the reponse time of of kernel significantly different when I use the first code rather than the second? Shouldn it not be the same? Is there any way that the response time can be made smaller without having to use probability distributions built into _Mathematica_? Code 1:               triangular = TriangularDistribution[{0, 12}, 6];     Manipulate[       Plot[{         PDF[triangular, x]*If[x <= Quantile[triangular, p], 1, 0],          CDF[triangular, x],          PDF[triangular, x]},          {x, 0, 12},         PlotRange -> All, Filling -> {1 -> Axis}, ImageSize -> Large, AxesLabel -> {x, ""}],        {p, .6, "Percentil"}, 0, 1, .001, Appearance -> "Labeled"}]      Code 2:               D = ProbabilityDistribution[       Piecewise[{{         x/36, 0 <= x <= 6},         {(12 - x)/36, 6 < x <= 12}}],        {x, 0,12}];      Manipulate[       Plot[{         PDF[D, x]*If[x <= Quantile[D, p], 1, 0],         CDF[D, x],          PDF[D, x]},          {x, 0, 12},         PlotRange -> All, Filling -> {1 -> Axis}, ImageSize -> Large, AxesLabel -> {x, ""}],        {p, .6, "Percentil"}, 0, 1, .001, Appearance -> "Labeled"}]


title: Generating function for Newton series?

text: The function GeneratingFunction gives generating function for Taylor series. Is there a similar function for Newton's series? $$f(x) = \sum_{k=0}^\infty \binom{x}k \Delta^k [f]\left (0\right)$$


title: How do you properly create Buttons to change dynamic variables using Table

text: In this example, I want a series of four buttons to change the value of a variable that is used dynamically to drive a plot. I am trying to figure out why using Table around the buttons causes a problem. This works:               {Button["1", freq = 1], Button["2", freq = 2], Button["3", freq = 3],       Button["4", freq = 4]}      Dynamic[Plot[Sin[freq * x], {x, 0, 2 \[Pi]}]]      Why doesn't this work:               Table[Button[ToString[i], freq2 = i], {i, 4}]     Dynamic[Plot[Sin[freq2 * x], {x, 0, 2 \[Pi]}]]


title: Scope of expression in a user-defined function

text: I have the following code:               fbasic = A + R + Z*Z *Z*Z;     f[A_, Z_, R_] := fbasic + R;     f[0, 2, 3]      The answer I am getting is > >     3 + A + R + Z^4 >   Which is not what I want because the `fbasic` is not replaced by the expression. How can I do that?


title: What kinds of uses of SymbolicC (introduced in Mathematica 8) do you foresee? Are there any neat examples already?

text: Mathematica 8 introduced SymbolicC, a set of Mathematica functions that capture C language constructions in the familiar Mathematica tree-like fashion. Additionally, there are functions to write SymbolicC trees as straight C code to a file. The tutorial clearly explains the functions, but -as far as I know- it doesn't provide any examples of useful applications of this capability. It sounds like it should be tremendously useful, but I have a hard time coming up with some creative uses of my own. A couple of years ago, I used Mathematica to 'flatten out' a recursive algorithm I had written in C to gain some speed. Mathematica wrote the whole program for me pasting C phrases together I had prepared in strings. SymbolicC would have been much neater, though not really necessary. Yesterday, Leonid Shifrin came up with a very nice application of symbolicC to make an alternative of CForm that doesn't make calls to the auxiliary function Power(). That's a good start. I'd like to ask the creative minds on StackOverflow to come up with more _ideas_ and/or actual _uses_ of SymbolicC. I'll accept the most upvoted answer. **EDIT** Mar 30 The response to the question is a bit scant so far. So, we have this mma extension with more than 60 functions added and virtually nobody has an idea of how to use them? Come on guys, show that you're creative!


title: Parametric 3D plot with parameters satisfying an implicit equation

text: I am trying to plot a function $ {\bf x}(t) = r(t)\hat{v} + {\bf b}(t) $, with unit vector $ \hat{v} $ and vector $ {\bf b}(t) $ given in spherical coordinates. For simplicity, assume that $ \hat{v} = (\sin\theta\cos\phi, \sin\theta\sin\phi, \cos\theta) $, and $ {\bf b}(t) = [t, \sin(a+t), \cos(b + at^2)] $, where $ a $ and $ b $ are constants. This is easy to plot, however, I want the angles $ \theta $ and $ \phi $ to satisfy an implicit equation, say, $ \cos\theta + a(\phi + b t)^2 + c = 0 $.


title: How to draw timing diagram from a 0 and 1 string list (2)

text: I like ubpdqn's last edition & Mr Wizard's refactoring to my last question very much. I inserted two `Reverse` just to make the diagrams and the strings match in order.               fun[str : {__String}] :=       Module[{fs, n, timd},        fs = Riffle[#, #]~Append~Last[#] & /@ ToExpression@Characters@str;       n = Length@First@fs;       timd = Reverse@fs~Append~PadLeft[{0}, n, {0, 1}];            ListLinePlot[MapIndexed[#1 + 2 First@#2 - 2 &, timd],         InterpolationOrder -> 0, Frame -> True,         FrameTicks -> {Thread[{Range[1.5, n - 1.5, 2], Range[n/2]}],           Thread[{Range[0.5, 2 Length@timd, 2],             Join[Reverse@str, {"clock"}]}], None, None},         PlotRange -> {{0, n + 1}, Automatic}]]      ![enter image description here](http://i.stack.imgur.com/Yh3Ud.gif) And here, I managed to make the input strings rotate dynamically with the following code, the problem is I failed to make the timing display rotates with the strings as well. Pls help.               str2 = {"11000011", "00000011", "11100111"};     Dynamic[      Refresh[str2 = {StringJoin[RotateRight[Characters[str2[[1]] ]]],          StringJoin[RotateRight[Characters[str2[[2]] ]]],         StringJoin[RotateRight[Characters[str2[[3]] ]]]         };       Column[{str2[[1]], str2[[2]], str2[[3]]}], UpdateInterval -> 1       ],      TrackedSymbols -> {}      ]


title: how to find the vector intersection in a collection of triangulated 3D points?

text: I'm trying to calculate the 3D point coordinates for the intersection of a vector with a plane. I have been using the following code to do this:               PointPlaneIntersection[{{x1_, y1_, z1_}, {x2_, y2_, z2_}, {x3_, y3_,      z3_}}, {{x4_, y4_, z4_}, {x5_, y5_, z5_}}] :=  Module[{t = -Det[{{1, 1, 1, 1}, {x1, x2, x3, x4}, {y1, y2, y3,           y4}, {z1, z2, z3, z4}}]/      Det[{{1, 1, 1, 0}, {x1, x2, x3, x5 - x4}, {y1, y2, y3,          y5 - y4}, {z1, z2, z3, z5 - z4}}]},  {x4 + t (x5 - x4), y4 + t (y5 - y4), z4 + t (z5 - z4)}]      which I found at: http://mathworld.wolfram.com/Line-PlaneIntersection.html I have the vector and a point of origin for this vector:               vec={1.11593, 0.0607521, 0.125472};pt={-45.0446, 0.0900457, -1.42599}      However, rather than having a know plane defined by 3 points, as the PointPlaneIntersection code needs, I have a group of planes/triangles defined by 3D points:               triangles={{{-46.4755, -0.0930855, -2.55178}, {-46.6708, -1.22548, -2.25304},{-46.9169, -0.664019, -0.916458}}, {{-46.4736,  0.544871, -1.66483}, {-46.4755, 0.0930855, -2.55178}, {-46.9169,-0.664019, -0.916458}}, {{-46.0117, 0.605676, -3.13173}, {-46.4755, -0.0930855, -2.55178}, {-46.4736, 0.544871, -1.66483}}, {{-45.6652, 1.74667, -1.92923}, {-46.0117, 0.605676, -3.13173}, {-46.4736, 0.544871, -1.66483}}, {{-45.2907, 1.39215, -3.80111}, {-46.0117, 0.605676, -3.13173}, {-45.6652, 1.74667, -1.92923}}, {{-46.4736, 0.544871, -1.66483}, {-46.9169, -0.664019, -0.916458}, {-46.8575, -0.142585, 0.141953}}, {{-46.2786, 1.32328, -0.512178}, {-46.4736, 0.544871, -1.66483}, {-46.8575, -0.142585, 0.141953}}, {{-45.6652, 1.74667, -1.92923}, {-46.4736, 0.544871, -1.66483}, {-46.2786, 1.32328, -0.512178}}};      This can be visualised:               Show[Graphics3D[{Yellow, Specularity[White, 20], Directive[Opacity[0.75]], EdgeForm[{Gray, Thin}], Polygon[triangles], Red, AbsolutePointSize[8], Point[pt], Blue, Thick, Arrowheads[0.02], Arrow[{pt, (pt + (vec))}]}], PlotRange -> All, Lighting -> "Neutral", Boxed -> False, Axes -> False, Ticks -> None, AxesLabel -> {"X", "Y", "Z"}, AxesStyle -> Gray, BoxRatios -> Automatic, AspectRatio -> Automatic, ImageSize -> 650, ViewPoint -> vec*10]      ![enter image description here](http://i.stack.imgur.com/SxjsL.png) Also, note that in the graphic produced the vector direction is away from the collection of triangles. I'm looking for a solution where it doesn't matter whether the vector is towards or away from the triangles...ie the code will effectively flip the vector round. Can anyone suggest a solution for selecting which triangle/plane the vector passes through? Or alternatively, could anyone suggest a good way to fit a surface (eg a bezier surface) to the points, then find the intersection of the vector with the surface? thank you for reading my problem, Dime


title: Cannot compile OpenGL code in Mathematica (vc2010-windows 8.1)

text: # LinkError of OpenGL * * * My enviroment is windows 8.1 x64, _Mathematica_ 9.0.1, opengl 1.1               targetDirectory = "E:\\Users\\Hyper\\Documents\\OpenGL";     sourceDirectory = "E:\\Users\\Hyper\\Documents\\OpenGL\\SourceFile";     includeDirectory = {"E:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\include",         "E:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\include\\GL"};     libraryDirectory = {"E:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\lib"};     LinkerOptions = {"opengl32.lib", "glaux.lib", "glu.lib", "glu32.lib",    "glut.lib", "glut32.lib", "opengl.lib"};          mainFile = Import[sourceDirectory <> "\\opengl-test1.txt"]          (*         #include <windows.h>           //#include <gl/glaux.h>        //#include <gl/gl.h>        //#include <gl/glu.h>       //#include <gl/glut.h>       #include <glaux.h>       #include <gl.h>       #include <glu.h>       #include <glut.h>       #pragma comment(lib, "opengl32.lib")       #pragma comment(lib, "glaux.lib")#pragma comment(lib, "glu.lib")       #pragma comment(lib, "glu32.lib")       #pragma comment(lib, "glut.lib")       #pragma comment(lib, "glut32.lib")       #pragma comment(lib, "opengl.lib")       int main(int argc, char* * argv)     {auxInitDisplayMode(AUX_SINGLE|AUX_RGBA);     auxInitPosition(0,0,500,500);     auxInitWindow(argv[0]);     glClearColor(0.0,0.0,0.0,0.0);     glClear(GL_COLOR_BUFFER_BIT);     glColor3f(1.0,1.0,1.0);     glMatrixMode(GL_PROJECTION);     glLoadIdentity();     glOrtho(-1.0,1.0,-1.0,1.0,-1.0,1.0);     glBegin(GL_POLYGON); glVertex2f(-0.5,-0.5);     glVertex2f(-0.5,0.5);     glVertex2f(0.5,0.5);     glVertex2f(0.5,-0.5);     glEnd();     glFlush();     }     *)          exe = CreateExecutable[mainFile, "opengl-test1-x64",   "IncludeDirectories" -> includeDirectory, "Language" -> "C++",   "LibraryDirectories" -> libraryDirectory,   "TargetDirectory" -> targetDirectory, "Debug" -> True,   "LinkerOptions" -> LinkerOptions]      ![enter image description here](http://i.stack.imgur.com/jmJcg.png) * * * I can build and run this little example, in VC2010-IDE enviroment, so I'm not sure where goes wrong.


title: Nonrectangular region for NDSolve

text: I have a PDE with mixed boundaries (Neumann and Dirichlet on some sides) in the region $(t,x,y) \in \left( 0, T\right) \times\left\\{ -L \leq x \leq L, 0 \leq y \leq h(x) \right\\}$ where $h(x)$ is something like $\exp\left\\{ -(x-x^*)^2\right\\}$, doesn't matter. And I have Neumann boundary condition on the curve $\left(x, h(x)\right)$. How can I provide such region to NDSolve?


title: Integral over squared Hermite polynomial

text: I would like to calculate the uncertainty of the nth Eigenstate of a 1-dim harmonic oscillator. To obtain the result I have to solve the integral $$\int_{-\infty}^{\infty} \psi^* x^2 \psi \:dx$$ with $$\psi(n,x)=\frac{e^{-\frac{x^2}{2}} H_n(x)}{\pi^{\frac{1}{4}}\sqrt{2^n n!}}$$, where $H_n(x)$ is the Hermite polynomial (degree n) in the physicist version (as implemented in Mathematica). In Mathematica this equals to the Integral over               (2^-n E^-x^2 x^2 HermiteH[n, x]^2)/(Sqrt[π] n!)      Doing this manually gives $1/2+n$, but i can't get Mathematica to solve this integral without specifying $n$. I used `               Assuptions=n ∈ Integers && n >= 0      Is there anyway to solve similar integrals with Mathematica? Edit: Thanks for you answer, but I should have mentioned, that I'm looking for a way to let Mathematica solve such problems analytical.


title: Mystery with ValueQ

text: Consider the following               ClearAll[jd];     ValueQ[jd]      We expect `False` and get it. Now consider               ClearAll[jd];     ValueQ[jd /. {foo -> Unique[]}]      which yields `True`. But               jd /. {foo -> Unique[]}      is just `jd` and has no value defined. What's going on here?


title: Add lines to 3D Plot

text: How can I add lines that demarcate the different regions of the following 3D plot:               Plot3D[1/(1 + E^(-a - c)), {a, -8, 8}, {c, -8, 8}]      To give you an idea of what I have in mind I have added the lines and descriptions in the 3D plot in paint; now I want to know how to do it directly in _Mathematica_. ![enter image description here](http://i.stack.imgur.com/HKHLP.gif)


title: What is the equation to plot a vertical line?

text: Please help. Trying to find area between three curves, `e^-x, x = 2, y = 1`. Can't find out how to plot `x = 2`. Don't want to use `Epilogue` unless it can shade the area enclosed by the three curves.


title: How to get an Excel-like surface plot with ListContourPlot3D

text: I'm trying to create an Excel like surface plot from an import of data from an Excel workbook. I get the data without issue. It is a set of percentages in bin ranges over a series of dates. I'd like to plot this as a surface. After some searching it appears that I need to use _ListContorPlot3D_. It seems that I need to transform the data into a list of 3d vectors. I want the dates to show in the plot so I use the _DateObject_ to let the plot know what it is. However, it wont plot. It complains that I have not provided a list of points of dimension 3. But it is a list of points of dimension 3; {Date, Bin, Value}. I thought this would be an easy thing to do with the import. What have I done wrong? Am I using the correct plot for this? A sample of the data, the transformation command, and the plot command is below. Many thanks for your help. Edmund               testData = {{{2014, 4, 30, 0, 0, 0.`}, 0.5037593984962406`,      0.2631578947368421`, 0.11278195488721804`, 0.045112781954887216`,      0.03007518796992481`, 0.007518796992481203`,      0.022556390977443608`, 0.007518796992481203`, 0.`, 0.`,      0.007518796992481203`, 0.`, 0.`, 0.`, 0.`,      0.`}, {{2014, 3, 31, 0, 0, 0.`}, 0.5072463768115942`,      0.2536231884057971`, 0.12318840579710146`, 0.050724637681159424`,      0.028985507246376812`, 0.007246376811594203`,      0.014492753623188406`, 0.014492753623188406`, 0.`, 0.`, 0.`, 0.`,      0.`, 0.`, 0.`, 0.`}, {{2013, 12, 31, 0, 0, 0.`},      0.49295774647887325`, 0.29577464788732394`, 0.09859154929577464`,      0.04225352112676056`, 0.035211267605633804`,      0.007042253521126761`, 0.014084507042253521`,      0.007042253521126761`, 0.007042253521126761`, 0.`, 0.`, 0.`, 0.`,      0.`, 0.`, 0.`}, {{2013, 9, 30, 0, 0, 0.`}, 0.4765625`, 0.25`,      0.125`, 0.0703125`, 0.046875`, 0.0078125`, 0.`, 0.015625`, 0.`,      0.0078125`, 0.`, 0.`, 0.`, 0.`, 0.`,      0.`}, {{2013, 6, 28, 0, 0, 0.`}, 0.3761467889908257`,      0.3211009174311927`, 0.14678899082568808`, 0.05504587155963303`,      0.05504587155963303`, 0.`, 0.009174311926605505`,      0.009174311926605505`, 0.`, 0.01834862385321101`,      0.009174311926605505`, 0.`, 0.`, 0.`, 0.`,      0.`}, {{2013, 3, 29, 0, 0, 0.`}, 0.42857142857142855`,      0.24761904761904763`, 0.14285714285714285`, 0.06666666666666667`,      0.01904761904761905`, 0.0380952380952381`, 0.01904761904761905`,      0.009523809523809525`, 0.009523809523809525`,      0.009523809523809525`, 0.`, 0.009523809523809525`, 0.`, 0.`, 0.`,      0.`}, {{2012, 12, 31, 0, 0, 0.`}, 0.39`, 0.23`, 0.22`, 0.03`,      0.01`, 0.06`, 0.01`, 0.04`, 0.01`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`,      0.`}, {{2012, 9, 28, 0, 0, 0.`}, 0.3473684210526316`, 0.2`,      0.25263157894736843`, 0.07368421052631578`, 0.042105263157894736`,      0.042105263157894736`, 0.010526315789473684`, 0.`,      0.021052631578947368`, 0.010526315789473684`, 0.`, 0.`, 0.`, 0.`,      0.`, 0.`}, {{2012, 6, 29, 0, 0, 0.`}, 0.28888888888888886`,      0.25555555555555554`, 0.2222222222222222`, 0.06666666666666667`,      0.1`, 0.022222222222222223`, 0.011111111111111112`,      0.011111111111111112`, 0.011111111111111112`,      0.011111111111111112`, 0.`, 0.`, 0.`, 0.`, 0.`,      0.`}, {{2012, 3, 30, 0, 0, 0.`}, 0.27906976744186046`,      0.19767441860465115`, 0.3023255813953488`, 0.05813953488372093`,      0.08139534883720931`, 0.03488372093023256`, 0.011627906976744186`,      0.`, 0.023255813953488372`, 0.011627906976744186`, 0.`, 0.`, 0.`,      0.`, 0.`, 0.`}};          plotData = Flatten[Table[{DateObject[testData[[x, 1]],       DateFormat -> {"Year", "Month", "Day"}], y - 1,       testData[[x, y]]}, {x, Dimensions[testData, 1][[1]]}, {y, 2,       Dimensions[testData, 2][[2]]}], 1];          ListContourPlot3D[plotData, Contours -> 1,       AxesOrigin -> {DateObject[{2014, 4, 30, 0, 0, 0.`}], 0, 0},       AxesLabel -> {"Date", "Bins", "%"}]


title: parameter optimization

text: Does anybody know of any tutorial material that explains how to use Mathematica to fit parameter values used in a set of ordinary differential equations to experimental values stored in a comma separated variable (CSV) file, and assumes very basic Mathematica programming experience? The ordinary differential equations are required to provide a time course simulation of the variables that is fitted to experimental data, in order to use the parameter values to predict hypothesis on the behavior of the system. Thanks for any assistance.


title: How to draw a graph about the FourierTransform of a 2D Function?

text: Here is a 2D function, and it cannot be calculated by the `FourierTransfrom`               n = 2; δ = 0.2;     p[x_, y_] = Cosh[n*Sqrt[2 Pi]*δ*Sqrt[x^2 + y^2]]*Exp[-((δ^2*(x^2 + y^2) + 2 n^2*Pi)/2)];          p[x,y] ContourPlot      ![enter image description here](http://i.stack.imgur.com/9xkKS.jpg) and my problem is how to draw a graph about its `FourierTransform` Function? Here is an example: if I have a function that can be calculated by `FourierTransform` like below:               n = 2; δ = 0.2;     p[x_, y_] = Cosh[n*Sqrt[2 Pi]*δ*x]*Cosh[n*Sqrt[2 Pi]*δ*y]*Exp[-((δ^2*x^2+ 2 n^2*Pi)/2)]*Exp[-((δ^2*y^2+ 2 n^2*Pi)/2)];     uu1[tx_, ty_] = FourierTransform[p[x, y], {x, y}, {tx, ty}];     ContourPlot[p[x, y], {x, -40, 40}, {y, -40, 40}]     ContourPlot[uu[tx, ty]^2, {tx, -0.5, 0.5}, {ty, -0.5, 0.5}]      we will get the answer below: ![enter image description here](http://i.stack.imgur.com/wg64K.jpg) And here, I suppose the function p[x,y] can not use `FourierTransform` ,I can use the function `Fourier`               data = Table[p[x, y], {x, -40, 40, 0.4}, {y, -40, 40, 0.4}];     ListDensityPlot[Re[Fourier[data]]]      ![enter image description here](http://i.stack.imgur.com/8VsWK.jpg) but the answer is not I wanted! I don't know why? and I hope I can get help from you!


title: How do I solve coupled ordinary differential equations?

text: I have four coupled ODE's. I am not sure how to plot and solve them using Mathematica. I won't give the exact problem, but the following is something analogous: The equations               a= x'[t]     a'=-c1*x[t]/c2+c1*(y[t]-x[t])/c2     b=y'[t]     b'=-c1*(y[t]-x[t])/c2      Can be written as               x'[t]= -c1*x[t]/c2 + c1*(y[t]-x[t])/c2     y'[t]= -c1*(y[t]-x[t])/c2      The question is, now how do I use these in NDSolve to give solution and later a plot as well? I have initial conditions to plug in, but I am hung up on how to solve these coupled equations... Thank you in advance. _Edit_ I do not know how to input this into NDSolve.


title: Retrieving other information on CountryData

text: The following input will produce some answers, however how do we find out other details, such as the specific year the result corresponds to, as well as the source from which the data is obtained?               CountryData["France", "MaleElderlyPopulation"]          CountryData["Australia", "MaleElderlyPopulation"]


title: Avoiding MainEvaluate in a CompiledFunction to fetch global variables

text: I'm trying to write a simulation using Mathematica 8.0. Since I will most likely be doing the same operation over and over again, I'm trying to `Compile` whatever I can. However, I've been having problems avoiding `MainEvaluate` calls when I define `CompiledFunction` objects which refer to global variables. A simplified sample of what I'm trying to use is:               g = 4.49*^3;     m = 1.;     s = 1.;     ϵ = 2.;     sAcceleration = Compile[{{sPosition, _Real, 1}},        (-g (m + s))/(sPosition.sPosition + ϵ*ϵ)^(3/2) sPosition];      I have also tried wrapping the whole thing inside a `Module`, to no avail:               sAcceleration2 =  Compile[{{sPosition, _Real, 1}},       Module[{gg = g, mm = m,  ss = s, ϵϵ = ϵ^2},         (-gg (mm + ss))/(sPosition.sPosition + ϵϵ)^(3/2) sPosition]];      They seem to run just fine. However, when I take a look at what the `CompiledFunction` is trying to do internally using `CompilePrint`               << CompiledFunctionTools`     CompilePrint[sAcceleration]     CompilePrint[sAcceleration2]      I get, respectively > 1 R1 = MainEvaluate[ Function[{sPosition}, g][ T(R1)0]] > > ... > > 3 R1 = MainEvaluate[ Function[{sPosition}, m][ T(R1)0]] > > 4 R4 = MainEvaluate[ Function[{sPosition}, s][ T(R1)0]] > > ... > > 7 R6 = MainEvaluate[ Function[{sPosition}, ϵ][ T(R1)0]] > > 8 R7 = MainEvaluate[ Function[{sPosition}, ϵ][ T(R1)0]] > > ... and > 1 R1 = MainEvaluate[ Function[{sPosition}, g][ T(R1)0]] > > 2 R3 = MainEvaluate[ Function[{sPosition}, m][ T(R1)0]] > > 3 R4 = MainEvaluate[ Function[{sPosition}, s][ T(R1)0]] > > 4 R6 = MainEvaluate[ Function[{sPosition}, ϵ][ T(R1)0]] > > ... Since I will most likely be toying with different values for these variables in different simulation runs, but they will be held constant within a given run, can I avoid both `MainEvaluate` and feeding these variables to my function as additional arguments? Thanks in advance.


title: Text as plot axes values

text: I have some chemical data that I am plotting using `ListLogPlot`.               data={{2776.37,2016.64,1483.51,1027.35,500.878,94.1385,310.402,282.548,            257.886,224.359,218.688,209.312,215.776,198.78},            {40.5063,24.633,12.069,8.3151,6.35135,15.0977,8.74372,15.5125,9.34959,            9.70696,11.125,12.1457,10.8075,9.7561},           {113.08,124.633,75.9698,59.5186,55.9459,7.81528,57.4372,69.5291,80.4878,            88.2784,105.563,127.935,148.571,148.78}};          ListLogPlot[data, Joined -> True]      ![enter image description here](http://i.stack.imgur.com/MCO17.png) I want to replace the x-axis tick values with the associated elements. e.g. replace 1,2,3,...,14 with               xaxis= {"La","Ce","Pr","Nd","Sm","Eu","Gd","Tb","Dy","Ho","Er","Tm","Yb","Lu"};      Any suggestions on how to achieve this? Is there another plot function that I should be using?


title: Odd colourization for FourierParameters. UI bug?

text: The Mathematica UI colourizes the FourierParameters in the following               Clear[x, y]     g[x_, y_] = x^2 y ;     f[x_, y_] =      FourierSeries[x^2 y, {x, y}, {4, 4}, FourierParameters -> {1, 2 Pi}]      as in the following ![colorized input](http://i.stack.imgur.com/F7FOh.png) "Why color" on right click says it is excess arguments, but the resulting series computation matches nicely, and returns without error, so this seems like a UI colorizing bug to me.


title: Timing Total crashes kernel

text: Here is a simple test function               test[n_] :=       Module[{i = 0}, Total[Nest[{++i, #}&, {0}, n], -1]]      On my system V9.0.1 running OS X 10.6.8 and with a clean kernel, the following works               Timing[test[26198]]      > >     {0.106564, 343180701} >   but then immediately evaluating               Timing[test[26199]]      fails. I get a beep and Help > Why the Beep?... shows ![alert.png](http://i.stack.imgur.com/o0elR.png) Can anybody verify this on another system different from mine? Can you cast any light on why it happens? I will submit a bug report to WRI if this is not just peculiar to my system.


title: How to update package?

text: when I use `<< PhysicalConstants`` I get the message like :General::obspkg: PhysicalConstants is outdated... see the Compatibility Guide for more infomation... The question is how to update it? My version is MA9.0.


title: Plotting surfaces described by redundant variables - Alternatives to use of Eliminate + ContourPlot3D

text: Suppose I want to plot a surface defined by equations involving redundant variables. Consider, for example, plotting the surface defined by the equations: $$ \left\\{ \begin{array}{l} \cos x + \sin y = z^2+\cos w \\\ \sin w=0 \end{array} \right.$$ for $-2 \pi \leq x \leq +2\pi$, $-2 \pi \leq x \leq +2\pi$, $-2 \leq z \leq +2$. I have used the following code for this:               eqs = Flatten[ Quiet @ Eliminate[{Cos[x] + Sin[y] == z^2 + Cos[w], Sin[w] == 0},                                       {w}]];     ContourPlot3D[ Evaluate[eqs], {x, -2 π, 2 π}, {y, -2 π, 2 π}, {z, -2, 2}]      It works quite well for simple examples like this, but it is not a good alternative for similar problems involving more complex equations (or more redundant variables).   Is there a more efficient algorithm for plotting surfaces defined this way?


title: Problem with manipulation and plot

text: I want to make my function trace the hypotrochoid through one period of its motion and trying to change the color of the trace, color of the radius, and change the color of the dot on it so I can view it easier I have came up with this following function                hypotrochoid[a_, b_, h_,t_] := {(a - b) Cos[t] + h Cos[(a - b)/b t], (a - b) Sin[t] -      h Sin[(a - b)/b t]};           myfigure[a_, b_, h_]:=Manipulate[ParametricPlot[hypotrochoid[a, b, h, t], {t, 0, c*2 \[Pi]},PlotRange -> {{-(a + b + h + 1/4), a + b + h + 1/4}, {-(a + b + h + 1/4), a + b + h + 1/4}}], {c, -1, 1}]      Though when I test it on               myfigure[5, 1, 1/2]      Nothing shows up on this testing. I know I do not have the coloring but not certain of the syntax require.


title: How to define a list that contains all primes less than x?

text: how can I define my own list in which I have all primes less than x?


title: CUDAFunctionload error

text: I am trying to get `CUDAFunctionLoad` to work with _Mathematica 9.0_. I installed the latest clang and the _Nvidia Tools 6.0_. but I keep getting the error message: > >     CUDAFunctionLoad::cmperr: "-- Message text not found -- >                                  "clang: error: unsupported option > -dumpspecs" " >   I note that others have the same problem. i asked _NVIDIA_ and _Wolfram Reaserch_ for help and they have not come up with any solution so far, although they suspect the problem is that clang in latest version is not compatible with _Mathematica 9.0_. Any help, insights or leads would be very much appreciated.


title: Matrix multipication

text: Is this matrix multiplication is possible? Microsoft mathematics gives me a answer for it? How it could be a correct? If we need multiple two matrix, number of rows and columns should be equal. So how it is possible? ![Is that possible?](http://i.stack.imgur.com/EI76V.png)


title: Can `Array` work as `Loop`?

text: I got Mathematica code from my friend:               n = 100     l = 0     gw = GaussianQuadratureWeights[n, 0, 2]     (*the result of gw maybe like this {{0.000286273, 0.000734634}, {0.00150805, 0.00170939}, {0.00370487, 0.00268393},...}}*)     J = Array[SphericalBesselJ[l, gw[[#, 1]]] &, n]      The first, I'm not sure with syntax because i'm not a Mathematica user. But in my understand this code just try to create Spherical Bessel array by using 2 parameters such as               l just a constant. its value is 1           qw this is two dimensional array       On Mathematica code up there for `gw[[#, 1]]` i think they just tried to call {{0.000286273, 0.00150805, 0.00370487, ...}} and put them one by one to second parameters of SphericalBesselJ . And finally, we will get a one dimensional `J` array If write it as pseudo code from my understanding it might be like this:               l = 1     n = 100     gw = gaussiannode(100) //generate 100 gaussian nodes     for (i==1, i<=n, i++):         J[i] = SphericalBesselJ(l, gw[1][i])      My question is "Is it the Mathematica code up there equivalent to my pseudo code?" My point is just want to know `Array` can work as `Loop` or not? if not please correct Mathematica code up there to the right way by using loop.


title: Details about Symbolize

text: When I'm using Symbolize function, there are some details that I'm not sure. For example:               << Notation`     Symbolize[Subscript[q, 1],Subscript[q, 2]];(*I want to declare two symbols with subscript*)        1. Can I type the name "Symbolize[...]" instead of using the Notation Palette？It seems there is a little distinction, Notation Palette has a colored region: ![enter image description here](http://i.stack.imgur.com/pX5Yj.jpg)   2. Does "Symbolize" support multiple inputs, such as the above example? What if i want to declare as many as 100 variables with subscript? I want to do differentiation on q1.               Subscript[q, 1] /:D[Subscript[q, 1], t, NonConstants -> {Subscript[q, 1]}] :=      Subscript[dq, 1];     D[Subscript[q, 1]^2, t]      I expect to get 2*q1*dq1, but Mathematica gives 0. Why is that?


title: Under OS X, is there a way to view graphics output when running in the command line?

text: Being a long time unix shell person, I prefer Mathematica's command line interface, over the notebook. (command history, etc...) It just learned that on OS X, the cli is available as MathKernel. What I'm wondering now is, is it possible to open graphics (and/or animations, sounds, etc) result, from within the command line?               In[16]:= Plot[Sin[x], {x, -Pi, Pi}]          Out[16]= -Graphics-      I would like to be able to view output #16.


title: Simplifying expression with patterns (Replace)

text: **Q1** : I need to simplify some algebraic expression, according to particular pattern, namely: \begin{equation*} x^m = \left\\{ \begin{array}{ll} 1 & \text{if } m \text{ is even} \\\ x & \text{if } m \text{ is odd} \end{array}\right. \end{equation*} for example: $$ a x^3 + b x y-c x^7 y^2 $$ should be simplified to $$ ax + bxy - cxy^2 $$ I need something like:               a x^3 + b x y - c x^7 y^2 /.{x^_ -> ... }      but, that will recognize the parity of the each power in the expression. **Q2** : How one can get only one term in the sum? For example, in the example there are three terms $$ a x^3, \ b x y, \ -c x^7 y^2 $$ is there any possibility to decompose the full expression to               A = {a x^3, b x y, - c x^7 y^2}


title: Buttons Which Change Color, Each Time Pressed

text: I need to have 100 buttons, which their color is defined by the parity of number of times they are pressed: If they're pressed an even number of times their color is blue, and otherwise red. I don't know how to use 'Button' and 'Dynamic' to do so. Thanks in advance.


title: Rounding values

text: In _Mathematica_ 8 when I enter `1 - 0.99 - 0.01` I get `8.67362*10^-18` instead of zero. How do I fix this problem? I am getting imaginary solutions because of this error in my program.


title: Moving maximum function?

text: How can I construct a moving maximum function? For example, if I have a list of 12 values: `{ 5, 6, 9, 3, 2, 6, 7, 8, 1, 1, 4, 7 }` and I want to maximize over 3 values then the expected result would be: `{ 6, 9, 9, 9, 6, 7, 8, 8, 8, 4, 7, 7 }`.


title: Quick way to invert a fraction

text: Over the years of using Mathematica, I find myself doing something along the lines of rewriting this: $\frac{[A^-_F]}{[A^-_U] + \frac{[H^+][A^-_U]}{\kappa_1}}$ as this: $\frac{[A^-_U] + \frac{[H^+][A^-_U]}{\kappa_1}}{[A^-_F]}$ on a constant basis. In other words, just switching the numerator and the denominator of a fraction. Copying and pasting is kind of a drag, especially when you have to do it many times, and Mathematica can be kind of persnickety when it comes to highlighting things. Is there a built in keyboard shortcut that can invert fractions automatically? If not, is there a way for me to build a custom keyboard shortcut in order to do so?


title: Pattern matching

text: This is a very simple question I hope you can help me with. I am experimenting with pattern matching. I want to write a pattern for a difference between two symbols, `a-b`, that recognises cases like `{a-2,a-2b,f[x]-g[x]}` as special cases while rejecting cases like `{a,a+b,a+2b,f[x]+g[x]}`. So I started experimenting Now when I write               MatchQ[a + 2b, a_ + b_]      It returns `True` When I write               MatchQ[a - 2b, a_ - b_]      It returns `False`, which surprises me given the first code snippet returns `True`. I imagined my question could be solved by:               mypattern = a_ - _Integer. b_.       But that doesn't seem to work. Any pointers greatly appreciated.


title: Sorting a list with secondary criterion

text: Is there an easy way to sort a list on multiple levels of criteria? By this I mean, first the list should be sorted according by criteria A (the same as using the usual sort function, `Sort[list, A[#1] < A[#2] & ]`. I am a big fan of using the pure ordering function in Sort.). However, then I want to have elements with the same value for criterion A to be sorted within their class by criterion B. In general, I would like to do this to an arbitrary depth of criteria. An example would be, given a set of colored blocks, first sort the blocks alphabetically by shape, then (maintaining that all the squares come before all the triangles) sort each cluster of shapes alphabetically by their colors. (Blue square, Purple square, Red square, black triangle, orange triangle, yellow triangle, etc.)


title: plotting a {{Latitude,Longitude}} list on top of a GIS shapefile

text: I have a dataset composed of points specified in {Latitude,Longitude} format. Call it `latlong` for the purposes of this question. It displays properly with               Graphics[{Point /@         Map[GeoGridPosition[GeoPosition[#],             "Mercator"][[1]] &, {latlong}, {2}]}]      I also have a shape file that contains the boundaries of the counties in which the `latlong` points reside. If I query `Import[demo.shp", "CoordinateSystemInformation"]`, I get               "GEOGCS" -> {"GCS_North_American_1983",        "DATUM" -> {"North_American_Datum_1983",          "SPHEROID" -> {"GRS_1980", 6.37814*10^6, 298.257}},        "PRIMEM" -> {"Greenwich", 0.}, "UNIT" -> {"Degree", 0.0174533}}      and if I just `Import` the shape file, it displays correctly on screen. I would like to display the points from `latlong` within the county borders from `demo.shp`. I have not been able to figure out how. I appreciate that this is as much a GIS question as it is a Mathematica question, but I hope somebody here can help.


title: Threading over a list of lists of lists and a list of atomic expressions

text: Although I solved the following problem using `MapThread`, I'm curious about why `Thread` does not work as I expect it to here. Given two lists of length n, where the first list is a list of lists of lists and the second is a list of atomic expressions, such as:               list1 = {{{1, 2}, {3, 4, 5}}, {{1, 3, 5}, {9, 8}}};     list2 = {"a", "b"};      and where `list1[[n]]` can contain 1 or more lists of atomic expressions. I would like to create a single list that places the nth element of the second list at the end of every sublist of `list1[[n]]`, producing:               {{{1, 2, "a"}, {3, 4, 5, "a"}}, {{1, 3, 5, "b"}, {9, 8, "b"}}}      I first tried the following               appendTo[ll_, item_] := Map[Append[#, item] &, ll];     Thread[appendTo[list1, list2]]      But this returns:               {{{1, 2}, {1, 3, 5}}, {{3, 4, 5}, {9, 8}}, {{"a", "b"}, {"a", "b"}}}      even though threading an undefined function seems to produce the right expressions:               Thread[f[a, b]]     {f[{{1, 2}, {3, 4, 5}}, "a"], f[{{1, 3, 5}, {9, 8}}, "b"]}      `MapThread` works fine:               MapThread[appendTo, {list1, list2}]     {{{1, 2, "a"}, {3, 4, 5, "a"}}, {{1, 3, 5, "b"}, {9, 8, "b"}}}      So why is `Thread` producing the behavior shown above instead of giving the same result as `MapThread`? Threading `Rule` on the same lists also produces what I expect:               Thread[Rule[list1, list2]]     {{{1, 2}, {3, 4, 5}} -> "a", {{1, 3, 5}, {9, 8}} -> "b"}