Using Read for calling external command does not release file handle

The standard and robust method for piping to/from external commands under Windows is to create a temporary file, save the input into it, pipe it to the command and save its output to a second file. Here is a crippled version of the built-in `RunThrough` (that is the standard way for piping), that omits the output, for testing purposes, and prevents the command window to pop up (you can check the definition of `RunThrough` by removing its `ReadProtected` attribute).               runThrough[comm_String, s_String] := Block[{in = OpenWrite[], out = OpenWrite[]},        WriteString[in, s <> "\n"]; Close /@ {in, out};        (* If[i > 2040, Print[{i, in, out}]]; *)        Read["!" <> comm <> " < " <> First@in <> " > " <> First@out];        DeleteFile@First@# & /@ {in, out}];      In the following example I called the Windows `ver` command that simply returns the OS version, so it's pretty harmless to run. The problem comes when this `runThrough` is run iteratively. **Always precisely and reproducibly at** `i=2045` on my machine, error messages start to rain.               Dynamic@i     Table[runThrough["ver", "x"], {i, 10000}]      > >     OpenRead::noopen: -- Message text not found -- (C:\...\Mathematica > 9.0.1\Documentation\English\PacletDB.m) >     General::stream: -- Message text not found -- ($Failed) >     OpenWrite::noopen: -- Message text not found -- > (C:\Users\...\AppData\Local\Temp\m-49f8c51e-d090-4dc3-87b4-0a5310380f70) >     General::stream: $Failed is not a string, InputStream[ ], or > OutputStream[ ]. >     ... >   If the commented line is uncommented (I left it for everyone to figure out the platform-dependent time of breakdown), I can see that the `out` file is not created by `OpenWrite`, as the result is `$Failed`. It happens to any external command, even for those that properly accept input from a pipe, not just OS natives like `ver`. Furthermore, somehow the kernel gets messed up, as any attempt after the messages to access the Documentation Center (for example `F1`-ing a function) brings up a dialog: > The file you tried to open was not found or could not be opened. Is it a problem of `OpenWrite` or I simply try to do too many things too fast and the OS cannot keep up with `Mathematica`? If so, how can I overcome such unwanted effects? (Fresh kernel, no package was loaded, Win7 64bit, _Mathematica_ 9.0.1)


How to plot BarChart with error bars on logarithmic scale in Mathematica 9?

I'm quite new in _Mathematica_ , and I would like to ask you to consider the next case: I need to plot bar chart with error bars on logarithmic scale. From Wolfram site I took the function which allows to plot error bars on a bar chart with normal (non-log) scaling. Thus, my ugly actual code looks like:               errorBar[type_: "Rectangle"][{{x0_, x1_}, {y0_, y1_}}, value_, meta_] :=        Block[{error},              error = Flatten[meta];             error = If[error === {}, 0, Last[error]];             { ChartElementData[type][{{x0, x1}, {y0, y1}}, value, meta],                {Black, Line[{{{(x0 + x1)/2, y1 - error}, {(x0 + x1)/2, y1 + error}},                                     {{1/4 (3 x0 + x1), y1 + error}, {1/4 (x0 + 3 x1), y1 + error}},                             {{1/4 (3 x0 + x1), y1 - error}, {1/4 (x0 + 3 x1), y1 - error}}}]}             }            ]          figdata = {{4.01 -> 0.76, 1.73 -> 0.14, 3.95 -> 0.35},                 {68.53 -> 16.32, 77.77 -> 11.13, 81.39 -> 27.32}};     xlables = {"r1", "r2"};     leftframename = "Frequency";          BarChart[ figdata, ChartElementFunction -> errorBar["Rectangle"],                ChartStyle -> {White, Gray, Black}, ChartLabels -> {xlables, None},                FrameLabel -> {None, Style[leftframename, 15, FontFamily -> "OpenSans"]},               FrameTicks -> {{{0, 10, 100, 1000}, None}, {None, None}},                Frame -> Left, BarSpacing -> {0, 0.5},                BaseStyle -> {FontWeight -> "Bold", FontSize -> 15},               ScalingFunctions -> "Log"]      And this produce the following graph: ![Graph](http://i.stack.imgur.com/haJJT.png) which is not what I really would like to receive. The problems, that I don't know how to solve:   1. How to plot error bars in a proper way on log scale in `BarChart`?   2. How to make `FrameTicks` visible and on the same distance between each other? Could anyone help me to put this together into working decision?


FindInstance (and Solve, ...) abysmally slow on a fully determined system of linear equations and inequalities: why?

I took a quick look for `FindInstance` and `Solve`-related questions but came up empty for the aspect that I am curious about. So here is my newbie question:               FindInstance[{       s==9,r==8,d==7,n==6,e==5,y==2,m==1,o==0     },{s,e,n,d,m,o,r,y},Integers]      runs as quickly as one would expect. But               FindInstance[{       s!=e!=n!=d!=m!=o!=r!=y,       s==9,r==8,d==7,n==6,e==5,y==2,m==1,o==0     },{s,e,n,d,m,o,r,y},Integers]      takes ages -- long enough that I ran out of patience before MMA was done. And now I am curious: Why would _Mathematica_ suddenly display less maths ability than a third-grader? * * * bill_s suggested something much faster, but it is not equivalent to the original problem. The original inequality required all variable values to be different from all other variable values, such that each value can only be used for one variable. The FindInstance statement in Bill's post only compares x[i] to the ith value, but not to the other n-1 values. In other news,               FindInstance[{       (*s!=e,s!=n,s!=d,s!=m,s!=o,s!=r,s!=y,*)       (*e!=n,e!=d,e!=m,e!=o,e!=r,e!=y,*)       n!=d,n!=m,n!=o,n!=r,n!=y,       d!=m,d!=o,d!=r,d!=y,       m!=o,m!=r,m!=y,       o!=r,o!=y,       r!=y,       s==9,r==8,d==7,n==6,e==5,y==2,m==1,o==0       },{s,e,n,d,m,o,r,y},Integers]      ~1.1 seconds (on my laptop).               FindInstance[{       (*s!=e,s!=n,s!=d,s!=m,s!=o,s!=r,s!=y,*)       e!=n,e!=d,e!=m,e!=o,e!=r,e!=y,       n!=d,n!=m,n!=o,n!=r,n!=y,       d!=m,d!=o,d!=r,d!=y,       m!=o,m!=r,m!=y,       o!=r,o!=y,       r!=y,       s==9,r==8,d==7,n==6,e==5,y==2,m==1,o==0       },{s,e,n,d,m,o,r,y},Integers]      2nd comment uncommentd. ~20 s.               FindInstance[{       s!=e,s!=n,s!=d,s!=m,s!=o,s!=r,s!=y,       e!=n,e!=d,e!=m,e!=o,e!=r,e!=y,       n!=d,n!=m,n!=o,n!=r,n!=y,       d!=m,d!=o,d!=r,d!=y,       m!=o,m!=r,m!=y,       o!=r,o!=y,       r!=y,       s==9,r==8,d==7,n==6,e==5,y==2,m==1,o==0       },{s,e,n,d,m,o,r,y},Integers]      Both comments uncommented. ~1 minute. The original version (multiple inequalities in one condition):               Timing[FindInstance[{         s!=e!=n!=d!=m!=o!=r!=y,         s==9,r==8,d==7,n==6,e==5,y==2,m==1,o==0},         {s,e,n,d,m,o,r,y},Integers]]      150 seconds!


Using undefined function in an expression

I want to use undefined functions in expressions to be simplified. For example. I want mathematica to simplify this input $(f^{\prime\prime}(t),g^{\prime\prime}(t))\cdot (-g^\prime(t),f^\prime(t)) $ into this output: $f'(t)g''(t)- f''(t)g'(t)$. How does one go about the "Simplify" command for that first expression in order to get the second one? How do you specify that $f$ is a function of $t$, without of course defining it, in an expression? Cheers


what is the best package/way to insert Mathematica code in latex docs?

I know that this question is not about strictly mathematica issue, but I think that in this site should be many pepople that use latex to distribute mathematica source code/examples. If the moderators think that I should delete this question, please tell me.. and I excsuse me, and I´m doing it as soon as possible. I have mathematica source code (with any long lines), and I want to attach to a job(using latex), as an appendix. What do you think is the best way(package) to insert the code (in sourcecode.nb) in the latex document?. I was reading in any posts o LATEX StackExchange about minted(would be neccesary to configure paths and other details, the package seems to be so pretty) and listings package but this packages seems to be more focused in languages as C, C++, java,... to highlight the reserved words. I was reading Highlighting Mathematica code in LaTeX document but I dont´see a suitable solution I was reading about minted and.. I understand that don´t supports Mathematica. http://pygments.org/languages/ but then I found http://pygments.org/docs/changelog/?highlight=mathematica where seems to mathematica be supported. Have you any suggestion?


How to insert zero counts uniformly with Dataset Counts query

`Missing[]` is generated when an association does not contain the specified key.               data = {<|"a" -> 1, "b" -> 2|>, <|"b" -> 3, "c" -> 4|>} // Dataset      ![enter image description here](http://i.stack.imgur.com/rbZ3l.png) This situation occurs when using `Counts` where there are zero instances of a value in some records, as illustrated in this result of a query that I won't bother copying here: ![enter image description here](http://i.stack.imgur.com/jRnMN.png) This is Not to be confused with counting missing values, eg, the 263 `Missing[]` `"age"` values in Titanic data, and the "" keys above). How to insert key-value pairs representing zero counts to obtain uniform keys in the {Association__}?. The inserted keys should ideally appear in the same order as they are by the built-in Datset Format functionality (not contained in the Normal form) . Desired output for `data` is:               {<|"a" -> 1, "b" -> 2, "c" -> 0|>, <|"a" -> 0, "b" -> 3,         "c" -> 4|>} // Dataset      ![enter image description here](http://i.stack.imgur.com/etqpK.png) EDIT: It seems `KeyUnion` performs exactly this function:               data[KeyUnion] // Normal          (*    {<|"a" -> 1, "b" -> 2,            "c" -> Missing["KeyAbsent", "c"]|>, <|"a" ->             Missing["KeyAbsent", "a"], "b" -> 3, "c" -> 4|>} *)      However, it seems immune to `ReplaceAll`:               data[KeyUnion, All, Replace[#, Missing[__] :> 0] &] // Normal           (* {<|"a" -> 1, "b" -> 2,        "c" -> Missing["KeyAbsent", "c"]|>, <|"a" ->         Missing["KeyAbsent", "a"], "b" -> 3, "c" -> 4|>} *)      EDIT 2: Elaborating on WReach's solution using KeyUnion composed with the subquery. Since the example data is actually structured as key-value pairs, it seems appropriate to extend this question as opposed to asking a new one, though the focus now is on KeyUnion, not the replacement for the `Missing` data.               raw2 = <|a -> {"Copy", "Copy", "Copy", "", "", "", "Copy"},          b -> { "Paste", "", "Paste", "Paste", "", "Paste", "Paste"},          c -> {"Copy", "Paste", "Copy", "Copy", "", "", "Paste"},          d -> {"Paste", "", "", "Paste", "", "Paste", "Paste"}|> //         Dataset;      Even though Dimensions are the same as `raw` in his answer, and also, `raw2[All, Counts] // Normal` gives:               <|a -> <|"Copy" -> 4, "" -> 3|>, b -> <|"Paste" -> 5, "" -> 2|>,       c -> <|"Copy" -> 3, "Paste" -> 2, "" -> 2|>,       d -> <|"Paste" -> 4, "" -> 3|>|>      It's not clear to me at what level to apply `KeyUnion`, eg:               raw2[All, KeyUnion, Counts] // Normal          (* <|a -> Missing["Failed"], b -> Missing["Failed"],       c -> Missing["Failed"], d -> Missing["Failed"]|> *)


How can I make a customized InputField for date inputs?

I want to make an `InputField` that only allows a specific date format to be entered. I want to display a field hint in the format "dd:mm:yyyy". Once the user clicks on the input field, then the user should be able to enter date values. The user should not be able to enter anything that in not in the correct format. I require the ability to insert a separator of my choice. In the example above, my field separator is ":". The user should not be able to enter any other separator except for the one that I have given. Can anyone help me?


Going full functional (Haskell style)

I'm trying to define some notation so that Mathematica code would be more functional, similar to Haskell (just for fun): currying, lambdas, infix operator to function conversion, etc.. And I have some questions about it:   * Is it possible to make all Mathematica `h_[x1_,x2_,...]` functions to work as `h[x1][x2][..]`?   * Can I distinguish inside `Notation` box between `<+1>` and `<1+>`, how do I check for + there?   * How to define right-associate apply operator with highest precedence (`$`)? This is what I have so far:               << Notation`;          lapply[x_, y_] := x[y]     rapply[x_, y_] := x[y]     InfixNotation[ParsedBoxWrapper["\\"], lapply]     InfixNotation[ParsedBoxWrapper["$"], rapply]         x_ \ y_ \ z_ := x[y][z]         x_ $ y_ $ z_ := x[y[z]]          Notation[ParsedBoxWrapper[     RowBox[{     RowBox[{"\[Lambda]", " ", "x__"}], "->",           "y_"}]] \[DoubleLongLeftRightArrow] ParsedBoxWrapper[     RowBox[{"Function", "[",      RowBox[{     RowBox[{"{", "x__", "}"}], ",", "y_"}], "]"}]]]          Notation[ParsedBoxWrapper[     RowBox[{"\[LeftAngleBracket]",      RowBox[{"op_", " ", "x_"}],           "\[RightAngleBracket]"}]] \[DoubleLongLeftRightArrow]        ParsedBoxWrapper[     RowBox[{     RowBox[{"#", "op_", " ", "x_"}], "&"}]]]     AddInputAlias["f" -> ParsedBoxWrapper[     RowBox[{"\[LeftAngleBracket]",      RowBox[{"\[Placeholder]", "\[Placeholder]"}],           "\[RightAngleBracket]"}]]]          Notation[ParsedBoxWrapper[     RowBox[{"{",      RowBox[{     RowBox[{"x_", " ", ".."}], " ", "y_"}],           "}"}]] \[DoubleLongLeftRightArrow] ParsedBoxWrapper[     RowBox[{"Range", "[",      RowBox[{"x_", ",", "y_"}], "]"}]]]          filter[f_][x_List] := Select[x, f]     map[f_][x__List] := Map[f, x]          filter\PrimeQ $ map\\[LeftAngleBracket]-1\[RightAngleBracket] $ map\ \     (\[Lambda] x -> 2^x)\ {1 .. 100}      **EDIT** : Also did some kinda lazy lists, soon it will be haskell inside Mathematica :)               SetAttributes[list, HoldAll]     list[h_, l_][x_] := list[h, l[x]]     list[x_] := list[x, list]          map[f_][list] := list     map[f_][list[x_, xs_]] := list[f[x], map[f][xs]]          take[0][_] := list     take[_][list] := list     take[n_Integer][list[x_, xs_]] := list[x, take[n - 1][xs]]          range[n_Integer] := range[1, n]     range[m_, n_] := list[m, range[m + 1, n]]     range[n_, n_] := list[n, list]          show[list] := "[]"     show[list[x_, l_]] := ToString[x] <> "," <> show[l]          show $ (take[10] $  map\ (\[Lambda] x -> x^2) $ range[10000])


Is there a "GrabHand" and "OpenHand" MouseAppearance in Mathematica?

MouseAppearance[Plot[Sin[x], {x, 0, 5}], "LinkHand"]      ![hand](http://i.stack.imgur.com/XjHbo.png) Unfortunately I cannot get a screen grab to show the link hand but it is a cartoon hand with a finger pointing. In most/many graphics packages there is also an open hand (open carton hand) and a closed hand (closed cartoon hand) used for sliding a graphics within a region. _I realize that if I can find some open source clip art_ then I can use this as a mouse appearance:               MouseAppearance[Plot[Sin[x], {x, 0, 5}], clip art]      But was wondering if undocumented open hand and grab hand exists within Mathematica? Intended usage: I have an application for sliding a graphic. I wanted to use an open hand over the graphic and grab hand/closed hand for sliding the graphic. My reason for seeking something built in is solely aesthetic so that it matches the "LinkHand" appearance. If I cannot have a built in solution I'll look for clip art for the full set of icons -- including the link hand.


How to change FormatType for output and Syntax error separately?

For some demand, I am using MathMLForm for all output               SetOptions["stdout", FormatType -> MathMLForm]      But this effect the syntax error format as well.(it's hard to understand and non-meaningful sometime in MathMLForm) Then I tried bollwed, but syntax error message is still in MathMLForm               SetOptions["stdout", FormatType -> MathMLForm];     SetOptions["stderr", FormatType -> OutputForm];      So how could I change FormatType for output and Syntax error separately ? Thanks! BTW : I am using version 9 under ubuntu 14.04 (32 bit)


SQL JDBC Zerodatetime

I am trying to **query SQL data with MATHEMATICA** - however, the **MySQL database contains zerodates** and that leads to the following error message: e.g. (1) *SQLSelect[conn, "orders", {"time_created"}, MaxRows -> 5]* --> **JDBC::error:** "!(\"Cannot convert value '0000-00-00 00:00:00' from column 1 to TIMESTAMP.\")" e.g. (2) *SQLExecute[conn, "SELECT * FROM orders", MaxRows -> 5]* --> **JDBC::error:** "!(\"Cannot convert value '0000-00-00 00:00:00' from column 6 to TIMESTAMP.\")" I found out that this is a typical issue with a JDBC connection and that this can be solved by allowing **zerodatetimes** as true with examples from other systems. What I didn't find out is: How to apply this **specifically in Mathematica?** Can you advise me? It would help me a lot - so thank you very much for any help!


Text analysis and loops

I need a loop for a text analysis involving about 1000 papers (identical structure of all papers) I have these two commands to read all the papers into memory.               papers =        Table[         StringJoin[{"/Users/maxmüller/Desktop/Arbeit/Info Jan2014/", ToString[i], ".pdf"}],          {i, 1, 1000}]          AllPaper = Table[Import[paper], {paper, papers}];      This is a too big a dataset for my laptop to hold in main memory, so I want to select the relevant info before I load all the data in the loop. I need following info for my analysis:               DOI = FindList["/Users/maxmüller/Desktop/Arbeit/Info/1.pdf", "ARTICLEDOI"]          Author = FindList["/Users/maxmüller/Desktop/Arbeit/Info/1.pdf", "/Author"]          Volume = FindList["/Users/maxmüller/Desktop/Arbeit/Info/1.pdf", "Vol.", 1]      It would be great if someone could help me to creat an efficient command for my analysis.


Where might I find Mathematica code for solving MHD viscoelastic fluid flow using Homotopy Analysis method?


Is there a way to show the details of a numerical computation?

I have recently started using Mathematica as a calculator while teaching (definitely overkill, but I try to use as few tools as possible). I would like my students to be able to trace simple numerical calculations, for example if I enter               a=1; b=2; c=3; x = 1 / (  (a+2b)/c^2 )      I would like to automagically generate               x = 1 / ((1 + 2 . 2)/3^2)      and even if I could               x = 1 / ((1 + 2 . 2)/3^2) = 1/ (5/9) = ...      Is there a way to do this? **Addition :** I found out that this seems to do a rather good job :               a = 1; b = 2; c = 3;     ClearAll["Global`*"]     a = "1"; b = "2"; c = "3";     x = 1/((a + 2 b)/c^2)      Now I need to automate it. Any suggestion ?!


How can I transform parts of an Integer list to a String list

There is a sorted list of Integers.               ilist = PadRight[Sort[ RandomSample[Range[1, 99999], 3], Less], 5]        It should become string area codes like:               {0123, 023345, 043563, 0, 0};        with trailing zeros.   Can I do this with one function?               slist=ReplaceAll[ilist,n_Integer :>"0"<>ToString[n]]        Note: last elements are zeros already and should not double.


Difference between vector's Dimensions

What's the difference between               projection= Table[Conjugate[autoVett[[k]].someVector1], {k, 1, r}]     Dimensions[projection]      that gave me as results `{12}` which is ok.               Dimensions[baseComp]     {8}     Dimensions[Transpose[{baseVector}]]     {12,1}     startState =        KroneckerProduct[baseComp, Transpose[{baseVector}]] ;     Dimensions[startState]     {96,1}     scompoStartState =        Table[Conjugate[CCNOTHvec[[k]].startState], {k, 1,          Length[CCNOTHvec]}];     Dimensions[scompoStartState]     {96,1}      What's the difference between a `{12}` vector and a `{96,1}` vector? I need to have just 96-dimensional vector.


Two dimensional NIntegration failure - non-numerical values

I've got this function:               E0[x0_, y0_, z_]:=          A/w[z]*Exp[-(x0^2 + y0^2)/(w[z]*w[z])]*Exp[(I*2*Pi*(x0^2 + y0^2))/(λ*2*R[z])]*Exp[I*ϕ[z]];      Where the `w[z], R[z]` and `Phi[z]` are given as presented here. Second function is as follows:               Transmission1[x0_, y0_] := 2*(1 + Cos[((2*Pi)/λ)*x0 - 2*ArcTan[(y0/x0)]]);      I want to perform an two dimensional NIntegration:               f1[x2_, y2_]:=         NIntegrate[E0[x0,y0,z]*Transmission1[x0, y0]*Exp[I*(kx1*x0 + ky1*y0)],             {y0,-0.00001,0.00001},{x0, -0.00001, 0.00001}];      where:               kx1 = ((2*Pi)/(λ*z))*x2;     ky1 = ((2*Pi)/(λ*z))*y2;      For any `{x2,y2}` values I get an error which states:               NIntegrate::inumr: "The integrand 2\ E^(I\((20000000 π x0 x2)/633+(20000000 π y0 y2)/633))\ (1+Cos[(2000000000\π\x0)/633-2\ ArcTan[Power[<<2>>]\ y0]])     has evaluated to non-numerical values for all sampling points in the region with boundaries {{-0.00001,0.00001},{-0.00001,0.00001}}"      How can I manage to solve this issue?


Data format of Date including data

I have               {{{1986, 1, 15, 0, 0, 0.}, 2.28}, {{1986, 2, 15, 0, 0, 0.}, 2.26},       {{1986, 3, 15, 0, 0, 0.}, 2.16}, {{1986, 4, 15, 0, 0, 0.}, 2.1},       {{1986, 5, 15, 0, 0, 0.}, 1.96}, {{1986, 6, 15, 0, 0, 0.}, 1.85},       {{1986, 7, 15, 0, 0, 0.}, 1.8}, {{1986, 8, 15, 0, 0, 0.}, 1.77},       {{1986, 9, 15, 0, 0, 0.},}, {{1986, 10, 15, 0, 0, 0.}, 1.73}}      for some data.I want to remove that hour ,min,sec part and also some missing data for some days.You can see there.I want those dates also to be filtered and not included. How the code be? I want in this format`{{{1986, 1, 15}, 2.28},{{1986, 2, 15}, 2.26},...`


Integrate of Heaviside Function returns an error answer

I try to evaluate an Integral of a `Heaviside` function, but it turns out with an erroneous output(zero). Here is my integral:               Integrate[HeavisideTheta[k - Sqrt[kx^2 + ky^2 + kz^2]],                {kx, -Infinity, Infinity},                {ky, -Infinity, Infinity},                {kz, -Infinity, Infinity}, {kx, ky, kz} ∈ Reals]      The right answer should be a volume of a sphere, but it seems Mathematica doesn't know it.


Reversing the ColorScheme used in an ArrayPlot and setting the font size in the color bar

I have a matrix of data that I am plotting via `ArrayPlot`.               FData = {{0., 0., 0.066812, 0., 0., 0., 0.}, {0., 0.479787, 0.,         0.0683112, 0., 0., 0.}, {0.0669646, 0., 0.0697005, 0., 0., 0.,         0.}, {0., 0.0683715, 0., 0., 0., 0., 0.}, {0., 0., 0., 0., 0., 0.,         0.}, {0., 0., 0., 0., 0., 0., 0.}, {0., 0., 0., 0., 0., 0., 0.}}      I would like to reverse the color bar colors in the Plot legend. I used:               ArrayPlot[      FData,      PlotLegends ->        BarLegend[{GrayLevel, {0, Max[FData]}},         LabelStyle -> {FontSize -> 20}], DataReversed -> False]      And this gives me: ![](http://i.stack.imgur.com/1bfiN.png) The colors are flipped in this figure and I'd like the darkest to represent the highest number in my matrix. When I try to "Reverse" my data (which doesn't seem sound to me) using the below snippet:               FData[[1 ;; 7, 1 ;; 7]]     ArrayPlot[      FData[[1 ;; 7, 1 ;; 7]],      PlotLegends ->        BarLegend[{GrayLevel, {0, Reverse[FData[[1 ;; 7, 1 ;; 7]]]}},         LabelStyle -> {FontSize -> 20}], DataReversed -> False]      And that gives me _nothing_! ## Edit/Errata I have been using `PlotLegends -> BarLegend[{GrayLevel, {0, 1}}, LabelStyle -> {FontSize -> 20}]` to set the font size. Based on the answers below, how can I go about changing the font size? I know this is very basic but I can't quite figure out whats going on!


I am missing a function like HoldPattern

_Temporary message: I am planning to edit this question, making the examples less confusing and by moving the things that are confusing to a separate question_ For any confusion about expressions that Mathematica does not seem to fully evaluate, see this question Throughout this question x is assumed to have a value. Maybe evaluate               x=3;      * * * I have had a lot of difficult moments with Mathematica where I wished I could just make evaluation stop. One basic example is where you have want to do the following               Evaluate[Symbol["x"]] = 7      But x already has a value. In this example we can do something with `ToExpression["x",InputForm, Hold]` or as Leonid has suggested, `ToHeldExpression`, but this is not really the point. Despite a warnings by Leonid, I like using Unevaluated. A similar problem arises here, as I will try to show. We might have               g[_Symbol]:="yay"      Then we can simply do               g[Unevaluated[x]]      -> "yay" and be satisfied. However, we must realize that we cannot do something like               g[Sequence[Unevaluated[x]]]      -> g[Unevaluated[x]] or, the trickier example, using               var := Unevaluated[Unevaluated[x]]      where I encourage you to do               var//Definition      -> var := Unevaluated[x] In the tricky example, we can try               g[var]      -> g[Unevaluated[x]] So that it does not evaluate to "yay" as we would have desired. **Edit** It may not seem natural at all to have Mathematica end up with an expression like g[Unevaluated[x]] which if you evaluate it gives something else. In my mind I was bluffing for a moment that I might understand what is going on, but I guess really I don't. Also note that we have               With[      {yyyy = g[var]}      ,      Identity[yyyy]      ]      -> g[Unevaluated[x]] which is even stranger. If this is a bug, please let me know. I guess I should have taken Leonids advice about Unevaluated :(. The function I defined below still works though... **End of edit** To come to the point, I feel like there should be a function like HoldPattern2, or HoldPatternRHS that works as follows               g[HoldPattern2[x]]      -> "yay" and               g[Sequence[HoldPattern2[x]]]      -> "yay" and               MatchQ[HoldPattern2[x], _Symbol]      -> True I hope the usefulness of this speaks for itself.. At some point I thought for a minute that HoldForm could be used for this (which I am a bit embarrassed about). My questions are   1. This function really does not exist, right?    2. There is no easy way to make this function, right? Just now I tried the following definitions               ClearAll[holdPattern2]     SetAttributes[holdPattern2, HoldAll];          holdPattern2 /: f_Symbol[y___, holdPattern2[x_], z___] :=       f[y, Unevaluated[x], z]      This seems kind of unstabile, but at least we have               g[holdPattern2[x]]      -> "yay" and               MatchQ[holdPattern2[x], _Symbol]      -> "yay" and               z = 4;     holdPattern2[z] = 3;     z      -> 3 **Edit** we even have               holdPattern2[r]:=x;     r//Definition      -> r := x Which is nice. **End of edit** I would like to think more about the flaws of this function myself, but I already spent more time asking this question than I planned. Maybe it is an interesting find (actually I am quite happy it works for all the examples :D). Feedback is welcome!


DAE - varying initial conditions

I want to solve a DAE-system and I want to vary more than one initial conditions and to manipulate them. I looked here: Putting NDSolve into ParametricPlot But it does not work:               alpha = 0.5     beta = 1     sol = ParametricNDSolve[{             x'[t] == -x[t]*a[t] - 3*x[t] + alpha*y[t]^2 +  1/2*beta*(r1[t]^2 - r2[t]^2),         y'[t] == -y[t]*a[t] - alpha*x[t]*y[t],         r1'[t] == -r1[t]*a[t] - 3/2*r1[t] + beta*x[t]*r1[t],         r2'[t] == -r2[t]*a[t] - 3/2*r2[t] + beta*x[t]*r2[t],        a[t] == -1/2*(3 - 3*y[t]^2 + 3*x[t]^2),        x[-10] == b, y[-10] == c, r1[-10] == 0.2, r2[-10] == 0.2},        {x, y, r1, r2},       {t, 1, -10}, {b, c}]          Manipulate[      ParametricPlot[y[c][t] + x[b][t], {t, 0, -5}], {b, 0, 1}, {c, 0, 1}]


Importing images from the web using ImportString & URLFetch

I can bring images from the web using the Import command like this:               Import["http://blog.wolfram.com/wp-content/uploads/2008/06/se-30.jpg"]      ![good image](http://i.stack.imgur.com/qlxsY.png) Sometimes the web request is more complicated so I must to use URLFetch. For that, this is what I have tried to do:               ImportString[         URLFetch["http://blog.wolfram.com/wp-content/uploads/2008/06/se-30.jpg"],     "JPG"]      ![unreadable image](http://i.stack.imgur.com/jtH3X.png) Do you know how to make the image load correctly? I suspect that this is related to strings encodings, but I have not been able to solve it.


Why my Mathematica 9.0.1 wont work with some samples of Mathematica in Graph Theory?

I updated my _Mathematica_ recently to 9.0.1 cause the previous version was giving me freaky result especially in `FindMinimumCostFlow` and `OptimumFlowData`. But even in new version I have problems.It can not still solve the multi-source multi-sink problem even the same example of _Mathematica_ documentation such as first of basic examples:               FindMinimumCostFlow[      Graph[{1, 2, 3, 4, 5, 6}, {UndirectedEdge[1, 2],         UndirectedEdge[2, 3], UndirectedEdge[3, 4], UndirectedEdge[1, 5],         UndirectedEdge[5, 6], UndirectedEdge[6, 4], UndirectedEdge[2, 5],         UndirectedEdge[3, 6]}, {ImageSize -> 110,         VertexShapeFunction -> {"Name"}}],      {1, 3, 4, -3, -4, -1}]      After evaluation it doesn't return any result. Can somebody help me on that?


How to create a 3D curved surface, given some discrete points in space?

I have some 3D point data and I want to create a curved surface with these points, and export the curved surface data (point coordinates) according to points density on the curved surface. How can I do that? The data is in 3 columns. I use `ListPlotPoint3D[]` to show the spatial distribution of these points.               w1 = Import["FaultMode_szk_test.txt", "Table"];          104.0152    31.3715 -1.8614     103.9882    31.3934 -4.7228     103.9611    31.4154 -6.5841     103.9341    31.4373 -8.4455     103.9070    31.4592 -9.3069      103.9591    31.3203 -1.8614      103.9318    31.3420 -4.7228     103.9045    31.3637 -6.5841     103.8772    31.3854 -8.4455      103.8498    31.4071 -9.3069      103.9035    31.2694 -1.8614      103.8762    31.2910 -4.7228      103.8490    31.3127 -6.5841      103.8217    31.3344 -8.4455      103.7944    31.3561 -9.3069      103.8480    31.2184 -1.8614      103.8207    31.2401 -4.7228      103.7932    31.2616 -6.9841      103.7735    31.2925 -8.6455      103.7475    31.3150 -9.3069      103.8003    31.1799 -1.8614      103.7825    31.2073 -3.7228      103.7662    31.2350 -5.5841      103.7285    31.2631 -7.4455         103.7079    31.2891 -9.3069          ListPointPlot3D[w1]


Nontrivial solutions of equation

Here, I have one problem in finding nontrivial solutions of a system of equations. I want to choose one variable, for example X1 and to get solutions of X2(X1) and X3(X1). It is not difficult when I have three unknowns, it can be solved by hand quickly, but if I have system with many unknowns, how can I find nontrivial solutions of a system with chosen unknown for example first X1 and to find others in function of X1. Here is a an example. I need X2(X1) and X3(X1)                A={{A11, A12, A13}, {A21, A22, A23}, {A31, A32, A33}};      X={{X1}, {X2}, {X3}};          Solve[(A-λ*IdentityMatrix[3]).X==0,{X2,X3}]      or with four unknowns I am looking for nontrivial solutions X2(X1),X3(X1),X4(X1)                A={{A11, A12, A13,A14}, {A21, A22, A23, A24}, {A31, A32, A33, A34}};      X={{X1}, {X2}, {X3}, {X4}};          Solve[(A-λ*IdentityMatrix[4]).X==0,{X2,X3,X4}]


Discretizing data using quantiles in Mathematica

I am trying to discretize a long array of real numbers into a uniformly distributed integer array. To do this I am identifying the quantile where each real value sits and writing it out to the output array as shown in the code below. But I am not sure this is the most efficient / optimised way to do this. Is there any more efficient code to discretize arrays?               Qsections = Range[1/#, 1, 1/#] &;      FindQuantile3[data0_, qvalue0_, qts0_] :=        Module[{data = data0, qvalue = qvalue0, qts = qts0},        quantilesT = Quantile[data, Qsections[qts]];        Position[quantilesT, Nearest[quantilesT, qvalue0][[1]]][[1, 1]]        ];     FindQuantile3[RandomReal[10,1000],5,7]      out: 3 (* meaning that 5 is in the 3rd quantile of the randomly created array if we divide it in 7 quantiles*) This is the result I want, but I find the function too complicated and slow for what it needs to do. Any improvement ideas?


Symbolic matrix equation

I am looking to a system of equations of the form $\pi =\pi P$, the one encountered in Markov chain theory. My $P$ variable is:               mat = {{-(l0 + m0), l0, 0, 0, 0, 1}, {0, -(l1 + l2 + m0), l1, l2, 0,      1}, {0, m1, -(m1 + l2 + m0), 0, l2, 1}, {0, m2,      0, -(m2 + l1 + m0), l1, 1}, {0, 0, m2, m1, -(m2 + m1 + m0), 1}};     mat // MatrixForm       My $\pi$ is defined through:               p = {{p1, p2, p3, p4, p5}};      And I used solve as:               Solve[p.mat == {{-(l0 + m0) p, 1}}, Flatten@p]      Is my code correct? I find a {} in the output. Is Mathematica unable to process?


How to create word clouds?

Word clouds are ~~rather useless~~ fancy and visually appealing plots, where words are plotted with different sizes according to their frequency in a corpus. Many applications exist out there (Wordle, Tagxedo, etc.) that can give an example. I am interested in the algorithm that achieves the closest possible packing of words or other irregular shapes. There is a method for defining the convex hull of an object (in the Computational geometry package), but I think one needs here the boundary that closes the least area. If this is calculated, perhaps the packing method of graph layout can be exploited by assuming that points on the hull of a word correspond to graph vertices... but this is just speculation. So far I could only list and style the words (that was the easy part):               tally = Tally@        Cases[StringSplit[ExampleData[{"Text", "AliceInWonderland"}],           Except@LetterCharacter], _?(StringLength@# > 4 &)];     tally = Cases[tally, _?(Last@# > 10 &)];     range = {Min@(Last /@ tally), Max@(Last /@ tally)};          words = Style[First@#, FontFamily -> "Cardinal", FontWeight -> Bold,           FontColor ->            Hue[RandomReal[], RandomReal[{.5, 1}], RandomReal[{.5, .8}]],           FontSize -> Last@Rescale[#, range, {12, 70}]] & /@ tally;          Framed[Grid@Partition[words, 10, 10, {1, 1}, {}],       FrameStyle -> {Gray, Thick}, RoundingRadius -> 10, ImageMargins -> 5]      ![Mathematica graphics](http://i.stack.imgur.com/VMSYz.png) Some possible specifications of the algorithm:   * According to this link (shared by cormullion) identifying the closest boundary of each word is not enough as words can appear **inside** other glyphs with holes, like P, A, etc. Thus indeed intersection of words must be tested.   * According to Szabolcs, the code might be able to **resize words** to fit them better   * Many applications are able to arrange the cloud to **fill up a user-specified shape** (e.g. ellipse, apple, Che Guevara, etc.) instead of being casually positioned along the ever-increasing spiral.   * It would be nice to allow individual words to have **different rotations**.   * As usually, a fully **vectorized** version is preferred over image-processing methods (if the former is faster).   * Also it would be nice to have post-rendering effects, like clickable words, mouseover effects, etc. One way to convert strings to vector graphics is:               First@ImportString[      ExportString[        Style["SomeText", Italic, FontFamily -> "Times", FontSize -> 36],         "PDF"], "PDF", "TextMode" -> "Outlines"]      Some related questions for those who want to do further research:   * Computing Text bounding boxes   * How to determine the convex hull of some text?   * How to partition a disk into individually spaced bricks?   * Character edge finding   * Intersecting graphics   * Algorithm to implement a word cloud like Wordle (thanks to cormullion for the link)


How to hide brackets and create bars over variables

I have two problems figuring out how to format my formulas properly so that when I print out the notebook the formulas look like the ones in my textbook. So far I've got this: $\sum\limits_{i=1}^5 x[[i]]-x$ but ideally I would want the i to be without the double square brackets, and also I would want a bar over the $2$nd $x$, and to make it the mean of the list $x$.


Display a number in Mathematica 9 in periodic form

I want to display a rational number in _Mathematica_ in periodic style. `PeriodicForm` isn't working anymore. It worked in _Mathematica_ 5 and now I'm using _Mathematica_ 9. I want to display the number $3.13678989898989898989\ldots$, where the repeating $89$ part should be displayed as $3.1367\overline{89}$


Solve works with numbers but not number stored in variable

I have the code:               theta = 0.1; phi = 0.1;     a = 1 - 3 Sin[theta]^2*Cos[phi]^2;     b = 1 - 3 Sin[theta]^2*Cos[phi - (2 Pi/3)]^2;     c = 1 - 3 Sin[theta]^2*Cos[phi - (4 Pi/3)]^2;     Solve[       a*b*Sin[(Sqrt[3] x - 3 y)/2] ==        a*c*Sin[(Sqrt[3] x + 3 y)/2] ==        -b*c*Sin[Sqrt[3] x],        {x, y}]      which I left running for 10 minutes before aborting. However if I simply replace the constants with their numerical values, aka I replace the last line above by               Solve[       0.965496 Sin[(Sqrt[3] x - 3 y)/2] ==        0.960503 Sin[(Sqrt[3] x + 3 y)/2] ==        -0.984803 Sin[Sqrt[3] x],        {x, y}]      The above runs straight away with no problems. I don't understand why it is doing this. Any pointers?


Connecting to a SQL Server Instance

What is the syntax for connecting to a specific instance of a sql server database? Here's my code:               Needs["DatabaseLink`"];     conn1 = OpenSQLConnection[       JDBC["Microsoft SQL Server(jTDS)", "ARC-WEB/SKWSPATIAL"],        "UserName" -> "Mathematica", databasename = "XYZ_Database",        "Password" -> "xxxxx"]      I have no problem connecting to ARC-WEB but cannot connect to one of the other instances. Mathematica 9.0 SQL Server 2008


How to superimpose contour lines on transformed image

My goal is to superimpose contours lines or contour plots on distance transformed image. ![enter image description here](http://i.stack.imgur.com/tjNE3.png)


Reference request for neural network programming in Mathematica

I'm looking for a good reference/book on programming neural networks in mathematica. I've been working through Freeman's "Simulating Neural Networks with Mathematica," but it is from 1994 so is quite dated. Is anyone familiar with a more recent book on the subject? For background, I'm very comfortable with pure mathematics, somewhat comfortable with general programming, and have been teaching myself to be proficient in mathematica. I'd like to play around with implementing neural networks on mathematica for use in forecasting of high frequency economic data, so anything with a finance bent is an especially welcome reference.


Solve equations for all values of variables, rejecting certain types of solution

I have an expression, `expr`, containing 3 variables, 4 coefficients and 2 non-zero generic constants. I want to solve for the 4 coefficients such that the equation holds for all values of the variables and for all non-zero values of the constants. It is possible to solve either `expr == 0` or `expr == 1`. Acceptable solutions should not assign a specific value to the constants. Also, I do not want solutions that set all 4 coefficients simultaneously to zero. Example: Let `x`,`y`,`z` be the variables, `a1`,`a2`,`a3`,`a4` be the coefficients and `b1`,`b2` be the generic non-zero constants.               expr =       -2*a3*b1 + a1*x + a2*x + a3*x + a4*x + (a3*b1*y)/b2 - (a4*b1*y)/b2 +         2*a1*z - 2*a1*b2*z - 4*a2*b2*z - 2*a3*b2*z - 2*a4*b2*z;          SolveAlways[{b1 != 0, b2 != 0, expr == 0}, {x, y, z}]     (* {{a2 -> -a1, a4 -> 0, a3 -> 0, b2 -> -1}, {a2 -> 0, a4 -> 0, a1 -> 0,        a3 -> 0}} *)          SolveAlways[{b1 != 0, b2 != 0, expr == 1}, {x, y, z}]     (* {{a2 -> -((2 a3)/(1 + b2)), a4 -> a3, a1 -> -((2 a3 b2)/(1 + b2)),        b1 -> -(1/(2 a3))}} *)      Here I would want to automatically select only the last solution, all the others do not meet my criteria. Also, it should be rearranged so as to assign a value to `a3` dependent on `b1`, not the other way around. Is there a way to do this?


Importing a Matrix whit different column numbers depending on the row

I have a bunch of coordinates given in a file. The file contains Startpoints and Endpoints of arrows in columns(Example):               t    start1    end1    start1   end2        1    1  2     2  2    0  0     1  1     2    0  0     1  4           Where the number of arrows is not constant over time. I tried to read the file like this and it did not work (especially the No_of_columns which gives the number of columns for a given row should depend on the row number as each row does not contain the same number of coordinates):               {{#1, #2}, {#3, #4}} & @@@ #[[All, 1 ;; No_of_columns(row) ;; 4]] &/Arrows;      I could also output another file stating the number of coordinate pairs in each row:               t   No_of_arrows      So basically I need a matrix whose column number is not the same for all rows. Is that even possible? EDIT: https://www.dropbox.com/s/xuuc6v0az73k49e/arrows.txt EDIT2: I will try to be more specific. I created (with a lot of help) a code animating rectangles movement in 2D. In the next step I want to connect those rectangles by arrows. Importantly those arrows come and go so that I would have to give another file stating the number of arrows at each time point (maybe?). So for now I need data looking like this (?)               Arrow_coordinates={{{{1,2},{2,2}},{{0,0},{1,1}}},{{{0,0},{1,4}}}}       In this case I could run an animation with 2 arrows in the first step and 1 in the second step. Animation of moving rectangles in 2D from data file


Can someone help me solve this x*y*z=180

I have one question I've been trying for a while but I can't get the result for my equation.. So I've been trying hard but I can calculate only by hand but the problem is that I am afraid to miss any combination.. So lets get to my equation x*y*z=180 x,y,z should be from [1-10] so which combinations are possible ? Thanks in advance have a great day


Mixing up eigenvalues with positive and negative imaginary parts

f[k_] = {{-0.001 - 2 I k, 1, -0.001, -0.501}, {0.001, -0.5 - I k, 0.001, 0.001},          {-0.001, -0.501, -0.001 + 2 I k, 1.}, {0.001, 0.001, 0.001, -0.5 + I k}};          y[k_] = Im[Eigenvalues[f[k]][[3]]];     Plot[y[k], {k, -1, 1}]      ![](http://i.stack.imgur.com/B4ZeL.jpg) 3rd and 4th eigenvalues are complex conjugates, as we can see from the graph the program mixed them, there are lots of jump discontinuities from the one with negative imaginary part to the one with positive. I suspect that the program sometimes takes as the 3rd eigenvalue (or root) the one with positive "Im" and sometime the one with negative "Im". Please help me to resolve this problem by a general approach (of course for this case one can take the Max of two as k>0 and Min otherwise to obtain the imaginary part of the desired eigenvalue).


How to manually set z-axis values in a 3d plot?

I'm plotting an hemisphere with               radius = 5;     Height = 0.2;     SphericalPlot3D[ radius, { θ, 0, π/2}, { ϕ, 0, 2 π},                       BoxRatios -> { 1, 1, ((0.5 Height)/(radius) + 0.03)}]      and I'm using `BoxRatios` to flatten the hemisphere so that it has a "height" of 0.2.   Is it possible to manually write/show the $z$-axis values so the visible range is not `{ 0, radius}`   but `{ 0, 0.2}`?


Solve set of non linear differential equations

I have set of differential equations. For example, I took two equations and tried to solve them as below. I am not getting any results. Please help me to figure it out the mistake. And I wonder if I can use matrices to solve such a system of equations.Please don't put down this question.This is very important to my research.               Clear[j, v, s]     j[V_] = v[t] + v[t]^2;     τ = 1;     s = 0.1;     ip = 0;     DSolve[{v1'[t] == -v1[t]/τ + (j[v2]*s) + ip,              v2'[t] == -v2[t]/τ + (j[v1]*s) + ip},    {v1, v2}, t]


Merge two Matrices without Duplicates

I have two matrices, for example:               data1 = {{"c1", "c2", "c3"}, {2, 5, 3}, {54, 2, 3}, {11, 2, 10}, {3,      5, 7}};      and               data2 = {{"c1", "c2", "c3"}, {11, 2, 10}, {3, 5, 7}, {2, 5, 3}, {54,      2, 3}, {3, 1, 4}, {5, 2, 3}};      I would like to merge these two matrices in a way that there is only one copy of the overlapping rows. This should lead to:               merged = {{"c1", "c2", "c3"}, {2, 5, 3}, {54, 2, 3}, {11, 2, 10}, {3,      5, 7}, {2, 5, 3}, {54, 2, 3}, {3, 1, 4}, {5, 2, 3}};      I'm looking for a procedure which works also for examples which don't overlapp.


Gray background in export pdf

I am trying to output a simple plot with a legend and the output keeps coming out with a gray background. A simple example is the following:               Plot[{Sin[x], Cos[x]}, {x, 0, 2*3.14}, PlotStyle -> {Red, Blue},      PlotLegends -> SwatchLegend[{Red, Blue}, {"sin(x)", "cos(x)"}]]     Export["trig.pdf", %]      which outputs (notice the gray background!), $\hspace{1cm}$![enter image description here](http://i.stack.imgur.com/QNmi3.png) I have tried setting "Background->White" in different places, but only managed to have certain regions to get a white background. How can I get an export the image with a white background (and keeping it in pdf format)? I am using Mathematica V9 on Linux. **Edit:**   1. I just upgraded to V10 with hopes that it would fix the issue and the problem still persists.   2. pdf and eps both show the gray background while image formats such as jpg don't. Oddly enough svg also doesn't show the gray background.   3. I'm using Ubuntu 14.04 with Intel 4th generation graphics card.   4. I tried using different pdf viewers and they all showed the same gray background.


TimeConstrained for Table?

Let's say that I have a function `f[i]` that takes quite a while to evaluate (evaluation time is different for different i) and I'd like to have as many values of `f[i]` as possible, for `i = 1, 2, 3, ...`, but in a specified amount of time (say, one minute) I want to stop evaluation and return values for `i = 1, ... iFeasible` (there is no way to calculate `iFeasible` before full computation). Basically, what I want to achieve is:               TimedConstainedTable[expr, {i, imin, imax}, maxTime]      To simplify: "If evaluating `Table[expr, {i, imin, imax}]` takes more time than `maxTime`, detect it, and return `Table[expr, {i, imin, iFeasible}]` (but do not evaluate values of expr for `i = imin, ..., iFeasible` again; extract them somehow from interrupted evaluation)." It is super easy to implement:               list = {}; TimeConstrained[Do[AppendTo[list, f[i]], {i, 10^6}], 60, list]      but also very inefficient. Any improvement would be great.


Plot various functions in different intervals

I need to do some really easy in **WolfarmAlpha online**. I want to to plot `2x` for {`1` to `3`} and x^2 for {`3` to `5`}. I tried multiple combinations, none of them gave me what I want. The following input did not work either.               Plot[(2*x),{x, 1, 3}], Plot[(x^2),{x, 3, 5}]


How can I thread lists of different sizes?

What I need is the equivalent of Maple's zip(`+`, A, B, 0). Sure I can get it with:               Thread[PadRight[A, max = Max[Length[A], Length[B]]] + PadRight[B, max]]      But is there a less verbose way to do this? P.S. Eventually the shortest solution seems to be:                Plus @@ PadRight[{A, B}]


How can I convert the dates returned by FinancialData into decimal representation?

I'm trying to run a regression using `Fit` on the output of `FinancialData["SPY", "Jan. 1, 2011"]`. However, the dates returned from `FinancialData` are not in a format that is recognized by `Fit`. The function returns dates in the format `{y,m,d}`, and I need the dates to be expressed in decimal form. I'm relatively new to Mathematica, but I've got to believe there's an easy way to transform the list provided by `FinancialData` into one that has the format of `{<date in decimal>, price}`. Any guidance would be most appreciated.


what is wrong in my program with PlotLegend option (Mathematica8)?

u = Sin[x];       v = Cos[x];     w = Cos[x]^2;     y = Sin[x]^3;          Needs["PlotLegends`"]          Plot[{u, v, w, y}, {x, -10, 10}, PlotRange -> All,       PlotStyle -> {AbsoluteDashing[{}], Dashed, DotDashed, Dotted},       PlotLegend[{{Graphics[{AbsoluteDashing[{}],            Line[{{7, 0.1}, {8, 0.1}}]}],          "a=0.02"}, {Graphics[{Dashed, Line[{{7, 0.3}, {8, 0.3}}]}],          "b=0.03"}, {Graphics[{DotDashed, Line[{{7, 0.5}, {8, 0.5}}]}],          "c=0.04"}, {Graphics[{Dotted, Line[{{7, 0.7}, {8, 0.7}}]}],          "d=0.07"}}]]      the error is: > An option must be a rule or a list of rules.... > > Coordinate Skeleton[2] should be a pair of numbers, or a Scaled or Offset > form Would You please help me!


Moving controls from Manipulate to a Palette ( or similar GUI object )

Consider the following snippet as a reference.                DynamicModule[{},        Manipulate[        Graphics[          Translate[            GeometricTransformation[              { Blue,                 Polygon[{{0, 0}, {1, 0}, {1, 1}, {0, 1}}]              }, {{scx, 0}, {0, scy}}            ],             Tuples[{Range[wi], Range[he]}] - 1          ],           ImageSize -> 400 {1, 1}        ],         {{scx, 1, "x scale"}, 0, 1},         {{scy, 1, "y scale"}, 0, 1},         {{wi, 1, "width"}, 1, 5, 1},         {{he, 1, "heigth"}, 1, 5, 1}       ]     ]      ![Mathematica graphics](http://i.stack.imgur.com/Y5HDw.png) A graphical drawing program with a lot of controls (buttons, sliders) would benefit (a lot) by freeing up space and moving controls to a `Palette`, or a similar construct. I am considering the redesign of a GUI and I am currently investigating the options and technical possibilities. - Looking at the reference code snippet (which is not the GUI in question, but makes asking the question - and answering! - so much easier) I have the following question. **Is it possible to move (one of) the sliders to a`Palette`, or similar construct?**


Passing Mathematica function via MathLink or LibraryLink to c (or c++)

I want to numerically solve the heat equation. To do so I wrote a program in C++ - It is a BVP $(\alpha T +\kappa \frac{\partial T}{\partial r}=f(t))$, where $f(t)$ is an arbitrary function, whose address I pass to the constructor of the struct `BoundaryCondition`               struct BoundaryCondition     {       enum class Side {LEFT,RIGHT};       double alpha;        double kappa;       double (*f) (double);       Side side;       BoundaryCondition(Side,double,double,double (*)(double));     };      Now I rewrite my code to use _Mathematica_ Interface. My plan is to write the functions for the left and right boundary conditions in _Mathematica_ , pass these functions(by name or by address???) and the initial data(array of real numbers) to my C++ code. Then I will just call these functions in an iterative algorithm. And finally - flush the results back to _Mathematica_ for post-processing (graphics, another calculation, etc.) Do you have any idea how to pass an arbitrary (unknown in advance) function (not just the usual data) to my, written in C++, library as an argument for further usage in the C++ code ?


Dataset: get number of levels and elements

The summary box for `Dataset` objects shows the number of levels and elements at the bottom. How can we get these values programmatically? For example, "4 levels, 350 elements" in the Planets dataset: ![Mathematica graphics](http://i.stack.imgur.com/bFxA3.png)


Output for Latex

I have a Mathematica command WriteString[str,TeXForm[ToString[a]^ToString[Divide[p, q]]]] where a=47, p=17 and q=2, but the result is $47^{\text{17$\backslash $n--$\backslash $n2}}$ I hope I have $47^{\frac{17}{2}}$. Can someone help me please. Thank you


How to get a list of available appearance/styles?

This is a basic question but I haven't found any answer yet :/ Available appearances for `Button[]` are mentioned in `Help`, those are `"Palette"`, `"FramedPalette"`, `"DialogBox"` and so on. But is this all? How could I get to know? For example there is also used in Help `"NoOp"` option in `MouseAppearance[]`. Are there any others in addition to those mentioned in `Help`. Is there somewhere more info about styles but for different functions too?


Locators and Table within a Manipulate are not behaving

I am putting together a Manipulate on vector addition for my intro physics class and everything works well except when I include a Graphics that has a Table within. The code is below. There are three controls for each vector; two sliders x1, and y1 for the vector components and a Locator p1 at the head of the vector. In the code you'll see second arguments of Dynamics that link the Locator coordinates p1 and the vector components x1 and y1. There is a second vector that starts at the head of the first and has similar controls associated with it. There are several Graphics that I've left out that don't matter. What I left in here are curved arrows to show the standard angle for each vector. The Arrows are created using Table as you can see. If you Show just the two vectors, as I have in the code below, everything works perfectly. As you move the Locator or the Sliders for one vector the other vector does not change magnitude or direction. If I include the angle arrow for vector 1, angleArrow1, in the Show command it still works perfectly. However, if I include the angle arrow for vector 2, angleArrow2, in Show the Locator at the head of vector 2 acts as if it is the Locator for vector 1. In other words, when I move the Locator at the head of vector 2 only vector 1 changes. However, moving the sliders for vector 2 works as do the sliders and Locator for vector 1. What is weird is that if I use the commented out version of angleArrow2 that doesn't use Table, but uses an explicit list, it works! I need Table to generate the list because I need an arc that grows as the angle grows and remains fairly smooth looking. So what is it about Table (and only in the angleArrow for vector 2) that is causing it to in effect link the two Locators? I've tried putting the angleArrow creation function into an Initialization at the end of the Manipulate and calling it when needed, but it still doesn't work. I've tried wrapping Evaluate around Table, or around Arrow, but still no help. I'll keep tinkering, but this has really got me stumped. Thanks!               Manipulate[(*The second argument of the Dymanics below allows us to \     link the Locator with variable p (={x,y}) to the two sliders with \     variables x and y.*)           theta1 =        Which[y1 >= 0, ArcCos[x1/Sqrt[p1.p1]], y1 < 0,         2 Pi - ArcCos[x1/Sqrt[p1.p1]]];      vector1 =        Graphics[{Green, Arrow[{{0, 0}, p1}],          Locator[Dynamic[           p1, (p1 = #; {x1 = p1[[1]], y1 = p1[[2]],               p2[[1]] = p1[[1]] + x2, p2[[2]] = p1[[2]] + y2}; #) &]]}];       angleArrow1 =        Graphics[Arrow[         Table[Min[0.5 Sqrt[p1.p1], 0.5] {Cos[j], Sin[j]}, {j, 0, theta1,            1/100}]]];           (*Stuff for vector 2*)           theta2 = Which[y2 >= 0, ArcCos[x2/Sqrt[x2^2 + y2^2]], y2 < 0,         2 Pi - ArcCos[x2/Sqrt[x2^2 + y2^2]]];           vector2 =        Graphics[{Green, Arrow[{p1, p2}],          Locator[Dynamic[           p2, (p2 = #; {x2 = p2[[1]] - p1[[1]],               y2 = p2[[2]] - p1[[2]]}; #) &]]}];           (*angleArrow2=Graphics[Arrow[{{x1+Min[0.5 Sqrt[x2^2+y2^2],0.5]      Cos[0],y1 +Min[0.5 Sqrt[x2^2+y2^2],0.5] Sin[0]},{x1+Min[0.5      Sqrt[x2^2+y2^2],0.5] Cos[theta2/2],y1 +Min[0.5 Sqrt[x2^2+y2^2],0.5]      Sin[theta2/2]},{x1+Min[0.5 Sqrt[x2^2+y2^2],0.5] Cos[theta2],y1      +Min[0.5 Sqrt[x2^2+y2^2],0.5] Sin[theta2]}}]];*)           angleArrow2 =        Graphics[Arrow[         Table[{x1 + Min[0.5 Sqrt[x2^2 + y2^2], 0.5] Cos[j],            y1 + Min[0.5 Sqrt[x2^2 + y2^2], 0.5] Sin[j]}, {j, 0, theta2,            1/100}]]];           (*Combine All The Graphics*)           Show[{vector1, vector2},        PlotRange -> {{-4.1, 4.1}, {-4.1, 4.1}}, ImageSize -> 500],           (*Controls*)           Row[{"Ax",         Manipulator[         Dynamic[x1, (x1 = #; {p1[[1]] = x1, p2[[1]] = x1 + x2}; #) &], {-4, 4}],        Spacer[4],         Dynamic[Style[Round[x1, 0.001], 14]]}],       Row[{"Ay",         Manipulator[         Dynamic[y1, (y1 = #; {p1[[2]] = y1, p2[[2]] = y1 + y2}; #) &], {-4, 4}],        Spacer[4],         Dynamic[Style[Round[y1, 0.001], 14]]}],       Row[{"Bx",         Manipulator[         Dynamic[x2, (x2 = #; p2[[1]] = x1 + x2; #) &], {-4, 4}],         Spacer[4], Dynamic[Style[Round[x2, 0.001], 14]]}],       Row[{"By",         Manipulator[         Dynamic[y2, (y2 = #; p2[[2]] = y1 + y2; #) &], {-4, 4}],         Spacer[4],         Dynamic[Style[Round[y2, 0.001], 14]]}],       {{p1, {1.5, 1.5}},None},      {{p2, {1.5 + Cos[Pi/6], 1.5 + Sin[Pi/6]}}, None},      {{x1, 1.5},None},      {{y1, 1.5}, None},      {{x2, Cos[Pi/6]},None},      {{y2, Sin[Pi/6]}, None},      {{theta1, Pi/4}, None},      {{theta2, Pi/6}, None}, TrackedSymbols -> {x1, y1, p1, x2, y2, p2}]


DistributeDefinitions doesn't work as expected when used for table iterator bounds?

I am new to parallelization in Mathematica, so this question may reflect some elementary confusion. I am attempting to parallelize a rather complicated module which, as part of its internal operation, builds some tables. I ran into some mysterious-looking errors, and the code doesn't work. It turns out that the errors occur even when I try to run some very simple code:               K=3;     DistributeDefinitions[K];     ParallelEvaluate[Table[0, {i, 1, K}]]      I am using 2 parallel kernels, so I would expect this to generate the result               {{0, 0, 0}, {0, 0, 0}}      It actually does generate this result but it also generates errors:               (kernel 1) Table::iterb: Iterator {i,1,K} does not have appropriate bounds.     (kernel 2) Table::iterb: Iterator {i,1,K} does not have appropriate bounds.      I suppose that this means the parallel kernels are returning the command unevaluated, and then it's being evaluated by the master kernel before the output is printed. What's going on -- how can I get the parallel kernels to use the value of K? I am using Mathematica 8.0.4.0. Thanks in advance for any insight!


Function to calculate and plot sample variogram

I'm trying to create a function that calculates and plots the sample variogram for a time series. It should take two arguments: data, a time series, essentially a list of reals; k, an integer greater than 0. It should produce a `ListLinePlot` with $k$ on the horizontal axis and $\hat{G_k}$ on the vertical axis. The plotting and such isn't really the problem. The problem is getting the mathematical formulas, which are below, into Mathematica formulas. $\hat{G_k}$ is essentially a ratio of variance at lag $k$ over the variance at lag $1$: $\hat{G_k}=\frac{s^2_k}{s^2_1},k=1,2,...$ $s^2_k=\frac{\sum_{t=1}^{n-k}(d^k_t-\bar{d}^k)^2}{n-k-1}$ $\bar{d}^k=(n-k)^{-1}\sum{}d^k_t$ $d^k_t=z_{t+k}-z_t$ $z_t$ is the time series of the length $n$. I've been beating my head against this for a while now. Any help would be appreciated. **Edit:** A variogram is statistical tool to assess whether a time series is stationary or not. For a stationary it starts out at $1$ for $k=1$ and then increases until it starts to hover around a certain value. The theory and formulas I have here is from Time Series Analysis and Forecasting by Example. You might be able to use the Search Inside at Amazon to have a look at it. **Edit2:** Here is a demoplot based on dummydata as to how the end result should look for a stationary time series. ![Mathematica graphics](http://i.stack.imgur.com/BvF5v.png)


Do multiple instances of Mathematica run completely independently?

Let me simplify the problem I am trying to solve so that the issue I face is highlighted.   Say, I want to generate $n$ samples of a Gaussian random variable. I have a script (say `random.m`) that does it. I have _Mathematica_ installed on a node with $4$ cores. I ssh into it and run $4$ instances of `"math -script random.m"` The idea is that I generate $\frac{n}{4}$ per instance. Now, my actual script is a little more complicated, with other variable names, etc. One of the features of _Mathematica_ is that the value of a variable is not restricted to a notebook (unless one does so explicitly).   My question basically is: **when I run 4 instances of a program, do they run completely independently of one another?**   (Even though I have the same variable names in `random.m`, the variables themselves are random. So, I don't want any cross-talk amongst the four instances.)


Lexicographic ordering of strings in Mathematica

I recently realized that Mathematica seems incapable of comparing strings in the "normal" expected lexicographic order. Indeed, for some simulations, I need to process text directly, without fiddling with it, and I would like to have such things as               If["aaa" < "aaaab", 1, 0] (* ---> 1 *)     Min["aaaa", "deaaaf", "dfeef", "a"]   (* ---> "a" *)      and so on. However, as far as I can tell this is not possible. Am I wrong? Or is there any work-around, or way for me to use lexicographic ordering? Do I have to code it by hand? Mathematica is so good at getting stuff right out of the box I have a hard time believing it (but this would echo some other contributors comment here, that strings are "second class" citizens in Mathematica)...


How to enter an equation into FindFit?

I have the equation                y = a + b Exp[-x/c]       data = {{462.36, 8872}, {408.18, 8780}, {374.4, 8915}, {322.8, 8937},             {274.00, 8919}, {243.03, 9114}, {209.32, 9277}, {178.91, 9394},             {140.71, 9508}, {113.08, 9592}};            nlm = FindFit[data, y = a + b Exp[-x/c], {{a, 100}, {b, 100}, {c, 10}}, x]            Show[        ListPlot[data,           PlotStyle -> {Darker@Green, PointSize[0.03]}],        Plot[y/. nlm, {x, 1, 600}]]       The above is how I currently have everything working and graphing. Update I have actually got almost everything working I have theline bieing drwan the only issue I am having is that the first 2 points of data and the beginning of the line being drawn actuall start before the y axis on the graph so if you look at the graph it is skewed to the left. I am trying to understand what value I will need to change to move this back to the right and I am struggling a little bit. any help will be appreciated. how can I enter that into the `FindFit` function?               FindFit[data, model, parms];      I have my data I just can't figure out how to get this into the `model` and `params` correctly. This is the eqaution that was given me for the data and just don't know how to input it or to show that it is going to be an exponential curve.


Thickness option in FillingStyle

I have the following `ListPlot`:               ListPlot[{{1, 3}, {2, 4}, {3, .3}, {4, 6}}, Filling -> Axis,      FillingStyle -> {Thickness[0.008], Black},      LabelStyle -> Directive[20], Frame -> True]      ![plot1](http://i.stack.imgur.com/qvCup.jpg) I have a problem with the lines below the points: They are too thin. How to change the Thickness propperly? `FillingStyle -> {Thickness[0.008], Black},` seems not to be correct.


Remove annoying Conjugate

Here is an expression               Conjugate[1/Sqrt[     1 + (-2 + es + Cos[kx] + Cos[ky] +      Sqrt[(-2 + es + Cos[kx] + Cos[ky])^2 + Sin[kx]^2 + Sin[ky]^2])^2/(     Sin[kx]^2 + Sin[ky]^2)]]      With the assumptions that `es`, `kx`, `ky` are real variables, I want to remove the head `Conjugate` in a safe manner with `Simplify` or `FullSimplify`. But unfortunately, Both `Simplify` and `FullSimplify` failed to do this seemingly simple job even you use `MapAll`. Most of the time, `ComplexExpand` can remove `Conjugate`. But not in this expression. `ComplexExpand` will yield ![ComplexExpand result](http://i.stack.imgur.com/JqAAH.gif) The reason that I insist on removing `Conjugate` is that I have to differentiate this kind of expression. With `Conjugate` in an expression, I will get results containing derivatives of `Conjugate`. So how do I remove `Conjugate` other than removing it manually? (Note that in my actual work, such `Conjugate` expressions are embedded in a much larger expression and I do not know in advance whether the expression `Conjugate` heads is real or not until I take a careful look at it.) ### Edit rcollyer mentioned `Refine`, but both Jens and I found it to be inefficient. But this inspired me to investigate the function `Refine`, and this aroused more confusion. According to _Mathematica_ 's documentation (the following sentences were extracted directly from the entry on `Refine`): > `Refine` gives the **form of _expr_ that would be obtained if symbols in it > were replaced by explicit numerical expressions** satisfying the assumptions > _assum_. `Refine` must have assumptions and performs only those **basic > simplifications which would be automatic for numeric inputs**.`Refine` is > one of the transformations tried by Simplify So I came up with several questions: How does `Refine` refine expr? Will it really try to plug several sets of possible numerical values which are satisfied by the assumptions and see what comes out after **the automatic simplification**? But if so, how could `Refine` be certain it had tried enough sets of values? If it was not like this, then what does _Mathematica_ 's documentation mean? I've tried several examples which are very confusing ( **es,kx,ky are all declared real variables in`$Assumptions`**): 1.               In:=Refine[Conjugate[Sqrt[Sin[kx]^2 + (Cos[kx] + Cos[ky] + Sin[es])^2]]]     out=Sqrt[(Cos[kx] + Cos[ky] + Sin[es])^2 + Sin[kx]^2]      `Conjugate` is gone. 2.               In:=Refine[Conjugate[Sqrt[Sin[kx]^2 + Sin[ky]^2 + (Cos[kx] + Cos[ky] + Sin[es])^2]]]     Out=Conjugate[Sqrt[(Cos[kx] + Cos[ky] + Sin[es])^2 + Sin[kx]^2 + Sin[ky]^2]]      Add one more term under the `Sqrt` and `Conjugate` remains. 3.               In:=Refine[Conjugate[Sqrt[Sin[kx]^2 + Cos[ky]^2 + (Cos[kx] + Cos[ky] + Sin[es])^2]]]     Out=Sqrt[Cos[ky]^2 + (Cos[kx] + Cos[ky] + Sin[es])^2 + Sin[kx]^2]      Change the added term from `Sin` to `Cos`, `Conjugate` is gone again. Although the above three examples completely confused me, I add one more.               In:=Refine[Conjugate[Sqrt[Tan[es]^2]]]     Out=Conjugate[Sqrt[Tan[es]^2]]      According mathematica's documentation on `ComplexExpand`: > `ComplexExpand` expands _expr_ assuming that all variables are real. > `ComplexExpand` automatically threads over lists in _expr_ So now I let `ComplexExpand` do the same job:               In:=ComplexExpand[Conjugate[Sqrt[Sin[kx]^2 + (Cos[kx] + Cos[ky] + Sin[es])^2]]]     Out=Sqrt[(Cos[kx] + Cos[ky] + Sin[es])^2 + Sin[kx]^2]          In:=ComplexExpand[Conjugate[Sqrt[Sin[kx]^2 + Sin[ky]^2 + (Cos[kx] + Cos[ky] + Sin[es])^2]]]     Out=Sqrt[(Cos[kx] + Cos[ky] + Sin[es])^2 + Sin[kx]^2 + Sin[ky]^2]          In:=ComplexExpand[Conjugate[Sqrt[Sin[kx]^2 + Cos[ky]^2 + (Cos[kx] + Cos[ky] + Sin[es])^2]]]     Out=Sqrt[Cos[ky]^2 + (Cos[kx] + Cos[ky] + Sin[es])^2 + Sin[kx]^2]      All of the `Conjugate`s are gone. So `ComplexExpand` recognized that all of the three arguments are real and `Refine` failed, even though they both used the same assumptions. Also, `Refine` did not fail consistently; it succeeded on two of the examples. This proves `Refine` should have the same abilities as `ComplexExpand`, at least in the above cases. So how does one explain the mysterious failure of `Refine` in the second example? What's more, `ComplexExpand` too has its failures. I really hope somebody could perfectly **explain the simplification procedure applied by _Mathematica_**. Help me clear out all the clouds from my head.


Convergence problems with numerical integration of specific functions

I want to numerically integrate two functions that have several poles inside the integration region. These are the functions:               ThermPotQuarkGluonLoop10 = 1/2*PreFactor* Jplus*Σx     ThermPotQuarkGluonLoop12 = -1/2*PreFactor*2*(Jplus (x - y) - Jminus (x + y)) nb*Nfx/ωpq;      with the following definitions:               ωpq = Sqrt[x^2 - m^2 - 2*Sqrt[x^2 - m^2] Sqrt[y^2 - m^2] z + y^2 - m^2];     Jplus = NG ((2*m^2 + Sqrt[x^2 - m^2] Sqrt[y^2 - m^2] z -         x y)/((x - y)^2 - ωpq^2));     Jminus = NG ((2*m^2 + Sqrt[x^2 - m^2] Sqrt[y^2 - m^2] z +         x y)/((x + y)^2 - ωpq^2));     nfxp = 1/(Exp[β (x + μ)] + 1);     nfxm = 1/(Exp[β (x - μ)] + 1);     nfyp = 1/(Exp[β (y + μ)] + 1);     nfym = 1/(Exp[β (y - μ)] + 1);     nb = 1/(Exp[β ωpq] - 1);     Σx = nfxp*nfyp + nfxm*nfym;     Σy = nfxp*nfym + nfxm*nfyp;     Nfx = nfxp + nfxm;     Nfy = nfyp + nfym;     PreFactor = αs/(4*Pi^3) Sqrt[x^2 - m^2] Sqrt[y^2 - m^2];      I've fixed several numerical values               hbarc = 1973*10^(-1);     β = 67*10^(-5) hbarc;     NG = 8;     αs = 3*10^(-1);     NC = 3;     m = 48*10^(-1)/hbarc;     μ = 300/hbarc;     Λ = 25*10^(-1)*μ;      Now I integrate it numerically:               NIntegrate[ThermPotQuarkGluonLoop10, {x, m, Infinity}, {y, m, Infinity}, {z, -1, 1}, AccuracyGoal -> Infinity, PrecisionGoal -> 3, WorkingPrecision -> 20]      and               NIntegrate[ThermPotQuarkGluonLoop12, {x, m, Infinity}, {y, m, Infinity}, {z, -1, 1}, AccuracyGoal -> Infinity, PrecisionGoal -> 3, WorkingPrecision -> 20, Method -> {"DuffyCoordinates", Method -> "GlobalAdaptive"}]      My questions are:   * The Code is working for the given numerical values. Why does no error/warning appear for the integration of `ThermPotQuarkGluonLoop10`? This expression has several poles within the integration region but Mathematica can handle it without that I fixed any specified integration method for dealing with poles   * When I assume higher masses (`m=95`) I get the NIntegrate::slwcon: warning. For the integration of ThermPotQuarkGluonLoop10 I can switch to `Method -> {"DuffyCoordinates", Method -> "GlobalAdaptive"}` and it's fine. But for the integration of `ThermPotQuarkGluonLoop12` it is not working without a warning. How can I get a correct integration?   * Are the chosen methods the right way to calculate the numerical integrals or shall I choose another preprocessor/method/rule?   * Is there a way to speed up the computation? Finally I apologize for my bad coding style. I'm a Mathematica beginner... Thank you very much for your help! Cheers, Startup


Use of StringExpression as argument

Is it possible to use a StringExpression as a pattern for an argument? I.E. something like               foo[chars__~~ WordCharacter.. ~~ num:NumberString] := {chars, num};      At the moment, I'm using a somewhat more convoluted function like               bar[str_String /; StringMatchQ[str, chars__~~ WordCharacter.. ~~ num:NumberString]] :=      StringCases[str,          chars__~~ WordCharacter.. ~~ num:NumberString :> {chars, num}][[1]];


What causes this strange convergent sum?

N[Sum[1/(x^2 + 1), {x, 1, Infinity}], 5]     N[Sum[1/(x^2 + x + 1), {x, 1, Infinity}], 5]      1.0767 0.79815 + 0.*10^-6 I What causes the strange number?


Strings and Formatting

There is something about strings which doesn't seem to be totally clear for me (for the moment): When entering "a string", the output, formatted as "Output" gives this string without the quotes. But when changing the "Output" format to "Text" format (which looks better for text as the typewriter font for Output—for my uses at least), the quotes come back! Why is that and how can I get non-typewriter fonts as output of evaluations, without the quotes coming back? Thanks for all help, as always!


What is wrong in my calculation with clebsch-gordan coefficients?

According to theory of angular momentum here must equal one. What's wrong?               Timing[Sum[     If[-5 <= (m1 + m2) <= 5,      ClebschGordan[{3, m1}, {4, m2}, {5, m1 + m2}] ClebschGordan[{3,      m1}, {4, m2}, {5, m1 + m2}], 0], {m1, -3, 3}, {m2, -4, 4}]]       Or one more example. It should coincide with null after after launching. I am exausted to rack my brains what's gonna wrong?!                   << Notation`          Notation[ParsedBoxWrapper[     SubsuperscriptBox["C",      RowBox[{"j1_", ",",      RowBox[{"m1_", ";", "j2_"}], ",", "m2_"}],      RowBox[{"j3_", ",", "m3_"}]]] \[DoubleLongLeftRightArrow]      ParsedBoxWrapper[     RowBox[{"ClebschGordan", "[",      RowBox[{     RowBox[{"{",      RowBox[{"j1_", ",", "m1_"}], "}"}], ",",      RowBox[{"{",      RowBox[{"j2_", ",", "m2_"}], "}"}], ",",      RowBox[{"{",      RowBox[{"j3_", ",", "m3_"}], "}"}]}], "]"}]]]          AddInputAlias[{"3j" -> ParsedBoxWrapper[     SubscriptBox[     RowBox[{"(",      GridBox[{{"\[Placeholder]", "\[Placeholder]", "\[Placeholder]"}, {     "\[Placeholder]", "\[Placeholder]", "\[Placeholder]"}}],      ")"}],      RowBox[{"3", "j"}]]], "Cl" -> ParsedBoxWrapper[     SubsuperscriptBox["C",      RowBox[{"j1", ",",      RowBox[{"m1", ";", "j2"}], ",", "m2"}],      RowBox[{"j3", ",", "m3"}]]]}]          sumf[j1_, j2_, M1_, M2_, m1_, m2_] :=      Assuming[{j1 >= 0, j1 >= m1 >= -j1, j2 >= 0, j2 >= m2 >= -j2},      Sum[If[j3 >= Abs[m1 + m2] && j3 >= Abs[M1 + M2], \!\(     \*SubsuperscriptBox[\(C\), \(j1, m1; j2, m2\), \(j3, m1 + m2\)]      \*SubsuperscriptBox[\(C\), \(j1, M1; j2, M2\), \(j3, M1 + M2\)]\),      0], {j3, Abs[j1 - j2], j1 + j2}]]          Timing[sumf[8, 4, 3, 2, 2, 1] // N]


Convert head Times to List

I can convert an expression with the head of Times,for example, `12*12.5*13*13.5*14*14.5` to `{12, 12.5, 13, 13.5, 14, 14.5}` by using the code below： > ReleaseHold[HoldForm[12*12.5*13*13.5*14*14.5] /. Times -> List] I have a list which contains a lot of such expressions,here is an example: > listSample={12*12.5*13*13.5*14*14.5, 12*12.5*13*13.5*14*14.5, > 12*12.5*13*13.5*14*14.5, 12*12.5*13*13.5*14*14.5, 12*12.5*13*13.5*14*14.5, > 12*12.5*13*13.5*14*14.5} I still want to convert all the heads `Times` to `List`,but I failed when tried to Map `HoldForm` to each listItem,because it alway evaluates first. Here is my code: > ReleaseHold[HoldForm[#] /. Times -> List]&/@listSample I want to get this result: > {{12, 12.5, 13, 13.5, 14, 14.5},{12, 12.5, 13, 13.5, 14, 14.5},{12, 12.5, > 13, 13.5, 14, 14.5},{12, 12.5, 13, 13.5, 14, 14.5},{12, 12.5, 13, 13.5, 14, > 14.5},{12, 12.5, 13, 13.5, 14, 14.5}}


how to deploy notebook into player pro

I want to ask how can I deploy`Mathematica` notebook into player pro. I know that online conversion to `Mathematica player pro` is there. But is there any function for player pro as there is `CDFDeploy` for deploying notebook in CDF?


Mark Minimum Value in DensityPlot

Let's take this example:               DensityPlot[Sin[x] Sin[y], {x, -4, 4}, {y, -3, 3}]      How do I retrieve the minimum value and position of the minimum of a plot from the plot? How do I tell Mathematica to mark the position of the minimum/minima within the plot? And for `ContourPlot`s               ContourPlot[Sin[x] Sin[y], {x, -4, 4}, {y, -3, 3}]      Is there a way to mark the exact minimum position within the plot even though it's a contour plot? Yes, Jens and Szabolcs, that would be the best way if i could manage to write the code for that. I'm still a beginner with mathematica and haven't managed so far to cope with that problem because....well i think i have to post a piece of my code to show it. I have deleted most of the variables and replaced them by constants for simplicity reasons:               eislexpl[epsilon_, n2_, x_] :=  28 (epsilon)^2 - 1 +      ((-2 Log[E^(1/2) x])/x^2 + (2.7(0.3 - epsilon))/x +      (10 epsilon^2 n2^(3/2))/x^(3/2));          eislminx2[epsilon_?NumericQ, n2_?NumericQ] :=      (minx = FindArgMin[{eislexpl[epsilon, n2, x], 0 < x}, x];     eislexpl[epsilon, n2, minx]);          ueislexpl[epsilon_, h_, n1_, n2_] :=      n1 (40  epsilon^2 - 1) + (1 -1.27 ) (1 + (n1 - 1) HeavisideTheta[1 - n1] -      (-1 + Exp[-(n1 - 1)]) HeavisideTheta[n1 - 1]) + n2  eislminx2[epsilon, n2] +      (h - n1 - n2) (28  epsilon^2 - 1);      ueislexpl[epsilon_, h_, n1_, n2_] is the function i need to find the minimum for. But the problem for me is, that it calls this function eislminx[epsilon_?NumericQ,n2_?NumericQ]. So my problem is that in order to have a function that mathematica is able to find a minimum for, i have to plug n2 in eislminx[epsilon_?NumericQ,n2_?NumericQ], so that this part of ueislexpl[epsilon_, h_, n1_, n2_] determined, but at the same time i want to find the minimum for ueislexpl[epsilon_, h_, n1_, n2_] with respect to n2. So if anybody know how to find the minimum of ueislexpl[epsilon_, h_, n1_, n2_] with respect to n2 and n1 i would be happy to learn how. Thanks for the help. Well, my actual question has been answered by kguler, thanks again ;) And the question of how to find the minimum of that function above i will source out to here: FindMinimum of function


Does Set vs. SetDelayed have any effect after the definition was done?

I was always assuming that the only difference between `Set` (`=`) and `SetDelayed` (`:=`) is that `SetDelayed` holds the right argument, so that `a := b` is effectively the same as `a = Unevaluated[b]`. Especially I assumed that after the assignment is done, there's no further difference for variables or functions assigned with `Set` and variables assigned with `SetDelayed`. Looking at `OwnValues` resp. `DownValues` seems to support that assumption. However I now noticed that when writing `?a`, Mathematica displays the type of assignment used for the definition, which means it has to store it somewhere. And I somehow doubt that it only stores it in order to show it with `?`. Therefore my question is: Is there any difference in the behaviour of values assigned with `=` and with `:=` (apart from the different output of `?`), assuming the actual assigned expression is the same (i,e, `OwnValues`/`DownValues` have the same value after both assignments)?


show density plot on US map

I have a bunch of data points in the form of `{latitude,longitude}`. How can I plot their density on a US map? Single points on the map do not show clearly their distribution, so I'd like it to be density or something more clear. Please suggest. Thank you.


why the variable scope is not local when using evaluate to plot multicurve?

I noticed a surprising problem when using evaluate to plot multicurve, "evaluate" function actually consider global variable first, not the local! I can illustrate the problem using the following simple example, say I want to plot multicurve Z=1*x^2, 3*x^2, 5*x^2, 7*x^2 using a two-variate function Z[x_,y_]:=y*x^2, the following will work:               Z[x_, y_] := y*x^2;     Needs["PlotLegends`"];     Plot[Evaluate[Table[Z[x, y], {y, 1, 7, 2}]], {x, 1, 5}, PlotRange -> All,      PlotStyle-> {Purple, Red, Green, Blue},      PlotLegend -> Table[Style[SequenceForm["y=", y], Bold, 16], {y, 1, 7, 2}],      AxesLabel -> {"x", "Z"}]      But inserting a global variable (say x=1) before the plot command will over ride the local variable used for the plot range ({x,1,5} in the example). So Instead of plotting Z=1*x^2, 3*x^2, 5*x^2, 7*x^2, it will plot Z=1*1^2, 3*1^2, 5*1^2, 7*1^2. Isn't this counter-intuitive? I think the ListPlot is more intuitive in terms of variable scope. Because the following implementation using ListPlot is not interfered by global variable x.               ListPlot[Table[Table[{x, Z[x, y]}, {x, 1, 5, 0.1}], {y, 1, 7, 2}],      PlotRange -> All, PlotStyle -> {Purple, Red, Green, Blue}, Joined -> True,     PlotLegend -> Table[Style[SequenceForm["y=", y], Bold, 16], {y, 1, 7, 2}],     AxesLabel -> {"x", "Z"}]


How to extract data depending on Position of First zero?

I have a file (attached as an image) which I imported to _Mathematica_ and only extracted the first and second column. My problem is that I want to extract the data beginning from the row where $A=0$. Assuming that the extraction of the 2 columns is called $s$ I could easily use `Drop` `Drop[s, 13]`, but I want the same for more files in which the `0` is not always at the beginning of the 14th row. I think I should wrap it in a function of the empty entries, but I have no clue how to do it. Does anyone have suggestions for what my approach should be? ![Revamped image description](http://i.stack.imgur.com/iQzq0.jpg)


Possible bug with FourierTransform linearity

Each component is easily transformed but the sum is not:               FourierTransform[f''[x], x, k]     FourierTransform[f'[x], x, k]      > >     -k^2 FourierTransform[f[x], x, k] >     -I k FourierTransform[f[x], x, k] >                 FourierTransform[f''[x] + f'[x], x, k]      > >     FourierTransform[f'[x] + f''[x], x, k] (*!!*) >   * * * `LaplaceTransform` behaves correctly:               LaplaceTransform[f''[x] + f'[x], x, k]      > >     -f[0]-k f[0]+k LaplaceTransform[f[x],x,k] + k^2 > LaplaceTransform[f[x],x,k] - f'[0] >   Just in case. Win7 V9.0.1.0 As **acl** has noticed on chat, `Distribute` would be **quick fix** but not sure how stable for more complicated cases:               Distribute[ FourierTransform[f''[x] + f'[x], x, k]]      > >     -I k FourierTransform[f[x],x,k]-k^2 FourierTransform[f[x],x,k] >


Why am I not getting Indeterminate for f[1] when f[x_] = (x - 1)/(x - 1)?

In Mathematica 9 If I write:               f[x_] = (x - 1)/(x - 1)      I get               1      And if then I write:               f[1]       I get               1      But if I write:               (1 - 1)/(1 - 1)      I get:               Indeterminate      Why am I not getting **Indeterminate** for f[1] when f[x_] = (x - 1)/(x - 1) ? What am I doing wrong?


Plot not working

I am trying to generate a plot for `S2[w]`. My code is below               L := 50     Umc := 4.31     Su[ω_, σ_, τ_] := (σ^2 *τ/π )*1/(1 \     + (τ *ω)^2)     Sw[ω_, σ_, τ_] := (σ^2 *τ/(2*π \     ))*(1 + 3*(τ* ω)^2)/(1 + (τ*ω)^2)^2          Ru[s_] := InverseFourierTransform[Su[ω, 1, L/Umc], ω, s]          S2 [ω_] := Integrate[Ru[s]*Cos[2*ω*s], {s, 0, Infinity}]          Plot[S2[ω] , {ω, 0, 1}]      I have no idea what I am doing wrong. The function outputs number for the prescribed range when I tested. Your help would be much appreciated. Thanks!


Exporting an overlay of two plots

I have a ListLinePlot and I'm trying to place a close-up of a specific range in the ListLinePlot. Using overlay I solved this problem with:               Overlay[{p1, Item[Show[p2], Alignment -> {-.7, .6}]}]      This results in something like the following image: ![Overlay example](http://i.stack.imgur.com/FTHOX.png) But I can't select this image and export it. I can do "Print Selection as" and save as pdf, but this rasterizes the image. I want the same resolution as with a normal graphics environment. How do I achieve this?


Verifying integration by parts of an arbitrary function

Suppose that I have an arbitrary differentiable function $G$ which depends on $s$: $G(s)$. Now suppose that I want to do the following integral: $$\int ds \;\; s \frac{\partial G(s)}{\partial s}.$$ However, I do not know the exact form of $G(s)$, so I cannot _do_ the integral; I can only _"expand"_ it. One method to do this is integration by parts. I _think_ that integration allows me to rewrite the integral as $$\boxed{\int ds \;\; s \frac{\partial G(s)}{\partial s} = sG(s) - \int ds \, G(s)},$$ but I would like to verify this to make sure I am not making any mistakes. **Is there any way that I can use Mathematica to verify that for the boxed equation, the left-hand side indeed equals the right-hand side?** I have tried this:               Integrate[s*D[G[s], s], s] == s*G[s] - Integrate[G[s], s]      but Mathematica (I am running version 8) does not know how to automatically evaluate this.


Can I modify line-break behavior of inline cells?

When I insert an `InlineCell` into a `TextCell` that is too long for the whole `InlineCell` to fit on the current line, _Mathematica_ pushes the whole `InlineCell` to the beginning of the next line. That is, _Mathematica_ seems to prefer dropping the `InlineCell` to the next line over inserting a line break within it. Can I force _Mathematica_ to fit as much of an `InlineCell` on a line as possible and put as little as possible on the next line? I have played around with `LinebreakAdjustments` for the `InlineCell` and the containing cell by setting various values to `0`, but have not been able to produce the behavior I would like. **Edit:** If I do not modify `LinebreakAdjustments` for the inline cell or modify any element besides the first (leaving the first element untouched), I get results like this (blue is an `InlineCell`): ![enter image description here](http://i.stack.imgur.com/rHoMJ.png) If I set the first element of `LinebreakArguments` (of the `InlineCell`) to `0` I obtain somewhat predictable behavior: ![enter image description here](http://i.stack.imgur.com/zvP3q.png) **Below is the behavior I am trying to produce**. I've just styled the text rather than use an inline cell: ![enter image description here](http://i.stack.imgur.com/eWGFp.png)


NonlinearModelFit Problem

I have some problems with the NonlinearModelFit: `NonlinearModelFit[data, A (1 + Cos[a x]) + B (1 + Cos[b x]) + c , {A, B, a, b, c}, x]` The model should fit my data: ![data plot](http://i.stack.imgur.com/BmqeC.jpg) I tried all sort of things described in this thread. The best Fit Mathematica gave me was a really noisy horizontal line. Even if I constrain c on a reasonable Value and give a good guess, things don't get much better. I don't know what to try next and hope to find help here in the forum. * * * Thank you again. I can't really give you more data, since this data is the result of a quantum chemical calculation and because of the periodicity I would just get the same data again for the next period (accuracy about 0.0000002). Just if you are interested: The data represents the absolute Energy [Hartree] of a ethylene dichloride molecule as a function of the Dihedral angle Cl-C-C- Cl. I did a little literature research and found that all the models you suggested here were at least once used to fit similar data in some papers. You are doing a great job in this forum, I much appreciate it.


Solved the differential equation, how to rearrange to find solution?

I have solved for values of $y(x)$ from $1 < x < 2$ and plotted them:               eqn1[w_, x_, y_, z_] :=  3 x y'[x] - 2 z^2  + 3 w y[x] == 5 x     eqn2 = eqn1[1, x, y, 2]     sol = NDSolve[{eqn2, y[1] == 2}, y[x], {x, 1, 2}]     Plot[Evaluate[y[x] /. sol], {x, 1, 2}, PlotRange -> All]      ![enter image description here](http://i.stack.imgur.com/lDBP6.png) I want to find the value of $x$ when $y=3$. Graphically, when $y=3$, $x \approx 1.55$. I tried this method to calculate the value of $x$ it didn't work:               Solve[{Evaluate[sol /. y -> 3]}, x, Method -> Reduce]


Importing tabular data that has been exported from Evernote

In Evernote you can embed HTML tables in the note. You can then export them to an xml format with the extension enex. I am trying to get the data from the table imported into Mathematica. Here is the data from a small test note I made and exported as test.enex:               <?xml version="1.0" encoding="UTF-8"?>     <!DOCTYPE en-export SYSTEM "http://xml.evernote.com/pub/evernote-export.dtd">     <en-export export-date="20120812T214410Z" application="Evernote/Windows" version="4.x">     <note><title>test</title><content><![CDATA[<?xml version="1.0" encoding="UTF-8"?>     <!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">          <en-note style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;">

heading 1	heading 2	heading 3

text 1	12.34	5

text 2
	9

text 3	13.33	10

</en-note>]]></content><created>20120812T144746Z</created><updated>20120812T214402Z</updated><tag>testtag</tag></note></en-export>      I am not really sure how to get this imported into Mathematica and then get the data extracted from the embedded HTML table. Any help would be appreciated. EDIT: Slightly changed the test data so that there is a missing data point, which it turns out happens in my real dataset.


Horizon Plots in Mathematica?

I am trying to create horizon plots in Mathematica similar to what is described here: http://timelyportfolio.blogspot.com/2012/08/more-on-horizon-charts.html Any suggestions how to approach this? ![Mathematica graphics](http://i.stack.imgur.com/4TUiG.png)


Assessing argument type in set delayed function definitions

I'm wondering how to properly assess the type of arguments passed to functions defined with `:=`. I want my functions to be the most efficient, unambiguous and clear as possible. When hacking together a function, I don't really care about the type of each argument passed to that function. I'll use an example taken from the documentation. A first function draft would look like this:               >> g[x_] := Prime[x] - x      Which works fine as long as the type of the argument passed to it is compatible with `Prime`. The following is inappropriate behaviour, and should be fixed by changing the function definition:               >> {g[10], g["z"]}     << {19, -"z" + Prime["z"]}      Here's where I don't know how to _correctly_ proceed. Once I make sure my function works, by providing it arguments of the correct type, I can change its definition to               >> g[x_Integer] := Prime[x] - x      or               >> g[x_?IntegerQ] := Prime[x] - x      which both work as expected. What's the difference between the two definitions, and which one should be used for maximum efficiency, robustness and cleanliness? **Example with one of my functions** This functions generates a set of points that, when passed to `Line`, draw a zig-zag. This case is more ambiguous than the previous. I can define it this way, which works:               >> contactCoordinates[nCtc_Integer, x0_Integer, y0_Integer,         offset_?NumberQ] :=          Table[{x, y0}, {x, x0, offset*nCtc, offset}]~Riffle~          Table[{x, y0 + offset/2}, {x, x0 + offset/2, offset*nCtc, offset}]      I could also replace `_Integer` by `_?IntegerQ`, with no noticeable difference. The problem is with `_?NumberQ`. I can't define the function using `offset_Number` - I have either to use `offset_?NumberQ` or `offset_Real`. Is one better than the other? * * *   1. http://reference.wolfram.com/mathematica/tutorial/PatternsForSomeCommonTypesOfExpression.html   2. Functions vs. patterns   3. http://stackoverflow.com/q/8922966/1142160


Programmatically minimize mathematica?

I can minimize a notebook easy enough with Mathematica code, but how does one minimize all of the Mathematica front end? Just as if you clicked the minimize button on the menu bar? This is for version 8 on windows XP if that helps.


Plot Log scale on X-Axis?

There's documentation on how to do a LogPlot with respect to Y-axis, but how would you do the same for the X-axis? Is there some Plot option? For example, here are some examples that plot Log scale on x-axis. http://en.wikipedia.org/wiki/Colors_of_noise


Speeding up random walk for many particles

I am trying to speed up this code for many particles to take a random walk. I'm not sure why it is so slow for such a simple task. I got a few hints from colleagues to reduce the precision of the calculations, compile some of the functions, parallelize the code, or implement C code. I tried to implement each of these, but I most likely don't know what I'm doing because I couldn't get it to work. The particles can and should be simulated in parallel to take advantage of the two cores. I have a bunch (10,000) particles that each take 1000 fixed steps in random directions. I have a bunch of lists with the length of number of particles, and I operate on those lists. This is faster than doing a nested loop, where I first loop over every particle and then loop over each time step. Two random angles are generated for each particle at each time step. Each particle's position is then incremented. I also want to know how many times each particle has crossed a spherical shell. The history of each particle is important: eventually, I will distinguish particles by the number of times they cross the shell so that they take bigger steps the more they have crossed. I tried timing each step, and it seems like the trig functions slow things down. Is there any way to speed this up? Is there a better way to write this code to make it much faster? Eventually, I would like to add some more complications to this code and run it for many more time steps and particles. So, any general speed tips would help. For comparison, the absolute timing of the Do loop is 3 seconds on my laptop with Core i5 M 540 @ 2.53 GHz, with 4 GB RAM.               numparticles = 10^4;     numsteps = 10^3;     radius = 1.;(*radius of shell*)     particlesx = Table[1.001, {numparticles}];(*x-coordinate for each particle*)     particlesy = Table[0., {numparticles}];(*y-coordinate for each particle*)     particlesz = Table[0., {numparticles}];     numcrossings = Table[0., {numparticles}];(*counts the number of crossings for each particle*)          Do[        \[Theta]rand = RandomReal[{0., Pi}, numparticles];(*random polar angle for each particle*)        \[Phi]rand = RandomReal[{0, 2.*Pi}, numparticles];(*random azimuthal angle for each particle*)        rold = particlesx^2 + particlesy^2 + particlesz^2;(*original distance from origin for each particle*)        particlesx = particlesx + 0.01*Sin[\[Theta]rand]*Cos[\[Phi]rand];(*update each particle's position*)        particlesy = particlesy + 0.01*Sin[\[Theta]rand]*Sin[\[Phi]rand];        particlesz = particlesz + 0.01*Cos[\[Theta]rand];        rnew = particlesx^2 + particlesy^2 + particlesz^2;(*new distance from origin*)        isitoutside = (rold - radius)*(rnew - radius);(*yields negative number if the particle crossed the sphere, else positive*)        switchsides = Map[If[# < 0, 1, 0] &, isitoutside];(*if the particle crossed, it increments numcrossings*)        numcrossings = numcrossings + switchsides;        , {step, 1, numsteps}]; // AbsoluteTiming


Where in the documentation can I find a list of function argument types?

Recently, I learned that it is possible to assign "types" to function arguments in the definition of a function. Suppose I have a function `stringFun` that does some operation (e.g., `StringSplit`) on an input string `str`. I could define the function in this way:               stringFun[str_] := StringSplit[str]      Or, I could define the argument `str_` as being of type `String`:               stringFun[str_String] := StringSplit[str]      What other argument "types" exist in Mathematica? Can I use, for example, `Real`, `List`, or `Table`? I am using Mathematica 7, and I am having some difficulty locating a list of "types" in the documentation. Thanks for your time.


Delete duplicates from hierarchy of lists

Is it possible for _Mathematica_ to compare a number of lists of different sizes, and delete duplicates in a hierarchical manner? For example, given the following lists:               list1 = {2, 5, 10, 11, 12, 17, 18};     list2 = {5, 8, 11, 16, 19, 21};     list3 = {5, 8, 9, 11, 16, 19, 21, 23};      I would like to output:               list1 = {2, 5, 10, 11, 12, 17, 18}     list2 = {8, 16, 19, 21}     list3 = {9, 23}      where `list1` keeps all its original elements, `list2` keeps only elements belonging to `list2` and not `list1`, and `list3` keeps only those elements not contained in `lists 1 & 2`. If this will take an inordinately long time, I am happy with just comparing the list with the previous list and deleting the duplicates from the second list.


DeleteDuplicates[] does not work as expected on floating point values

Here is my simple example, and in this case function `DeleteDuplicates` does not work as expected. I want to `FindRoot` of my function $\chi[\nu]$, and since function $\chi$ is very sensitive to initial guess I decided to generate many initial conditions and leave only those solutions which are distinct. For this purpose I want to apply `DeleteDuplicates` on the resulting list of solution. Here is the definition of my function:               χ[ν_] := 2*PolyGamma[1] - PolyGamma[1/2 + I*ν] - PolyGamma[1/2 - I*ν]      Here I generate many solution according to many random initial guesses               m = Table[v /. FindRoot[χ[v] == -1.2 - 0.2*I, {v, RandomComplex[]}], {i, 1, 10}]      And finally, I want to leave only distinct solutions:               DeleteDuplicates[m]      Unfortunately, the operation `DeleteDuplicates[m]` does not change the list `m`, although there are many identical values. Namely:               DeleteDuplicates[m]      > >     {1.06423 + 0.0968739 I, 1.06423 + 0.0968739 I, >      1.06423 + 0.0968739 I, 1.06423 + 0.0968739 I, 0.0250407 + 1.00352 I, >      1.06423 + 0.0968739 I, 1.06423 + 0.0968739 I, 1.06423 + 0.0968739 I, >      0.0250407 + 1.00352 I, 1.06423 + 0.0968739 I} >   I'm puzzled. Any help or suggestions are very welcome! Thanks!


Additive SparseArray Assembly

The goal is to assemble a `SparseArray` in an additive fashion. Let us assume we have a large `List` of indices (some will be repeated). We generate a simple test list of indices and values               ind = RandomInteger[{1, 4}, {10, 2}];     val = RandomReal[{-1,1}, Length[ind]];      where each value corresponds to an index from `ind`. I would like to build a `SparseArray` in a way such that the repeated index values are summed into the array. If we simply use:               SparseArray[ind -> val, {4,4}]      only the first index encounter is written into the `SparseArray`, all repeated indices are ignored. **Current Solution (slow + ugly)** This solution is slow and is only shown to make precise what exactly I am trying to accomplish. We pre-allocate a sparse array of the correct size and use `Do` to accumulate the values at each index:               n = 5;     ind = RandomInteger[{1, n}, {3*n, 2}];     val = RandomReal[{1, 1}, Length[ind]];     A = SparseArray[{1, 1} -> 0, {n, n}];     Do[        A[[Sequence @@ ind[[i]]]] += val[[i]]     ,{i, 1, Length[val]}     ]      There are some great tips on working with `SparseArrays` in Efficient by- element updates to SparseArrays and SparseArray row operations. A clever combination of `GatherBy`, `Sort`, etc. operations on `ind` and `val` may be good path to head down. I just can't see it yet.