When are EvaluationNotebook[] and ButtonNotebook[] different?

I am looking for a concrete code example where `EvaluationNotebook[]` and `ButtonNotebook[]` will return different results. The docs for `ButtonNotebook` say: > If a button in a palette initiates evaluation in another notebook, then > `ButtonNotebook[]` will be the palette, but `EvaluationNotebook[]` will be > the other notebook. How can a palette button initiate an evaluation in a different notebook? A basic test where they return the same (the palette):               CreatePalette[      Button["press", Print@{EvaluationNotebook[], ButtonNotebook[]}]]      I am looking for an example where `EvaluationNotebook` and `ButtonNotebook` return different results _when invoked from the same button_. Of course `ButtonNotebook` will return `$Failed` when not invoked from a button. * * * **Addendum** I'd like to point out that this question is not merely of theoretical interest. The fact that `ButtonNotebook` exists at all suggests that it must be different from `EvaluationNotebook` in some non-trivial way. Understanding the behaviour of `EvaluationNotebook`/`ButtonNotebook` is important to create robust code that will work correctly in edge cases too. I can not see their difference, so there must be some edge case I have not thought of.


How can I get the frame ticks from DateListPlot?

`DateListPlot` very nicely chooses major and minor frame tick and frame tick label/markers. I am building a custom graphics function where either the `x` or `y` axis is time and I would like to use what`DateListPlot` provides. How can I do this without simply overlaying and using `Show`?


How to apply a tensor to a list of arguments

The problem I have is the following: Let `C` be a list of coordinates, say, `C = {x1, x2, ..., xn}` and `T` be a tensor (possibly with symmetries) defined using the `Array` command (e.g., for a tensor with $3$ covariant components):               T = Array[ tt, { dim, dim, dim}]      where `dim = n`.   Now what I want is to declare that each and every component is a function of the coordinates. Unfortunately, a command like:               T = Array[ tt[ x1, x2, ..., xn], { dim, dim, dim}]      does not work. Any suggestions?


Boundary effect of Graphics3D object Tube[]

I draw a Graphics3D object of two tubes:               Graphics3D[{Tube[{{-0.2, -1, 0}, {-0.2, 1, 0}}, 0.05],          Tube[{{0, 0, -1}, {0, 0, 1}}, 0.05]}, Boxed -> False]      And I get this: ![enter image description here](http://i.stack.imgur.com/rdTNI.jpg) Now I want to have some edge effect of the two tubes, so that more parts of the back tube are excluded by the front tube, with the desired result like this: ![enter image description here](http://i.stack.imgur.com/vZMe9.jpg) Replacing `Tube[a_]` by `{EdgeForm[{White,Thick}],Tube[a]}` does not work, is there a simple way to do?


Recursive function on list

Please consider the following: I have to deliver the weekly customer demand `data` on time. I can start to produce my products one week in advance. So I was thinking of producing always one third (=`1/Length@data`) of the customer demand of week `i` in week `i-1`:               data={500.`, 5000.`, 6000.};     result=data /.     {a_, b_, c_} :>     {(a + (b + c*1/3)*1/3)*1/3, (a + (b + c*1/3)*1/3)*2/3, (b + c*1/3)*2/3, c*2/3}      As in reality `Length@data` differs from 3 I need a function which takes `Length@data` somehow into consideration. I was thinking about:               MyFunction[data_List]:=     Module[     {L=Length@data},     data/.{list1}:>{list2}     ]      Whereas `list1` represents the pattern of length `L` and `list2` the replacement function of length `L+1` (as I start to produce one week in advance). Has anyone an idea of the easiest way of defining such a recursive function? EDIT: To see the difference between the stretched and non-stretched customer demand, please consider the following plot. Here you can see that the production level per week is lower when stretched (green line) resulting in lower average weekly capacity demand within the factory.               ListLinePlot[{Prepend[data,0],result},PlotStyle->{Dashed,Green}]


Fitting triangular function with HeavisideTheta

I have a problem fitting a triangular function (like potential vs. time in cyclic voltammetry) with a `HeavisideTheta` function. I just want to get used to `HeavisideTheta`as I have to apply it later on, on more complex curves, but I already encounter problems. This is what I have done so far:               data = {{0, 0}, {0.1, 0.1}, {0.2, 0.2}, {0.3, 0.3}, {0.4, 0.4},              {0.5, 0.5}, {0.6, 0.6}, {0.7, 0.7}, {0.8, 0.8}, {0.9, 0.9},              {1, 1}, {1.1, 0.9}, {1.2, 0.8}, {1.3, 0.7}, {1.4, 0.6},              {1.5, 0.5}, {1.6, 0.4}, {1.7, 0.3}, {1.8, 0.2}, {1.9, 0.1}, {2, 0}}          pos[x_] := a*(x - x0)          neg[x_] := -b*(x - x0)          model = neg[x]*HeavisideTheta[x - x1] + pos[x]*(1 - HeavisideTheta[x - x1]);     langfit = NonlinearModelFit[data, neg[x]*HeavisideTheta[x - x1] +                 pos[x]*(1 - HeavisideTheta[x - x1]), {a, b, x0, x1 }, x]      NonlinearModelFit returns: > NonlinearModelFit::nrjnum: The Jacobian is not a matrix of real numbers at > {a,b,x0,x1} = {1.,1.,1.,1.}. >>               Show[ListPlot[data, PlotRange -> {{-2, 2 }, {-1, 2}}], Plot[langfit[x], {x, -2, 2}]]


Deleting parts from a nested list

I have a very long nested list. Here is a short example:               list = {{1.2, {1, 1, 1, 1}, {2, 2, 2}}, {0.9, {3, 3, 3, 3}, {4, 4, 4}}, {1.4, {4, 4, 4, 4}, {5, 5, 5}}}      Now I want to cancel all entries if the first entry of each part of the list (`list[[i]]`) is > 1. So that the new list would only consist of the second part of list (`list[[2]]`)               newlist = {0.9, {3, 3, 3, 3}, {4, 4, 4}}      I have already tried my luck with `Position` and `Delete`, but with no success. Thanks a lot for your help!


Why does ImportString["1c", "Table"] eat the letter c?

I have some whitespace-separated matrix data that I read with `Import[..., "Table"]`. The data contained mixed strings and numbers (the strings are for row and column names). I noticed this weird behaviour:               ImportString["123c", "Table"]          (* ==> {{123}} *)      Mathematica ate the letter `c`!! Why? It doesn't eat any other letters:               ImportString["123a", "Table"]     (* {{"123a"}} *)          ImportString["123e", "Table"]     (* {{"123e"}} *)      What is the explanation and what is a good workaround? * * * **Update:** It seems that this happens even if the labels is quoted in the file:               ImportString["\"24c\"", "CSV"]          (* ==> {{24}} *)


Game of Life in 3D

Is there a three-dimensional cellular automaton that in some sense generalizes Conway's Game of Life? If so, how might we use the `CellularAutomaton` command to simulate it? How might we visualize it?


How to enter textual subscripts and superscripts?

When I add a sub- or superscript to a letter in a `"Text"` cell using the "Writing Assistant" palette this letter becomes `Italic`: ![screenshot](http://i.stack.imgur.com/kit5g.png) Moreover the letter "v" in the subscript is wrongly formatted as being a variable. How to typeset it as `Plain`?


Transcendental equation Non-linear how to solve

I am trying to solve the following NON linear system:                   NSolve[(5/           10)*((4*Pi*Cos[(2*Pi*y)/(Sqrt[3]*(246/100))]*             Sin[(2*Pi*x)/(246/100)])/(246/100)) + (25/16)*(x + 0) ==        0, {x, y}, Reals]      Butit seems that mathemathica do not converge.


NMinimize gives an obvious wrong value

I'm trying to minimize a function of 2 lists of the same lenght, but for now the first list has one element, the second is constant. Essentialy, this baffles me:               In[32]:= NMinimize[{estimator[{l}, {1}], l > 1.1}, {l}]     Out[32]= {-1.144, {l -> 10.5229}}     In[30]:= estimator[{10.522949782193457`},{1}]     Out[30]= 0.154163      So mathematica gives me a value and parameter, which are in no way related. I know the function is positive, since it's a transfomation of a metric. The true parameter is 4, and somewhere around that should be the minimum. This is the output of               DiscretePlot[estimator[{l},{1}], {l, 2, 8, 0.01}]      Imgur, so my function isn't a total mess and the minimum seems to be close to 4 :) **I have no idea what to do about this, any help is appreciated!** I'll start to read up on the precision part of mathematica, which i never had to care about till now. After reading Minimize failing on a polynomial, i tried all methods of NMinimize and a new random seed. Same, bad, result :(               In[43]:= NMinimize[{estimator[{l}, {1}], l > 1.1}, {l}, Method -> "NelderMead" ]     Out[43]= {-1.144, {l -> 10.5229}}     In[44]:= NMinimize[{estimator[{l}, {1}], l > 1.1}, {l}, Method -> "DifferentialEvolution" ]     Out[44]= {-1.144, {l -> 10.523}}     In[45]:= NMinimize[{estimator[{l}, {1}], l > 1.1}, {l}, Method -> "SimulatedAnnealing" ]     Out[45]= {-1.144, {l -> 10.5229}}     In[46]:= NMinimize[{estimator[{l}, {1}], l > 1.1}, {l}, Method -> "RandomSearch" ]     Out[46]= {-1.144, {l -> 10.5229}}     In[47]:= NMinimize[{estimator[{l}, {1}], l > 1.1}, {l}, Method -> {Automatic, RandomSeed -> 1} ]     Out[47]= {-1.144, {l -> 10.5229}}      For completeness, here are my functions. x is a list of generated random numbers from a csv file, constantpart should be self-explanatory :). Of course, most these sums are obsolte for M=1, but like i said, there will be 2 parameterlists with size M, if this problem is solved.               x = RandomVariate[ExponentialDistribution[4], 10000]     n := Length[x]     constantpart = Pi/n^2 Sum[Sum[Exp[-Abs[x[[j]] - x[[i]]]], {i, 1, n}], {j, 1, n}]     M = 1     g[th_, wh_] := -2 Pi/n Sum[wh[[m]] th[[m]] Sum[((1 + th[[m]]) Exp[-x[[j]]] - 2 Exp[-x[[j]] th[[m]]])/(th[[m]]^2 - 1), {j, 1, n}], {m, 1, M}]     h[th_, wh_] := Pi Sum[Sum[wh[[m]] wh[[l]] th[[m]] th[[l]] (th[[m]] + th[[l]] + 2)/((th[[m]] + 1) (th[[l]] + 1) (th[[m]] + th[[l]])), {l, 1, M}], {m, 1, M}]     estimator[th_, wh_] := g[th, wh] + h[th, wh] + constantpart      edited the sampling of x, the test evaluation and the constant part. thanks for the comments so far!


How can I get the approximate analytical solution to this simple algebra equation?

Is there a way to get the analytical form to the root of this equation `2 A e (-ArcTanh[smax/s0] + ArcTanh[(smax Cos[w \\[Zeta]])/s0]) == F0` `\\[Zeta]` is the variable to be solved and is bounded by (1/2 Pi / w, Pi / w) Thanks~


Why doesn't "Defer" work with "TableForm"?

Background:I want to create a "palette" that contains buttons that evaluate the selected part of the expression and replace the selection with the result, just like what the built-in palette _"Algebraic Manipulation"_ does. I found a way to achieve this feature in the documentation of `Button`:               Button[Defer[Expand[\[SelectionPlaceholder]]], None, BaseStyle -> "Evaluate"]      As you know, this creates a button named Expand that `Expand` the selected expression and replace it with the result.               (a + b)^5      Select the expression above and click the button, the expression will change to:               a^5 + 5 a^4 b + 10 a^3 b^2 + 10 a^2 b^3 + 5 a b^4 + b^5      I think this feature is very convenient, and I would like to create more stuff with it.e.g: create a button of this style with `TableForm`,I tried the following code:               Button[Defer[TableForm[\[SelectionPlaceholder]]], None, BaseStyle -> "Evaluate"]      Well, this is a simple imitation of the example shown above. But it gives me a button with a single **SelectionPlaceholder**. Finally,I found that `Defer` won't work with `TableForm`. When you execute:               Defer[TableForm[{1, 2, 3}]]      It gives me the `TableForm` of `{1,2,3}`. But when I use the following code:               Tableform = TableForm; Defer[Tableform[{1, 2, 3}]]      it works fine:                Tableform[{1, 2, 3}]      And then I can achieve what I want with this:               Tableform=TableForm;     Button[Defer[Tableform[\[SelectionPlaceholder]]], None, BaseStyle -> "Evaluate"]      **Q:** Could anyone gives me more details of how these things work? Bonus: How can I create this kind of " **inline execute** " palette with more complicated user-defined functions? (I would like to add it to the **Palettes Menu** , but I have no idea of where to get my user-defined function initialized every time I start the palette.) And is there any other way to create a **"inline execute"** button?


How to edit InputField while using EventHandler?

I try to edit `InputField` while using `EventHandler`'s `MouseClicked`, but the `InputField` is not editable. I tried like this `EventHandler[InputField[Dynamic[s]], {"MouseClicked" :> (Print[1])}]` When i Click on `InputField` it print 1 but the `InputField` is not editable.


Making NIntegrate behave like a listable function

I have a function defined by $$f(t)=\int\limits_0^t g(x) dx$$ $g(x)$ is a complicated function (specifically the Mittag-Leffler function which has recently been implemented in Mathematica 9 as `MittagLefflerE[a,b,t]`) and so I evaluate this integral numerically using `NIntegrate`. I want to perform two tasks with this function---Plot it as a function of the limit $t$, _and_ evaluate it's value at a number of different time instances. I have stored these values of time in a vector of the form `{t1,t2,t3,...,tn}`. Mathematica's documentation suggests that to plot the function I will have to define it as `f[t_?NumericQ] := NIntegrate[g[x],{x,0,t}]` which works perfectly fine. However, I cannot use this definition of the function $f$ to now evaluate it's value at every element of my list. I assume the issue is because `NIntegrate` is not listable. Is there any way I can get around this?


Why is there a huge performance gap using Map with more than 100 List entries

im using Map on a List like this:               cube= {{1, 1, 1}, {1, 1, 2}, {1, 1, 3}, {1, 1, 4}, ... , {5, 5, 4}, {5, 5, 5}}      Mapping the whole List with 125 entries takes like 2.5s.               AbsoluteTiming[      Map[Apply[d[[#1, #2, #3]] &, #] &, cube];      ]          {2.552146, Null}      Mapping in two sublists with less than 100 entries the whole thing takes nearly no time.                AbsoluteTiming[          Join[            Map[Apply[d[[#1, #2, #3]] &, #] &, cube[[1 ;; 99]]],            Map[Apply[d[[#1, #2, #3]] &, #] &, cube[[100 ;; 125]]]            ];           ]          {0., Null}      Why is there a huge performance gap? An how do I avoid it except splitting my list?


How to define a function of z[bar], etc

Using Displaying index as subscript on output: e.g. C[i] -> C_i with Notation[...] or Interpretation[..]? I have often ended up wanting to define functions of annotated variables to better match my whiteboard mathematics. Naively, I would want to do things like:               f[z[bar]_] := z[bar]^2;     relativez[z_, z[bar]_] := z / z[bar];      However, this doesn't work. Obviously, I can do things like               f[zbar_] := zbar^2;     f[z[bar]]      But I would prefer to have it map to my math better if a simple variation of this pattern works.


Providing a color function for ListPointPlot3D

Is there a way to write `ListPointPlot3D` expression, so when given a list of points, the the color of the points plotted is a function of the index/element number of the list? Suppose `list` contains the points to be plotted and the color function is `Blend[{Yellow, Brown}, n]`, with `n` being the index a point in `list`, then `list[[1]]` should be yellow and `list[[-1]]` should be brown. I feel like I'm almost there, but I cannot manage to combine the pieces, hope someone can help me!


Fitting composed model to experimental data

I have mathematical model based on equation: $y(x) = 1 - \sum_{b=1}^{\inf} 2c_b \sin(c_b x/L) \exp(ax) $ (1), where $c_b$ are the positive roots of equation: $c_b \cot c_b + aL = 0$ (2). $L$ is a known constant, and $a$ is parameter. I would like to fit the model to experimental data and obtain value of $a$. How to implement model based on system of such equations to _Mathematica's_ FindFit? In particular, my problem lies in the second equation, which has more than one solution, and every positive one must be accounted in eq.1. Any help appreciated.


Looking for "Longest Common Substring" solution

I'm looking for robust code to solve the "Longest Common Substring" problem. I can just code it up from that description, but I'd thought I'd ask here, first, in case someone knows of an implementation either distributed with Mathematica or available from an open source. I found a hint here that a solution might be part of the (huge) `Combinatorica` package, but a quick search of the documentation did not disclose it.


Possible to evaluate only selected cells?

Is it possible to evaluate only the selected cells programmatically that I am interested in? Say in current cell to bottom of the notebook, instead of evaluate notebook or cells?


How to obtain the orthogonal matrix that diagonalize a symmetric matrix

I have a real symmetric matrix **H** which is in symbolic form, I need a matrix **P** that can diagonalize **H** ; also **P** is orthogonal and its columns are the eigenvectors of **H**. How can I doing this in mathematica? Below is my sample matrix.                H = {{λ - u, -t, -Δ, 0},          {-t, -λ - u, 0, -Δ},           {-Δ, 0, -λ + u,  t},          {0, -Δ, t, λ + u}} // MatrixForm


How to clear all variables except one?

I have a lot of variables: $a,b,c,d, \ldots $ I want to clear the values of all of them except $b$. It's really lengthy to write               Clear[a];      Clear[c];     ...      Is there any command which clears all variables except a chosen one?


Strange double evaluation using MorphologicalGraph

(MMA 9.0.0 on Mac OS/X 10.8) Please consider the following snippet (this is as SMALL as I could make it -- my attempts at making a smaller repro-case eliminated the effect that I am investigating)               Manipulate[      With[{img =          Image@RandomVariate[           NormalDistribution[0.5 + p - p, 0.25], {25, 25}]},       With[{grf =          (* comment the following line to stop          the double-evaluation *)          MorphologicalGraph@           ColorNegate@            Image@             WatershedComponents@              Binarize@               img},        GraphicsGrid[{{img, grf}}]        ]],      (* click the + on the controller, wait a second,      and you will see double-evaluation *)      {p, 1, 10, 1,        Appearance -> "Open"}]      In the interactive block that results, press the `+` and `-` keys to advance or retract the value of `p`. If you are patient, on each press of `+` or `-`, after a delay of 1 second or so, the entire display will evaluate a second time. This behavior is rather obvious and jarring since the generated image and graph are random. If you remove the call of `MorphologicalGraph`, the behavior does not happen. Somehow, `MorphologicalGraph` seems to be (hypothetically) causing an extra evaluation step after a 'settling time'. I'd like to at least understand this behavior if not get rid of it.


Building a tree

Given a list of word characters, such as this one, I'd like to build a tree, similar to this makeTree function, but with the tree in a different format. So, for an input such as               test = {{"h", "e", "l", "l", "o"}, {"h", "o", "l", "o"}, {"h",          "e", "a"}, {"h", "e", "l", "l", "o", "s"}, {"b", "r", "o"}};      I'd like the output to be               output = StartOfString[       "h"["e"["a"[EndOfString],          "l"["l"["o"[EndOfString, "s"[EndOfString]]]]],         "o"["l"["o"[EndOfString]]]], "b"["r"["o"[EndOfString]]]]      So that               TreeForm@output      gives ![Mathematica graphics](http://i.stack.imgur.com/P4dPk.png) So far I haven't got a perfect solution, that's why I'm not posting. I know I must be missing lots of good ways to do this. What I want is not so much one single good solution, or "a fix to what I tried", but to see several ways to tackle the problem, particularly but not at all limited to elegant rule-based solutions


Handling Indeterminate Forms

I'm running a sum, the elements of which are calculated by calling functions that I wrote. The only issue is, I've implemented this pretty stupid solution where I have 4 or 5 (nested!) if statements to handle cases where mathematica returns `Indeterminate` when it should be returning "0". What I'm essentially looking for is some kind of "If" statement that returns either 0 if Mathematica returns `Indeterminate`, and evaluates to something I have implemented already otherwise. Any ideas? I've tried using combinations of the `If`/ `Check` functions, without too much luck. **Summary:** I'm trying to write an `If` statement that checks for `Indeterminate` values, and returns one of two values. Any ideas?


Getting all the countries' flags and then using them as chart labels?

What's the code to list all the world's flags?               CountryData["G8", "Flag"]      works to get those particular flags, but what about all the world's flags?               CountryData["World", "Flag"]          (* Missing["NotApplicable"] *)      This works, but seems contrived; is there a shortcut?               CountryData[#, "Flag"] & /@ CountryData[]      More importantly, is it possible to insert the flags as `ChartLabels` in, say, `BarChart`? **EDIT:** Following up on Mr. Wizard's solution, I find that some flags, when inserted as `ChartLabels`, are shifted down: ![chart with flag labels](http://i.stack.imgur.com/Cqamc.png) The rule used to create the flags is:               # -> Image[CountryData[#, "Flag"], ImageSize -> {15, 20}] & /@        CountryData[];      which is necessary in this application since the data is associated to country code. The code to generate the bar chart is somewhat lengthy and irrelevant, but essentially, it just calls `ChartLabels` to insert the images. Any idea why Philippines and United Kingdom are translated downwards? A related question is how to rotate the flags $90^\circ$ to render the `BarChart` on its side.


Replace distinct values of list with values of another list

First of all I´m new to Mathematica; I´m trying to exchange distinct values of a list with values of another list (piecewise). I thought `ReplacePart` in combination with `Position` will do it, but it doesn´t yield the wanted result. Here is an example: original data:               data = Table[RandomInteger[]*100, {x, 0, 20}, {y, 0, 20}, {z, 0, 20}];      next get the position:               posSelect = Position[data, a_ /; a == 100, {3}, Heads -> False];      generate 2nd list:               lengthSelect = Length[Extract[data, posSelect]];     newVal = RandomInteger[1, lengthSelect];      updated list               data2 = data     data2 = ReplacePart[data, posSelect -> newVal];      data2 now contains at each selected position the entire elements of newVal. What is wrong with this approach? How to correctly exchange these selected values with the values of the 2nd list?


Combining list x-y data with a list of errobars into one list (mathematica-style)

Suppose I have a list of data I can ListPlot:               { {x1,y1}, ... }      , and a list of y-errorbars:               {erry1, erry2, ... }      Is there a nice, high level way to make it into a list for ErrorListPlot:               { {{x1,y1}, ErrorBar[erry1]}, ... }      It of course easy to do it through iteration in Table, however I keep reading about, how it is not the right way in Mathematica to use iterations (at least over lists).


How to read from /dev/random?

I am looking to read a few bytes from `/dev/random` on OS X and Linux. The simplest approach fails on both operating systems (see below). Why? What is a workaround?               In[1]:= random = OpenRead["/dev/random"]          During evaluation of In[1]:= OpenRead::noopen: Cannot open /dev/random. >>          Out[1]= $Failed          In[2]:= BinaryRead["/dev/random", "Integer32"]          During evaluation of In[2]:= BinaryRead::nffil: File not found during BinaryRead[/dev/random,Integer32]. >>          Out[2]= $Failed


Height average between 4 points

I have a $3D$ space, if I had a square in this space:               square = {{ 0, 0, 100}, { 100, 100, 50}, { 0, 100, 22}, { 100, 0, 86}};      how could I get the average height of any point in this field where `0 < x < 100` and `0 < y < 100`? For example I want the `z` value on `x == 40 && y == 33`.


Why doesn't PatternTest work with Composition?

While playing around with the solutions to this question, I've found some very strange behaviour:               MatchQ[3,_?Composition[Not,OptionQ]]     (*     ==> False     *)     MatchQ[3,_?(Not[OptionQ[#]]&)]     (*     ==> True     *)     Composition[Not,OptionQ][3]     (*     ==> True     *)      So what's wrong with the first pattern? Or did I just find some bug?


How to use Function[] in MatchQ[] and control argument's evaluation?

> **Possible Duplicate:**   >  Why doesn't PatternTest work with Composition?               x := 2*3;     In[84]:= MatchQ[x,_?Function[Null,NumericQ@Unevaluated@#,HoldAll]]     Out[84]= False     In[83]:= MatchQ[x,_?(Function[Null,NumericQ@Unevaluated@#,HoldAll])]     Out[83]= True      Why the difference? Why the `#` is highlighted in front-end, indicating there is syntax error? What's the best way to use a `Function[]` in `MatchQ[]` to validate an expression by pattern matching its unevaluated form?               In[126]:= NumericQ[HoldAllComplete[2*3]]     Out[126]= False      What to put in `<test>` so the following return `False`?               MatchQ[x,_?<test>]


How to apply multiple/complicated requirements for a pattern in a function input

In this question. I suggested that to test whether the input of a function was a matrix of numbers one could create the following test:               matrixnumQ[exp_] := MatrixQ[exp, NumericQ]      and then define the function as:               myfunction[W_?matrixnumQ]:=W      This is simple enough in this case but is there a way to test patterns on inputs in a single line if the pattern test is more complex than that above. Something like:               myfunction[W_?MatrixQ[#,NumericQ]&]:=W      This clearly doesn't work but just to give you the idea of what I'm looking for


A function that only evaluates on lists of pairs

> **Possible Duplicate:**   >  Why doesn’t PatternTest work with Composition? I'd like my function to only evaluate when the argument is a list of pairs. It seems like `Repeated` and a question mark should work:               fourPears[argument_?MatchQ[#, {{_, _} ..}] &]      but it does not. What's wrong with this?


Why does my function defined with constraints on patterns not work?

> **Possible Duplicate:**   >  Why doesn't PatternTest work with Composition? My function is something like this,               a[x_Real?(# > 0) &] := Plot[x*Sin[y], {y, 0, 10}];      But, `a[5]` returns nothing but `a[5]`. This function doesn't work either,               a[x_Real/;(# > 0) &] := Plot[x*Sin[y], {y, 0, 10}];      I'm very much confused. Can anybody tell me why these won't work?


Efficient way to give symbolic elements symmetry

I have a symbolic expression that represents a set of operators. These operators have quite a bit of symmetry to simplify expressions:               A[{1,2},{3,4}]==A[{3,2},{1,4}]==A[{1,4},{3,2}]==A[{3,4},{1,2}]     S[{1},{2}]==S[{2},{1}]      I will use the first term of the series to denote positions.               3->"d"     A[{1,2},{"d",4}]      So for example:               In:     temporary=S[{1}, {2}]*v[{1, 2}, {3, 4}]      + S[{2}, {1}]*v[{3, 2}, {1, 4}]      + S[{2}, {1}]*v[{3, 4}, {1, 2}]          Out:     3*S[{1},{2}]*A[{1, 4}, {3, 2}]      At current I simply have replacement rules that move indices in a logical way for example:               temporary//.{     x_[{x1_, x2_}, {x3_, x4_}] /; (!condition[x1,x3]) :> v[{x3, x2}, {x1, x4}]     }          (*Condition is a statement that checks the order of indices, for example       if x1="b" and x3="a" it would return false and so the expression would be      reordered so that "a" is now in position 1 and "b" in position 3.*)      It seems if there has to be a better way to do this. Bonus: Is there a simple way to find the original of a unique value. Say `Unique[a]=a$532 unUnique[a$543]=a`.


Question about usage of Style as Dynamic object

I saw a `Dynamic` snippet in this answer, which wrote > >     DynamicModule[{font}, >      Row[{PopupMenu[Dynamic[font], >         FE`Evaluate[FEPrivate`GetPopupList["MenuListFonts"]]], Spacer[20], >         Style["The quick brown fox", 20, FontFamily -> font]}]] >   Things confusing me most are that I thought the `Style[ ... ]` part should be wrapped in a `Dynamic[ ... ]`, but to my surprise it doesn't need one in the above code for (at least looks like) working correctly! So I did some experiments in Mathematica 9: **Working:**               DynamicModule[{col},      Row[{        PopupMenu[Dynamic[col], {Red -> 1, Blue -> 2}],        Style["text", FontColor -> col, 20]        }]      ]          DynamicModule[{col},      Row[{        PopupMenu[         Dynamic[col], {RGBColor[1, 0, 0] -> 1, RGBColor[0, 0, 1] -> 2}],        "\!\(\*StyleBox[\"\\\"text\\\"\", Rule[FontColor, $CellContext`col$$]]\)"        }]      ]      **Not Working:**               DynamicModule[{col},      Row[{        PopupMenu[Dynamic[col], {Red -> 1, Blue -> 2}],        col        }]      ]          DynamicModule[{col},      Row[{        PopupMenu[Dynamic[col], {Red -> 1, Blue -> 2}],        Style["text", col, 20]        }]      ]          DynamicModule[{col},      Row[{        PopupMenu[         Dynamic[col], {RGBColor[1, 0, 0] -> 1, RGBColor[0, 0, 1] -> 2}],        "\!\(\*StyleBox[\"\\\"text\\\"\", $CellContext`col$$]\)"        }]      ]      **Questions:**   * Why is this `Dynamic`-wrapping-free behavior of `Style`? My personal suspicion is, a _proper_ form ( _i.e._ with explicit option names) of `Style[ ... ]` is handled by the FrontEnd. Please correct me if I'm wrong.   * Should I take advantage of this feature(?), or should I generally avoid it?


How to remove selected wire frames from bounding box in 3D plots?

In 3D plots one can eventually hide the whole bounding box by the use of option `Boxed -> False`. How to remove only a selected part of the wire frame that surrounds the plot?


Performance of Dispatch and lists of Rules

_The issue outlined here seems to be no longer present in version 10, if you use a`Dispatch` table! This because a `Dispatch` table is now an atom._      My question arose when I tried to answer this question by Mr.Wizard Consider these definitions               Clear @@ Names["x" ~~ DigitCharacter ..]     rules2 = Array[Symbol["x" <> ToString[#]] -> # &, 100000 ];     dRules2 = Dispatch[rules2];      We have               AbsoluteTiming[Symbol["x" <> "100000"] /. dRules2]      > >     {0.000956,100000} (*version 9*) >     {0.000022,100000} (*version 10*)   >                 AbsoluteTiming[Symbol["x" <> "100000"] /. rules2]      > >     {0.005132,100000} (*version 9*) >     {0.100221,100000} (*first time version 10*) >     {0.014408,100000} (*after first time version 10*) >   It was to be expected that the dispatch tables are faster. It seems `Dispatch` tables became faster in V10, but regular replacement by a long list of rules become considerably slower. That is not the point here however, point is that the following breaks the dispatch table in version 9.               Update[x10]     AbsoluteTiming[Symbol["x" <> "100000"] /. dRules2]      > >      {0.076655,100000} (*version 9*) >      {0.000026,100000} (*version 10*) >                 Update[x10]     AbsoluteTiming[Symbol["x" <> "100000"] /. rules2]      > >      {0.017523,100000} (*version 9*) >      {0.063556,100000} (*version 10*) >   Where all the evaluations have slowed down substantially (except there is no "first time delay" in version 10). The version 9 dispatch table is slower than the regular list of rules. I do not expect many people to use `Update`, but this should still be relevant to many people, as I believe an assignment causes an update. See an example further below. I found out that updating a variable present in the list of rule causes the expression (list/dispatch table) containing the rules to be rebuilt. This takes a long time. We can see that the rules get rebuilt from the following examples. Let               rules = {y1 -> 1, y2 -> 2, y3 -> 3};      Then               Trace[y1 /. rules, TraceOriginal -> True]      > >     {y1/. rules,{ReplaceAll},{y1},{rules,{y1->1,y2->2,y3->3}},y1/. > {y1->1,y2->2,y3->3},1} >   and               Update[y3]     Trace[y1 /. rules, TraceOriginal -> True]      > >      {y1/. > rules,{ReplaceAll},{y1},{rules,{y1->1,y2->2,y3->3},{List},{y1->1},{y2->2}, >      {y3->3,{Rule},{y3},{3},y3->3},{y1->1,y2->2,y3->3}},y1/. > {y1->1,y2->2,y3->3},1} >   In the second case we see the Trace is longer. We basically see that the expression `rules` gets rebuilt. The rule containing `y3` gets a little more attention. An example where this does not happen is the following. Let               blockRules = {HoldComplete[x, 1], HoldComplete[y, 2],         HoldComplete[z, 3], HoldComplete[x, 4]};      Then we have               Equal @@ {Trace[Cases[blockRules, _[x, y_] -> y, 1, 1],          TraceOriginal -> True]        Update[z];        Trace[Cases[blockRules, _[x, y_] -> y, 1, 1],         TraceOriginal -> True]}      > >     True >   despite the fact that we updated. HoldComplete prevents the tracking of symbols and therefore the expression does not get rebuilt. The point is that I find this behaviuor of `Dispatch` (and also the lists of rules) very troubling. Note that HoldPattern will not save you, it does not have attribute HoldAllComplete, so even lists of rules with this wrapper will get rebuilt. Lists of rules will always contain many symbols, so the risk of updating one is very high I'd say. To be complete, here is an example using HoldPattern. We have               hPRules = {HoldPattern[y1] -> 1, HoldPattern[y2] -> 2,         HoldPattern[y3] -> 3};     Unequal @@ {Trace[y1 /. hPRules, TraceOriginal -> True], Update[y3];        Trace[y1 /. hPRules, TraceOriginal -> True]}      > >     True >   The same happens for assignment. To be really complete, here is another example               Composition[Length,        Flatten] /@ {Trace[y1 /. hPRules, TraceOriginal -> True], y3 = 2;        Trace[y1 /. hPRules, TraceOriginal -> True]}      > >     {7, 18} >   Where again our list of rules got rebuilt. Well I guess the questions are a bit contrived. To share my worries was the main point. But here it is I guess: In version 9, should we be very careful with `Dispatch` and lists of `Rule`s? Does anybody know a good way around this?


Measuring the area of non analytical regions in a plot

As the title says, I want to measure the area of different closed regions in a plot. Let me be more specific by giving a characteristic example. In the following figure, we observe that inside the black closed curve several regions (islands) depicted with different colors appear. ![enter image description here](http://i.stack.imgur.com/MpNDW.png) The outermost black limiting curve has an analytical expression and can be obtained by a simple contour plot. On the other hand, all the internal color islands do not have analytical expressions and are created using `ListPlot` for plotting all the consecutively points forming each island. Now, I want to obtain, at least a rough estimation about the percentage of the total area occupied by the different islands. In other words, to know how "big" are the different sets of islands. In the particular example we can distinguish five different types of islands: (i) the central blue one; (ii) the central green one; (iii) the set of four purple islands; (iv) the set of three orange islands; (v) the set of two elongated red islands. So, my question: Is there a way to compute the percentage of the total area occupied by each of these sets of islands using Mathematica? Using a FORTRAN code I can compute these percentages. However, this is a very time consuming procedure, since I have to define a dense grid of points inside the closed curve, then integrate each one and finally classifying them into different types thus counting the required percentages. So, I would be really very grateful, if I could speed up this task by using Mathematica. The exact percentages as they have computed by the FORTRAN code are: blue ---> 15.44%, green ---> 15.76%, red ---> 5.82%, magenta ---> 1.76%, orange ---> 9.66%, All the data files and the Mathematica notebook used to create the above plot can be found here: Files


How to calculate the area of a listplot

I need to calculate the area enclosed in a two-dimensional listplot and following an answer to a similar question I tried this way:               imgnorm = (mnorm =      MorphologicalComponents[      Erosion[Binarize[        ListLinePlot[{list}, ImageSize -> Large, Axes -> False]],        0.5]]) // Colorize          listareas = {area1 = 1/. ComponentMeasurements[{mnorm, imgnorm}, "Area"], area2 = 2/. ComponentMeasurements[{mnorm, imgnorm}, "Area"]}      It works fine, however it is not precise enough for what I need to do because part of the area is taken by the black line. The list is quite big and the points don't form a polygon. EDIT: Here is the plot: ![list plot](http://i.stack.imgur.com/DOsRf.jpg) Any help would be appreciated, thank you in advance.


How do I obtain the enclosed area of this particular parametric plot?

I'm trying to find a way to obtain the enclosed area of this particular plot. Can someone show me how?               curveplot = ParametricPlot[{Sqrt[Abs[Cos[t]]] Sign[Cos[t]],      Sqrt[Abs[Sin[t]]] Sign[Sin[t]]}, {t, 0, 2 π},      PlotStyle -> {{Thickness[0.01`], Darker[Purple]}},      AspectRatio -> Automatic, PlotRange -> All, AxesLabel -> {"x", "y"}]      ![Parametric Plot](http://i.stack.imgur.com/UWb4w.png)


Finding the centroid of the area between two curves

When I have an area bounded by curves, is there a built-in way to find the center of the area? Or do I have to plot it first and then use `ComponentMeasurements` on it? For example: the area under $y= 1-x^2/4$ and above the $x$ axis: ![my region](http://i.stack.imgur.com/yj80Q.png)


How can I get Mathematica to write Log instead of ArcTan?

`ArcTan` really bothers me, so is there a way to make _Mathematica_ write `Logarithm` instead of `ArcTan`? What I'm after is some kind of a `ArcTan` to `Log` converter such as the following list from Wiki


Color based on (discrete) derivative of function

I am making a very basic stock simulation. I want `ListLinePlot` to color my stock viewer based on whether the price went up or down from the previous price. Here is what I have:               RemoveScheduledTask[ScheduledTasks[]];     price = 100;     time = 0;     nextPrice := price += 2Random[]-1;     nextTime := time += Random[];     data = Table[{nextTime, nextPrice},{i,1,1000}];     Dynamic@ListLinePlot[         data,         ImageSize->1000,         PlotRange->{{time-525,time+25}},         ColorFunction->Function[If[Last@data[[-2]]<Last@data[[-1]], Green, Red]]     ]     RunScheduledTask[         data = Rest[data];         AppendTo[data,{nextTime,nextPrice}];,         .1     ];      Currently this code makes the graph all one color (not what I want). Does anyone know how to implement the functionality that I want? Also any general code improvements are very welcome (I feel like the way I am pushing/popping `data` is inefficient).


Plot maximum and minimum temperature of a day for range of time interval

How to display (in any graphic representation) the maximum and minimum temperatures for one city in one of these selected time periods over the 5-day period? The time periods are:   * Morning (06:00 to 12:00)   * Afternoon (12:00 to 16:00)   * Evening (16:00 to 20:00)   * Night (20:00 to 06:00 the next day).  I'd like the x-axis to show the date and the y-axis to show temperatures. I already wrote a small bit of code which can find the mean in a given time interval               Mean[Select[       Flatten[        WeatherData[         "Your_City_Name",          "Temperature", {{2012, 11, 5, 6, 0}, {2012, 11, 5, 12, 0}}]        , 1], NumberQ       ]      ]


Symbolic derivatives of special functions yield incorrect results

When I evaluate with _Mathematica_ this expression               D[ Abs[ Zeta[x + I y]], {x, 2}] + D[ Abs[ Zeta[x + I y]], {y, 2}]      > >     0 >   the result is zero which is an error.   Could you explain what's wrong?


Increasing the size of numbers in a legend bar

I would like to know how you go about increasing the size of numbers which appear in a legend to make them larger than the default (which is too small for publication purposes). Example:               ContourPlot[Fn[1, 0.1, n, v], {v, 0.1, 5}, {n, 0.1, 1},        ClippingStyle -> Automatic,       PlotPoints -> 100,        ColorFunction -> "BlueGreenYellow",        LabelStyle -> Directive[Thick, Large],        FrameLabel -> {Style["V", Large], Style["n", Large]},        PlotLabel -> Style["(a)", Large],       PlotLegends -> Automatic]


How to generate a list with a loop, and put it into a variable?

I am pretty new to _Mathematica_ and to coding in general. I want to do a very specific thing, but I unable to do it. Please explain in detail how I can make this work. Here's the details on what I am trying to do: I have the following matrix, which included two variables which are lists in themselves, to analyze these lists using loops I want to make a list of lists using a loop so that the OUTPUT of the function will be this:               matrix = {       {{0, 1}, {-b3 - gain11[[1]]/m, -a3 - gain22[[1]]/m}},       {{0, 1}, {-b3 - gain11[[1]]/m, -a3 - gain22[[2]]/m}},       {{0, 1}, {-b3 - gain11[[1]]/m, -a3 - gain22[[3]]/m}},       {{0, 1}, {-b3 - gain11[[2]]/m, -a3 - gain22[[1]]/m}},       {{0, 1}, {-b3 - gain11[[2]]/m, -a3 - gain22[[2]]/m}},       {{0, 1}, {-b3 - gain11[[2]]/m, -a3 - gain22[[3]]/m}},       {{0, 1}, {-b3 - gain11[[3]]/m, -a3 - gain22[[1]]/m}},       {{0, 1}, {-b3 - gain11[[3]]/m, -a3 - gain22[[2]]/m}},       {{0, 1}, {-b3 - gain11[[3]]/m, -a3 - gain22[[3]]/m}}     }      As you may have noticed, it's the same list repeated 9 times, where it fetches data from two lists, from `gain11` and `gain22`, each with three elements, so that all possible combinations have been made. I have tried to use               For[i = 1, i < 4, i++,       For[j = 1, j < 4, j++, {{0, 1}, matrix = {-b3 - gain11[[i]]/m, -a3 - gain22[[j]]/m}}]]      but all that does is overwrite itself. I end up with only the last value. Help would be appreciated.


How can I create an advanced grid interface on Mathematica?

Working on a CDF for report creation, I miss having a nice grid interface, where I would have basic operations like being able to sort a columns by clicking on the columns head (ascending and descending), or maybe group and ungroup data. This is a great example of what can be done in _Mathematica_ , but the code is not avaliable.


Why PlotLegends doesn't give the legends ？

I am using Mathematica 9. The problem I have is with plotlengends, in particular,               g2 = ListPlot[{{2, 1}, {3, 4}, {3.5, 4.2}, {4, 6}},        PlotStyle -> {Dashing[Large]}, PlotLegends -> {"Dashed"},        Joined -> True];     g1 = ListPlot[{{2, 1}, {3, 4}, {3.5, 4.2}, {4, 6}, {4.5, 6.6}, {5,          7}, {6, 9}, {8, 11}}, Joined -> True, PlotStyle -> {Dotted},        PlotLegends -> {"Dot"}];     Show[g1, g2]      ![enter image description here](http://i.stack.imgur.com/sQODN.png) As you can see, the problem is that looking at this lengends, there is no way you can tell which curve coresponds to which one in the legends (for instance, is the dash curve coresponds to the top legend or the bottom legend?). Changing the color will not work because this plot has to be in black and white only. Please help.


Why Trace[] shows some internal warnings on a standard Plot command in V9?

For fun, I like to use `Trace` with option `TraceInternal->True` to see if I figure how some of the commands work internally. I just noticed something strange. In Version 9, I got lots of what seem like error messages that I do not get in Version 8. This example below is using `Plot` (I have not tried many other commands, will do that later). Consider the most basic plot. See the difference in Trace between V8 and V9:                  Trace[Print@Plot[Sin[x], {x, -Pi, Pi}], TraceInternal -> True]      ![enter image description here](http://i.stack.imgur.com/qAwyF.png) ofcourse, the command works just fine at the end in V9, and one gets the plot. So these messages do not affect the final result, and hence, from a user point of view, one can argue that they should not matter as long as the final result is the same. They could be some internal trace messages that are left there in final build or such? I am just curious, that is all, if someone might know what they could mean, since they do indicate some sort of an error condition, yet final plot is just fine.


Exporting summation of interpolating functions to excel

I search the forum and found a question about exporting interpolating functions to excel. Unfortunately, I can't use it to export the results to excel. This is the equation : `u = StateResponse[ssm, UnitStep[t] , {t, 0, 1},Method -> {"NDSolve", MaxSteps -> 1600000}]` and the answer is : `11.2822InterpolatingFunction[{{0.,1.}},<>][t]+0.1206InterpolatingFunction[{{0.,1.}},<>][t]+34.117InterpolatingFunction[{{0.,1.}},<>][t]+2.335InterpolatingFunction[{{0.,1.}},<>][t]+63.1235InterpolatingFunction[{{0.,1.}},<>][t]+5.8206InterpolatingFunction[{{0.,1.}},<>][t]` I would appreciate that someone can help me to export this equation to a excel file.


Break[] inside ColorFunction

f[x_?NumericQ]:= (Do[Break[],{i,1,2}];x)     Plot[x,{x,0,1},ColorFunction->(ColorData["Rainbow"][f[#]]&)]      > Break::nofwd: No enclosing For, While, or Do found for Break[]. What's going on here? I've tried setting `HoldFirst` attribute on `f` and I've also tried using `Unevaluated` which gives surprising results:               (* Works fine, gives plot colored as expected *)     Plot[x, {x, 0, 1},       ColorFunction -> (Unevaluated[ColorData["Rainbow"][f[#1]]] &)]          (* Gives a black and white plot with error:        "Unevaluated is not a Graphics primitive or directive" *)     ListContourPlot[IdentityMatrix[3],       ColorFunction->(Unevaluated[ColorData["Rainbow"][f[#1]]]&)]      **Edit** This on the other hand works:               Plot[x,{x,0,1},ColorFunction->Function[c,ColorData["Rainbow"][f[c]]]]      Which only difference is that it uses `Function[c,ColorData["Rainbow"][f[c]]]]` instead of `Function[ColorData["Rainbow"][f[Slot[1]]]]]`


Are you interested in purchasing David Wagner's "Power programming with Mathematica"?

I recently contacted McGraw-Hill to see if they have a mechanism in place for printing out-of-print books that are still of interest. Specifically, I asked about "Power programming with Mathematica" by David Wagner, as I am personally interested in obtaining a copy, and suspect that others might also be interested. Here is the literal response I received from McGraw-Hill: > Good morning Todd, > > If there was a high enough demand for the book there is a possibility. If > you can let me know how many you're looking for, and the name of the school > or business you're with I can contact the editor and check to see if there's > something that can be done. > > McGraw-Hill Education * * * First, please don't get your hopes up, as nothing may come of this; however, I am committed to seeing this through if there is sufficient community support to get the publisher to make it available again, if only for a limited time. If you would be interested in purchasing a copy of Wagner's text, please respond in the affirmative by making a comment to this question, such as "yes, I would like to purchase a copy." In this way, I can directly "show" our community's interest to the publisher. At this time, I can't speak to cost, but it is clear that we need a "critical mass" to get the publisher's attention to make it worthwhile. Keep your fingers crossed and show your support!


Logarithmic scale in the legend of a ListContourPlot

Is there a way to use a logarithmic scale in the colour legend of a `ListContourPlot`? The contours can be logged by taking the `Log10` of the data, but this doesn't transfer to the legend. As an example, with the code:               test = Flatten[Table[{i, j, Log10[RandomReal[{0, 1*^10}]]}, {j, 1, 100}, {i, 1, 100}], 1];          ListContourPlot[test, InterpolationOrder -> 0, PlotLegends -> Automatic,          Contours -> 20, ColorFunction -> "Rainbow", ColorFunctionScaling -> True,          PlotRange -> All]      ![Mathematica graphics](http://i.stack.imgur.com/Wv8Rt.png) I get equally spaced contours for values <7, 8, 9 and 10. Could I plot these data with equally spaced contours corresponding to values 0.1, 1 and 10? * * * Another example, where you'd expect to see logarithmic data:               test = Flatten[Table[{i, j, Log10@Exp[-(i + j)^2]}, {j, 1, 10}, {i, 1, 10}], 1];     ListContourPlot[test, InterpolationOrder -> 0,       PlotLegends -> Automatic, Contours -> 20, ColorFunction -> "Rainbow",       ColorFunctionScaling -> True, PlotRange -> All]      ![Mathematica graphics](http://i.stack.imgur.com/uUmAm.png)


When is the output of examples in function documentation rasterized?

Upon building documentation in Workbench, Workbench sometimes converts the output of examples on function pages into rasterized images, and sometimes not. Does anybody know what controls this behavior? For example, say if we have a package containing the following code:               MakeBoxes[tensor, StandardForm] = InterpretationBox[         StyleBox@GridBox[             {{                 "T",                  StyleBox@GridBox[{{"a"}, {"b"}}]             }},              ColumnSpacings -> 0.05         ],          tensor     ];          TestSymbol[n_] := Table[tensor, {n}];      And let the documentation notebook of TestSymbol contain the following examples:               TestSymbol[1]     TestSymbol[2]     TestSymbol[3]     TestSymbol[4]     TestSymbol[5]     TestSymbol[6]      The output of the first 5 examples are left untouched by the documentation build process, but somehow output of the 6th gets rasterized. (And for any `TestSymbol[n]`, with `n > 5` for that matter). The culprit seems to be the `ColumnSpacings` option; if I remove that then none of the output gets rasterized. I tried digging through the documentation tools source code, but unfortunately that was like searching for a needle in a haystack. Does anybody have a clue what's causing this behavior?


Problem using replace to simplify logarithms

Is there a way to combine logarithm terms like               9 m Log[m]-9 m Log[M]+16 m M Log[m]-16 m M Log[M]      into               9 m Log[m/M] + 16 m M Log[m/M]      ? I've tried using normal replacement rules (rule=a1_ Log[a2_]-a1_ Log[a3_]->a1_ Log[a2/a3] for example) but this doesn't seem to work when the logarithms are multiplied by an integer. Thanks


Is this a bug in FunctionDomain (V.10)?

I used               FunctionDomain[1/(x^3 + 1), x, Complexes]      and got > 1 + x^3 != 0 Is this a bug in FunctionDomain (V.10)? Can I receive $x \neq -1$, $x \neq \dfrac{1-\sqrt{3}I}{2}$ and $x \neq \dfrac{1+\sqrt{3}I}{2}$? With _Maple_ , I tried ![enter image description here](http://i.stack.imgur.com/Smkbo.jpg) If I used               FunctionDomain[1/(x^3 + 1), x]      I got true answer > x < -1 || x > -1


Select Solution with real (positive, etc) coefficients - ignoring variables

I often need to solve equations for numerical coefficients while preserving numerous variables (e.g. to preserve scaling relations). Thus I end up with a set of solutions like $$ \left\{-\frac{(0.156113\, +0.0384783 i) d^{6/13} f^{6/13} m^{16/13} r^{9/13}}{g^{9/13} L^{6/13}}, -\frac{(0.156113\, -0.0384783 i) d^{6/13} f^{6/13} m^{16/13} r^{9/13}}{g^{9/13} L^{6/13}}, [...] , \frac{0.160785 d^{6/13} f^{6/13} m^{16/13} r^{9/13}}{g^{9/13} L^{6/13}}\right\} $$ where [...] is possible _lots_ more, ugly solutions --- while I just want the last one (for example). **How can I select only the solution with the type of numerical coefficient I want (e.g. Real, or real & positive, etc)?** Solve[eq,var, **dom** ] doesn't seem to work with 'inexact coefficients', and trying things like 'Select[...]' seem to have the same problem. I've found I can brute force proper selection if I just replace every variable with unity (i.e. {Sols} /.f->1 /.d->1 /.m->1 $...$ But that realls sucks... Any help would be appreciated, thanks!


Applying chain rule to evaluate a derivative when the component function is not differentiable at one point

I got the following question. Can anyone help me? Thanks! Y is a smooth function of X. and X is a function of r, which kinks at r=r0, but is smooth everywhere else. I was try to compute dY/dX at X=X(r0). If dX/dr exists at r=r0, then we can simply apply the chain rule to get dY/dX=(dY/dr)/(dX/dr) evaluated at r=r0. I was wondering if we can simply do dY/dX = lim_e->0 (Y(r0+e)-Y(r0-e))/(X(r0+e)-X(r0-e))=(Y'(r0+)-Y'(r0-))/(X'(r0+)-X'(r0-)), where Y'(r0+) and Y'(r0-) are right and left derivative of Y w.r.t. r at r=r0, and similarly for X'(r0+) and X'(r0-))


Multiply list of pure functions by list of scalars?

I am trying to write a function that returns a list of pure functions. The last step in the function, is to multiply the list of pure functions by a list of scalars (i.e. matrix multiplication). When I try to evaluate the resulting functions, it does not work. **Code**               calcShapeFunctions[nnpe_] := Module[        {m, xiCoord, etaCoord, p, c},        m = Array[          Function[{xi,              eta}, {1, xi, eta, xi*eta, xi^2, eta^2, xi^2*eta, xi*eta^2,               xi^2*eta^2}[[#]]] &, nnpe];        xiCoord = {-1, 1, 1, -1, 0, 1, 0, -1, 0};        etaCoord = {-1, -1, 1, 1, -1, 0, 1, 0, 0};        p = m[[1 ;; nnpe]];        c = Array[Through[p[xiCoord[[#]], etaCoord[[#]]]] &, nnpe];        Return[p.Inverse[c]];        ];      **Incorrect Output**               Through[calcShapeFunctions[3][x, y]]      returns: > {(1/2 Function[{xi, eta}, {1, xi, eta, xi eta, xi^2, eta^2, xi^2 eta, xi > eta^2, xi^2 eta^2}[[1]]] - 1/2 Function[{xi, eta}, {1, xi, eta, xi eta, > xi^2, eta^2, xi^2 eta, xi eta^2, xi^2 eta^2}[[2]]])[x, y], (1/2 > Function[{xi, eta}, {1, xi, eta, xi eta, xi^2, eta^2, xi^2 eta, xi eta^2, > xi^2 eta^2}[[2]]] - 1/2 Function[{xi, eta}, {1, xi, eta, xi eta, xi^2, > eta^2, xi^2 eta, xi eta^2, xi^2 eta^2}[[3]]])[x, y], (1/2 Function[{xi, > eta}, {1, xi, eta, xi eta, xi^2, eta^2, xi^2 eta, xi eta^2, xi^2 > eta^2}[[1]]] + 1/2 Function[{xi, eta}, {1, xi, eta, xi eta, xi^2, eta^2, > xi^2 eta, xi eta^2, xi^2 eta^2}[[3]]])[x, y]} **Desired Output**               Through[calcShapeFunctions[3][x, y]]      should return: > {1/2 - x/2, x/2 - y/2, 1/2 + y/2} **Further Thoughts** Assuming we can get this to work, how would I go about obtaining the derivatives of the pure function with respect to one of its independent variables (xi and eta)?


AbsoluteTiming affected by surrounding code

In the process of simplifying code posted for another question, I noticed `AbsoluteTiming` returned different results for the same code being timed, `Range[0, 99]`, when the surrounding code was different. It was constantly different. What is going on? Is `Map` caching and `Do`-`AppendTo` not? Is the call to `Range[0, 99]` close enough to to cost to retrieve the value from the cache so the sum of timing is only off by ~0.01? I have changed the order, `Map` then `Do`-`AppendTo`, and still the `Map` is faster by ~0.01. I also tried substituting `Range[0, Mod[i++, 10000]]` to negate the caching effect, same results. I tried timing different code and noticed the same difference. * * *               iterations = 10000;     times1 = {};     Do[AppendTo[times1, AbsoluteTiming[          Range[0, 99]          ][[1]]]       , {iterations}];          times2 = Map[        AbsoluteTiming[           Range[0, 99]           ][[1]]         &, Range[1, iterations]];               PrintStats[times_] :=      Print["Sum: ", Fold[Plus, 0., times], "  Min: ", Min[times],        "  Max: ", Max[times], "  Mean: ", Mean[times], "  StdDev: ",        StandardDeviation[times]]          PrintStats[times1];     ListPlot[times1, PlotRange -> All]     Histogram[times1]          PrintStats[times2];     ListPlot[times2, PlotRange -> All]     Histogram[times2]      _Summary Results of Five Runs:_ Do-AppendTo:               Sum: 0.042083  Min: 3.*10^-6  Max: 0.000029  Mean: 4.*10^-6  StdDev: 0.*10^-7     Sum: 0.039829  Min: 2.*10^-6  Max: 0.000019  Mean: 4.*10^-6  StdDev: 0.*10^-7     Sum: 0.041112  Min: 2.*10^-6  Max: 0.000030  Mean: 4.*10^-6  StdDev: 0.*10^-7     Sum: 0.042261  Min: 0.  Max: 0.000043  Mean: 4.2261*10^-6  StdDev: 1.07875*10^-6     Sum: 0.040704  Min: 3.*10^-6  Max: 0.000025  Mean: 4.*10^-6  StdDev: 0.*10^-7      Map:               Sum: 0.030643  Min: 2.*10^-6  Max: 0.000012  Mean: 3.*10^-6  StdDev: 0.*10^-7     Sum: 0.030974  Min: 2.*10^-6  Max: 0.000014  Mean: 3.*10^-6  StdDev: 0.*10^-7     Sum: 0.030379  Min: 0.  Max: 0.000012  Mean: 3.0379*10^-6  StdDev: 5.08615*10^-7     Sum: 0.030504  Min: 2.*10^-6  Max: 0.000012  Mean: 3.*10^-6  StdDev: 0.*10^-7     Sum: 0.030612  Min: 2.*10^-6  Max: 0.000012  Mean: 3.*10^-6  StdDev: 0.*10^-7      _Detailed Results of First Run:_ ![enter image description here](http://i.stack.imgur.com/uHK16.png)


overriding the format of 'copy-as' latex?

In the answer to Bold face formatting for vectors instead of overarrows like latex \mathbf{}? was a nice method of specifying the visual display for a variable, so that I can do something like the following to generate display output for vectors in the way that I want it:               Clear[vecX]     Format[boldVector[v_]] := Style[HoldForm[v], FontFamily -> "Arial Black"]     vecX := boldVector[x]     Abs[vecX - vecX'] // TraditionalForm      Is there a way to specify how text in copy-as Latex should appear? For example, if I could do copy-as latex and have `vecX` above show up as `\vecX`, then I can have my latex macros deal with the formatting in that context:               \newcommand{\vecX}[0]{\mathbf{x}}


Exporting B Spline Function to Excel

I am trying to export the data from a B Spline Function to a table in excel. I have tried exporting as many different file types (.xls, .txt, .dat), but all of them show up in excel as all of the data in one cell. Currently, all I have successfully done is this, showing a plot of "data1", a set of ordered pairs that I imported, and the B-spline fit for this data set.               f = BSplineFunction[data1]     Show[ListLinePlot[data1, PlotStyle -> Red],       ParametricPlot[f[t], {t, 0, 1}]]      I would like to export the data from the B-spline function in a way that can be viewed as a table in Excel. Thank you.


How to round tick line ends in the plots

I would like to have rounded ticks in my Mathematica plots. They look much better for thick frames               Plot[ {Sin[x], Cos[x]}, {x, 0, 3 Pi}, Frame -> True, FrameStyle -> Directive[Black, Thick]]      gives ![plot with square tick ends](http://i.stack.imgur.com/AN7Ep.png) but I would like to round them, to get something like ![plot with round tick ends](http://i.stack.imgur.com/F3jUQ.png) There is a function `CapForm["Round"]` but it is not clear how to use it with plots.


Creating overlapping histogram plots

I am plotting two histograms on the same graph:               g1 = Histogram[bc, ChartStyle -> {Red}]     g2 = Histogram[bcx]     Show[g1, g2, PlotRange -> {{0.1, 0.6}, All}]      ![enter image description here](http://i.stack.imgur.com/3AVG7.png) But I would like the plots to overlap so that they are "see-through" and I can compare them. I've been trying with               ChartStyle -> {"Overlapped"}      which hasn't been working.


LinearSolve symbolic equations

I am trying to use mathematica to solve the following system of equation, but I can not for the life of me get it to work. I have the following:               Stiffness = ((Y*A)/L )*{{1, -1, 0, 0}, {-1, 2, -1, 0}, {0, -1,       2, -1}, {0, 0, -1, 1}} // MatrixForm          Displacements = {{0}, {a}, {b}, {0}} // MatrixForm          Force = {{x}, {(7*L^3 )/162}, {(10*L^3)/81}, {y}} // MatrixForm      I need to solve:               Stiffness * Displacements = Force      When I use LinearSolve it just spits back the input command. I need to solve for a, b, x, and y. Thanks for the help.


Graph plotting: specify layers for layered drawing

Mathematica can do layered graph drawing with `LayeredGraphPlot` or `GraphLayout -> "LayeredEmbedding"`. Is it possible to specify which node goes on which layer instead of letting the system figure this out? Determining the precise location on the layer would be left to the layout algorithm.


Package found with `Needs`, but not with `ParallelNeeds`

I want to use a self-written package in a parallel computation. However while `Needs["mypackage`"]` works without problems, `ParallelNeeds["mypackage`"]` can't open my package. The immediate reason is related to the fact that I added to `$Path`, and the package is in one of the directories I've added. `ParallelTable[$Path,{1}]` reveals that this addition is not propagated to the subkernels, despite the fact that it is changed in the user kernel init file (`$UserBaseDirectory/Kernel/init.m`), and thus long before any subkernels are launched in the Notebook. Explicitly using `DistributeDefinitions[$Path]` didn't help either. So my question is: Why isn't the $Path propagated to the kernels, and more importantly, what can I do about it?


Integral equation numerical solution with NDSolve

I'm trying to solve something like: `f[x] == Integrate[f[x]*g[x]]` where `g[x]` is known and `f[x]` is the function to solve (numerically is fine). I've seen some examples of integral equations but wonder if there is a direct way to solve it with Mathematica.


How to change the values dynamically in a grid

I am trying to write a function which creates a `Grid` which has no value in the starting and when some value is passed to it, it should show that value in that `Grid` dynamically. But it is not changing it dynamically. The two user defined functions are               createGrid[rows_, column_] := (list = {};        For[i = 1, i <= rows,i++, (individualColumns = {};        For[j = 1, j <= column,j++, (Subscript[e,i, j]="";individualColumns = Append[individualColumns,Subscript[e,i, j]];)];      list = Append[list, individualColumns];)]; layoutGrid[list])      This createGrid function generates null values which is then passed to user defined function layoutGrid.                layoutGrid[list_] :=      Panel[Grid[list, Background -> LightBlue, Spacings -> {0, 0}, ItemSize -> {0, 0},   Alignment -> {Center, Center}],ImageSize -> {780, 480}, Background -> LightBlue]      I am calling the createGrid function by passing 20 rows and 20 columns as arguments.               Dynamic[createGrid[20,20]]      It creates the `Grid` having 20 rows and 20 columns having no value. In createGrid function, variable Subscript[e,i,j], i defines the row number and j defines the column number After building the empty `Grid`,when I am assigning some value to Subscript[e,1,2] like               Subscript[e,1,2]=10;      It does not show in the `Grid` dynamically. Why?


a mysterious error in multiple symbolical integration

I am trying to do the following integration:               Ld = 2;     a1 = 0.3;     a2 = 1;              potd[R_, z_] =           -Integrate[(0.5/(2*a1)*Exp[-(Abs[z1]/a1)] +                 0.5/(2*a2)*Exp[-(Abs[z1]/a2)])*              Integrate[               BesselK[0, a/Ld]*a*                ArcSin[(2*a)/(                 Sqrt[(z - z1)^2 + (a + R)^2] +                   Sqrt[(z - z1)^2 + (a - R)^2])], {a, 0, Infinity},                GenerateConditions -> False], {z1, -Infinity, Infinity},              GenerateConditions -> False];      then I evaluate the result for different pairs of `R`, `z`. _Mathematica_ complains that > NIntegrate::inumr: The integrand a ArcSin[(2 > a)/(Sqrt[Power[<<2>>]+Power[<<2>>]]+Sqrt[Power[<<2>>]+Power[<<2>>]])] > BesselK[0,a/2] has evaluated to non-numerical values for all sampling points > in the region with boundaries {{∞,0}}. >> The point is that there is no `NIntegrate`: what does it mean? I upload the function from my notebook so you can see that I am not using a `NIntegrate`. ![image](http://i.stack.imgur.com/gME0t.jpg)


MLEvaluate() Function Gives Error

I am trying to link my C++ program to Mathematica Kernel. I am trying to use the MLEvaluate() evaluate but I receive an error while compilation. My codes are as below:               #include <mathlink.h> //mathlink header     #include <stdio.h> //standard io header     #include <iostream>     using namespace std;          /* initialising variables */     MLENV env = (MLENV)0;     MLINK link = (MLINK)0;          int main(int argc, char *argv[]) {         int errno;         int packet;         int input;              /* initialises MathLink environemnt object */         env = MLInitialize(0);              /* links the program to the MathKernel */         link = MLOpenString(env, "-linkmode launch -linkname 'C:\\Program Files\\Wolfram Research\\Mathematica\\9.0\\math.exe'", &errno);                  MLEvaluate(link,"2+2+2");              /* get packets until we find a ReturnPacket or error */         while ((packet = MLNextPacket(link)) && packet != RETURNPKT) MLNewPacket(link);              /* once the results is returned */         if (MLError(link)) printf("\nError Has Occured!\n");    //if an error is returned         else {                                                      //if an integer is returned             int result;             MLGetInteger(link, &result); //we know that the result is an integer in this case             printf("\nResult: %d\n", result);     }              printf("\nPress Enter to Exit...");         getchar(); //holds the console till users presses enter         getchar(); //holds the console till users presses enter         return 0;      } the error is get however is:               Error   1   error LNK2019: unresolved external symbol _MLEvaluate referenced in function _main  C:\Users\arvindrajan\Documents\Visual Studio 2013\Projects\MathematicaConsoleApplication\MathematicaConsoleApplication\main.obj MathematicaConsoleApplication      any advise? thanks


Clustering of 2D map, based on similarity in spectra

I have experimental 2D-spectroscopy data, in a format similar to this:               |    |    | f1 | f2 | f3 | . . .     | x1 | y1 | I  | I  | I  | . . .     | x1 | y2 | I  | I  | I  | . . .     | .  | .  | .  | .  | .  | . . .     | .  | .  | .  | .  | .  | . . .      where {x1,y1} are the map coordinates, f1-fn represent the frequency axis values and the rest is the Intensity (counts/second) obtained for each frequency. What I'd like to be able to do is to let Mathematica model the clusters of similar spectra inside this map, to find its main components. So I've been looking into clustering methods, but so far it's been a bit over my head. Ideally I'd like a solution where   1. I can define the number of clusters to look for (e.g. if I know of mainly two type of spectra to be present in the map, it should look for 2 clusters + background)   2. allow me to define some kind of threshold value that defines how close the individual spectra are allowed to be to each other    3. obtain the errors from this cluster-fit   4. If possible predefine the components representative spectra, if I already have a good model function for them.   5. Let me then export the spectra based on similarity (e.g. points more than 90% likely to stem from one component) so that I can fit them afterwards and create histograms   6. let me visualise the resulting clusters on the xy-grid So, to cut a long story short: how do I get arrays of xy-Points containing similar spectra? **Edit** : added an image depicting the situation ![Example of a map, showing 3 different spectra from the map](http://i.stack.imgur.com/QxsjZ.jpg)


Suppress connection to Wolfram|Alpha when making unit conversions

I want to speed up calculations with unit conversions. I suspect primarily that some units evaluate from Wolfram|Alpha. Any way to prevent this automatically, so that _Mathematica_ throws errors/warnings instead of grabbing units from Wolfram|Alpha?


2 Equations continuous at a point

I want to get continuous point between two equations. My equations are:               To[x_] := 2 c1 Cosh [x Sqrt[((f0 - b g0)/q)]] + g0/(f0 - b g0);               Tu[x_] := 10 Exp[-m x];      I try to find c1 and m constants which are in terms of g0. I have boundary conditions which are; > >     T = Tu   @ x = +L/2 >   >     D^2 k T'[x] = Du^2  ku Tu'[x]     @ x = + L/2 >   So, I have two uknown "c1,m" and two boundary conditions for single point. It should be continuous at L/2. Actually boundary conditions for +- L/2 ( because cosh is symmetric, but I assume m is positive , so just for positive part of boundary) Like that plot,for example, he had found Tu= 10.3 e^-598(x-0.005), it is continuous at 0.5 mm with cosh function. ![enter image description here](http://i.stack.imgur.com/GxDDd.png) In the same manner, it should be obtained thanks to boundary conditions. Then I applied boundary conditions in order to find "c1,m" to be continuous at L/2.               Solve[g0/(f0 - b g0) + 2 c1 Cosh[1/2 L Sqrt[(f0 - b g0)/q]] -         10 E^(-((L m)/2)) == 0, c1]          {{c1 -> -((         E^(-((L m)/2)) (-10 f0 + 10 b g0 + E^((L m)/2) g0) Sech[           1/2 L Sqrt[(f0 - b g0)/q]])/(2 (f0 - b g0)))}}      c1 is okay, then for finding m I applied derivative boundary condition,               Solve[2 c1 Sqrt[(f0 - b g0)/q]          Sinh[1/2 L Sqrt[(f0 - b g0)/q]] dia^2 k - (-10 E^(-((L m)/2))           m Du^2 ku) == 0, m]      And program gave error as:               S`olve::nsmet: This system cannot be solved with the methods available to Solve.`      How can I get c1 and m in terms of g0 ? When I obtain c1 and m in terms of g0, constant temperature condition will be used for g0:               int=Integrate[To[x],{x,-L/2,L/2}]          NSolve[int=220,g0]


How to work with Experimental`NumericalFunction?

This question is intimately connected with previous one: "How to create internally optimized expression for computing with high WorkingPrecision?" Oleksandr R. correctly states in the comment: > A good answer will hopefully discuss the `Experimental`NumericalFunction`, > which is a structure produced by `FindMinimum` from the function and its > `Jacobian` that is optimized for fast numerical evaluation. I know almost > nothing about these objects or how to create/use them, but I would like to > find out. From other questions on this site it is apparent that other built-in numerical functions also use `Experimental`NumericalFunction` which seems to be the standard way to optimize numerical evaluation. It is not documented but it is placed in the `Experimental` context which "contains functions that are being considered for official inclusion in future versions of _Mathematica_ ". This undocumented function is of crucial importance because currently it is **the only way to optimize _arbitrary precision_ calculations**. For `MachinePrecision` we have `Compile` but nothing documented for arbitrary precision. How to work with `Experimental`NumericalFunction`?


Simplifying complex expressions

I'm trying to work with complexes and I want _Mathematica_ to know that all variables are real unless I explicitly assigned the variable with an `I` so I wrote:               $Assumptions = Except[I,_] ∈ Reals      It worked fine for simple expressions               f = Exp[-I*a] * a + Exp[-I*b]     Simplify[Conjugate[f]]      > Exp[I*a] * a + Exp[I*b] but for a more complex expression:               g = Exp[-I*a] * a + Exp[-I*b] * b     Simplify[Conjugate[g]]      > Exp[-I*a] * a + Exp[-I*b] * b which is wrong. What can I do about it?


Series coefficients for an infinite sum?

I'm working through Carl Bender's Mathematical Physics lectures on YouTube (which are great fun), and I'd like _Mathematica_ 's help solving terms in the perturbation series. It would be convenient if expressions like               SeriesCoefficient[Sum[a[n] b^n, {n, 0, ∞}], {b, 0, 3}]      gave `a[3]` as a result. Replacing $\infty$ with an integer greater than 3 is fine, but easy to lose track of in my notes. Is it possible to add an assumption that the series converges, and would that solve my problem? Other solutions? **Edit** For an example of how I hope to use this functionality, consider solving $x^5 + x = 1$ by inserting the perturbation parameter $b$ in front of $x$ (but not $x^5$). I want to apply `SeriesCoefficient` to the result of               x^5 + b x - 1 /. x -> Sum[a[n] b^n, {n, 0, ∞}]      and build up a list of coefficients that equal zero.


How do I use Subgraph to sample the $n$ vertices of a graph with the greatest connectivity?

Let $G$ be an arbitrary graph with some number of vertices $||V||$ and some number of edges $||E||$. We can use `Subgraph` to generate, well, a subgraph of `G` with the vertices we desire. However, how can I use the `patt` option for `Subgraph` (or any method) to grab the set of `n` vertices with the greatest degree in $G$? In other words, if we make a list `Sort[VertexDegree[G]]`, how can we select vertices for the subgraph starting from the right-hand-side of the output list then working our way to the left?


Pattern matching with PDF, Distributed and multivariate distributions

I have defined a function to compute the Shannon entropy of a probability distribution:               ent[p_] := Expectation[-Log[PDF[p, x]], x \[Distributed] p]      This works fine for univarite distributions:               nd = NormalDistribution[]     ent[nd]          Out[9]= 1/2 (1 + Log[2 \[Pi]])      I would have expected `ent` to work with multivariate distributions as well, since `x \\[Distributed] p` in `ent` should cause `x` to be bound to vectors of the appropriate length to make `PDF[p, x]` work, but I get               nd2 = ProductDistribution[nd, nd]     ent[nd2] // FullSimplify          Out[10]= Expectation[-Log[        PDF[ProductDistribution[NormalDistribution[0, 1],           NormalDistribution[0, 1]], x]],       x \[Distributed]        ProductDistribution[NormalDistribution[0, 1],         NormalDistribution[0, 1]]]      I can write a specific function for each arity:               ent2[p_] := Expectation[-Log[PDF[p, {x, y}]], {x, y} \[Distributed] p]     ent2[nd2]          Out[11]= 1 + Log[2 \[Pi]]      Is there a way to write ent to be generic wrt to the dimention of the distribution? I would also like to better understand why `ent` does not work for multivariate distributions as is. The definition seems mathematically correct for any dimention.


Why the complicated pattern in this 3D plot?

ListPointPlot3D[     Table[{n, s, (Prime[n]^s/(Prime[n]^s - 1))}, {n, 1, 2000}, {s, 2, 80}], PlotRange -> All]        ![enter image description here](http://i.stack.imgur.com/3opta.png) Is the pattern the result of the data, the plotting function, or a bit of both? **Edit** fixed bad exponents, replaced the plot.


blank null sequence acts weirdly

Could someone please explain why the `___` pattern matches the first but not the second case?               MatchQ[Sum[1/2 (-kx^2 - ky^2) n^2, kx, ky], Sum[s___, kx, ky]]     MatchQ[Sum[E^(1/2 (-kx^2 - ky^2) n^2), kx, ky], Sum[s___, kx, ky]]


Define a function that takes ragged array

newbie here. I want to define a function that takes a ragged array and return another one, but how. Say, I want to define a simple function behaves like this `{var,itr} := {var,itr+1}`. `var` can be anything, while `itr` is an integer. First, I know, this will work. ` fun[{var_,itr_}] := {var,itr+1} ` But how to use `Function` to do this, because I want to generate a function that takes a ragged array. I tried this without a second thought. ` gen[d_]:=Function[{{var,itr}},{var,itr+d}] ` Which had failed, of course. It seems `Function` could only use a symbol or a list of symbol as its first parameter. **Appending** The reason is, I'm trying to get the iteration times of `NestWhile[f, expr, test]`, it seems `f` could only takes 1 parameter. So I need a function that will take a ragged array to do this. But I don't want to write such function every time, so I want to define a function that could generate one for me. **Completely example** Oringinally. ` NestWhile[#+1&, 1, #<100&] ` What I want to do is below. ` NestWhile[gen[#+1&],{1,0},#<100&] ` And `gen` is a function that generates a such function. Below is what I do. ` gen[fun_]:=Function[{var,itr},{fun[var],itr+1}] ` That's where I'm wrong.


Ordinary differential equation invloving the function composition

I want to solve the following function:               DSolve[(A1*Exp[B1*f[x]] + A2*Exp[B2*f[x]])*f'[x] == A1*Exp[B1*x] + A2*Exp[B2*x], f[x], x]      And this is what I get as an answer:               {{f[x] -> InverseFunction[(A1 E^(B1 #1))/B1 + (A2 E^(B2 #1))/B2 &][(A1 E^(B1 x))/B1 + (A2 E^(B2 x))/B2 + C[1]]}}      Mathematica says that some results could be given in the form of the inverse functions. Does anybody know how I can solve this to get some result? Generally the given equation involves the function composition, and has the following form: $(g \circ f)f'=g$, where Where $g \circ f=g(f(x))$. By inspection, $f(x)=x$ is a solution. There are also other solutions. Anybody has idea how to tackle the problem to find more solutions?


Manipulating the pitch of a sound

After reading Manipulating a continuous stream of sounds I have to ask about controlling the frequency of a `Sin` sound in a continuous manner, with a `Play` inside a `Manipulate`, for example. The result may sound something similar to whistling, a musical saw or a theremin. The problem with `Play` is that it generates an output box to be played after and not dynamically. Is it possible in Mathematica?


Plot3D with coloring based on phase value of f

I'm reading a sample chapter of _Visual Complex Functions_ by E. Wegert. Near the bottom of this page, there is a link "Download Sample pages 1 (pdf, 2.4 MB)" which allows you to read Chapter 2 of the text. On page 28, he has a color circle in Figure 2.8, which is based on `Hue` and the argument of the complex number. Mine winds up a little differently from his, as his is rotated 180 degrees from mine.               DensityPlot[Arg[x + I y], {x, -2, 2}, {y, -2, 2},       RegionFunction -> Function[{x, y}, 1 < x^2 + y^2 < 1.5],       ColorFunction -> Hue, PlotLegends -> Automatic, ImageSize -> 300]      ![Wegert1](http://i.stack.imgur.com/zrGCs.png) On page 28, he pictures what he calls a "Colored Analytic Landscape" of the function $f(z)=(z-1)/(z^2+z+1)$. That is, he plots $\ln(|f|)$, and the color is based on $\arg f$. Here is my first attempt to do the same thing.               f[z_] := (z - 1)/(z^2 + z + 1)     Plot3D[Log[Abs[f[x + I y]]], {x, -2, 2}, {y, -2, 2},       ColorFunction -> Function[{x, y, z}, Hue[Arg[f[x + I y]]]],       AxesLabel -> {x, y, z}, Mesh -> None, BoxRatios -> {1, 1, 1},       ImageSize -> 300]      ![Weger2](http://i.stack.imgur.com/cNMWL.png) Unfortunately, my image does not match his. Of course, that's partly because my color wheel is not rotated, but here is a description of my real question. Notice what happens when I do a density plot of `Arg[f[x+I y]]` and place it side-by-side with a top view of my surface:               GraphicsRow[{{Plot3D[Log[Abs[f[x + I y]]], {x, -2, 2}, {y, -2, 2},          ColorFunction -> Function[{x, y, z}, Hue[Arg[f[x + I y]]]],          AxesLabel -> {x, y, z}, Mesh -> None, BoxRatios -> {1, 1, 1},          ViewPoint -> {0, 0, Infinity}]}, {DensityPlot[         Arg[f[x + I y]], {x, -2, 2}, {y, -2, 2}, ColorFunction -> Hue]}}]      ![Wegert3](http://i.stack.imgur.com/ofbdw.png)![Wegert4](http://i.stack.imgur.com/kgs3f.png) They don't have the same color scheme. What am I missing?


How to create 2k sized vector in k sized loop

I want to solve a system of simple differential equations. At some point I need to solve non-linear system of algebraic equations with Newton method. I would like to efficiently create a right hand side vector using Table[] or similar command. The problem is that the system consists of two equations, so what I need is:               F=Table[     (*do something*)     ,{i,1,k}]      but in fact $F$ should have $2k$ entries. For example for $k=5$ `Length[F]` should return $10$. How to achieve that efficiently? I know I can create different values for odd indexes and even, but then I need additional `If[]` or to break the whole code into two `Table[]` executions what I would like to avoid. I could possibly also create two element lists {a,b}, and flatten it at the end... But It still seems quite expensive.


How to obtain a smaller-sized output from Solve

I am solving a system of 15 simultaneous linear equations using `Solve`. On running the code, I get a message saying "A very large output was generated" with options for viewing the ouput. I want to use the solution inside a larger program where the next step relies on the ouput of `Solve`. I am stuck unless there is a reasonable way for me to capture the output from `Solve`. Is there a way to do this?


Reducing a multi-variate polynomial to have terms upto certain degree

I have a polynomial in x and y. I want to keep all the terms with (combined) degree 4. Any pointers will be appreciated. Simple tricks for doing the same with univariate polynomial don't seem to work.


Changing the inter-item spacing in Legends (version 9)

The new legending functionality in version 9 is much easier to use than the `PlotLegends` package and other bespoke ways of creating legends in earlier versions. However, the vertical spacing between items is larger than I would like. How can I reduce this spacing? Changing the `LegendMarkerSize` option to a smaller number without changing the size specified in the `LegendMarkers` option just ends up cutting off the graphic. `LegendMargins` doesn't affect the inter-item spacing, only the space between the whole legend and other items.               PointLegend[{RGBColor[1, 0, 0], RGBColor[0, 0, 1]}, {"Series 1", "Series 2"},       LegendMarkers -> {{"\[FilledCircle]", 20}, {"\[FilledCircle]", 20}},       LegendMarkerSize -> 19,       LabelStyle -> {FontFamily -> "Arial", FontSize -> 20}]       ![enter image description here](http://i.stack.imgur.com/mWl0m.png)


How to sort my list?

For example I have two lists of such structure               L1 = {{"Australia",a1}, {"USA",a2}, {"Norway",a3},...}     L2 = {{"Russia",b1}, {"Norway",b2}, {"Japan",b3},...}      I would like to sort countries of the list `L2` in the countries' order of `L1` to compare it entirely (I mean the values matching for each country). Thus I would like to gain something resembling this as a result where `L3` is the sorted `L2`:               L1 = {{"Australia",a1}, {"USA",a2}, {"Norway",a3},...}     L3 = {{"Australia",b26},{"USA",b13} {"Norway",b2},...}


Using NSolve on an equation that involves Mean and TruncatedDistribution

What I would like to do is create a mixture distribution that has a specified mean by varying one parameter in the distribution. To do this I've written the following code;               dist := MixtureDistribution[{0.1,0.9}, {UniformDistribution[{39.3, 40.5}],     TruncatedDistribution[{40.5, 104}, NormalDistribution[a, 11.4]]}]          NSolve[Mean[dist] == 82.63344, a]      Which just returns a "PolynomialGCD::lrgexp" error. What I ended up doing is putting values in using trial and error until it gave me the correct mean (so it does have a solution). Is there any way so solve this equation without resorting to trial and error? I think the TruncatedDistribution / Mean combination is what is causing problems. When I remove the TruncatedDistribution NSolve quickly returns a solution. The following link discussed this issue; Calculating the Mean of a Truncated Multinormal Distribution When I replaced                NSolve[Mean[dist] == 82.63344, a]      With               NSolve[NExpectation[x, x \[Distributed] dist2] == 82.63344, a]      All I got was an execution that seemed to go forever (I aborted after 10 mins). Any advice on how to solve this equation efficiently would be greatly appreciated.


How to do computations simultaneously in multiple notebooks?

I have a Mathematica script which takes a few hours to run. I want to be able to open another notebook while it's running and do some other computations. I have enough many cores on my computer for this to be possible so it shouldn't be an issue. What do I need to configure so I can be running several notebook scripts in parallel?


Using physical dimensions in Mathematica DSolve

I would like to calculate a system of two differential equations in Mathematica using `DSolve`, like:               fx''[x] + a*fx[x] == -I*eta*fy''[x] - b*fy[x], ...      where `fx[x]` and `fy[x]` are unknown functions. Using `DSolve` I can easily find some solutions of the type `fx[x] = C[1]*cosh[x/L] + C[2]*a*sinh[x/L]`, where `L` is a term of the dimension of `x`. The problem is, that the parameters `a` and `b` in my equations have physical dimension (e.g. meter). From the analysis of the solution the two terms in the result have different physical dimension, which is nonsensical. Another option is that Mathematica rescaled `C[1]` so that finally it has dimension of `a*C[2]`. My question is: Can I somehow control the physical dimensions of the parameters `(a,b)` in the differential equations or the constants `C[1]`, `C[2]` in the result?


How to use the output we see of expression when this expression is inside Dynamic

Consider this example:               Manipulate[status = Dynamic[If[a < b, Yes, No]], {a, 2}, {b, 5}]      The output of this calculation is               (*Yes*)      when I call status again I get `Yes` as expected. No when I want to used the output of status in further calculation I failed. I tried to do the following:               status === Yes      the results is `False` The full form of status is not what is seen in the output. My question is, how to use the output of expression no matter what the definition of that expression is. (Note: `status[[1]]` does not help because the level of the output is unpredictable) Thank you.


Custom distance metric for agglomerative clustering in Mathematica

Is it possible to have a custom distance metric defined to determine the distance between two clusters in Agglomerative clustering in Mathematica? I have a 3 dimension data with string values along all three dimensions. I want to define my own way of measuring the distance between any two clusters (Strings here...) Also, I want to stop the clustering when the distance between two clusters is greater than a particular threshold value "T". Is this available in Mathematica?


How to repeatedly show variations on a plot

I would like to show graphics repeatedly with changes in parameters. Neither of the following show anything. Nor do they give an error message.               Do[Plot[y = Sqrt[(1/n) x], {x, 0, 1}], {n, 1, 5}]          For[n = 1, n < 6, n++, Plot[y = Sqrt[(1/n) x], {x, 0, 1}]]      These merely show the plot for n=1.               Do[Return[Plot[y = Sqrt[(1/n) x], {x, 0, 1}]], {n, 1, 5}]          Do[(Pause[1]; Return[Plot[y = Sqrt[(1/n) x], {x, 0, 1}]]), {n, 1, 5}]          For[n = 1, n < 6, n++, Return[Plot[y = Sqrt[(1/n) x], {x, 0, 1}]]]      (I tried Pauses in the others, to no avail.) How do I make this work?


Tabulating Numeric Approximation

I was wondering how to approximate or tabulate values for this numeric approximation: It is the following: The confusing part is how to implement the subscripts in mathematica. $y_{i+1} = (t_i - y_i)h + y_i$ I want to do something of the following for this numeric solution.               x[t_] = t/(1 + t^4);     data = N[Table[{t, x[t]}, {t, -5, 5}], 2];     tableofcontents = Prepend[data, {"t", "x(t)"}];     Text@Grid[tableofcontents, Alignment -> Right, Dividers -> {Center, {False, True}},        Spacings -> 1]      ![Mathematica graphics](http://i.stack.imgur.com/rFWjP.png)


Efficiently generating n-D Gaussian random fields

I am interested in an efficient code to generate an $n$-D Gaussian random field (sometimes called processes in other fields of research), which has applications in cosmology. I wrote the following code:               fftIndgen[n_] := Flatten[{Range[0., n/2.], -Reverse[Range[1., n/2. - 1]]}]          Clear[GaussianRandomField];     GaussianRandomField::usage = "GaussianRandomField[size,dim,Pk] returns     a Gaussian random field of size size (default 256)  and dimensions dim      (default 2) with a powerspectrum Pk";          GaussianRandomField[size_: 256, dim_: 2, Pk_: Function[k, k^-3]] :=      Module[{noise, amplitude, Pk1, Pk2, Pk3, Pk4},     Which[     dim == 1,Pk1[kx_] :=      If[kx == 0 , 0, Sqrt[Abs[Pk[kx]]]]; (*define sqrt powerspectra*)     noise = Fourier[RandomVariate[NormalDistribution[], {size}]]; (*generate white noise*)     amplitude = Map[Pk1, fftIndgen[size], 1]; (*amplitude for all frequels*)     InverseFourier[noise*amplitude], (*convolve and inverse fft*)     dim == 2,     Pk2[kx_, ky_] := If[kx == 0 && ky == 0, 0, Sqrt[Pk[Sqrt[kx^2 + ky^2]]]];     noise = Fourier[RandomVariate[NormalDistribution[], {size, size}]];     amplitude = Map[Pk2 @@ # &, Outer[List, fftIndgen[size], fftIndgen[size]], {2}];     InverseFourier[noise*amplitude],     dim > 2, "Not supported"]     ]      Here are a couple of examples on how to use it in one and 2D               GaussianRandomField[1024, 1, #^(-1) &] // ListLinePlot     GaussianRandomField[] // GaussianFilter[#, 20] & // MatrixPlot      The performance is not optimal — On other interpreted softwares, such Gaussian random fields can be generated ~20 times faster. Do you have ideas on how to speed things up/improve this code? I'd be curious/interested in an efficient way to proceed on the sphere!


Sizing cells in a GraphicsGrid/GraphicsRow

I would like to add a colour bar to a plot. I tried to use `GraphicsRow` for this. In a `GraphicsRow`, each item is given the same space, resulting in this:               Clear[colorbar]     colorbar[colorFunction_: Automatic, divs_: 25] :=       DensityPlot[y, {x, 0, .1}, {y, 0, 1}, AspectRatio -> Automatic,        PlotRangePadding -> 0, PlotPoints -> {2, divs}, MaxRecursion -> 0,        FrameTicks -> {None, Automatic, None, None},        ColorFunction -> colorFunction]          GraphicsRow[{DensityPlot[Sin[Norm[{x, y}]], {x, -10, 10}, {y, -10, 10}],                  colorbar[]}]      ![Mathematica graphics](http://i.stack.imgur.com/d8bM1.png) **The colour bar has too much space around it. How can I specify the amount of space`GraphicsRow` should give a particular item?** Alternatively, what is a better way to include the colour bar? * * * ### Answer summary After experimenting with this for a while, it seems that the situation is the following (simplified):   * `Grid` and friends (`Row`, `Column`) will size the grid cells to fit each item individually (cells resized to fit items).   * `GraphicsGrid` will first set up a grid with fixed cell sizes, then fit each item into the cells (items resized to fit cells). `GraphicsGrid`-like solutions are more convenient when the whole graphic need to be sized to a specification. **István's answer** hacks `GraphcisRow` by setting a negative spacing and thus pushing the elements closer together. It's the most convenient for this situation, but it doesn't generalize for many cells. **R.M.'s solution** suggests using `Grid` instead. This generalizes well, but requires pre-sizing all items individually, and no resizing is possible after (e.g. just before import). Since `GraphicsGrid` is implemented in terms of `Inset`, the most general easily resizable solution would be implementing a `GraphicsGrid`-like construct where cell size ratios can be specified. **kguler's last answer** illustrates this best. Several other solutions used `Inset` directly as well. A problem with resizing these solutions can be that the aspect ratio of elements is size-dependent (due to the absolute sizes used in `ImagePadding`), so how they fit into a fixed aspect ratio `Inset` will depend on the scale. Note for example the difference in scaling behaviour between István's solution and kguler's solution at small sizes: in kguler's solution (using a cell aspect ratio matching that of the colour bar) the colourbar suddenly get shrunk compared to the main plot at small sizes, but the tick marks will never overlap with the other plot. in István's solution (which uses overlapping square cells) the colour bar never gets overshrunk, but the tick marks will overlap the main plot. **Update:** Version 9 has built-in support for plot legends, including colour bars. `Legended` is used to append a legend to a graphics object.


Graph does not accept Property Options

My question is concerned with the `Graph` functionality, which was newly implemented in Mathematica 8. I already used `GraphPlot` and `LayeredGraphPlot` in the previous versions and in principle appreciate the new capabilities. However, I still wonder if the current implementation is complete. E.g. in the code below, I try to use `VertexCoordinates` for each vertex, which according to the documentation for `Graph`, should work.               vertices1 = {        Property[1, {VertexCoordinates -> {0, 3}, VertexSize -> 0.3}],        Property[2, VertexCoordinates -> {1, 2}],        Property[3, VertexCoordinates -> {3, 3}]      };          Graph[vertices1, {1 \[UndirectedEdge] 2, 2 \[UndirectedEdge] 3},  GraphLayout -> {"LayeredDrawing", "LayeredLeft"}]      Other Options within `Property`, e.g. `VertexSize`, work correctly. `VertexCoordinates` has no effect whatsoever. `VertexCoordinates` will work as an option for `Graph`, but not as a `Property` for a particular vertex. My other concern relates to `GraphLayout` and in particular to the Suboption `"PackingLayout"`, which also seems to have no influence whatsoever. E.g. if I use `"LayeredDrawing"`, the Suboptions `"LayeredLeft"` or `"LayeredTop"` create the same `Graph`. What is your experience?


Animating the steps of a Kohonen SOM in Mathematica

As the title suggest, I'm trying to make an animation of how a bunch of points into 2-D (and possibly 3-D space) evolves by each step of my program. In order to do so I've data which contains the x and y position of every single point of the map at a given "time" t, which is defined by jumping over 20 elements of the list. i.e. t=0 goes from row 1 to row 20, t=1 from row 21 to row 40, etc... here's the file: Full Version: https://www.mediafire.com/?irgddwos6qn5kb1 Light Version: https://www.mediafire.com/?rdx66fsyzejonhx and here's what i've written in order to obtain x and y positions of points at a given time:                   dati = Import["...\\KOHONEN SOM\\output.dat"]         {a, b} = Transpose[dati];         neuro = 20;         x = Array[h, neuro];         y = Array[j, neuro];         Table[x[[k]] = Table[a[[k + i*neuro*4]], {i, 0, 50000}], {k, 1, neuro}];         Table[y[[k]] = Table[b[[k + i*neuro*4]], {i, 0, 50000}], {k, 1, neuro}];         X = Array[l, 50000];         Y = Array[s, 50000];         Table[X[[l]] = Table[x[[j]][[l]], {j, 1, neuro}], {l, 1, 50000}];         Table[Y[[l]] = Table[y[[j]][[l]], {j, 1, neuro}], {l, 1, 50000}];      Note that the i*neuro*4 thing is in order to take a little less of all the data i have I've also been able to make plots of each evolution step, as shown here:                POW = Table[        ListPlot[Transpose[{X[[l]], Y[[l]]}], PlotRange -> All], {l, 1,          50000}];      This allows me to have the single frames of the animation, but yet, I haven't been able to combine them into an animation. Moreover, I was looking for having the points connected by a line in the animation itself, so that, if I'd start increasing the numbers of neuro, it wouldn't be a mess to understand what's going on... Many thanks in advance.


In a DynamicModule, is it possible to use multiple EventHandler declarations?

> **Possible Duplicate:**   >  Wrapping EventHandler by Table I am running _Mathematica_ 7. However, I am new to using `Dynamic`, `DynamicModule`, `EventHandler`, and the like. I would like to create a `Graphics` object containing `numDisks` `Disk` objects, where `numDisks` is a positive integer. I would like each of the `Disk` objects to be `Red`, `Green`, or `Blue`. The default color is `Red`, but if a disk is clicked, that disk goes to the next color, cyclically (`Red`-->`Green`-->`Blue`-->`Red`-->...). Is it possible to accomplish this using a `DynamicModule` and multiple `EventHandler` declarations? I have tried the following. This code generates `numDisks` disks in a row. When the user clicks anywhere within the `Graphics` box, the color of _all_ three disks changes to the next color in the sequence.               radius = 1;     numDisks = 3;          DynamicModule[{col = Red},      EventHandler[       Graphics[        Table[{Dynamic[col], Disk[{2.5*(i - 1), 0}, radius]}, {i, 1,           numDisks}],        PlotRange -> All],       {"MouseClicked" :> (col =            col /. {Red -> Green, Green -> Blue, Blue -> Red})}]      ]      ![Three Disks](http://i.stack.imgur.com/uAT32.gif) However, what if I would like each of the `numDisks` `Disk` objects to have its own color, which can be changed _independently_ of that of all of the other `Disk` objects? Is this possible? Can this be accomplished somehow using multiple `EventHandler` declarations? Thanks for your time.


Create string from character code

Is it possible to convert a charcode/keycode to a string? I want to do this to create variables in a generated equation.