Interactively select a row/column of a Grid

I need a simple way to display tabular data (preferably with `Grid`) and also be able to select a row or column of the table. I've tried different approaches, but I ran into dead ends. Let's define an example table that contains entries of various types and sizes, and a dynamic variable, `over`, that holds whether the mouse is over a particular row or not (it is easy to extend this approach to inclue setter/toggler controls, or for selecting columns, but that is not the direct aim of this post):               data = {         {11111111, 2, 3}, {4, "55555\n55555\n55555", 6666666.6666},         {11111111, 2, 3}, {4, "55555\n55555\n55555", 6666666.6666}     };     over = False & /@ data;  (* no row is selected at initialization *)      ## 1. With multiple `Item`-s My first approach is the one I thought would work best: treating elements of the grid as `Item`-s, and dynamically update the background of only those entries which are in the given row. It is important to wrap entries individually in `Item[..., Frame -> True]`, so that mouse-movements are captured in the whole cell of the grid and not just where the number is. Unfortunately though when `Item`-s are wrapped in `EventHandler`, `Item`-specific options are lost. Note how frames are missing in the displayed grid on the right:               (* simple example showing that Item options are not forwarded by EventHandler *)     {Grid[{{1, 2}, {Item[3, Frame -> True], Item[4, Frame -> True]}}],      Grid[{{1, 2}, {EventHandler[Item[3, Frame -> True], {}],                     EventHandler[Item[3, Frame -> True], {}]}}]}      ![Mathematica graphics](http://i.stack.imgur.com/1xiVI.png) Accordingly, the full row-selector construct fails too, as neither `Frame`, nor `Background` options are evaluated at all. As a consequence, the `EventHandler` is restricted to the numbers only, and not to the full cell of the grid (see the dynamicaly displayed `over`), and no background is updated.               Dynamic@over     Grid@MapIndexed[EventHandler[         Item[#1, Frame -> True,           Background -> Dynamic@If[over[[First@#2]], LightBlue, White]],         {"MouseEntered" :> (over[[First@#2]] = True),           "MouseExited" :> (over[[First@#2]] = False)}] &, data, {2}]      ![enter image description here](http://i.stack.imgur.com/UO0n6.gif) ## 2. Multiple one-row `Grid`-s Ok, so if `Item` cannot be used, one has to treat rows as individual objects, for example by assigning same column-sizes for all the rows as individual `Grid`-s. But specifying fixed column sizes is both tedious and prone to break when resized/pagebreaked/etc.               Dynamic@over     Column[MapIndexed[EventHandler[         Grid[{#1},           Background -> Dynamic@If[over[[First@#2]], LightBlue, White],           Dividers -> All, ItemSize -> 7],         {"MouseEntered" :> (over[[First@#2]] = True),           "MouseExited" :> (over[[First@#2]] = False)}         ] &, data],      Spacings -> {0, -.2}      ]      ![enter image description here](http://i.stack.imgur.com/aQ6yK.gif) Note that I had to use a fixed `ItemSize` value (which cannot be calculated programmatically prior to displaying the `Grid`), and also negative spacing, as the individual row-`Grid`-s are layered on top of each other and alignment is not perfect. This shows when the window is resized or in any way the output is forced to resize in the page. At least now the mouse is captured in the whole row-space. **Questions**   1. How to create a row/column selector effectively, that retains the economic layout of `Grid`?   2. If this is not possible, can we programmatically get the optimal cell-sizes of a `Grid` to force on multiple one-row `Grid`-s?   3. Is it a bug that `EventHandler[Item[..., opts]]` does not apply `opts` when inside `Grid`? Any workaround?


What is the confidence limit on this convergence?

When I run this,               Product[n^MoebiusMu[n],{n,1,Infinity}]        I get $\frac{1}{4 \pi^{2}}$ Over on Math Overflow they are saying it shouldn't happen. So, how do I determine if it really converges? **Edit** If we could re-order the square-free numbers into sequence by their greatest factors, this product would converge absolutely to $1$. This sum:               Sum[MoebiusMu[n],{n,i,Inifinty}]        would converge absolutely to $0$ with the same re-ordering. **Edit 2**               ListPlot[Table[n^MoebiusMu[n], {n, 1, 1000}]]        ![MoebiusMu Plot](http://i.stack.imgur.com/mLKGc.gif)


Get name of hidden inbuilt functions (like Ticks drawing)

how do I get the name and definition of a builtin Mathematica functions? For instance, I would like to see how default Tick plotting function is implemented. However, it is not clear where it is and what is its name, because its name never appears for the user. Example:               Plot[ {Sin[x], Cos[x]}, {x, 0, 3 Pi}, Frame -> True, FrameTicks -> {None, Automatic}]      Basically I want to know, how do I get the name of the function called under the `Automatic` label? Thanks!


Embedding a "Details Section Style" within a Section or SubSection

When presenting a technical derivation within a Section of a Mathematica notbook, I often encounter the situation where a lot of "detail" separates equations (x) and (x+1), and I suspect many readers would prefer not to see this detail. I could use a collapsible subsection to hold the required material, but at the end of the subsection I would have to create a new Section to continue the main flow of the document. I find this to be stylistically awkward. Have any of the wizards solved this sort of problem? Perhaps by developing a Style for a special section that can be collapsed or expanded in a standalone manner that doesn't interrupt the flow of the main document? Thanks, Tom


How can I assign some part of data from one list to another list?

I don't know this is correct question or not,but I have a doubt. I have two `Lists` names are `list1` and `list2`                list1={a,b,c};      list2={10,20,30};      I want to assign `Part[list2,1]` value (10) to the `Part[list1,1]`.that means `Part[list1,1]` act as `Variable`. after assigning, If I evaluate `list1`,it will shows `{a,b,c}`, if I evaluate `list2`,it will shows `{10,20,30}`. if I evaluate `a`,it will shows `10`. I want like this.. Is it possible like this?


Extracting columns of text from a rectangular string

I have _very large_ rectangular strings (on the order of 30-100 MB in size), which I import into Mathematica from text files using a command like `text = Import["test.txt", "String"];`. A small representative example string `str` is below. Lines of text in the rectangular strings are delimited by the `"\n"` character. I would like to write an _efficient_ function that extracts columns of text from the string. It must be efficient because my actual strings are so large. It seems that splitting the string into individual characters, using something like `Map[Characters, StringSplit[str, "\n"]]`, is not an option, because it seems to take too much memory. So, in `takeFun` below, I have instead located the positions of characters in each column. Can you think of a more efficient way to write `takeFun`? By efficient, I am referring to memory conservation, not speed. Thank you!               str =      "ABCDE     abcde     12345";          pos = Prepend[StringPosition[str, "\n"][[All, 1]], 0];          (* Define a new string take function *)     takeFun[s_, p_, index_] := StringTake[s, Partition[p + index, 1]]          (* Take first column *)     takeFun[str, pos, 1]          (* Take second column *)     takeFun[str, pos, 2]          (* Take fifth column *)     takeFun[str, pos, 5]      which gives this output: > {"A", "a", "1"} > > {"B", "b", "2"} > > {"E", "e", "5"}


Scale label problem of multiple ListLogPlot graphs

Consider the following code:               data1 = {{0.70, 0.05}, {0.71, 0.06}, {0.72, 0.07}};     data2 = {{0.72, 0.07}, {0.72, 0.08}, {0.72, 0.1}, {0.72, 0.2}, {0.72,0.4}, {0.73, 0.6},{0.73, 0.8}, {0.73, 1.0}, {0.73, 2.0}, {0.74, 4.0}, {0.74, 5.0}, {0.74, 6.0}, {0.75, 8.0},{0.78, 10.0}};     data3 = {{0.72, 0.07}, {0.74, 0.08}, {0.76, 0.1}, {0.84, 0.2}, {0.9, 0.4}, {0.96, 0.6}, {1.0, 0.8}, {1.02, 1.0}, {1.12, 2.0}, {1.22, 4.0}, {1.26, 5.0}};          sg = ListLogPlot[Tooltip[data1], Joined -> True, Mesh -> Automatic];     sl = ListLogPlot[Tooltip[data2], Joined -> True, Mesh -> Automatic];     lg = ListLogPlot[Tooltip[data3], Joined -> True, Mesh -> Automatic];     Show[sg, sl, lg, PlotRange -> All]      There is no problem with the individual plots but their scales mess up when I combine them using Show command.The scale label just simply disappear. Any idea on how to fix this?


How do I indent C code generated by SymbolicC?

I'm continuing to experiment with the `SymbolicC`` package, and it's crucial to be able to inspect the generated code in order to do, well, anything useful with it. The `ToCCodeString` makes this possible, but as far as I can tell, produces code with sensible line breaks but no indentation. Reading unindented code is sort of possible, but not at all fun. Is there an option to turn indentation on? Right now, I've set things up so I can use the "Artistic Style" package for this purpose, and while it looks like a pretty nice program, relying on it means one more dependency on top of Mathematica and Visual Studio. **UPDATE** to add: I'm interested in inspecting code that I generate programmatically, and developing the program to do the generation interactively in a notebook. I'd prefer not to have to take manual steps like using `ToCCodeString` to generate the string, and then copy'n'paste it to Visual Studio to inspect it unless I really have to.


Plotting the set where $F(x,y)\leq0$ holds

I was using Wolfram Alpha to explore some set which is defined by an inequality. Somehow I was not able to reproduce the picture with mathematica. What is the best way of plotting a set defined as $F(x,y)\leq0$ where $F$ is a polynomial? I have tried ImplicitPlot, but this did not give nice results. Further, how is it possible to add something to such a plot? In fact I would like to also plot a certain curve which lies inside the set defined by the inequality. How is it possible to obtain this in the same graph?


CompiledFunction returns machine numbers smaller than $MinMachineNumber

When thinking on the workaround for this `LogLogPlot` bug suggested by halirutan I noticed that `CompiledFunction` actually can return machine numbers smaller than `$MinMachineNumber`. Consider:               f = Compile[{{t, _Real}}, Exp[-9 t^2]];     num = f[8.872]     num < $MinMachineNumber     MachineNumberQ[num]     MachineNumberQ[num2 = ToExpression[ToString[num, StandardForm]]]      > 2.191864698767832`*^-308 > > True > > True > > False As you see, `num` is smaller than `$MinMachineNumber` BUT `MachineNumberQ` returns `True`. Conversion of this number into `String` and backward returns arbitrary-precision number. Moreover, `CompiledFunction` accepts such numbers and works with them correctly:               f2 = Compile[{{x, _Real}}, Sqrt@x];     f2[num]      > 1.480494747970364`*^-154 How this behavior could be explained? Does it mean that `CompiledFunction` actually CAN work with arbitrary-precision numbers? P.S. I use _Mathematica_ 8.0.4 under Windows 7 x64.


Apply ColorData scheme for Plot from green to red

I'd like to apply a ColorData to this plot:               \[ScriptCapitalM] =        MixtureDistribution[{0.55, 0.35,          0.1}, {DiscreteUniformDistribution[{0, 0}],          NormalDistribution[0.25, .05],          DiscreteUniformDistribution[{1, 1}]}];          Plot[{CDF[\[ScriptCapitalM]]@x}, {x, -.001, 1.001}, Filling -> Axis,       PlotRange -> All, PlotStyle -> {{Blue, Thick}},       Frame -> {{True, False}, {True, False}},       FrameLabel -> {Style["Costs", Bold, 40],         Style["CDF(Costs)", Bold, 40]},       FrameStyle -> Directive[Thick, Black, 30], GridLines -> Automatic,       GridLinesStyle -> Directive[Gray, Dashed],       ColorFunction -> (ColorData["HTML", "MidnightBlue"])]      that starts from green (left) to red (right). I've checked the available schemes but apparently none matches my objective. Any ideas how to this? Thanks!


Dynamic legends involving show

My question is how do I get dynamic legends (legends that turn data on/off) to work with Show? This is an extension of an old question here; How to dynamically toggle curves on/off in a crowded Plot? The application I have is to show data using a histogram and overlay many different distributions on top of it. Here is the code               randData = RandomVariate[NormalDistribution[], 10^3];     estDists =        EstimatedDistribution[randData, #] & /@ {NormalDistribution[mu,           sigma], StudentTDistribution[mu, sigma, 5]};     pdfs = PDF[#, x] & /@ estDists;     histPlot = Histogram[randData, Automatic, "ProbabilityDensity"];     distPlots =        Plot[pdfs, {x, Min[randData], Max[randData]},         PlotLegends -> LineLegend[estDists]];     Show[{histPlot, distPlots}]      ![enter image description here](http://i.stack.imgur.com/fWLYL.png) Now that's fine if you have 2 or 3 fitted distributions but if you have 10 it gets a little crowded. I found a very nice solution to this (see link above) that lets you click on the legend to toggle the curves on/off. I'll repeat the code here;                (*Don't allow the Plot to evaluate yet*)     Attributes[DynamicLegend] = {HoldAll};          DynamicLegend[(plotfnc_)[f_, args___, (opts___)?OptionQ]] :=       Module[{plot},(*evaluate the plot*)plot = plotfnc @@ {f, args, opts};       (*if it does not have a legend,there is nothing to do*)       If[! MatchQ[plot, _Legended], Return[plot]];       DynamicModule[{(*get the directives and legend_text from the plot*)         leg = plot[[2, 1]],(*by default,         all plots are visible (not transparent)*)         trans = Table[False, {Length[plot[[2, 1, 1, 1]]]}]},         Dynamic[(*dynamically re-         evaluate the plot with dynamic PlotStyles and PlotLegends*)         plotfnc @@ {f,            args,(*prepend the directives with Transparent on dynamic \     switches*)PlotStyle ->             Table[With[{i = i},               Flatten[Directive[                If[TrueQ[trans[[i]]], Transparent, Directive[]],                 leg[[1, 1, i]]], 1, Directive]], {i,               Length[leg[[1,                 1]]]}],(*turn the legend_text's into Togglers and shove \     them back into the*)(*LineLegend structure.Also,           delete the old directives in the*)(*LineLegend structure to \     force PlotLegends to pick up the new*)(*directives,           so legend lines turn on/off with the curves*)           PlotLegends ->             ReplacePart[leg,              Join[{{1, 1} -> Sequence[]},               Table[With[{i = i}, {1, 2, i} ->                  Toggler[                  Dynamic[trans[[i]]], {True -> leg[[1, 2, i]],                    False -> leg[[1, 2, i]]}, FrameMargins -> 0]], {i,                 Length[leg[[1, 2]]]}]]],            FilterRules[{opts},             Except[{PlotStyle,               PlotLegends}]]},(*only need dynamic updates when trans is \     modified*)TrackedSymbols :> {trans}]]]      And can use it for a single plot               dynamicDistPlots = DynamicLegend[Plot[pdfs, {x, Min[randData], Max[randData]},      PlotLegends -> LineLegend[estDists]]]      But can't get it to work with the histogram               Show[{histPlot, dynamicDistPlots}]      I've had a play with applying the DynamicLegend to the Show and even tried to modify the DynamicLegend function (although I think that was a bit over by head). Any help would be appreciated as this would be a great tool to compare distributions.


Selective thinning of string elements in nested lists

I have a nested list similar to this example list (but much bigger and more messy):               str = {{{"a a-a", "a a-b", "a a-c", "a a-d"},              {"a b-a", "a b-b", "a b-c", "a b-d"}},             {{"b a-a", "b a-b", "b a-c", "b a-d"},              {"b b-a", "b b-b", "b b-c", "b b-d"}}};      I am trying to selectively to remove most of the entries whilst keeping the "...-c" entries within the nested structure so that I end up with something like this:               cstr = {{{"a a-c"}, {"a b-c"}}, {{"b b-c"}, {"b b-c"}}};      or at least this:               cstrflat = {{"a a-c", "a b-c"}, {"b b-c", "b b-c"}};      I can find the positions of the desired entries with:               Position[Map[StringMatchQ[#, ___ ~~ "-c"] &, str, {3}], True]      > {{1, 1, 3}, {1, 2, 3}, {2, 1, 3}, {2, 2, 3}} or use `Cases` to get a flattened list with:               Cases[str, _?(StringMatchQ[#, ___ ~~ "-c"] &), {3}]      > {"a a-c", "a b-c", "b a-c", "b b-c"} but, I can't work out how to thin-out the existing nested list structure. I think it might be possible with `Select` but my attempts so far haven't worked. Any suggestions? Are there other ways to do this sort of thing?


A list of cities in a time zone meeting a specified criterion

Is there a way to get _Mathematica_ V9 or Wolfram|Alpha, given a city as input (e.g., `"Urbana Champaign, IL"`), to return a list of cities that fall in a time zone within a certain maximum absolute value difference from the time zone of the given city? Generally, is there a way to get a list of cities by absolute value difference from the time zone a given city falls in?


RotateRight ith row of a matrix by i - 1

first time stack exchange poster here! So I was working on a problem, the purpose of which was to write a function in the procedural style to rotate right the ith row of a matrix by i - 1 spaces. Ok, easy enough here was my implementation:               rotateRowsProcedural[mat_?MatrixQ] :=     (       clonedMat = mat;       i = 1;       While[i <= Dimensions[clonedMat][[1]],         clonedMat[[i]] = RotateRight[clonedMat[[i]], i - 1];         i++;       ];       clonedMat     )      This was too boring so I decided I wanted to try and solve the problem using pattern matching approach and I came up with               rotateRowsPattern[matrix_?MatrixQ] :=        matrix /. mat : {x__List} :> (RotateRight[#, Position[mat, #][[1, 1]] - 1] & /@ {x}) `      Now I thought this was pretty awesome I mean to me its the essence of _Mathematica_. However, I then decided to compare the efficiency of the two functions               Mean[Table[Timing[rotateRowsPattern[RandomInteger[{0, 10},{1000, 1000}]]][[1]], {100}]]      > 0.038844               Mean[Table[Timing[rotateRowsProcedural[RandomInteger[{0,10},{1000,1000}]]][[1]], {100}]]      > 0.0165361 I was surprised that the procedural implementation was faster. Then I thought it over and I think it is the case that calling `Position` in the pattern implementation must slow things down. My question then is if I want to use pattern matching how can I reference the location of `x` (from `x__List`) so that I don't have to call `Position`. Also, I'm aware that combining `Map` and `Range` would be the most concise way to do this but I'm interested in the pattern matching.


A rotation-like transform on a matrix

_Do not be confused with comments, those are for previous version of the question_ - Kuba Imagine I have a matrix of the form:               MatrixForm[{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}]      I would like to apply a transform that generates a matrix of the form:               MatrixForm[{{4, 8, 12, 16}, {3, 7, 11, 15}, {2, 6, 10, 14}, {1, 5, 9, 13}}]      What would be the appropriate terminology for this transformation? It looks a bit like a 90 degree counterclockwise rotation of the elements in the matrix. Is there a simple way to do it in _Mathematica_ with large matrices?


Separating positive and negative numbers into two arrays

$c$ is a vector with real numbers.I want to separate the positive ones and the negative ones into two vectors: $a$ and $b$. I have the following problem: When I do:               c = RandomReal[{-1, 1}, 20];     {a, b} = GatherBy[c, Positive]      Sometimes, $a$ is the one with positive numbers, and some other times $b$ is the one with the positive numbers. Any solution to this problematic randomness?


I am referencing to this question on mathunderflow:   What is the average of rolling two dice and only taking the value of the higher dice roll? Now I tried:               Mean[Max[DiscreteUniformDistribution[{1, 6}], DiscreteUniformDistribution[{1, 6}]]]      and               Mean[Max[DiscreteUniformDistribution[{{1, 6}, {1, 6}}]]]      but both only give me the wrong answer $\frac{7}{2}$. What shall I do to get the right result:$$E[X] = \sum_{x=1}^6\frac{2(x-1)+1}{36}x = \frac{1}{36}\sum_{x=1}^6(2x^2 - x) = \frac{161}{36} \approx 4.47$$


Any other way to get a better FindFit for my data besides good initial parameters?

I fit some data with `FindFit` and `NonlinearModelFit` with some constraints and I am not getting a good fit with my data. I read around other questions such as FindFit not giving a good fit despite good initial parameters, FindFit: why do I get negative value as result?, FindFit returns worse result when putting constraints on parameters, and some of them have initial starting values that do help the fit. Unfortunately, I do not have an exact starting value for my parameters. All i know is that in my data, kd'/kd ~ 10^-6. I am just wondering if there are other ways to fix a `FindFit` in order to get a better fit.               data = { {75, 5.965}, {68.75, 6}, {63.45, 6.01}, {58.95, 6.03}, {55, 6.04}};     func = ((6.02*kd) + (deltaa''*x) + (5.65*kd'))/(kd + kd' + x);          ff = FindFit[data, {func, kd > 0, kd' > 0, 5.62 < deltaa'' < 6.02}, {{kd}, {kd'}, {deltaa''}}, x]     (*{*kd -> 1395.46, kd' -> 0.00336158, deltaa'' -> 5.71117}*)     fitfunc = func /. ff;          nlmfit1 = NonlinearModelFit[data, {func, kd > 0, kd' > 0, 5.62 < deltaa'' < 6.02}, {kd, kd', deltaa''}, x]     (*(8400.66 + 5.71117 x)/(1395.46 + x)*)               Show[ListPlot[data],Plot[{fitfunc}, {x, 75, 55}, PlotLegends -> "fitfunc"]]      ![enter image description here](http://i.stack.imgur.com/x8j8E.jpg) In my script above, I did not add any starting parameters because I am estimating different values and changing them to see how they fit the data. I know kd and kd' are both positive as well as kd'/kd ~ 10^6 that was stated above. Even though I am constantly trying to figure out estimated initial values, it is not changing the fit. I am just wondering why my fit is bad and what else can I do in order to get a better fit.


How to extract data beginning on the closest number to zero?

I have a list from which I want to extract only the values beginning from where b (from {a,b}) is the closest to zero. For example: I want extract data={{2, -0.036704}, {56.7499, 0.95489}, {73.7349, 0.73489}, {2, -0.237504}} from the following list: list={{1, 0.67342}, {77.7499, -0.93489},{6.73448, 0.056704},{2, -0.036704}, {56.7499, 0.95489}, {73.7349, 0.73489}, {2, -0.237504}} Thanks in advance


CreateDocument options needed to suppress the default notebook menu

What are the options needed in Mathematica 10 to suppress the menu on top of any notebook created with CreateDocument? For example, the Messages window as well as the windows generated by CreatePalette or MessageDialog don't have the top menu. The underlying need is that I'm creating an application that has its own main menu and I want for the user to see only my application's menu on top of the window.


Dropping Higher Order Terms in symbolic evaluation

I have a series of symbolic manipulations (along with some coefficients). As a sample, here is one of the intermediate forms               -1.00 (-0.707 (1.00+0.500 ax^2+0.375 ax^4+0.313 ax^6+0.273 ax^8) ay-0.0884 (1.00+0.500 ax^2+0.375 ax^4+0.313 ax^6+0.273 ax^8)^3 ay^3-0.0387 (1.00+0.500 ax^2+0.375 ax^4+0.313 ax^6+0.273 ax^8)^5 ay^5-0.0228 (1.00+0.500 ax^2+0.375 ax^4+0.313 ax^6+0.273 ax^8)^7 ay^7) Sign[(1.00+0.500 ax^2+0.375 ax^4+0.313 ax^6+0.273 ax^8) ay      As part of the calculations, Mathematica generates large expressions that can be further simplified by dropping higher order terms (such as powers > 10). Is there someway to force Mathematic to drop high order terms in the evaluation? Thoughts much appreciated.


How can I combine several 2D-plots to one big 3D plot?

So I've been able to make a list given by               list = Table[{xValues, f[xValues, t (*fixed*)]}, {xValues, xmin, xmax}]      For example:               list =       Table[{x, Sin[x/(2*Pi)*1/10]*Cos[1/(2*Pi)]}, {x, 1, 10}]      this list is easily plotted with the command `ListPlot[list]` (or even `ListLinePlot` if I wanted some kind of interpolation between my points). Now if I go to the 3D-case it becomes slightly harder! So I again make my list of data, this time given by:               Plotdata =       Table[{x, y, Sin[x/(2*Pi)*1/10]*Cos[y/(2*Pi)*1/10]}, {x, 1, 10}, {y,         1, 10}]      This now gives me a nested list, and my attempt to plot it with `ListPlot3D` is futile. I'm wondering if I need to do something special to get this done? My goal would be to get a nice 3D-plot of the whole. I know I could do it for my example with the regular `Plot3D` command, but that's just an example, the real case involves a lot of functions which can't be done by the plot-command (or would demand to much time). My problem comes essentially down to the above. I'm hoping someone could help me.


Should Read[] not close its Stream?

I read a record from a file.               Read[file,Record];        It reads and opens a stream. Should `Read` not close its stream after reading, like `ReadList` does?               ReadList[file,Record,1];


Using non-trivial objects in RLink

I would like to use RLink to access igraph, which has an R interface. I do not know R; my motivation for learning it is to be able to access igraph easily. I installed igraph using `install.packages("igraph")`. This seems to have worked fine (I'm doing this on Windows, where package installation is supported). I can load the package using `REvaluate["library(igraph)"]` Now I would like to reference some igraph functions and use them, in analogy to this:               sin = RFunction["sin"]     cos = RFunction["cos"]     sin@cos[1]      I did               fullgraph = RFunction["graph.full"]     diameter = RFunction["diameter"]      I created a graph using `g = fullgraph[5]` and I tried `diameter[g]`. The value it returns is `{0.}`. This is not the same what I get using `REvaluate["diameter(graph.full(5))"]`, which returns `{1.}`. **What am I doing wrong?** Does RLink support the kinds of objects returned by igraph, or does it only support basic built-in types? Another thing I observed is that if I try these commands several times, then `sin@cos[1]` (with the above definitions) will stop working too in the sense that it will throw error about being unable to set variables (RLink's internal state probably becomes inconsistent), but I can't reproduce this consistently.


Volterra integral equation : 'literally match the independent variables' message

I want to solve an Volterra type Integral equation, and as a practice I entered the following code to my mathematica:               Clear[Func, x, t]; DSolve[     D[Func[x], x] == Integrate[Func[t], {t, 0, x}], Func[x], x]      But I got an error message, > DSolve::litarg: To avoid possible ambiguity, the arguments of the dependent > variable in > > (function) > > should literally match the independent variables. >> I guess that the argument of Func[...] should be always 'x' (not 't') in the above example. I first thought changing my code to               Clear[Func, x, t]; DSolve[     D[Func[x], x] == Integrate[Func[x], {x, 0, x}], Func[x], x]      But it seems it's not the integral equation I want to solve. Also in that case I got the following warnings, > Solve::ifun: Inverse functions are being used by Solve, so some solutions > may not be found; use Reduce for complete solution information. Are there any ways to assign variable to the bounds of the integration interval? Thank you in advance,


Mathematica 7: "LessEqual::nord:" error when using NMinimize on a real function

I encounter a problem (Mathematica 7) similar to Strategies to avoid LessEqual::nord in NMinimize? but the advised strategies don't work for me. Also, I get different results with different approaches, though a standard evaluation of the different approaches results into the same number. I think this will become clear when looking at the function. My first approach is to define the function first and then minimize the sum of the squared real and imaginary part. To save a second evaluation, my second approach was to define a Module which directly returns the sum of the squared parts. Here are both the definitions:               eqnS[R_?MachineNumberQ,         k0_?MachineNumberQ, eps_?MachineNumberQ, mu_?MachineNumberQ] :=        2/(3 k0^2) (Exp[-I k0 R] (1 + I k0 R) - 1) -         1/(3 k0^2) (2 + eps mu)/(eps mu - 1);          mineqnS[R_?NumericQ,         k0_?NumericQ, eps_?NumericQ, mu_?NumericQ] := Module[{t},        t = 2/(3 k0^2) (Exp[-I k0 R] (1 + I k0 R) - 1) -           1/(3 k0^2) (2 + eps mu)/(eps mu - 1);         Re[t]^2 + Im[t]^2];      Now, using               k0 = 2 Pi/(510 10^-9);     eps = .7062 + I 2.0307;     mu = 1;      and then comparing               NMinimize[{Re[eqnS[R, k0, eps, mu]]^2 +         Im[eqnS[R, k0, eps, mu]]^2,        R >= 10^-9 && R <= 300 10^-9}, R, MaxIterations -> 200,       Method -> "NelderMead"]          NMinimize[{mineqnS[R, k0, eps, mu],        R >= 10^-9 && R <= 300 10^-9}, R, MaxIterations -> 200,       Method -> "NelderMead"]      the first approach without the "Module" and a doubled evaluation results to               {4.16756*10^-31, {R -> 1.10178*10^-7}}      which gives the **correct** result **without** errors. But the second, "Module", one, results (without the displaying the errors here) to               {3.76855*10^-29 + 0. I, {R -> 1.78688*10^-7}}.      And this, even though               mineqnS[10^-8, k0, eps, mu] ==       Re[eqnS[10^-8, k0, eps, mu]]^2 +         Im[eqnS[10^-8, k0, eps, mu]]^2 // N      gives me a "True"! The message for the second attempt reads               LessEqual::nord: Invalid comparison with 3.768547875531289`*^-29+0.` I attempted.      PS: In V8, the problem is still there.


GraphicsGrid command

When we merge some colorful plots to a single image, with the command `GraphicsGrid`, the quality of output image will be lost, slightly. That is, for instance all bright colors will darken and the fonts will be blurred. How can this problem be fixed? Is there any other commands to merge some plots (mathematical ones) to a single image without losing the quality? Please run the following commands               m := 1     n := -1     Subscript[Ω, 0] := 0.33     cn := (1 - (1 - m)*Subscript[Ω, 0])/(      1 - Sqrt[24] n (B)^(3/2))     v[N_] := (E^(3 N) f[N])^-(1 + 1)     f[N_] := (B + (1 - B)*E^(-6*N))^(1/2)     qnp := -1 + (       3 (2 (1 - B) cn v[N] (1 + (Sqrt[6] B^(3/2) n)/f[N]^(3/2)) f[N] +           E^(-3 N) (2 - (E^N)^(3/2) m) Subscript[Ω, 0]))/(       4 (cn (1 - (2 Sqrt[6] B^(3/2) n)/f[N]^(3/2)) f[N] +           E^(-3 N) (1 - (E^N)^(3/2) m) Subscript[Ω, 0]))     SetOptions[Plot, Frame -> True, Axes -> {False, False},        FrameStyle -> Directive[Black, 20, Bold], PlotRange -> {0.6, -1.1},        ImageSize -> 400,        FrameLabel -> {Style[N, FontSize -> 20, Bold],          Style["q", FontSize -> 20, Bold]}];     P16 := Plot[Evaluate[qnp /. B -> 0], {N, -3, 3},        PlotStyle -> {Thick, Dashing[{0.03, 0.01}], Brown}]     P26 := Plot[Evaluate[qnp /. B -> 0.33], {N, -3, 3},        PlotStyle -> {Dotted, Blue, Thick}]     P36 := Plot[Evaluate[qnp /. B -> 0.66], {N, -3, 3},        PlotStyle -> {DotDashed, Red, Thick}]     P46 := Plot[Evaluate[qnp /. B -> 0.99], {N, -3, 3},        PlotStyle -> {Thick, Black}]     Co16 := Graphics[       Text[Style["m=1", FontSize -> 13, Bold], {2.35, 0.31}]]     Co26 := Graphics[       Text[Style["\!\(\*SuperscriptBox[\(n\), \((I)\)]\)=-1",          FontSize -> 13, Bold], {2.5, 0.18}]]     L56 := Graphics[{Thick, Black, Line[{{1.95, 0.1}, {2.95, 0.1}}]}]     L66 := Graphics[{Thick, Black, Line[{{2.95, 0.1}, {2.95, 0.4}}]}]     L76 := Graphics[{Thick, Black, Line[{{2.95, 0.4}, {1.95, 0.4}}]}]     L86 := Graphics[{Thick, Black, Line[{{1.95, 0.1}, {1.95, 0.4}}]}]     Sh1 = Show[P16, P26, P36, P46, Co16, Co26, L56, L66, L76, L86]          m := -1     n := -1     Subscript[Ω, 0] := 0.33     cn := (1 - (1 - m)*Subscript[Ω, 0])/(      1 - Sqrt[24] n (B)^(3/2))     v[N_] := (E^(3 N) f[N])^-(1 + 1)     f[N_] := (B + (1 - B)*E^(-6*N))^(1/2)     qnp := -1 + (       3 (2 (1 - B) cn v[N] (1 + (Sqrt[6] B^(3/2) n)/f[N]^(3/2)) f[N] +           E^(-3 N) (2 - (E^N)^(3/2) m) Subscript[Ω, 0]))/(       4 (cn (1 - (2 Sqrt[6] B^(3/2) n)/f[N]^(3/2)) f[N] +           E^(-3 N) (1 - (E^N)^(3/2) m) Subscript[Ω, 0]))     SetOptions[Plot, Frame -> True, Axes -> {False, False},        FrameStyle -> Directive[Black, 20, Bold], PlotRange -> {0.6, -1.1},        ImageSize -> 400,        FrameLabel -> {Style[N, FontSize -> 20, Bold],          Style["q", FontSize -> 20, Bold]}];     P16 := Plot[Evaluate[qnp /. B -> 0], {N, -3, 3},        PlotStyle -> {Thick, Dashing[{0.03, 0.01}], Brown}]     P26 := Plot[Evaluate[qnp /. B -> 0.33], {N, -3, 3},        PlotStyle -> {Dotted, Blue, Thick}]     P36 := Plot[Evaluate[qnp /. B -> 0.66], {N, -3, 3},        PlotStyle -> {DotDashed, Red, Thick}]     P46 := Plot[Evaluate[qnp /. B -> 0.99], {N, -3, 3},        PlotStyle -> {Thick, Black}]     Co16 := Graphics[       Text[Style["m=-1", FontSize -> 13, Bold], {2.44, 0.31}]]     Co26 := Graphics[       Text[Style["\!\(\*SuperscriptBox[\(n\), \((I)\)]\)=-1",          FontSize -> 13, Bold], {2.5, 0.18}]]     L56 := Graphics[{Thick, Black, Line[{{1.9, 0.1}, {2.95, 0.1}}]}]     L66 := Graphics[{Thick, Black, Line[{{2.95, 0.1}, {2.95, 0.4}}]}]     L76 := Graphics[{Thick, Black, Line[{{2.95, 0.4}, {1.9, 0.4}}]}]     L86 := Graphics[{Thick, Black, Line[{{1.9, 0.1}, {1.9, 0.4}}]}]     Sh2 = Show[P16, P26, P36, P46, Co16, Co26, L56, L66, L76, L86]          GR := GraphicsGrid[{{Sh1, Sh2}}, Frame -> True,        FrameStyle -> Directive[Thick]]          Import[Export["fig1.jpg", GR]]


Problem with replacing a head with another head using pattern

Why would this work               Times[a, b, c, d] /. Times :> List     (* {a, b, c, d} *)      but this doesn't work (the `Times` still remains even when the `List` has been added)?               Times[a, b, c, d] /. Times[p__] :> List[p]     (* {a b c d} *)      Applying `Trace` shows that `Times` might have applied itself to `p__` before the pattern is matched, so that the expression now became just `a b c d/. p__:>{p}`. If that's the case, why would `Times[p__]` become `p__`?               Times[a, b, c, d] /. Times[p__] :> List[p] // Trace     (* {{{Times[p__],p__},p__:>{p},p__:>{p}},a b c d/. p__:>{p},{a b c d}} *)


How can i generate a curve arrow tube?

Following the document, I generate a curve arrow tube using following code:               arrowtube =       With[{ra = .1, arhd = .25},        Graphics3D[{Arrowheads[arhd],          Arrow[Tube[           BSplineCurve[Table[{Cos[t], Sin[t], 0}, {t, 0, 3 Pi/2, Pi/10}]],            ra]]}, Boxed -> False, ViewPoint -> {1, 1, 1},         ImageSize -> {100, Automatic}, Method -> {"ShrinkWrap" -> True}]]      and it gives me ![curve arrow tube](http://i.stack.imgur.com/WOkkh.png) It seems that the arrow doesn't align with the curved path. How can I fix this?


Matrix as a function of $x$

I need to use four functions of $x$               DD11 = @(x) x+0*x;     DD12 = @(x) x^2+0*x;     DD21 = @(x) cos(x)+0*x;     DD22 = @(x) 1+0*x;      and since they all represent the same physical quantity, and also for the sake of convenience, I would like to define in a matrix form:               DD = @x [x x^2; cos(x) 1];      If I do this, how will I recall the different elements at a given point later on? For example, the syntax `DD[1,2](0)` or `DD(0)[1,2]` don't work... Thanks!


combining NeighborhoodGraph and RandomGraph

I have `Combinatorica`` and `GraphUtilities`` loaded in version 9 of _Mathematica_. If I then set:               G = RandomGraph[20,0.5];     G1 = NeighborhoodGraph[G,1];      I get the error message that `NeighborhoodGraph` requires a graph object at position 1. How do I convert `G` into a graph object? I can get this process to work with named graphs in _Mathematica_ using `GraphData` but am clearly missing something with random graphs.


How to replace an element in a list based on the value of the next element?

I use _Mathematica_ a little bit. I try to understand it, but it is hard I have a list of 5 numbers selected randomly from 0 and -1. I have to replace a 0 with a 1 when the 0 is followed by -1. My wrong solution is:               list = RandomInteger[{-1, 0}, 5]      (* {0, 0, 0, -1, 0} *)          list /. x_ /; x == 0 -> 1     (* {1, 1, 1, -1, 1} *)      I need get: `{0, 0, 1, -1, 0}`. How do I manipulate a list to change the previous element if the next element is -1?


Strange behaviour of UpSet

Can anyone explain what is going on here? I want to modify `TensorRank` for `IdentityMatrix`, but it fails on its first attempt:               Unprotect[IdentityMatrix];     Attributes[IdentityMatrix]      > >     {} >                 TensorRank[IdentityMatrix[_]] ^= 2;      > _UpSet::write: Tag IdentityMatrix in TensorRank[IdentityMatrix[_]] is > Protected. >>_               Attributes[IdentityMatrix]      > >     {Protected} >   Huh? Unprotecting it for the second time does work however:               Unprotect[IdentityMatrix];     TensorRank[IdentityMatrix[_]] ^= 2;     TensorRank[IdentityMatrix[n]]      > >     2 >   This is on 9.0.1 for OS X, and I'm seeing the same behaviour on the cloud (version 10 for Linux).


Is Mathematica 10 color managed?

With `ColorProfileData[`] Mathematica 10 can handle device-dependent color spaces. However, images with embedded color profiles, e.g. sRGB, are rendered and displayed differently from Adobe Photoshop (which, of course, supports color management). Does MMA 10 supports ICC color profiles for rendering images?


Removing some data and replacing them with new ones

I have a data list where the elements have the form (time, velocity ). I need to remove some malformed elements in places where the data does not change smoothly and then replace those points by interpolating the elements before and after them. Here is an example of my data:               {{27.342, -0.01}, {27.443, -0.03}, {27.546, -0.01}, {27.743, -0.01}, {27.945, -0.01},       {28.145, -0.03}, {28.246, -0.05}, {28.346, -0.06}, {28.547, -0.01}, {28.747, -0.01},       {29.149, -0.01}, {29.249, 0}, {29.45, -0.01}, {29.651, -0.05}, {29.852, -0.05},       {30.053, -0.01}, {30.153, -0.01}}      For instance the 7th and 8th elements are malformed since the wind cannot change from -0.3 to -0.05 and -0.6 and then back to -0.01 in 0.1 sec0, so I want to replace them with -0.03 and -0.02.


Assumptions within Simplify

I am using the ratio between two error probabilities in various functions. I want _Mathematica_ to display this ratio in the most simple manner. How do I let _Mathematica_ know that, in this case, the simplest manner is as the top line in the picture below? How do I let _Mathematica_ factor the expression into `(e1)`, `(e2)`, `(1 - e1)` and `(1 - e2)`? ![http://i.stack.imgur.com/89eol.png](http://i.stack.imgur.com/89eol.png)


Counting function, comparing lists

# Update I would now like to produce a plot that explores the difference between the squarefree count and the expected mean (without using SquareFreeQ) - something along the lines of:               a = PrimeOmega[Range[1000]];     b = PrimeNu[Range[1000]];     ListLinePlot[{#/Zeta[2] - Accumulate[Flatten[Inner[If[#1 === #2, 1, 0]      &, a, b, List]]]}, Filling -> Axis]      or               a = PrimeOmega[Range[100]];     b = PrimeNu[Range[100]];     Plot[{x/Zeta[2] - Accumulate[Flatten[Inner[If[#1 === #2, 1, 0] &, a, b, List]]]},      {x, 0, 100}, Filling -> Axis]      In the hope of achieving something similar to:               Plot[{{x/Log[x]} - PrimePi[x]}, {x, 0, 100}, Filling -> Axis]      Or alternatively, slightly alter Artes' cf plot (see below). Instead of:               cf = {#, Count[Range[#, # + 500], _?SquareFreeQ]} & /@ Range[0, 100000, 500]      Using something like:               a = PrimeOmega[Range[100000]];     b = PrimeNu[Range[100000]];     cf = {#, Count[Range[#, # + 500], _?Accumulate[Flatten[Inner[If[#1 === #2, 1, 0]      &, a, b, List]]]]} & /@ Range[0, 100000, 500]      ... Much clumsier, I realise, but I would like to avoid using SquareFreeQ if I can. # Old I would like mathematica to output instances where `PrimeOmega[x]=PrimeNu[x]` up to a given range. (Clearly in this example, the output will be the set of square free numbers.)               a = PrimeOmega[Range[1000000]];     b = PrimeNu[Range[1000000]];     Count[Transpose[{a, b}], {1, 1}]     a = PrimeOmega[Range[1000000]];     b = PrimeNu[Range[1000000]];     Count[Transpose[{a, b}], {2, 2}] .....      works, but is (a) very slow, and (b) very clumsy. I was wondering if there was a more succinct way of putting it? In addition, I would like to ultimately create a plot for what will essentially be a counting function for `PrimeOmega[x]&&PrimeNu[x]=={1, 1},{2, 2}...` etc. Is there any way of doing this?


System Identification with large Input/Output Data

I have some questions about system identification. I made some measurement of current step (input) and voltage response(output) and I want to fine the parameters of my impedance. The sample rate is 1000 samples/s so that I have a very large list of current and voltage samples include noise (40000 Samples). My voltage is U(kT) and current is I(kT) where k=1,2,3,.....40000.   1. to filter the noise I used `ExponentialMovingaverage`; is there any other possibility to filter the noise from the list?   2. in _Mathematica_ there is a function with the name `NonlinearModelfit` to find system parameters. Is there any other possibility to find the system parameters like nonlinear Least Square?


Solve[ ] with Method -> Reduce gives a different result than Reduce[ ]

Why does               Solve[Sqrt[x + Sqrt[x]] - Sqrt[x - Sqrt[x]] ==           m Sqrt[x/(x + Sqrt[x])], x, Reals, Method -> Reduce]      give a different result than               Reduce[Sqrt[x + Sqrt[x]] - Sqrt[x - Sqrt[x]] ==            m Sqrt[x/(x + Sqrt[x])], x, Reals]      note that the first one says $1<m<2$ while the second one says $1<m\le 2$.   The documentation says > With `Method->Reduce`, `Solve` uses only equivalent transformations and > finds all solutions.


Reading from STDIN, or: how to pipe data into Mathematica

Today I tried using Mathematica's plotting capabilities to display the output of a C++ program. This made me wonder whether it is possible to somehow tell a Mathematica script to read from STDIN and then do something with that, a la               #/usr/local/bin/MathematicaScript -script          (* Mathematica plotting script *)     data = ReadStream["STDIN"];     plot = ListPlot[data];     Export[plot, ...];      which can then be used like               ./cppDataGenerator | mathematicaPlotScript      However, I couldn't find much on that in the documentation, the entries always focus on output or string streams, and trial and error didn't yield a result either. So the question is: **How can I make a Mathematica script listen on the standard input?**


Selecting for 2D points that are within a threshold distance of an upper- and lower-bound number of points

I have a very large set of 2D points:               numberOf2DPoints = 10^6;     pointList = RandomReal[{0, 1000}, {numberOf2DPoints, 2}];      I'd like to find a way to quickly generate a distribution I can study for the number of points within a distance $r$ from each point, and then I'd like to select points that have at least a lowerbound $k_a$ and an upperbound $k_b$ number of points within a distance $r$ of themselves. Is there a way to use a function like `Nearest` to accomplish this? Clarification --- The lowerbound $k_a$ and upperbound $k_b$ refers strictly to the count for the number of points in a circular disk of radius $r$ centered on a particular point (hopefully this makes sense). So I'd want basically a simple histogram for what this distribution of point counts looks like, and to select points that have satisfy the upper- and lowerbound point count criterion.


How to automate a FrontEnd return?

I use some custom shortcut keys in `KeyEventTranslations.tr`. One is for the `Delete All Output` function:               Item[KeyEvent["w", Modifiers -> {Control}],          FrontEnd`FrontEndExecute[FrontEnd`FrontEndToken["DeleteGeneratedCells"]]]      or simply:               Item[KeyEvent["w", Modifiers -> {Control}], "DeleteGeneratedCells"]      This works as expected, putting up the dialog: "Do you really want to delete all the output cells in the notebook?". Is there any way to set up `KeyEventTranslations.tr` that when I hit `Ctrl`+`w` the dialog is automatically acknowledged and I don't have to hit `Enter`? The same goes for the `Quit kernel` function, that also puts up a dialog.


Mathematica and System Modeler licensing per year or forever?

I am confused about how Mathematica licensing works and there seem to be no clear explanations on the Wolfram site.   * I got Mathematica Starter last year and installed both at work and home (included for "free")   * I assume my Home Edition 9 is permanent, ie, never needs to be renewed and will last forever, ie I "bought it". Unfortunately I am stuck on 9 because 10 will not run on XP.   * My Mathematica 10 which I recently upgraded seems to be working fine at work, will it last forever, or will I at some point get some "expired" message?   * I have already got an "expired" message for SystemModeler which I got at the same time, and I can no longer use SystemModeler. Is this because "Starter" expires after a year?   * The "Modeling & Simulation Suite" which they advertise including both Mathematica and SM does not say whether it is a yearly deal or permanent. Which is it? ![System Information](http://i.stack.imgur.com/E5IHd.png)


Generating x,y coordinates for an edge detection

I'd like to be able to process a number of graphics that have edge contours and output a list of $x$, $y$ coordinates to be used for generating a spline in another program, or in Mathematica, to make a SOR, prism, etc. Essentially, given a photo of a turned spindle, output the radius as a function of length. > ![enter image description here](http://i.stack.imgur.com/UhLrU.png) I was working with code from Get x and z coordinate from an image and make a parametric surface. I've got to the point where I can output a graph of the "height" vs length, but I need to get a list of coordinates. I suppose being able to draw a line to measure from in the case of tricky graphics or slanted [eventual] centers of rotation would be a helpful feature.


Animate ParametricPlot3D for two different parametric equations

I want to write a computer program to generate 3-D plots (with x-y-t axes) to demonstrate the evolution of the two missiles in the following case: i. $x = 100t$, $y = 80t-16t^2$ for $0\leq t\leq 5$ for the incoming missile ii. $x= 500-200(t-2)$, $y = 80(t-2)-16(t-2)^2$ for $2\leq t\leq 7$ for the interceptor missile I coded it like this:               ParametricPlot3D[{{100 t, 80 t - 16 t^2, 60 t}, {500 - 200 (s - 2),      80 (s - 2) - 16 (s - 2)^2, s}}, {t, 0, 5}, {s, 2, 7}]      The problem is that How can I animate this two functions in 3D form (with x-y-t axes)? I want it to display two moving objects,so i can see if there's any collision.By the way,please help me to correct the code if I'm wrong.


Default Chart Color Doesn't Match

I have looked through other posts to find out what the default plot color is, but when I use it, the color doesn't seem to match. Can anyone explain why I'm seeing different output? The reason I ask is that I'd like to provide higher level plotting function that have an optional color parameter. If you don't provide your own color, I'd like to use Mathematica's defaults...but it doesn't create the same output.               BarChart[Range[5]]      ![Default Mathematica BarChart](http://i.stack.imgur.com/dfJi6.png)               BarChart[Range[5], ChartStyle -> ColorData[1, 1]]      ![Mathematica BarChart with ColorData\[1,1\]](http://i.stack.imgur.com/KdLwu.png) Thanks, Bill Update: Thanks for the help so far. It looks like BarCharts get a different color set than regular plots, because `ColorData[1, 1]` is the default color for Plot and ListPlot:               Plot[Sin[x], {x, -Pi, Pi}, PlotStyle -> Thickness[0.02]]      ![Sin Plot](http://i.stack.imgur.com/A97wC.png) But I do like the color set that is the default for BarChart:                BarChart[{Range[5]}]      ![BarChart with progressing colors](http://i.stack.imgur.com/hM18h.png) As I look through the available color pallets, I'm not sure I see those as an option:               Grid[Partition[         Framed[Show[ColorData[#, "Image"], ImageSize -> 100],          FrameStyle -> Gray] & /@ ColorData["Indexed"], 6, 6, 1, {}],          Spacings -> .25]      ![color pallets](http://i.stack.imgur.com/ry4fz.png) Some further reflections. It hit me that the colors used for the BarChart are actually some type of gradient. It seems to be a "pastel rainbow" if I can call it that. It goes from blue to red, but it's not the bright rainbow colors, and it seems to lock in the first and last colors while changing the colors of the bars in a smooth fashion according to some function (I will be trying to figure this out). You can see what I'm talking about if you plot the following: `BarChart[{Range[40]}, ImageSize -> Large]` I tried matching this to one of the named gradients, but none of them match. That first bluish/purple color is not represented in any of these plots (was looking for Red and Green around 0.8 with a Blue around 1):               Plot[{ColorData[#, x][[1]], ColorData[#, x][[2]],          ColorData[#, x][[3]]}, {x, 0, 1}, PlotStyle -> {Red, Green, Blue},         PlotLabel -> #] & /@ ColorData["Gradients"]


Mathematica output format for big numbers

I need to write output of a Mathematica expression (a list of equations) in a file. I use                   WriteInput[fname_, var_, eqlist_] := Module[{str, leq},         str = OpenWrite[fname];         leq = Length[eqlist];         WriteString[str, "{"];         removebracketvar[x_] :=          StringReplace[StringReplace[ToString[x],{"["-> "","]"->"",","->""}],Whitespace->""];         (*write equations*)         Do[          WriteString[str,          removebracketvar[ToString[eqlist[[i]] , InputForm]] ];         WriteString[str , ";\n"] ,         {i, leq}];         WriteString[str, "}"];         Close[str]         ]      This works fine for small coefficients, e.g.,                SetDirectory["/home/mydir"];WriteInput["sys1.txt",{x[1,1],x[2,1],x[1,2]},        {3.4x[1,1]^2,x[2,1]^2,x[1,2]^2}]      i.e., it generates the following file sys1.txt               {3.4*x11^2;     x21^2;     x12^2;     }      However, the problem comes up when 1. the coefficients are integer, e.g.,               SetDirectory["/home/mydir"];     WriteInput["sys1.txt", {x[1, 1], x[2, 1], x[1, 2]}, {3.0 x[1, 1]^2, x[2, 1]^2, x[1, 2]^2}]      which writes sys1.txt as               {3.*x11^2;     x21^2;     x12^2;     }      where '3.' is not appropriate for the later operations on the file by some other external code. 3.0 or 3 is what I want. Coefficients in scientific form are also problematic. e.g.,                 SetDirectory["/home/mydir"];       WriteInput["sys1.txt", {x[1, 1], x[2, 1], x[1, 2]},         {3.998723445*10^6 x[1, 1]^2, x[2, 1]^2, x[1, 2]^2}]      gives               {3.998723445*^6*x11^2;*x11^2;     x21^2;     x12^2;     }      where it has this weird `*^` notation for the exponents. I want _10^(6)_ instead, or just in the non-scientific form, i.e., 3998723.445 is also fine. Is there any good way of tweaking this short code to get the coefficients in the form I want?


When to use Get vs Needs

When should I use `<<` vs `Needs`? I just always use `Needs` as `<<` seems less safe. I tried to find the answer in the documentation, but all it really seems to say is that `Needs` uses `Get`. My understanding is that `Needs` will only do the import once, whereas `Get` will happily do it again. So is this just a style issue? Or are there reasons to use one or the other?


Speed up Fourier for Booleans

I'm calculating a bit of the power spectrum of a two color cellular automaton using:               Abs[Fourier[#, FourierParameters -> {-1, -1}][[All, 1 ;; 100]] & /@          Transpose[CellularAutomaton[...]]]^2 // Total      Since I'm new to Mathematica, some trivial questions:   * Does it automatically optimize for the type of input data (just integers 0 and 1) or should I manually use `Compile`? Can I give it some hints about the input?   * Is Mathematica lazy enough to see that I only care about the first 100 frequencies and won't calculate the others? (the ones I care about are significantly less than the length of the input data, is there a better way to do this?) * * * This is to match a paper, everybody else seems to use this form which would be more efficient because it doesn't have to thread the `Fourier` over all columns:               CellularAutomaton[...] // Transpose // Total // Fourier // Abs


Manipulating local or external variable within NDSolve

I am wanting to save and use the value of a variable within `NDSolve[]` but without that variable being part of the equation itself. Code below (ODE for the Leaky Integrate-and-Fire neuron) expresses what I want to do, with the value for the end of the refractory period updated within a `WhenEvent[]` statement. Unfortunately it doesn't work and the error message suggests why not - but I don't know the solution though I am sure a simple one must exist.               trest = 0;     With[{τ = 10, R = 1, Jm = 1.5, vthresh = 1, vreset = 0, v0 = 0, tref = 3 },      lif = NDSolve[{v'[t] == If[ t >= trest, -(v[t] - Jm R)/τ, 0],              v[0] == v0,              WhenEvent[ v[t] >= vthresh, {v[t] -> vreset, trest -> Evaluate[ t + tref ] } ]},             v[t], {t, 0, 60}] ]      > >     NDSolve::wenset: Warning: the rule trest->Evaluate[t+3] will not > directly set >     the state because the left-hand side is not a list of state variables. > >> >   I realise that this can be done by adding another variable into the ODE, making its time `derivative == 0` and just changing its value within the `WhenEvent[]` statement but this is rather messy and has potential to confuse the ODE solver.


Does Mathematica use first order or second order order unification?

When Mathematica is pattern-matching expressions, does it use first order or second order unification. Just to clarify the difference between first order and second order unification:   In Second order unification, it is possible to replace a pattern variable with a function: When the expression `3+3` or `Plus[3,3]` is matched with the pattern `f[3]`, the matching succeeds and `f` is bound to `Plus[#, #]&` or `Plus[3, #]&`.


Plotting an Unreasonable Function

Without getting into too much detail, the following (very complicated) function recently appeared as a solution to a combinatorics problem I've been thinking about: $$P(n) = \frac{52!}{52^{52}} \cdot \sum_{1=i_{1} < i_{2} < \ldots < i_{51} < i_{52} \le n} \left[ \prod_{k=1}^{51} \left( \frac{k}{52} \right)^{i_{k+1}-i_{k}-1}\right]$$ I'd like to plot this sucker in Mathematica but as it stands I don't see how that's going to happen. If there's a way to simplify this expression or some sort of efficient way to evaluate it I'd really appreciate any help. I know that $P(n)=0$ for $1 \le n < 52$, $P(52)=\frac{52!}{52^{52}}$, and $P(n)$ should grow quickly towards 1 and then plateau, so it should look something like the CDF of the normal distribution centered around 52 when all's said and done. Thanks!


How to convert a hex color string to RGBColor?

For example: `"#FF8000"`. How could I convert it to `RGBColor` or `Hue`?


Is it possible to define more than 9 shortcuts for notebook cell styles?

You can define shortcuts for notebook cell styles in the stylesheet editor, by adding `MenuCommandKey->"7",` etc. to the style definition. That is, you can define `Alt`-`1` to set/create a cell with one style, `Alt`-`2` a different style, ..., through `Alt`-`9`. From the documentation in Mathematica 8 for `MenuCommandKey` for styles: > Acceptable values include None and "1" through "9". So it appears that there are only 9 possible shortcuts. But there are more than 9 styles I commonly use. Is it possible to define additional such shortcuts?


Function saved in a package won't load in the deployed CDF on startup

I wrote a function and saved it in a package. I saved a copy of the package in the Autoload folder too. I deployed a CDF that contains this function. When I open the CDF later, this function (which represents modified input fields) is not evaluated. But when I do any operation that evaluates this function (like a button click), it gets evaluated and the cdf works just fine. I am using Mathematica 9 to deploy the cdf and also to run it to check it. Updated, the package's code down below -               BeginPackage["ModifiedInputFields`"] InputFieldsCreation[noOfrows_,       noOfInputFields_] :=     (          Module[         {inputvaluelist = Table[0, {noOfrows}, {noOfInputFields}]},         (                 If[             (noOfrows > 0),             (*If noOfrows value is greater than 0*)                  (                 {                     Table[                              (                                 With[{i = i, j = j}, (Row[{                                              Dynamic[InputField[                                                     Dynamic[inputvaluelist[[i, j]]],                                                     Number,                                                     ContinuousAction -> True,                                                     ImageSize -> {50, 20},                                                     Alignment -> Center                                                        ]]                                         }])]                                 (*with is closed*)                                ),                                 {i, 1, noOfrows},                                 {j, 1, Length[Part[inputvaluelist, i]]}                         ],(*Table closed*)                     Dynamic[inputvaluelist]                 }                  ),             ("")           ]             )       ]     (*Module closed*)     )     EndPackage[]       What I am looking at is to also be able to extract all the inputs that the user gives in the input fields into a list that we pass on to other functions. So that is a critical feature, which I am worried might also be a reason for the package giving trouble at cdf startup.


FindEdgeCut with weighted graphs

If I want to find a minimum cut between two nodes in a weighted graph, I would use FindEdgeCut as follows:               g = Graph[{1 \[UndirectedEdge] 2, 2 \[UndirectedEdge] 3, 1 \[UndirectedEdge] 3,          3 \[UndirectedEdge] 4}, EdgeWeight -> {2, 3, 5, 123}];     FindEdgeCut[g,1,4]      This function, however, returns the edge 3-4, so obviously the edge weights have not been considered. I can find the minimum cut by using the maximum flow and so on, but I was wondering whether this error is more easily fixable or maybe it's just me and I don't see the error.


Unexpected result of summation

I wrote small module that gives me incorrect output-set, it should be a single number! I don't understand what went wrong. This is the form of summation used: $$\frac{1}{2} (b-a) \sum_{i=1}^n w_i\,f\left(\frac{b-a}{2}x_i+\frac{a+b}{2}\right)$$ where ${x,w}$ are generated by `GaussianQuadratureWeights` command:                 Needs["NumericalDifferentialEquationAnalysis`"]         GaussLegendreQuadrature[a_, b_, n_] := Module[{weights, i},            (* GaussianQuadratureWeights[n, a, b] gives a list of the               n pairs {Subscript[x, i], Subscript[w, i]} of the elementary               n-point Gaussian formula for quadrature on the interval a to b,               where Subscript[w, i] is the weight of the abscissa               Subscript[x, i].*)                 weights = GaussianQuadratureWeights[n, -1, 1];            Return[(b - a)/2 \!\(         \*UnderoverscriptBox[\(\[Sum]\), \(i = 1\), \(n\)]\(         \*SubscriptBox[\(weights\), \(i, 2\)]\ f[         \*FractionBox[\(a + b\), \(2\)] +          \*FractionBox[\(b - a\), \(2\)]          \*SubscriptBox[\(weights\), \(i, 1\)]]\)\)]];              f[x_] := Sin[x];         GaussLegendre[0, 1, 8]


How to make functions from datasets

I have a csv that encodes the results of plugging certain parameters (say, `A` and `B`) into certain functions (say, `f` and `g`). Think matrix with (say, 4) columns and a million rows with the columns corresponding to `A, B, C = f(A, B)`, and `D = g(A, B)` respectively. I'd like to be able to use the dynamic visualization features of mathematica, but this requires turning this data into discreet functions, and the columns into their own lists to use as domains in the Manipulate environment. I want to be able to do something like `Manipulate[Plot[function[A, B], {A, (list of values)}], {B, (list of values)}, {function, {f, g}}]` I have been poring over the Help guide for hours and this seems to be such a basic thing to do that I feel crazy for not being able to find it.


How do I identify the source of a "Tag times protected" error?

I have some code that looks like               Table[         a = 1;         b = {2, 3}         c = i;,         {i, 2}     ]      which gives an error: > Set::write: Tag Times in c {2,3} is Protected. >> In this case, it is quite clear that there is a semicolon missing after `b = {2, 3}`, which is causing this error. However, sometimes I encounter this in large code blocks spanning several lines, which is very difficult to debug. How can I automate this semicolon hunting to make debugging easier?


Mathematica document not retaining margins from stylesheet when printing?

In the process of creating my resume in Mathematica, I needed to adjust the margins of the default stylesheet so that section headers would take up less whitespace. After modifying the stylesheet using the instructions mentioned here, the changes clearly show up in my document in Mathematica. ![Before printing](http://i.stack.imgur.com/vzphS.png) However, after I export the document to a PDF, either by saving or by printing, my work is undone. ![After printing document](http://i.stack.imgur.com/gTS9L.png) So I've resorted to copying and pasting screen captures of my resume into MSPaint and then printing from there. This is a huge pain. What am I doing wrong? Is there a setting I have to modify to get my stylesheet margins to stick in the PDF version?


Dropping n consecutive terms from a list periodically

Suppose I have the following list               lis = Range[100];      and I want to remove n consecutive terms periodically from the list. For example suppose I want to drop terms 4 and 5, 9 and 10, 14 and 15 etc. I could do this sequentially as follows:               Drop[Drop[lis, {5, -1, 5}], {4, -1, 4}];      This gives:               {1, 2, 3, 6, 7, 8, 11, 12, 13, 16, 17, 18, 21, 22, 23, 26, 27, 28,      31, 32, 33, 36, 37, 38, 41, 42, 43, 46, 47, 48, 51, 52, 53, 56, 57,      58, 61, 62, 63, 66, 67, 68, 71, 72, 73, 76, 77, 78, 81, 82, 83, 86,      87, 88, 91, 92, 93, 96, 97, 98}      This gets really messy if I have to drop `n` consecutive terms where `n` is large. Is there a way to do this with just one `Drop` function or a better more compact and efficient way to achieve this where my list is huge. In my example above, `n` is `2`, but it could be `3`, `4` etc. What I want is a general solution. Thanks.


NDSolve runs out of memory

I need to solve a second order ODE numerically. The ODE depends on two parameters (a,b). Things work fine when 'a' is small, but for large 'a' the solutions are oscillating rapidly and Mathematica takes a long time to solve or eventually just runs out of memory. I need to integrate over quite a large range (10,000) and that is part of the problem, but I actually only need the value of the `InterpolatingFunction` produced at the end point. Is there a way to tell Mathematica I just want this last point? And not store the rest (very large) `InterpolatingFunction` in memory? i.e. just integrate so far, take that point use as ICs for next leg, then integrate to next pt, take that as IC and integrate onwards,etc... Or just some other strategy for using `NDSolve` with such highly oscillatory solutions. Some definitions:               M=1;     rstar[r_] := r + 2 M Log[r/(2 M) - 1];     $MinPrecision = 45;         wp = $MinPrecision;     ac = $MinPrecision - 8;     \[Lambda][l_] = l (l + 1);     rinf = 10000;     rH = 200001/100000;     nH = 200;      The ODE is:               eq[\[Omega]_, l_] := \[CapitalPhi]''[r] + (2 (r - M))/(      r (r - 2 M)) \[CapitalPhi]'[      r] + ((\[Omega]^2 r^2)/(r - 2 M)^2 - \[Lambda][l]/(      r (r - 2 M))) \[CapitalPhi][r] == 0      Without going into detail about why I have these initial conditions, they are :               HorizonICs[l_?IntegerQ, \[Omega]_?NumericQ] :=       Module[{\[CapitalPhi]inrH, d\[CapitalPhi]inrH},      Clear[b];        b[0] = 1; b[-1] = 0; b[-2] = 0;        b[n_] :=        b[n] = Simplify[      1/(2 n (n - 4 I \[Omega])) (-2 I \[Omega] b[-2 + n] +          2 I n \[Omega] b[-2 + n] + l b[-1 + n] + l^2 b[-1 + n] +          n b[-1 + n] - n^2 b[-1 + n] - 4 I \[Omega] b[-1 + n] +          8 I n \[Omega] b[-1 + n])];       uintrunc[r_, n_] := Sum[b[i] (r - 2 M)^i, {i, 0, n}];       \[CapitalPhi]inrH = (Exp[-I \[Omega] rstar[rH]] uintrunc[rH, nH])/(       2 M);      d\[CapitalPhi]inrH =        D[(Exp[-I \[Omega] rstar[r]] uintrunc[r, nH])/(2 M), r] /.         r -> rH;      ]      Solve as               \[CapitalPhi]inExt[\[Omega]\[Omega]_ ,       l_] := \[CapitalPhi]inExt[\[Omega]\[Omega], l] = \[CapitalPhi] /.       NDSolve[{eq[\[Omega]\[Omega], l], \[CapitalPhi][rH] ==          N[HorizonICs[l, \[Omega]\[Omega]][[1]], wp], \[CapitalPhi]'[          rH] == N[HorizonICs[l, \[Omega]\[Omega]][[2]],           wp]}, \[CapitalPhi], {r, rH, rinf}, WorkingPrecision -> wp,        AccuracyGoal -> ac, MaxSteps -> \[Infinity],        Method -> "StiffnessSwitching"][[1]];      You can also look for another solution that has the property of being simple near infinity and we set the ICs there. This is the particular solution that seems to be really really slow and causes memory crash. Some definitions:               M = 1;     r0 = 5/2;     rstar[r_] := r + 2 M Log[r/(2 M) - 1];     $MinPrecision = 45;         wp = $MinPrecision;     ac = $MinPrecision - 8;     \[Lambda][l_] = l (l + 1);     rinf = 10000;     ninfphase =      50;       Set init conditions:               Infinitycs = Module[{n = ninfphase, c},      Clear[c];     veqexp =      CoefficientList[      Series[(-2 - l r - l^2 r + 2 (r + I r^3 \[Omega])      \!\(\*SuperscriptBox["v", "\[Prime]",     MultilineFunction->None]\)[r] + (-2 + r) r^2      \!\(\*SuperscriptBox["v", "\[Prime]",     MultilineFunction->None]\)[r]^2 + (-2 + r) r^2      \!\(\*SuperscriptBox["v", "\[Prime]\[Prime]",     MultilineFunction->None]\)[r])/        r /. {v'[r_] :> Sum[-i c[i]/r^(i + 1), {i, 1, n}],          v''[r_] :>           Sum[i (i + 1) c[i]/r^(i + 2), {i, 1, n}]}, {r, \[Infinity],         n - 1}], r^-1];     Do[c[i] = c[i] /. Simplify[Solve[veqexp[[i]] == 0, c[i]][[1]]];      Print, {i, 1, n}] ;     Table[c[i], {i, 1, n}]];          InfinityICs[ll_?IntegerQ, \[Omega]\[Omega]_?NumericQ] := Module[{c2},     Do[c2[i] =      Infinitycs[[i]] /. {l -> ll, \[Omega] -> \[Omega]\[Omega]}, {i, 1,      ninfphase}];     vtrunc = Sum[c2[i]/r^i, {i, 1, ninfphase}];     init = 1/r Exp[I \[Omega]\[Omega] rstar[r] + vtrunc] /. r -> rinf;     dinit =      D[1/r Exp[I \[Omega]\[Omega] rstar[r] + vtrunc], r] /. r -> rinf;     Clear[c2];     {init, dinit}]      Solve it               \[CapitalPhi]out[\[Omega]\[Omega]_,      l_] := \[CapitalPhi]out[\[Omega]\[Omega], l] = \[CapitalPhi] /.      Block[{$MaxExtraPrecision = 100},        NDSolve[{eq[\[Omega]\[Omega], l], \[CapitalPhi][rinf] ==           N[InfinityICs[l, \[Omega]\[Omega]][[1]], wp], \[CapitalPhi]'[           rinf] ==           N[InfinityICs[l, \[Omega]\[Omega]][[2]],            wp]}, \[CapitalPhi], {r, rinf, r0}, WorkingPrecision -> wp,         AccuracyGoal -> ac, MaxSteps -> \[Infinity]]][[1]];


How to use the Testing Notebook to test a package?

I think an important purpose of the new `Testing Notebook` in version 10 should be to test user packages (instead to test the builtin functions in the `System` context). However, what's the proper way to load a package into the testing notebook? I didn't find an example in documentation. What I have tried is to simply load it as an input. But it doesn't seem to work. For example, I have a file test.m in the system directory, with               BeginPackage["test`"]     testFunc     EndPackage[]      Then I start Mathematica, open `File->New->Testing Notebook`, and input the following as separate input cells:               << test.m (* also tried Needs["test`"] without difference *)      and               testFunc      If I evaluate each cell by hand, there is no problem. But if I quit the kernel (to start over) and then hit the `run` button, I sometimes got `testFunc::shdw` message. By sometimes I mean I did a few tests, each time quit the kernel and start over, and the result is either as left or right of the attached figure ![enter image description here](http://i.stack.imgur.com/lTalR.png) I got really confused here. Also, in the expected output of the right panel, the context becomes explicit. This is quite annoying for a long expression with a long context. I was wondering if it is normal.


Input Aliases in Mathematica 10

In Mathematica 9, typing in an input alias such as `intt` would result in the keyboard cursor automatically positioned within the first `SelectionPlaceholder` and ready to type inside it. However, in Mathematica 10 when I type it the keyboard cursor is placed to the side of the selection placeholder. Is anyone else experiencing this? In MMA10, how do you go creating a placeholder so that when you type the alias the keyboard cursor is already positioned within the first box?


Classify the classic tennis example

When using the classic tennis data (reference here) with **Classify**               sunny = "Sunny";     overcast = "Overcast";     rainy = "Rainy";     high = "High";     low = "Low";     tennis = {      {sunny, low, True} -> True,      {sunny, high, True} -> False,      {sunny, high, False} -> False,      {overcast, low, True} -> True,      {overcast, high, False} -> True,      {overcast, low, False} -> True,      {rainy, low, True} -> False,      {rainy, low, False} -> True     };     cl = Classify[tennis]      (resulting in a Breiman-Cutler ensemble classification) I get the unexpected result               cl[Keys[tennis]]          {True, True, True, True, True, True, True, True}      I would expect that at least the given input is being classified correctly. What is wrong here? ![Wolfram Desktop Option](http://i.stack.imgur.com/qNpMh.png)


What is the precedence of FrameStyle, FrameTicksStyle, and LabelStyle? How to have a LabelStyle different from FrameStyle

From the documentation:               Plot[2 Sin[x], {x, 0, 10}, Frame -> True, FrameLabel -> {x, y},       PlotLabel -> 2 Sin[x], LabelStyle -> Orange]      ![enter image description here](http://i.stack.imgur.com/kirjg.png) But then add a frame style:               Plot[2 Sin[x], {x, 0, 10}, Frame -> True, FrameLabel -> {x, y},       PlotLabel -> 2 Sin[x], FrameStyle -> Green, LabelStyle -> Orange]      ![enter image description here](http://i.stack.imgur.com/jYpk4.png) To me this is unexpected. I thought `FrameStyle` controlled the frame style not the frame tick or frame label style (if explicit options had been entered for `FrameTicksStyle` and `LabelStyle`). It is possible to separate the styles of the frame and the frame ticks (via `FrameTicksStyle`). I'm assuming I am missing something **very** obvious here but how can a user give separate the styles of the frame and the frame labels? i.e. How can I create a plot with a blue frame and red frame labels? (I know I can use `Style` when entering frame labels but I am seeking an answer in terms of plotting options -- if one exists.)


How can I make points "glow"?

I have a set of points in the plane which I would like to have "glow". I would like for each point to glow individually and I would also like some increase in the intensity corresponding to an increase in density of the points. I've come up with a couple ideas for how to do this using `DensityPlot` but neither are quite what I'm hoping for. I'll describe them below. I need some points, say               pts = Table[{Re[E^(I t/2 - t/10)], Im[E^(I t/2 - t/10)]}, {t, 1, 50}];      The first idea is to consider an density function like $$ \frac{1}{\epsilon + \min_{a \in \text{pts}}\operatorname{dist}((x,y),a)}. $$ My code for this is               eps = 1/16; exponent = 1/2;          distfunc1[x_, y_] =         1/(eps + Min[           Table[              ((x - pts[[k, 1]])^2 + (y - pts[[k, 2]])^2)^(exponent),              {k, 1, Length[pts]}           ]        ]);          Show[        DensityPlot[distfunc1[x, y], {x, -1, 1}, {y, -1, 1},            PlotPoints -> 40],        Graphics[{PointSize[0.007], Point[pts]}]     ]      which produces ![enter image description here](http://i.stack.imgur.com/gEYhF.png) The non-differentiability of the density function leads to sharp divisions between the glows. To get around that I considered adding the distances instead of taking the minimum, like $$ \sum_{a \in \text{pts}} \frac{1}{\epsilon + \operatorname{dist}((x,y),a)}. $$ My definition is               distfunc2[x_, y_] =         Sum[           1/(((x - pts[[k, 1]])^2 + (y - pts[[k, 2]])^2)^(exponent) + eps),           {k, 1, Length[pts]}        ];      By varying the parameters `eps` and `exponent` I can get parts of what I want. For example with `eps = 1/4` and `exponent = 1/2` I get nice smooth glows around the outer points but the inner region becomes too "hot": ![enter image description here](http://i.stack.imgur.com/5TAjM.png) With `eps = 1/2` and `exponent = 1/1400` the middle is no longer too hot and has the brightest glow from the density but the outer points no longer have significant idividual glows: ![enter image description here](http://i.stack.imgur.com/Y39gz.png) I haven't yet found a way to have a nice strong glow in the center as well as distinct, nontrivial glows for each of the outer points. I appreciate any ideas you may have. Also, I'm new to _Mathematica_ and I don't really know how `ColorFunction` works. Is it easy to increase the range of lights/darks (i.e. increase contrast) in the color function used by `DensityPlot` to render its pictures? I would like the darkest color to be near-black in the above pictures if possible.


How to pass a list as function argument?

I have the following function               lFreqPhylo[a_, Q_, b_, p_] :=  Sum[Log[freqFunction[r[[p]][[i]], L[[p]][[i]], a, Q, b, {i, 1, nbranches[[p]]}];      The objects _L_ , _r_ and _nbranches_ are simply lists of data, and the argument p tells the function which dataset to refer to. I'd like to define a function which sums all of the datasets (here n=2) and uses a different argument a and b for each dataset, so to write it our by hand,               lFreqPhylo[a1, Q, b1, 1] + lFreqPhylo[a2, Q, b2, 2]      To this end, I defined two lists,               A = {a1,a2}      and               B = {b1,b2}      (This list has more elements but I'm giving the example of 2 elements to keep it simple.) What this means is that I'd need to pass the lists A, B and the index to each list (p in lFreqPhylo) to a new function lFreq. The following approach however failed:               lFreq[A__, B__, Q_] := Sum[lFreqPhylo[A[[p]], Q, B[[p]], p], {p, 1, 2}]; (*Doesn't work!*)      How can I pass the two lists, A and B, to the function lFreqPhylo such that I can (a) use the 'Sum[...]' expression on the right hand side, (b) use the list elements, a1, a2, b1 and b2, as arguments of the function? Thanks in advance, Rafal


How to get Matlab data imported with the same dimensions?

I have some Matlab image data with the following dimensions (output is from Matlab):               >> size(im)     ans =         86    86     3    45      The data imports just fine in Mma, except the dimensions are reversed, and there's one extra dimension:               In[179]:= i = Import["Attractims.mat"];               Dimensions[i]          Out[180]= {1, 45, 3, 86, 86}      It's easy enough to throw out that first dimension. But how can I massage the list to produce one whose dimensions are in the same order as in Matlab? In other words, I want to reverse the order of the dimensions in a multi- dimensional list. At first this seemed like a trivial problem, but when I sat down to do it I found that I couldn't. Help? EDIT: If you want to check out the Matlab file yourself, you can get it (for the time being) at: http://www.shanehoversten.com/so_help_mma/Attractims.mat. (Note: it's ~750k) As I mentioned below in comments, I was unable to get Leonid's approach to change the dimensions of the imported data. However, R.M.'s approach _almost_ works: the dimensions of the array are changed appropriately, but the X and Y are reversed. To see what I mean, download and import the data above using something like:               In[340]:= mma = Import["/wherever/Attractims.mat"];     In[341]:= mma2mat = Flatten[mma, Table[{i}, {i, Depth[mma] - 1, 1, -1}]];     In[342]:= Dimensions[mma2mat]     Out[342]= {86, 86, 3, 45, 1}      So far so good. But if you do:               Image[mma2mat[[All, All, All, 45, 1]], "byte"]      you can see that rows and columns have been transposed. I'm having a hard time wrapping my head around this thing, but if this produces the 'correct' image in Matlab:               image(im(:,:,:,45))      then shouldn't the converted version do the same? In any event, thanks to your collective help I'm able to do the work that needs doing, but it would be nice to understand if I could...


How to fit one distribution to another?

I have a custom distribution created to model some experimental observations. While too complicated to include in this question, I can provide an example and some illustrations to convey a sense of it. Take the following as representing the `PDF` of the distribution:               pdf = (0.334336 (E^(2.56822 (-4.1816 - Log[x])) Erfc[              3.54409*10^7 (-4.1816 - Log[x])] +             E^(0.904055 (4.1816 + Log[x])) Erfc[              3.54409*10^7 (4.1816 + Log[x])]))/x;      Which one can readily plot:               Plot[pdf, {x, 0, 0.05}, PlotRange -> {All, {0, 100}}]      ![PDF\[dist\]](http://i.stack.imgur.com/fsHsy.png) Defining the distribution, `dist` as :               dist = ProbabilityDistribution[pdf, {x, 0, ∞}]      I can generate `RandomVariates` of `dist` and plot them in a `Histogram`:               Histogram[RandomVariate[dist, 10^5], {0, 0.05, 0.0005}, "PDF",       ImageSize -> 300, PlotRange -> {All, {0, 100}}]      ![histogram](http://i.stack.imgur.com/I5Zsy.png) You can see that the histogram and plot of the PDF look pretty similar. So far so good. I have conjectured that if one takes sufficient observations the data will eventually converge to an exponential distribution. So, I thought to estimate an exponential distribution from (in this case) generating a bunch of random data using the original distrubtion.               Plot[{       PDF[EstimatedDistribution[RandomVariate[dist, 10^4],          ExponentialDistribution[λ]], x],       pdf}, {x, 0, 0.05},      ImageSize -> 300, PlotRange -> {All, {0, 100}}]       ![estimated dist converging](http://i.stack.imgur.com/kKj9A.png) I like this, BUT this leads to my first question: **Where do all those squiggles in the PDF of the exponential distribution come from?** Take a closer look: ![squiggle zoom](http://i.stack.imgur.com/qp5bU.png) Does this seem normal? Shouldn't I get a smooth curve? Hopefully someone will have an insight, but this got me wondering and led me to a second and maybe more interesting question: **Does Mathematica have a way to directly fit one distribution to another without (in the above case) the intermediate step of generating a set of random variates first?**


When using NETLink, what is sufficient sanitization?

I am writing a webapp where I use MM via NETLink to process user inputs. In one example, the user will have a textbox in which they can write some simple numerical expression, and using MM together with MathJAX, I'll return this expression as nicely-formatted math. In this example, the user content gets wrapped up in               TeXForm[HoldForm[ ... ]]      My question is this: what are **sufficient** sanitization checks for their input? I want to ensure that I don't end up with something like               TeXForm[HoldForm[1+1]]; BoringCommand[PowerfulCommand[malicious code]]      For example, I could check the input against having either square bracket character and any capital letter, which would work in all the cases I can think of, but I don't know enough to be sure that will work in all cases.


Vector Analysis: Why are the Grad, Laplacian and Div being evaluated to zero

For the non linear partial differential equation below, why are the Gradient, Laplacian and Divergence being evaluated to zero despite using the `VectorAnalysis` package.               Needs["VectorAnalysis`"]     Needs["DifferentialEquations`InterpolatingFunctionAnatomy`"];     Bo = 1/300;     \[Delta] = 10^-3;     \[Epsilon] = 10^-6;     r = 0;     m = 0.05;     \!\(     \*SubscriptBox[\(\[PartialD]\), \(t\)]\(h[x, y, t]\)\) +       Div[-h[x, y, t]^3 Bo Grad[h[x, y, t]] +         h[x, y, t]^3 Grad[          Laplacian[h[x, y, t]]] + ((\[Delta] h[x, y, t]^3) Grad[          h[x, y, t]])/(Bi h[x, y, t] + K1)^3 +         m (h[x, y, t]/(K1 + Bi h[x, y, t]))^2 Grad[          h[x, y, t]]] + \[Epsilon]/(Bi h[x, y, t] + K1) + r \!\(     \*SubscriptBox[\(\[PartialD]\), \(x\)]\((     \*SubscriptBox[\(\[PartialD]\), \(x\)]     \*FractionBox[     SuperscriptBox[\(h[x, y, t]\), \(2\)], \(K1 + Bi\ h[x, y, t]\)]\      \*SuperscriptBox[\(h[x, y, t]\), \(3\)])\)\)      I am doing this because I'd like to evaluate the magnitude of each of these terms at a certain time step. Here is a simple sample code **without the Vector Analysis package** that works fine: I solve a PDE using NDSolve and then plot each term (I call each of the two terms Eq1 and Eq2 here) at a certain time step.               sol = u /.        NDSolve[{D[u[t, x], t] ==            0.5 D[u[t, x], x, x] + u[t, x] D[u[t, x], x],            u[t, -Pi] == u[t, Pi] == 0 , u[0, x] == Sin[x]},          u, {t, 0, 2}, {x, -Pi, Pi}][[1]];          Eq1 = 0.5 D[u[t, x], x, x];     Magnitude1[t_, x_] = Eq1 /. u -> sol     Plot[Magnitude1[1.5, x], {x, -\[Pi], \[Pi]}]      ![enter image description here](http://i.stack.imgur.com/PXEO3.png)               Eq2 = u[t, x] D[u[t, x], x];     Magnitude2[t_, x_] = Eq2 /. u -> sol     Plot[Magnitude2[1.5, x], {x, -\[Pi], \[Pi]}]      ![enter image description here](http://i.stack.imgur.com/SQ0b7.png)


How to speed up Minimum Spanning Tree algorithm?

How to speed up MST algorithm? I work with graphs and I have adopted Prim's algorithm for my needs, from here. The graphs which I use are very dense (number of vertexes: $V=500$ and every vertex is connected with other $N-$1 vertexes). For such graph my computer (i5 2500K@4.6GHz) needs about 40 seconds to compute MST (Prim). I read this: Performance Tuning in Mathematica What is the best way to optimize this code?   1. Compile? I tried this but I can't force it to work...   2. Maybe change some procedural parts of code to functional? If it possible, how? For me, Prim, seems to be procedural in its roots.   3. Or should I change algorithm to Kruskal or Boruvka? For now, I successfully use `Parallelize` function, so I can compute many different graphs in parallel on 4 cores. But how make it faster when computing each single graph? This is my code (adopted for my needs;):               getMstPrim[metricMatrix_] :=      Module[{groupOne, groupTwo, kk, paths, current, rule = {}, n},       n = Length[metricMatrix[[2]]];       groupOne = {RandomInteger[{1, n}]} ;                               (*        initialaze from any points, groupOne is inside points of the tree *)       groupTwo = Complement[Range[1, n], groupOne];           (*        groupTwo is outside points of the tree *)       For[kk = 1, kk < n, kk++,        paths =          Table[{metricMatrix[[i, j]], {i, j}}, {i, groupOne}, {j,            groupTwo}]; (*         current possible connections between group one and two *)        current = Last[First[Sort[Flatten[paths, 1]]]];   (*         sort for shortest weight*)        groupOne = Union[groupOne, current];                              (*         add the current path to goupe one *)        groupTwo = Complement[groupTwo, current];                   (*         remove the current path from goupe two *)        rule =          Append[rule,           current]                                                   (*         store the paths for final use *)        ];       rule       ]        `metricMatrix` is list of lists (~500 x 100).


Does Mathematica v.8 (or will v.9) run on Windows 8 systems with ARM processors? (like the MS Surface Tablet)

Today I was reading that the Microsoft _Surface RT_ is available for pre- order. (For the curious, click here.) I know the version of Widows 8 that runs on x86 processors should be compatible already with Mathematica 8... but what about the version of Windows 8---called Windows 8 RT---designed for ARM processor devices, like Microsoft's Surface device? Also, from what I've read there will also be an Intel version, called the _Surface Pro_ , that will run Windows 8 Pro. (Note I'm not sure if this will be an ARM or x86 Intel processor.) Summarizing my question(s): Will Mathematica run on the _Surface RT_ or the _Surface Pro_? Info about the Surface on Wikipedia here.


Clustered and Grouped Bar Chart in Mathematica v8.0

How would I create a clustered and grouped bar chart that looks like this (which was painstakingly created using Excel)? ![enter image description here](http://i.stack.imgur.com/76Wrd.png) I have seen examples for Mathematica v6.0 but none for Mathematica v8.0. The data I used to create this chart is as follows:               "Cluster","KPI","Bar","Value"     "Cluster1","Utilisation","Bar1",92     "Cluster2","Utilisation","Bar1",78     "Cluster3","Utilisation","Bar1",68     "Cluster4","Utilisation","Bar1",56     "Cluster5","Utilisation","Bar1",84     "Cluster1","Availability","Bar1",8     "Cluster2","Availability","Bar1",21     "Cluster3","Availability","Bar1",24     "Cluster4","Availability","Bar1",36     "Cluster5","Availability","Bar1",7     "Cluster1","Utilisation","Bar2",92     "Cluster2","Utilisation","Bar2",78     "Cluster3","Utilisation","Bar2",72     "Cluster4","Utilisation","Bar2",59     "Cluster5","Utilisation","Bar2",67     "Cluster1","Availability","Bar2",8     "Cluster2","Availability","Bar2",16     "Cluster3","Availability","Bar2",23     "Cluster4","Availability","Bar2",31     "Cluster5","Availability","Bar2",23     "Cluster1","Utilisation","Bar3",77     "Cluster2","Utilisation","Bar3",82     "Cluster3","Utilisation","Bar3",78     "Cluster4","Utilisation","Bar3",66     "Cluster5","Utilisation","Bar3",85     "Cluster1","Availability","Bar3",23     "Cluster2","Availability","Bar3",14     "Cluster3","Availability","Bar3",20     "Cluster4","Availability","Bar3",28     "Cluster5","Availability","Bar3",9     "Cluster1","Utilisation","Bar4",100     "Cluster2","Utilisation","Bar4",83     "Cluster3","Utilisation","Bar4",75     "Cluster4","Utilisation","Bar4",59     "Cluster5","Utilisation","Bar4",80     "Cluster1","Availability","Bar4",0     "Cluster2","Availability","Bar4",16     "Cluster3","Availability","Bar4",20     "Cluster4","Availability","Bar4",35     "Cluster5","Availability","Bar4",14      * * * For convenience, here is the same sample data in a different form:               {{"Cluster1", {{92, 8}, {92, 8}, {77, 23}, {100, 0}}},      {"Cluster2", {{78, 21}, {78, 16}, {82, 14}, {83, 16}}},      {"Cluster3", {{68, 24}, {72, 23}, {78, 20}, {75, 20}}},      {"Cluster4", {{56, 36}, {59, 31}, {66, 28}, {59, 35}}},      {"Cluster5", {{84, 7}, {67, 23}, {85, 9}, {80, 14}}}}      Or:               {{"Cluster1",{{"Bar1",{92,8}},{"Bar2",{92,8}},{"Bar3",{77,23}},{"Bar4",{100,0}}}},     {"Cluster2",{{"Bar1",{78,21}},{"Bar2",{78,16}},{"Bar3",{82,14}},{"Bar4",{83,16}}}},     {"Cluster3",{{"Bar1",{68,24}},{"Bar2",{72,23}},{"Bar3",{78,20}},{"Bar4",{75,20}}}},     {"Cluster4",{{"Bar1",{56,36}},{"Bar2",{59,31}},{"Bar3",{66,28}},{"Bar4",{59,35}}}},     {"Cluster5",{{"Bar1",{84,7}},{"Bar2",{67,23}},{"Bar3",{85,9}},{"Bar4",{80,14}}}}}


FindMaxValue and FindMaximum - how to find GLOBAL maximum and not just LOCAL maximum

I will not be able to provide a _simple_ minimum working example here as this seems to be very specific. I have an interpolating function which I substituted into a PDE and then plot said PDE at a certain time for x and y. I'd like to find the global maximum of this function. Finding the maximum was described here. However, I find that this just finds the local maximum. As soon as the first maximum value is encountered, the FindMaximum or FindMaxValue are stopped and I don't get the global maximum. For instance, when I run FindMaximum or FindMaxValue on the interpolating function that generates this: ![enter image description here](http://i.stack.imgur.com/HDBqE.jpg) The local maximum very close to the left bottom corner is returned as **1.7291*10^-6**. Obviously the maximum is around **0.00002**. ## I have attached my .mat files **_here_**. The notebook that I use to plot and calculate maximum is as:               $HistoryLength = 0;          Needs["VectorAnalysis`"]     SetCoordinates[Cartesian[x, y, z]];     Needs["DifferentialEquations`InterpolatingFunctionAnatomy`"];     (*Loads the files*)     L = 79.5788;     fileList = FileNames["L_lambda_max_1wl_zg.mat", NotebookDirectory[]];     fileListxy = FileNames["L_lambda_max_1wl_zg.mat", NotebookDirectory[]];     fileListt =        FileNames["L_lambda_max_1wl_zg_time.mat", NotebookDirectory[]];     datat = Import[fileListt[[1]]];     trup = Max[Flatten[datat]];     tsrup = Ceiling[        0.9 Flatten[Position[Ceiling[Flatten[datat]], Ceiling[trup]]]];     ts = tsrup[[1]];     dataxy = Import[fileListxy[[1]]];     solution = ListInterpolation[dataxy, {{0, L}, {0, L}, Flatten[datat]}];          (*Plots the data at 0.99 final time*)     Plot3D[      solution[x, y, 0.99 datat // Flatten // Last], {x, 0, L}, {y, 0, L},       PlotPoints -> 65]     fac datat // Flatten // Last                    (*Defines EqS and plots it and finds the maximum*)     Clear[EqS, EqM]     fac = 0.6;     xg = 0.0     Bi = 1;     Bo = xg 1/300;     K1 = 1;     \[Epsilon] = 10^-6;     \[Delta] = 10^-3;     m = 2*0.025;     r = 0;     EqS = Div[(-h[x, y, t]^3)*Bo*Grad[h[x, y, t]]];               Res[x_, y_, t_] = Abs[EqS /. h -> solution];     EffectofG =       Plot3D[Res[x, y, fac datat // Flatten // Last], {x, 0, L}, {y, 0, L},        MaxRecursion -> 2, PlotPoints -> 65, PlotRange -> Automatic]     FindMaxValue[{Res[x, y, fac datat // Flatten // Last], 0 <= x <= L,        0 <= y < L}, x, y]          (*Defines EqnM, plots it and finds the maximum *)          EqM = Div[m*(h[x, y, t]/(K1 + Bi*h[x, y, t]))^2*Grad[h[x, y, t]]];     Clear[ResM];     EqM;     Bi = 1;     K1 = 1;     \[Epsilon] = 10^-6;     \[Delta] = 10^-3;     m = 2*0.025;     r = 0;     ResM[x_, y_, t_] = Abs[EqM /. h -> solution];     EffectofM =       Plot3D[ResM[x, y, fac datat // Flatten // Last], {x, 0, L}, {y, 0,         L}, MaxRecursion -> 2, PlotPoints -> 65]     FindMaxValue[{ResM[x, y, fac datat // Flatten // Last], 0 <= x <= L,        0 <= y <= L}, x, y]      This was generated using a massive mathematica script and I don't think it would be to many people's interest to run the script for several hours to generate this data. Hence, I just uploaded the data. Edit: As per rm-rf's suggestion (see comments) I tried `NMaximize` with the following change in syntax. I replaced:               FindMaxValue[{ResM[x, y, fac datat // Flatten // Last], 0 <= x <= L,        0 <= y <= L}, x, y]      with:               NMaximize[{ResM[x, y, fac datat // Flatten // Last]}, {x, y}]      I find that as I increase the value of `fac` in my code to say 0.99 times the end time, it gives me a LOCAL maximum instead of a GLOBAL maximum.


Define a color of the pressed button of a SetterBar

It is easy to define a background color for the SetterBar buttons, so that all the buttons that are not pressed have the specified color, while the pressed one is gray. Here is the example:               SetterBar[2, Range[5], Background -> LightBlue]      in which the buttons that are not pressed are LightBlue. How to make another way around? That is, how to make all buttons gray except the pressed one, which should take a specified color?


Erfi[z] expansion in Mathematica: is this a bug?

Looking at the expansion:               Series[Erfi[x], {x, Infinity, 1}]      I obtain               -I+E^x^2 (1/(Sqrt[\[Pi]] x)+O[1/x]^2)      (note the imaginary argument in front). This looks wrong as I don't think there should be an imaginary number out front; I had thought that this was due to some branch cut about the positive x axis, but this doesn't look like the case. Looking at the output of Mupad (in Matlab), I obtain the correct expansion listed in the response here. Is this a bug?


Uniform scaling of a Table of Graphics objects?

Row[Table[Graphics[Rectangle[{0, 0}, {2^k, 1}]], {k, 0, 5}]]      yields ![enter image description here](http://i.stack.imgur.com/YAOwv.png) However, I'd like uniform scaling of the rectangles, i.e., each rectangle should look twice the width (but same height) as its predecessor. How can I force "absolute sizing" here? Second, how can I align the bottoms of the rectangles? I tried inserting `Alignment->Bottom` in several spots, none of which worked.


Estimate Imagesize of any given Particular Control object?

I make different controls(InputFields,Text,panel, etc) in my code for which the corresponding code is below.                 inputFieldValue = 10;       (*Markers*)       markers = Row[{                     Column[{                     MouseAppearance[                                    Style["\[FilledUpTriangle]", Bold, Black, {15,15},ShowStringCharacters -> False],                                     "LinkHand"                                     ],                     MouseAppearance[                                     Style["\[FilledDownTriangle]", Bold, Black, {15, 15}, ShowStringCharacters -> False],                                     "LinkHand"                                   ]                            },                           Spacings -> 0,                           Alignment -> Center,                           Background -> RGBColor[0.65, 0.65, 0.65]                          ](*Column is CLosed*)                     },                    BaselinePosition -> Axis                   ];        (*InputField*)        field = Dynamic[Row[{InputField[                                 Dynamic[inputFieldValue],                                 Number,                                 ContinuousAction -> True,                                 ImageSize -> {50, 20},                                 Alignment -> Center                                      ]                             },                             BaselinePosition -> Axis                           ]                        ];      I want to find exact `ImageSizes` of the controls for accurate placement in another grid. I am listing the options that I have with me here. case1:                    Rasterize[markers][[2, 2]]      case2:                   Rasterize[field][[2, 2]]      and also,I arrange this controls in different formats.like, arrange1:                userField = Row[{                 markers,                 field                 },             Frame -> False             ]      arrange2:                    panelRow =                  Panel[Row[{userField, userField, userField, userField, userField,                        userField, userField, userField, userField, userField                          }],                        FrameMargins -> -3, Appearance -> "Frameless"                      ]      case3:                Rasterize[userField][[2, 2]]      case4:               Rasterize[panelRow][[2, 2]]      if you evaluate `case1`,the `ImageSize` is ({9,23}) which is wrong as I have already mentioned `size` of markers is `{15,15}`. Based on the options provided here, I did try to use the `Rasterize` function with no success. My idea is to figure out the `Imagesize` and span them across a layout whose pixel or unit value is 10. Also, if I have an image of an odd dimension, for example, like `ImageSize -> {67, 38}, I want to set my values for the control object to next closest higher multiple of span value, which in the case of my example is {70, 40} so that my control object will not suffer due to insufficient spaces. Yet another option that I did try was to use `Options[markers]` which also does not give me the value of the size of the control objects. Right now, I am putting my control objects into `Pane` with scroll bars to accommodate for different sizes of the control objects without compromising the size or display of the control objects.


How to convert output of a For loop into a list

I have written a For loop in my Mathematica notebook. This For loop, when activated, will generate a sequence something like:                   0.1         Null         0.3         0.4         Null         0.6      etc. The output solely consists of numbers and nulls. **What I want to do is plot these values generated by my For loop, using ListPlot**. However, to use ListPlot I must first have a list, and the output of my For loop isn't in the form a list. How can I convert the output of my For loop into a list? (Note: My For loop generates a large amount of numbers, so it is too laborious to manually enter these values into a list one by one). My For loop is:                   For[i = 0,  i <1000,  i++,            Print[                  For[n = 100, n < 600, n++,                     If[Abs[Nest[f, i*StepSize1, n] - 0.51304]<0.0001,                         {Print[i* StepSize1], Break[]}, {Indeterminate, Break[]}]                     ]                  ]           ]      StepSize is pre-defined, by the way.