title: Measure relative lengths of rectangular objects

text: I'm working on a method for measuring the relative lengths of the objects, with the intention of showing that the objects are longer in the center of the image that at the top/bottom. The image is binarized, with some small dots that look like noise. Measuring the object lengths is made more difficult by the fact that some are broken. (I can use dilation to fix this) `ImageTake[b, {390, 660}, {733, 1016}] // ColorNegate` TOP ![enter image description here](http://i.stack.imgur.com/rPhH6.jpg) BOTTOM The original image is taken from the blue channel and looks almost identical to the above A quick method I have tried is to use the `ComponentsMeasurements[]` function that can return the longest axis of the best shape ellipse - but I'm not sure if that function works on the individual objects in the image. **Question 1** - Does the above method measure the best fit ellipse for each object (line) or does it do for groups of lines in the image instead? **Question 2** - I was going to use a iterative search in each row to identify the start end end locations for each object for measuring their relative lengths (longest axis in pixels). Doing this for all objects is not necessary, only to show that objects get longer towards the centre of the image. If you have a better idea then I would be very grateful if you would share your thoughts. Regards, * * * Thanks Carmullion. I would prefer not to use ComponentMeasurements as I am not sure if it measures individuals or small groups of objects (used an image with different dimensions to get the following results): `test3 = ComponentMeasurements[MorphologicalComponents[bResize], "Length"];` `ListPlot[data, PlotRange -> {{0, 397}, {0, 35}}, AxesLabel -> {"Height/pxls", "Length"}]` Small objects (noise) accounts for the points that span the scatter plot close to the axes. I can get rid / minimize these by adjusting the `Binarize` parameter ![enter image description here][2]


title: How to frame a PairedHistogram and manipulate the frame ticks?

text: How can I `Frame` a `PairedHistogram` and manipulate the frame ticks? I want to specify and control the frame ticks in the paired histogram below.               spacez = RandomVariate[PoissonDistribution[11], 1000];     spacem = RandomVariate[PoissonDistribution[11], 1000];     PairedHistogram[spacez, spacem, {1, 11, 1}, PlotRange -> {{All, All}},       ChartStyle -> {{Red, Blue}}, BaseStyle -> {FontSize -> 24},       AxesStyle -> Thick, BarSpacing -> 0,       ColorFunction -> Function[Opacity[0.5]], BarOrigin -> "XAxis"]      ![enter image description here](http://i.stack.imgur.com/56cNC.jpg)


title: How to construct a stacked barchart

text: UPDATED to clearify I want to construct a stacked barchart from a list with three elements:               list = Table[{i, x, y}, {i, 10}]       where x has a value between 0 and 100, and y has a value between 0 and 100 so it looks like this:               llist = {{1, 6, 611}, {2, 57, 732}, {3, 5, 526}, {4, 91, 72}, {5, 45,      583}, {6, 98, 552}, {7, 16, 981}, {8, 54, 439}, {9, 80, 804}, {10,      9, 633}};      I want to stack y based on brackets of x (eg. brackets of size 10). Based on the list above this gives the following brackets.   * Bracket `0 - 10` consists of $y$ value (s) `611, 526, 633`   * Bracket `10 - 20` consists of $y$ value (s) `981`   * Bracket `20 - 30` consists of $y$ value (s) empty    * Bracket `30 - 40` consists of $y$ value (s) empty    * Bracket `40 - 50` consists of $y$ value (s) `583`   * Bracket `50 - 60` consists of $y$ value (s) `732, 439`   * Bracket `70 - 80` consists of $y$ value (s) empty    * Bracket `80 - 90` consists of $y$ value (s) `804`   * Bracket `90 - 100` consists of $y$ value (s) `72, 552` The result should look something like this: ![enter image description here](http://i.stack.imgur.com/uZVhV.png) Some context: this is a plot I want to make to show how much influence is exerted (y values) on certain policy positions (x values). The first elements are actors. So Actor 1 exerts 611 influence on policy position 6 (first bracket 0-10). For each bracket I want to visually see how much influence is exerted by the actors and how this looked stacked


title: The same analytical expression gets inconsistent FourierTransform results

text: I have an expression which is just a linear combination of plane waves, and I'd like to calculate FT of it. I know what I will get should be a bunch of delta functions, but it turns out _Mathematica_ gives me a completely wrong result:               FourierTransform[(E^(-I (k1 + k2) (x1 + x2)) (E^(I (k2 x1 + k1 x2)) +          E^(I (k1 x1 + k2 x2))))/(4 \[Pi] (I + 2 k1 - 2 w) (-I - 2 k2 + 2 w)),          {x1, x2}, {p1, p2}]      > 0 However, if I re-organize the numerator of this expression to a simpler form of plane waves               E^(-I (k1 + k2) (x1 + x2)) (E^(I (k2 x1 + k1 x2)) + E^(I (k1 x1 + k2 x2))) // ExpandAll      > E^(-I k2 x1-I k1 x2)+E^(-I k1 x1-I k2 x2) and then insert the above expression back to the numerator, after `FourierTransform` I get the correct result:               FourierTransform[(E^(-I k2 x1 - I k1 x2) + E^(-I k1 x1 - I k2 x2))/                  (4 \[Pi] (I + 2 k1 - 2 w) (-I - 2 k2 + 2 w)), {x1, x2}, {p1, p2}]       > (DiracDelta[-k2+p1] DiracDelta[-k1+p2])/(2 (I+2 k1-2 w) (-I-2 k2+2 > w))+(DiracDelta[-k1+p1] DiracDelta[-k2+p2])/(2 (I+2 k1-2 w) (-I-2 k2+2 w)) So the question is: is it a bug or what?


title: Solving for $d$ in $x= E^d mod(n)$

text: With regards to Public Key Cryptography, I have been tasked with the problem of attacking some information given in an assignment and discovered a private key used to digitally sign a message. Known: b=6457627465447259726545623456572345278769729879898923141341234834576924 E=636639191847512969815095201268921757340802323904442331816314803438352146049271931476368280851309606530687971170887811 e=28392183987218362187611 n=2586209689424400825455988397587474553299674868150931056740574331530510902486656504548725769127921248580701626507593549 x=(b^e)* E mod n x=2247676102207626815073883524633387712906791776446694001817826764472164534453199201306883083874653906533041962112997091 z=1073329998123424673279340351490160754917466285560207441443387824222426450994108105554368670865577655836728118040 The problem scenario is as follows: Alice computes her RSA public key, given by n. Her encryption exponent is e. Nancy sent an encrypted email that is contained in E. Bob wants to know what the message is, so he sends a phony email to Alice asking her to digitally sign it. He picks number b, computes (b^e)*E mod n, and then asks Alice to sign it. From this signing of his number, you are then able to derive the private key Alice used to sign the message. Message Signing: x ≡ E^d mod n Message Signature Check: x^e ≡ E mod n To find d, it must be solved for in the following equation: Z= x ≡ E^d mod n where Z,x,E,n are known How do I determine what d is?


title: Infix strange behaviour

text: Maybe this is a bug or maybe Infix acts differently than the other functions. The fact is that both:               TreeForm[Infix[f[x, a]]]      and               ToString[Infix[f[x, a]]]      crash the kernel. I use Mathematica 9.0 and maybe there are other cases that Infix behaves strangely. Does anybody can explain why this happens ?


title: Speed improvement in string distance function

text: I'm using this distance function to compare distance between strings:               distance[str1_String,str2_String] := Module[{split,r},         split="*"<>#<>"*"&/@StringSplit@str1;         r=N@Total[Boole@StringMatchQ[str2,#,IgnoreCase-> True]&/@split]/Length@split         ]     totalDistance[str1_String,str2_String]:=(distance[str1,str2]+distance[str2,str1])/2      `totalDistance` works just nice, but it's one order of magnitude slower than native distance functions like `EditDistance`. Here is some code test:               testList=ConstantArray["Distance String Test with Mathematica",50000];     totalDistance["String distance test with MMA",#]&/@testList//AbsoluteTiming//First     EditDistance["String distance test with MMA",#]&/@testList//AbsoluteTiming//First      > 4.063474 > > 0.433012 Some clue on how to optimize this code?


title: Why is Text in an Image cut off?

text: I want to create a long, skinny `Image` containing only text. This makes a square image of the default size.               Image@Graphics[      {       FontSize->20,       Text["now is the time for all good men to come to the aid of their country"]      }     ]      ![enter image description here](http://i.stack.imgur.com/ANRhV.png) So I prescribe the dimensions I want:               Image@Graphics[      {       FontSize->20,       Text["now is the time for all good men to come to the aid of their country"]      },      ImageSize->{1000,30}     ]      ![enter image description here](http://i.stack.imgur.com/t0CP5.png) and the result is cropped well inside the `ImageSize` so some of the text is missing. But the `Graphics` alone is appearing correctly.               Graphics[      {       FontSize->20,       Text["now is the time for all good men to come to the aid of their country"]      },      ImageSize->{1000,30}     ]      ![enter image description here](http://i.stack.imgur.com/2WAaJ.png) Why does `Image` mysteriously crop the input?


title: What is the right way to construct DynamicModule

text: When I'm creating `DynamicModule`s for CDF purposes I'm usualy basing on my experience with that, particular goal and content rather than on deep insight. **I want to ask for advice what is a good place for definitions of rather non- dynamic parts of the code. More precise question is at the end so you can scroll down and come back later :)** I'm going to show couple of ways, their advantages and disadvantages. ## Initialization :>               DynamicModule[{}, st1@"title"                   , Initialization :> (st1 = Style[#, Bold] &)]      > >     st1["title"] >   Well, that's not what we want.   * I know I can use `Dynamic` but here and after we are assuming that the less inside `Dynamic` the better. There is no special need for it so I will not do this.   * Notice that we can `Shift`+`Enter` again and saving such `DynamicModule` will result in proper display of content. **Double evaluation** is the only inconveniece. ## scoped Initialization :>               DynamicModule[{st1}, st1@"title"                   , Initialization :> (st1 = Style[#, Bold] &)]      > >     st1$$["title"] >   It is natural one may want to scope this name but now it is not going to work even with double evaluation. ## Initialization ->               DynamicModule[{}, st2@"title"                   , Initialization -> (st2 = Style[#, Bold] &)                  ]      > >     title >   Whoah, `**->**` seems to be a solution... nope. Unfortunately I can't recall the example but I've faced a problem when I tried to switch `:>` to `->` once in the past. The CDF was build with `:>` and `->` broke it. Moreover, if we try to scope the name it is going to fail: ## scoped Initialization ->               DynamicModule[{st2}, st2@"title"                   , Initialization -> (st2 = Style[#, Bold] &)                  ]      > >     st2$$["title"] >   * * * ## Body of DynamicModule This is the way I'm using for defining static parts of the code. It works for scoped and unscoped names:               DynamicModule[{st2},                   st2 = Style[#, Bold] &;                   st2@"title"                  ]      > title   * However there is one issue discussed here. We can not use `SetDelayed` but we assumed it should be a static content so it doesnt matter (or at least I can't recall any counterexample).   * This is also not very convenient if there is a lot of static content one want to define. I like to have body skeleton on top so it is easy to manage the whole project easily. I'm afraid I can't have both. ;) * * * ## Outisde In case of static elements that are imidiately on top there is also a way to define them **outside`DynamicModule`**. FE is going to store them and such CDF will work. However not everything is on top at start. * * * ## Questions Main question is:   * Is the habit to define static content in `Body` and dynamic parts in `Initialization` the best approach? Secondary qestion:   * What is the difference between `->` and `:>` with `Initialization`, is one better from another? Documentation center says: > "The typical usage is `Initialization:>expr`." > but on the other hand `InputAutoReplacement` puts `Initialization->`.


title: Confidence level for Binomial

text: > For 617519 first time births there were 317528 boys. Give an estimate with > 99% confidence interval for the probability that the first time birth is a > boy. I have searched for the confidence interval function. However, I cannot find any match with probability and confidence interval within the `HypothesisTesting` package. The result I am looking for is:               (*0.51255,0.51583*)


title: Is it possible to enable syntax highlighting for \[Function]?

text: This is a bit of a long shot but I am wondering if it is possible to enable syntax highlighting in a function defined with `\\[Function]` without resorting to anything too heavy duty. For example I would like the `a` in the second line to be colored as it is in the first: ![enter image description here](http://i.stack.imgur.com/9S4FB.png) * * * This is apparently enabled out of the box in versions 8 and 9.


title: Speeding up Import and Export in CSV format

text: I am handling large numerical data in _Mathematica_. In smaller problems everything worked fine using `Export` and `Import` with the parameter `csv` and nothing more. Now I am facing a much larger data volume and plain `Export` and `Import` is way too slow for CSV format. What I want to do: First, exporting a numerical list of approximately $1400 \cdot 260$. Then I perform some calculations outside of mathematica and finally I import a csv file back using `Import`. In this question I read how to improve the speed of `Export` with CSV. I tried               Export["data.csv",        ExportString[Transpose[temp], "CSV", "FieldSeparators" -> ", "],        "Table"];      for a toy-example of dimension $9 \cdot 6$. This could be               temp = RandomReal[{0, 1000}, {9, 6}];      The problem is that I got additional blank lines in my CSV file. How can I avoid those blank lines? I did not have them using plain `Export`. Second part of the question: can I use a similar approach to speed up `Import` for CSV files? I work in English locale in Windows 7 and _Mathematica_ 8. My data should be comma-separated. The result of the above looks like this:               155.9418457227914,427.72566448956945,462.4370455183139,434.230107096781,377.73423736605037,457.7044624877774,229.5721937681028,453.6973831247924,827.5146478718962          656.9573702857699,975.1048399942904,716.715190156526,67.07781324817643,168.78248854317894,863.1953962590844,997.7580107302701,427.94798294100747,565.2955778916687          192.3648037459477,435.0418975785194,126.17228368369842,772.0737083559297,453.73573640921836,957.9178360741387,920.4158275934401,234.75353158374764,162.82606110943834          841.7132070637356,799.1268178998612,931.2448706410551,950.7753472229233,114.01596316796622,145.0771999411104,287.47149951303663,786.9008107323455,99.09420650484662          116.9916885502289,715.7594598282562,970.6252946068753,654.1742185278038,262.3778046629968,200.13980161337577,347.24862854841354,314.5612015073982,241.11046402342163          203.65015448763597,952.1236458849723,578.2673369638862,527.2990305555661,655.1228742370724,318.81372163827496,311.2738362265584,315.97629887850667,514.7676854642548      EDIT: A small example of the data that I want to import (2nd step) can be found here. The true problem size is here.


title: Select and plot real positive solutions for a sixth order parametric equation

text: I need your help in order to solve the following problem: I have a sixth order equation: $ax^6+bx^5+cx^4+dx^3+ex^2+fx+g=0$ and I solved it using `Solve[]` command, so I obtained 6 root objects. Now I would like to evaluate these solutions for different ranges of the equation coefficients (a between a1 and a2, b between b1 and b2, etc), selecting the only one real positive solution (that always exists for each coefficient combination) within the six, and then use the Manipulate command in order to plot the surface corresponding to these real positive solutions as function ofthe other parameters. Any help would be greatly appreciated. Some notes: I solved my Equation with this command line:               soldi = Solve[modqTomb - modqTomx == 0, di]      then I obtained my roots objects that are too long to post here. I then tried to plot the solution selecting only the real positive one with this line                   Plot3D[Select[Evaluate[di /. soldi] /. {csik -> 0.001},FreeQ[di /. #, Real] && (di /. #) > 0 &],{omegao, 50*2*Pi, 5000*2*Pi}, {psiqgamma, 1*10^-6, 3.38*10^8}]      But obviously it did not work. I also tryed too split the different command and a lot of other combination but no one seems to work. I'm sorry but I am a new userof Mathematica. **ADDITIONAL INFORMATION** I defined                omegab = \[Sqrt]((2*(omegao^2 + psiqgamma) +Sqrt[(2*psiqgamma*(psiqgamma+omegaao^2))])/2);      omegap = \[Sqrt](omegao^2 + psiqgamma);         a = -omegab^2 + omegap^2;      b = 2*di*omegap*omegab;      c = omegab^4 - omegao^2*omegab^2 - 4*di*csik*omegao*omegap*omegab^2 -omegap^2*omegab^2 + omegao^2*omegap^2 - psiqgamma*omegab^2;      d = 2*omegab*(-csik*omegao*omegab^2 - di*omegap*omegab^2 +di*omegap*omegao^2 + csik*omegao*omegap^2 + psiqgamma*di*omegap);      modqTomb = ((a*c + b*d)^2 + (c*b - a*d)^2)/(c^2 + d^2)^2;      modqTomx = (4*di^2)/(-4*di*csik*omegao*omegap - psiqgamma)^2;      soldi = Solve[modqTomb - modqTomx == 0, di]      I would like to plot the surface of the real solution as function of the parameters: omegao, csik and psiqgamma (for each triplet I obtain 6 roots of which 1 is positive)


title: Prenex and Skolem normal forms

text: In MMA version 7 there was a big advance in logic support ("Boolean computations" is the official name). This was not further developed in version 8.0. So now we have a fairly robust support for propositional calculus, but not too much for predicate calculus. To this end, it would help a lot if we had an internal function capable of transforming a formula (logic formula, I mean) into the Prenex normal form or, even better, into a Skolem normal form. Is anybody aware of a 3rd party package which addresses this problem?


title: Customizing decimal mark used in plot frame tick labels

text: I am using the `Plot` function in a usual way. I use Mathematica 9.0.1.0 in English (I do not know if it is available in other languages, but I do not mind), and as a result of that, the numbers that appear in the frame tick labels use _dots_ as decimal markers. I need all numbers in the plot to be shown with a _comma_ as a decimal marker. Is that possible? Here you have a MWE —nothing special:               Plot[Sin[x], {x, 0, 10}, PlotRange -> Automatic, Frame -> True,       Axes -> False, AspectRatio -> 1/GoldenRatio, ImageSize -> 600,       Frame -> True, FrameTicks -> Automatic,       LabelStyle -> Directive[FontFamily -> "Calibri", FontSize -> 12]]      This is what I get: ![Minimum Working Example](http://i.stack.imgur.com/dLrmP.png) This is a minor issue, as I can export the image and change its labels outside Mathematica, but in case I would like to do this inside Mathematica, how could I get it? ADDITIONAL INFORMATION: I've tried it by using `$Language = "Spanish"`, with no success.


title: How can I set Grid alignments using numbers?

text: There is an example in the `Alignment` documentation (it also appears in the `Grid` documentation):               Grid[{{Graphics[Rectangle[], ImageSize -> 20],         Graphics[Rectangle[], ImageSize -> 30]}, {Graphics[Rectangle[],          ImageSize -> 40], Graphics[Rectangle[], ImageSize -> 50]}},       Alignment -> {{Right, Left}, {Bottom, Top}}]      ![enter image description here](http://i.stack.imgur.com/fH8Dr.png) The `Alignment` documentation indicates that numbers can be used for the alignment. Therefore the example above should be able to be re-written as               Grid[{{Graphics[Rectangle[], ImageSize -> 20],         Graphics[Rectangle[], ImageSize -> 30]}, {Graphics[Rectangle[],          ImageSize -> 40], Graphics[Rectangle[], ImageSize -> 50]}},       Alignment -> {{1, -1}, {-1, 1}}]      However this has no effect: ![enter image description here](http://i.stack.imgur.com/70XD4.png) So what is the correct way to use numbers for `Alignment`?


title: How to evaluate only arguments, but leave topmost expression unevaluated?

text: I want to represent expressions mostly in unevaluated form, but being able to evaluate it's subparts. For example, how to evaluate only arguments, but leave topmost expression unevaluated? For example, so that               1 + Cos[0]      give               1 + 1      **UPDATE** I want Mathematica to act something like follows. If I write               <something> 1 + Cos[0]      it should respond with               <something> 1 + Cos[0]      i.e. having expression as is, unevaluated Then if I enter something               <something> 1 + Evaluate[Cos[0]]      it should respond with               <something> 1 + 1      I.e. I want to CONTROL evaluation, not allowing Mathematica to evaluate what it wants. Only what I want. Imagine gradual scholar math text where expression is converted gradually portion by portion and presented at intermediate stages. Since I don't know how it can be implemented, I am not describing this with much detail. It can be some combination of holding heads or some global modes turnable on and off. The goal is not to loose my work done while entering long expressions, which Mathematica tends to throw out by evaluating. The solution should not be complex like in referred answer, it should be some simple built-in feature.


title: Purpose of construct `With[{var=myComputation[...]}, var/;True]`?

text: Could someone please give an illustrative example showing the purpose of construct of form `With[{var=myComputation[...]}, var/;True]`? Also, I wonder what kind of reference material are available for getting familiar with programming idioms for Mathematica. I mean besides the basic syntax that one can learn and re-learn from standard documentation, there are repeated patterns that programmers use. Somewhat similar to design patterns and "proramming pearls" for Java.


title: How to inject an evaluated expression into a held expression?

text: I know that there are methods to structurally manipulate held expressions (discussed e.g. here), but I failed to apply those for this particular problem:               (Hold[{3, 4, 5 | 6}] /. (Verbatim@Alternatives)[x__] :> RandomChoice@List@x)      > >     Hold[{3, 4, RandomChoice[{5, 6}]}] >   The code should replace any `Alternatives` in the held expression with an appropriate choice from the alternatives, in this case either 5 or 6, i.e. it _should_ evaluate the replacement.


title: Replace inside Held expression

text: I wish to make functional replacement inside `Held` expression like this:               f[x_Real] := x^2;     Hold[{2., 3.}] /. n_Real :> f[n]     => Hold[{4., 9.}]      But I get `Hold[{f[2.], f[3.]}]` instead. What is the best way to make such replacement without evaluation of the `Held` expression?


title: Efficiently collecting results inside a compiled function

text: When we don't know the number of results that will be generated, the usual way to collect results is `Reap`/`Sow`. Another alternative is linked lists. Neither of these are available in compiled functions. `AppendTo` does work, but it has an $O(n^2)$ complexity, so it will be unacceptably slow for long result lists. There was a very clever suggestion to use `Internal`Bag` in these situations:   * Internal`Bag inside Compile Unfortunately a compiled `Bag` will only hold scalars. Let's try to use vectors:               cf = Compile[{},        Module[{bag = Internal`Bag[{{0, 0, 0}}]},         Do[Internal`StuffBag[bag, {i, i, i}], {i, {1, 2, 3}}];         Internal`BagPart[bag, All]       ]]      `CompilePrint` shows that this calls `MainEvaluate`, so this does not work. **What is the best way to collect a large number of results in a compiled function when the number of results is not known before the computation and the result type is not a (fixed size) vector or matrix?** * * * ### Benchmarking the answers   * **Andy's answer**              cf = Compile[{len},            Module[{bag = Internal`Bag[Most[{0}]]},               Do[Internal`StuffBag[bag, {i, i, i}, 1], {i, len}];              Partition[Internal`BagPart[bag, All], 3]            ]          ];          Do[cf[500000], {100}]; // Timing          (* ==> {2.87, Null} *)      I needed to initialize the `Bag` using `bag = Internal`Bag[Most[{0}]]` to let `Compile` know that it is holding integers, not reals (see here).   * **Leonid's answer**              cf2 =        Compile[{len},        Module[{arr, lim, ctr},         arr = ConstantArray[{0, 0, 0}, 10];         lim = Length[arr];         ctr = 1;         Do[          If[ctr == lim,           arr = Join[arr, Table[{0, 0, 0}, {lim}]];           lim = Length[arr]];          arr[[ctr++]] = {i, i, i},               {i, len}         ];         Take[arr, ctr - 1]        ]       ];          Do[cf2[500000], {100}]; // Timing          (* ==> {16.474, Null} *)      Comparing the computational complexity of the two solutions by direct measurement:               data = Table[        {Round[2^k], First@AbsoluteTiming@Do[cf[Round[2^k]], {100}]},         {k, 13, 19, 1/2}];     data2 = Table[        {Round[2^k], First@AbsoluteTiming@Do[cf2[Round[2^k]], {100}]},         {k, 13, 19, 1/2}];          ListLogLogPlot[{data, data2}]      ![Mathematica graphics](http://i.stack.imgur.com/5oFkN.png) (They're the same.)


title: what is the command to make Mathematica beep each time there is an error even for the same command?

text: sorry for a basic question, but does any one know what is the trick to make the front end beep at me each time I issue the same command (which contain an error)? It now only beeps the first time, but when I SHIFT+ENTER the same command again, it stops beeping. I want it to beep each time. here is an example:               expr = 0.09 - (0.00043739999999999995*          Sin[x])/(Sqrt[1 - 0.36*Sin[x]^2]*(0.0225 - 0.0081*Sin[x]^2))     FullSimplify[expr]      now it beeped and gave message to the notebook               Indeterminate      and the following messages to the console:                Mathematica beeped to let you know that a warning or error       message was generated by the kernel. You can disable this beep by resetting       MessageOptions in the Option Inspector.      But when I typed the above again:               FullSimplify[expr]      I see no more messages to the console and no more beeps but only the `Indeterminate` message comes out to the notebook. Only way to see the error again and hear the beeps is to do `Remove["Global`*"]` and run everything again. Strange thing, is that this behaviour does not happen for everything. For example, if I type               Simplify[1/0]      I will see a new error a hear a new beep EACH time I execute the command. I have a feeling that the kernel is remembering things. But I do not want to clear everything each time. I am using 8.04, and this is a picture of my setup: ![enter image description here](http://i.stack.imgur.com/bEhuJ.png) and here is the messageOptions in the advanced setup ![enter image description here](http://i.stack.imgur.com/Tfhml.png) I tried to change the `MaxMessageCount` to 100 but no change. same for the `MessageCountRestTime`. thanks


title: Deriving least-squares equations in Mathematica

text: I define $Y = a + b*x + e$, and I want to find values for $a,b,$ by least squares, so I minimize $RSS = sum((Y_i - a - b*x_i)^2)$ I then take derivatives, ${d RSS \over da} = 0$ and ${d RSS \over db} = 0$ and solve. Now if I put these formulas into _Mathematica_ ,               f2[a_, b_, y_, x_, n_] = Sum[(y[i] - a - b*x[i])^2, {i, n}]           Solve[{D[f2[a, b, y, x, n], {a}] == 0, D[f2[a, b, y, x, n], {b}] == 0}, {a, b}]      I get the following error. > Solve::nsmet: This system cannot be solved with the methods available to > Solve. The derivatives work, but _Mathematica_ doesn't know how to expand out the summations. Any thoughts? I've tried `Expand`, `Sum`, `Distribute` (as suggested in some different expanding `Sum` questions). I've also seen some thoughts on how to define _Mathematica_ rules for summations (anyone have those?).


title: How can I work out which functions work with SetOptions?

text: Not all functions seem to work with `SetOptions`. e.g.               SetOptions[Grid, BaseStyle -> Directive[Red]];     Grid[{{"hello", "world"}}]          hello world      the font _is not_ red.               SetOptions[Row, BaseStyle -> Directive[Red]];     Row[{"hello", "world"}]          hello world      ...and the font _is_ red. ![enter image description here](http://i.stack.imgur.com/TWDM4.png)               SetOptions[InputField, FieldSize -> 5];     InputField[Dynamic[x]]      the input field size is _much_ larger than 5. But on the other hand               InputField[Dynamic[x], Sequence @@ Options[InputField]]      yields an input field with field size 5. ![enter image description here](http://i.stack.imgur.com/XAS9x.png) ...and so on. What is the easiest way to work out (i.e. make a list of ...) which functions can't be used with `SetOptions`?


title: TeXForm and large brackets (\Biggl[ etc)

text: ## Goal I am trying to export a very long expression like               expr = c1*bracket1[a+b+c2*bracket2[d+e+f...]]+...      to LaTeX using `TeXForm`. `bracket1[arg_]` should end up as `\Biggl\\{<arg>\Biggr\\}`, `bracket2[arg_]` as `\biggl<arg>\biggr]` and so on. ## What I have What I have managed so far is defining a format for `bracket1` and `bracket2` that adds text before and after the argument:               Format[bracket1[arg_]] := Row[{"beginbracket1",arg,"endbracket1"}]     Format[bracket2[arg_]] := Row[{"beginbracket2",arg,"endbracket2"}]      This renders `expr` (without the ellipsis) as               In[1]  := expr//TeXForm     Out[1] := \text{c1} \text{beginbracket1}a+b+\text{c2} \text{beginbracket2}d+e+f\text{endbracket2}\text{endbracket1}      ## What I have not / Questions   1. The above does not work if I include `TeXForm` in the `Format` definition. I think I read somewhere that the `TeXForm` is not distributed to the recursive calls of `Format` during formatting. The implementation above leads to `StandardForm` being cluttered by the strings as well. Is there a way to restrict this formatting to TeXForm?   2. What I could not achieve as well was outputting raw LaTeX commands:              Format[foo,TeXForm] := "\\foo"      produces              In[1]  := foo//TeXForm     Out[1] := "\text{$\backslash \backslash $foo}"      and using `[\Backslash]` instead of `\\\` only reduces the number of `$\backslash$` to one. Is there a way to define raw TeX commands? ## Remarks   * I would like to avoid using `\left` and `\right` because of the line breaks which are necessary due to the length of the expressions.   * I would be content with a solution which allows me use the different sizes of LaTeX brackets (and braces and parentheses) without the raw TeX commands. It would be nice to know whether raw TeX is possible at all though.


title: Get histogram of number of vertices per component of graph H

text: I have a huge graph with ~8k vertices and ~1k components. I want a histogram showing the number of vertices for each component. How do I do this? EDIT: I'm trying ubpdqn's approach, but not gettting the expected results. Here are the details of my graph and the resulting histogram:               H = ExampleData[{"NetworkGraph", "HighEnergyTheoryCollaborations"}]          Histogram[Length /@ ConnectedComponents[H], LabelingFunction -> Above, BaseStyle -> 20]      Result: ![enter image description here](http://i.stack.imgur.com/AnD2P.png)


title: Which Method option should I choose for NIntegrate in two dimensions?

text: I want to integrate an interpolating function `a[x,y]` over a certain region in the xy-plane. My problem is that _Mathematica_ is taking too long. I am hoping someone knows a method which will speed up the calculation. Here is my integration expression               NIntegrate[a[x, y], {x, -12, 12}, {y, -12, 12},        AccuracyGoal -> 8, PrecisionGoal -> 8, Method -> "LocalAdaptive"]      I chose "LocalAdaptive" because I read that it is usefull for integration in higher dimensions. And my interpolating function, `a[x,y]`, looks like this: ![enter link description here](http://i.stack.imgur.com/PM0GL.jpg)


title: Control over depth-first scan and breadth-first scan

text: Is there a way to **conditionally** take control/modify the flow during a depth-first scan or the breadth-first scan ? Say, **for example** , if a particular node if found, consider it as a leaf- node and continue with the rest of the processing as usual (meaning do not traverse its child-nodes).


title: Integrand evaluating to non-numerical values

text: I have solved a system of equations using NDSolve just fine. From there, I can plot the solutions $u(x)$ and $v(x)$, as well as its derivatives, just fine. But, when I want to evaluate the energy density for v, defined as $E(x)=\frac{\alpha}{2}(\frac{\partial v}{\partial x})^2+\beta((v^2-1)^2+\epsilon_2v)$, as well as the total energy, $\int_{0}^{10}E(x)dx$, I run into the following problem:               NIntegrate::inumr: "The integrand energiephi6 has evaluated to non-numerical values for all sampling points in the region with boundaries {{0,10}}."      Here's the code:               eps = 1/4;     eps2 = 1/10;     eps3 = 1/10;     alpha = 1;     beta = 3;     a = 5.6294;     sol = NDSolve[{D[u[x], x,        x] == -(6 u[x]^5 - (8 + 4 eps) u[x]^3 + (2 + 4 eps) u[           x] + (v[x]^4 - 2 v[x]^2 + eps2*v[x] + 1)*2 u[            x]/(u[x]^2 + eps3)^2),      alpha*D[v[x], x,         x] == -beta (4 v[x]^3 - 4 v[x] + eps2)/(u[x]^2 + eps3),      u[0] == 0, u'[0] == a, v[0] == 1, v'[0] == 0}, {u, v}, {x, 0, 10}];     phi6n = Evaluate[v[x]] /. sol     phi6Dn = D[phi6n, x]     energiephi6[x] = 0.5*alpha*phi6Dn[x]^2 + beta ((phi6n[x]^2 - 1)^2 + eps2*phi6n);     energietotale6 = NIntegrate[energiephi6, {x, 0, 10}]     Plot[Evaluate[u[t]] /. sol, {t, 0, 10}, PlotRange -> All]     Plot[phi6n, {x, 0, 10}, PlotRange -> All]     Plot[phi6Dn, {x, 0, 10}, PlotRange -> All]     Plot[energiephi6, {x, 0, 10}, PlotRange -> All]      Thus far, all I could do was to identify this line as the culprit:               energiephi6[x] = 0.5*alpha*phi6Dn[x]^2 + beta ((phi6n[x]^2 - 1)^2 + eps2*phi6n);


title: Scalar product of two vectors have the least value

text: In geometry 3D, let $A(1,2,-3) $ and $B(-1,4,1)$ are two points. In the plane $(P):2x-3y+3z-17=0$, find a point $M$ such that the scalar product of two vectors $AM$ and $BM$ will have the least value. How do I tell Mathematica to do that?


title: How to convert String to an Expression inside Manipulate which depends on control variable

text: Normally, in `Global` context, these 2 are equivalent               eqn = "r-x";     r = -2;     Plot[ToExpression[eqn], {x, -5, 5}]      and               eqn = r - x;     r = -2;     Plot[eqn, {x, -5, 5}]      But inside Manipulate (which is a `DynamicModule`) and assuming `r` is a control variable, then these are not equivalent. There is some context or scope change that is causing this which I do not fully understand. i.e. the following do not work the same way:               Manipulate[           eqn = "r-x";      Plot[ToExpression[eqn], {x, -5, 5}],      {{r, -1, "r"}, -2, 2, .1, Appearance -> "Labeled"},      TrackedSymbols :> {r}           ]      and               Manipulate[           eqn = r - x;      Plot[eqn, {x, -5, 5}],      {{r, -1, "r"}, -2, 2, .1, Appearance -> "Labeled"},      TrackedSymbols :> {r}           ]      The reason this would be useful, is that one can use an `InputField`, to enter an equation as a `String`, then convert it to an `Expression` and use it inside Manipulate, where the equation can have in it a variable which happens to be a control variable. Here is an example:               Manipulate[      Plot[ToExpression[eqn], {x, -5, 5}],      Grid[{        {"r=", Control[{{r, -1, ""}, -2, 2, .1, Appearance -> "Labeled"}]},        {"eqn", InputField[Dynamic[eqn], String], Dynamic[eqn]}        }],      {{r, -2}, None},      {{eqn, "r-x"}, None}      ]      ![enter image description here](http://i.stack.imgur.com/lrEaV.png) The idea is that one can enter an expression in the InputField with `r` in it, and then change `r` using the slider afterwords. The current solution to this is shown in this Prevent interdependence of controls but it is a work around and it helps if one understands better why the above example does not produce the same result when used inside Manipulate.


title: Creating a Network from a Output

text: So I used the locator pane to derive the positions of a vertex on a picture. The picture was the Maryland Power Grid and the vertices were the generators and loads of the power system. When I clicked the vertex and recorded it returned this (Vertex number {x-pos,y-pos}). After recording all the vertices I have a list of data and from this list I would like to graphically plot this network with their relative coordinates. From the output I would like to graphically create a minimum spanning network with the loads as either a certain color/shape and the generators as another distinct color and shape. From this I would like to run calculations such as Monte Carlo Simulations, create an adjacency matrix, and possibly even mess around with Markov Random Fields. I need help figuring out how to graphically represent it with color/shape distinctions between the loads and generators and produce a minimum spanning network from the output I received. The Input code was:               im= Import["http://esm.versar.com/pprp/ceir16/Images/Figure2_20.jpg"];     Module[{picturesize,i,bigger,imagesizes},     picturesize=675;     values={};     i=1;     imagesizes=ImageDimensions[im];bigger=1;     DynamicModule[{pt={0,0}},     If[imagesizes[[1]]<imagesizes[[2]], bigger=2];     TableForm@{         Button["Record!",AppendTo[values,{i,pt}];i++;],         LocatorPane[             Dynamic@pt,             Dynamic@Graphics[                 Join[                     {Inset[im,{0,0},{0,0},{1,1}]}                      ],             PlotRange->{{0,imagesizes[[1]]/imagesizes[[bigger]]},{0,imagesizes[[2]]/imagesizes[[bigger]]}},             ImageSize->picturesize]     ],     Dynamic[N@pt],     Dynamic[MatrixForm@values]     }]     ]      ![enter image description here](http://i.stack.imgur.com/hfqLA.jpg) The Output was:               ({       {1, {0.0996, 0.4195}},       {2, {0.1046, 0.392}},       {3, {0.1144, 0.468}},       {4, {0.1164, 0.4415}},       {5, {0.1432, 0.4455}},       {6, {0.1442, 0.376}},       {7, {0.147, 0.5085}},       {8, {0.16, 0.4965}},       {9, {0.1628, 0.5305}},       {10, {0.1708, 0.484}},       {11, {0.1776, 0.379}},       {12, {0.1836, 0.4335}},       {13, {0.1856, 0.408}},       {14, {0.1936, 0.4495}},       {15, {0.2034, 0.5295}},       {16, {0.1974, 0.3595}},       {17, {0.2122, 0.4395}},       {18, {0.2152, 0.4465}},       {19, {0.2252, 0.3555}},       {20, {0.229, 0.4415}},       {21, {0.2716, 0.3535}},       {22, {0.2952, 0.313}},       {23, {0.3258, 0.4265}},       {24, {0.3446, 0.475}},       {25, {0.3476, 0.4315}},       {26, {0.3536, 0.408}},       {27, {0.3584, 0.3545}},       {28, {0.3694, 0.3665}},       {29, {0.3732, 0.384}},       {30, {0.393, 0.3535}},       {31, {0.395, 0.4205}},       {32, {0.4028, 0.3625}},       {33, {0.4028, 0.378}},       {34, {0.4088, 0.3525}},       {35, {0.4108, 0.4345}},       {36, {0.4286, 0.4505}},       {37, {0.4336, 0.405}},       {38, {0.4434, 0.247}},       {39, {0.4542, 0.303}},       {40, {0.4532, 0.4415}},       {41, {0.4612, 0.3515}},       {42, {0.469, 0.3455}},       {43, {0.47, 0.3685}},       {44, {0.477, 0.391}},       {45, {0.4888, 0.31}},       {46, {0.4948, 0.3315}},       {47, {0.4958, 0.371}},       {48, {0.4986, 0.217}},       {49, {0.4918, 0.4375}},       {50, {0.5214, 0.376}},       {51, {0.5244, 0.3455}},       {52, {0.5284, 0.4315}},       {53, {0.5294, 0.457}},       {54, {0.5302, 0.471}},       {55, {0.5302, 0.2875}},       {56, {0.554, 0.243}},       {57, {0.554, 0.323}},       {58, {0.554, 0.299}},       {59, {0.559, 0.231}},       {60, {0.559, 0.2575}},       {61, {0.559, 0.2725}},       {62, {0.5628, 0.244}},       {63, {0.5668, 0.221}},       {64, {0.5668, 0.316}},       {65, {0.5708, 0.1755}},       {66, {0.5816, 0.2665}},       {67, {0.5836, 0.224}},       {68, {0.5916, 0.152}},       {69, {0.5806, 0.307}},       {70, {0.5826, 0.3365}},       {71, {0.5876, 0.32}},       {72, {0.5974, 0.242}},       {73, {0.5984, 0.2845}},       {74, {0.6044, 0.2865}},       {75, {0.5856, 0.397}},       {76, {0.5906, 0.3605}},       {77, {0.5916, 0.388}},       {78, {0.6014, 0.3385}},       {79, {0.6054, 0.388}},       {80, {0.6132, 0.299}},       {81, {0.6132, 0.2865}},       {82, {0.6142, 0.2745}},       {83, {0.6182, 0.375}},       {84, {0.6252, 0.245}},       {85, {0.6252, 0.3355}},       {86, {0.629, 0.3605}},       {87, {0.63, 0.371}},       {88, {0.63, 0.388}},       {89, {0.633, 0.474}},       {90, {0.635, 0.3535}},       {91, {0.641, 0.3525}},       {92, {0.639, 0.411}},       {93, {0.6438, 0.3585}},       {94, {0.6458, 0.4355}},       {95, {0.6488, 0.473}},       {96, {0.6548, 0.2695}},       {97, {0.6576, 0.38}},       {98, {0.6646, 0.4455}},       {99, {0.6736, 0.3685}},       {100, {0.6764, 0.4415}},       {101, {0.6774, 0.396}},       {102, {0.6902, 0.402}},       {103, {0.6932, 0.373}},       {104, {0.6962, 0.473}},       {105, {0.6972, 0.453}},       {106, {0.718, 0.389}},       {107, {0.7268, 0.292}},       {108, {0.7228, 0.4335}},       {109, {0.7288, 0.457}},       {110, {0.7426, 0.296}},       {111, {0.7406, 0.4235}},       {112, {0.7644, 0.295}},       {113, {0.7624, 0.457}},       {114, {0.7802, 0.4225}},       {115, {0.7802, 0.2855}},       {116, {0.7822, 0.3355}},       {117, {0.797, 0.4315}},       {118, {0.799, 0.4495}},       {119, {0.8028, 0.4415}},       {120, {0.8168, 0.1235}},       {121, {0.8088, 0.459}},       {122, {0.8226, 0.1045}},       {123, {0.8186, 0.3465}},       {124, {0.8168, 0.468}},       {125, {0.8286, 0.244}},       {126, {0.8256, 0.2825}},       {127, {0.8266, 0.329}},       {128, {0.8226, 0.38}},       {129, {0.8196, 0.4345}},       {130, {0.8394, 0.167}},       {131, {0.8532, 0.291}},       {132, {0.8602, 0.1245}},       {133, {0.8652, 0.1085}},       {134, {0.8898, 0.166}},       {135, {0.8938, 0.133}},       {136, {0.9164, 0.221}},       {137, {0.9244, 0.153}},       {138, {0.9284, 0.1845}},       {139, {0.1076, 0.4125}},       {140, {0.1224, 0.3445}},       {141, {0.15, 0.4205}},       {142, {0.4028, 0.4215}},       {143, {0.4642, 0.33}},       {144, {0.467, 0.3395}},       {145, {0.5362, 0.242}},       {146, {0.548, 0.2525}},       {147, {0.5638, 0.131}},       {148, {0.6102, 0.1775}},       {149, {0.629, 0.3435}},       {150, {0.64, 0.456}},       {151, {0.6458, 0.317}},       {152, {0.6488, 0.3535}},       {153, {0.6508, 0.385}},       {154, {0.6538, 0.3365}},       {155, {0.6636, 0.328}},       {156, {0.6626, 0.161}},       {157, {0.6764, 0.3555}},       {158, {0.6854, 0.456}},       {159, {0.7002, 0.465}},       {160, {0.708, 0.387}},       {161, {0.715, 0.4345}},       {162, {0.716, 0.2635}},       {163, {0.7812, 0.1815}},       {164, {0.8958, 0.1925}}      })      So finally got it to work:               graphicslist =        Table[Rectangle[mpg[[i, 2]] , mpg[[i, 2]] + {.005, .005}], {i, 1, Length@mpg}];       Graphics[graphicslist]      And it returned: ![enter image description here](http://i.stack.imgur.com/LsuXL.jpg) Now I want a way to get the minimum spanning tree and from there get the adjacency matrix. Any Ideas?


title: Calling a DLL with two inputs and one output

text: I need to call a DLL that requires two real number inputs to get one real output back. I can get one of the simple example uses of `DefineDLLFunction` to work, but I don't understand what the syntax would be for using two inputs. I am not familiar with C++, C#, Visual Basic, so if any of that is required I'll need to be spoon fed. The dll I'm trying to use is from Refprop. It provides real fluid property data. Here is what works in MATLAB:               temp=200;     p=1000;     fluid='methane';     rho=refpropm('D','T', temp, 'P',p,fluid)      This will return the density (D) for methane with a temperature (T) of 200 and pressure (P) of 1000. refpropm is the name of the dll.


title: Row and Column Headings for a Grid

text: It would be useful for me if I could write:               Grid[{{a, b}, {c, d}, {e, f}},       GridHeadings -> {{"r1", "r2", "r3"}, {"c1", "c2"}}]      just like               TableForm[{{a, b}, {c, d}, {e, f}},       TableHeadings -> {{"r1", "r2", "r3"}, {"c1", "c2"}}]      except that I don't want the two lines `TableForm` produces. How could I add this additional option to `Grid`?


title: Efficient matrix / array generation

text: What is the most efficient way of generating the following matrix? $\left( \begin{array}{ccccc} 1 & 0 & 1 & 0 & 1 & 0 & 1 & \dots\\ \frac{1}{2} & \frac{1}{2} & 0 & 0 & \frac{1}{2} & \frac{1}{2} & 0 & \dots\\ \frac{1}{3} & \frac{1}{3} & \frac{1}{3} & 0 & 0 & 0 & \frac{1}{3} & \dots\\ \frac{1}{4} & \frac{1}{4} & \frac{1}{4} & \frac{1}{4} & 0 & 0 & 0 & \dots\\ \frac{1}{5} & \frac{1}{5} & \frac{1}{5} & \frac{1}{5} & \frac{1}{5} & 0 & 0 & \dots\\ \frac{1}{6} & \frac{1}{6} & \frac{1}{6} & \frac{1}{6} & \frac{1}{6} & \frac{1}{6} & 0 & \dots\\ \frac{1}{7} & \frac{1}{7} & \frac{1}{7} & \frac{1}{7} & \frac{1}{7} & \frac{1}{7} & \frac{1}{7} & \dots\\ \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \ddots\\ \end{array} \right)$ where the first line begins $\{1,0,1,0,1,0,1,0,1,0,1,0\dots\}$ The second: $\{\frac{1}{2},\frac{1}{2},0,0,\frac{1}{2},\frac{1}{2},0,0,\frac{1}{2},\frac{1}{2},0,0\dots\}$ The third: $\{\frac{1}{3},\frac{1}{3},\frac{1}{3},0,0,0,\frac{1}{3},\frac{1}{3},\frac{1}{3},0,0,0\dots\}$ and so on. My effort is               y = 14; m = 7;     Table[Take[Drop[Take[Flatten[ConstantArray[Flatten[Riffle[Array[0 &, {n, n}],      Array[1 &, {n, n}]]], y - n]], y], n], y - m]/n, {n, 1, m}] // MatrixForm      but calculates too many unnecessary terms.


title: What does Binomial return for non-integer arguments?

text: Mathematica returns values for non-integer arguments passed to `Binomial`. What is the definition of `Binomial` for such continuous arguments? Example:               Binomial[9, 2]     36     Binomial[9, 2.3212312]     49.801     Binomial[9, 3]     84


title: Defining a function as a sum of several Gaussians

text: I have a function that is a summation of several Gaussians. Working with a 1D Gaussian here, there are 3 variables for each Gaussian: `A`, `mx`, and `sigma`: $A \exp \left ( - \frac{\left ( x - mx \right )^{2}}{2 \times sigma^{2}} \right )$               A*Exp[-((x - mx)^2/(2 sigma^2))]      The number of Gaussians in the final function will be vary each time the function is called, so my question is: **What is the best way to define a function in Mathematica that can handle this variation, rather than hard- coding each Gaussian?** I was thinking along the lines of providing a list of `{A,mx,sigma}` to the function, so that if I want one Gaussian, I provide:               f[{{A,mx,sigma}}]      And if I want two Gaussians, I provide               f[{{A,mx,sigma},{A2,mx2,sigma2}}]      which would give:               A*Exp[-((x-mx)^2/(2sigma^2))] + A2*Exp[-((x-mx2)^2/(2sigma2^2))]      and so on. But I'm not at all sure how to design the function `f[]` to do this efficiently (for example, can it be done without a `For[]` loop? Can it be compiled in future if necessary?). Any help much appreciated - I did several searches on here and couldn't find anything, but I realise that might be because I'm not sure how to define my problem succinctly, so apologies if it has been asked before and I've missed it.


title: axis label and ticks alignment of ListPlot3D and Histogram3D

text: I have a question on axis label alignment of ListPlot3D and Histogram3D. These labels are not aligned with the axis of the view, but only horizontally. I have tried very hard to align them manually, but the method sucks and still the output lacks precision and neatness. I wonder if M 9.0.0 has this facility? If no, then please suggest some clean way which aligns through exact calculations. Thanks in advance.               ListPlot3D[Table[Sin[i + j^2], {i, 0, 3, 0.1}, {j, 0, 3, 0.1}],      AxesLabel-> {Xaxis, Yaxis}, PlotLabel -> Sin[i + j^2], PlotStyle -> Purple]          Histogram3D[RandomVariate[NormalDistribution[0, 1], {500, 2}],     AxesLabel ->{Xaxis, Yaxis}]      Image by P.Fonseca ![enter image description here](http://i.stack.imgur.com/NiCuL.gif)


title: Why is $ProcessorCount different than the selected number of cores in PBS?

text: By using `ParallelTable` and submitting my Mathematica code to a cluster, I noticed that it was enhancing the speed even when I selected a **single core** in a **single node** , comparing to the use of standard `Table`. Verifying the number of cores using `$ProcessorCount`, I got 16. For selecting the number of cores I have submitted a bash file in terminal (already logged in SSH) using               qsub -I run_inter.sh      The file "run_inter.sh" contains               #!/bin/sh     #PBS -l walltime=10:00:00          #PBS -q par32     #PBS -l nodes=1:ppn=1      where "par32" is a machine with 32GB of RAM. Is there any reason for Mathematica to ignore the specification of core number and use 16 anyway?


title: How to obtain all the distinct De Bruijn sequences?

text: In combinatorial mathematics, a $k$-ary De Bruijn sequence $B(k, n)$ of order $n$ is a cyclic sequence of a given alphabet $A$ with size $k$ for which every possible subsequence of length $n$ in $A$ appears as a sequence of consecutive characters exactly once. Each $B(k, n)$ has length $k^n$ and there are $\dfrac{(k!)^{k^{n-1}}}{k^n}$ distinct De Bruijn sequences. By using `DeBruijnGraph` and `FindEulerianCycle` should be possible to obtain all the distinct sequences. In the example below I should obtain 24 sequences ($k = 3$, $n = 2$). However, I get only three distinct sequences:               out=FindEulerianCycle[DeBruijnGraph[3, 1], 24];     (First /@ #) & /@ out      > {{1, 1, 2, 1, 3, 2, 2, 3, 3}, {2, 1, 1, 2, 2, 3, 1, 3, 3}, {3, 1, 1, 2, 1, > 3, 2, 2, 3}} How can I obtain all the distinct De Bruijn sequences?


title: Measures of association, Concordant and Discordant

text: I want to calculate concordant and discordant pairs on nx2 tables. * * *               |    Value1   |  Value2  |     |_____________|__________|     |    0.3434   | 1        |     |    0.2132   | 2        |     |    0.3      | 3.3245   |     |    0.6      | 0.12321  |     |    0.745234 | 523      |     |    4        | 0.2134   |     |    3        | 111      |     |    .        | .        |     |    .        | .        |     |    .        | .        |     |    .        | .        |     |    .        | .        |     |_____________|__________|      This is a n x 2 table. How can I calculate concordant and discordant pairs? I am sorry I can't find suitable question tag.


title: Raise systemwide keypress event

text: Is there a way to raise system-wide "keypress" events programmatically from within Mathematica? Say "Ctrl+C" or "Ctrl+V", which all other programs can recognize? This is an attempt to gain simple control/automation of other programs from within the Mathematica environment


title: Printing grouped cells

text: How can I print grouped cells with CellPrint ? The closest thing I have to what I want to do is this               CellPrint[CellGroup[{TextCell["i","Item"],ExpressionCell[Defer[x^2;],"Input"]},1]]      But the cells aren't grouped.


title: How to define a pure function with a Module?

text: I was not able to use a self defined (using Module and For loops) piecewise function to fit data. It seems that the problem is that I have to define a pure function. I would like to learn how to define pure functions in the following example using Modules and For loops. Please help. So let's consider a problem - we have some data, and a self defined piecewise function f[z] that goes exactly through all the data points. LinearModelFit fitting data with f[z] should return value parameter equal to 1. Disclaimer: it will return a constant instead (basically will not understand what is the f[z] provided and will use a constant to fit the data). However, in the second part of the following example I will define a function g[z] (which will be equal to f[z]) using Piecewise[] and it will work perfectly (LinearModeFit will return 1). **So, once again, I would like to write f[z] using Module and For loops so that it works in LinearModelFit the way g[z] does.**               x = Table[x + Random[], {x, 1, 5}];     y = 2 # + Random[] & /@ x;     data = Transpose@{x, y};      # Part 1: self defined function f[z]               fpiecewise[x_, xlist_, ylist_] := Module[{i = 1},        For[i = 1, i < Length[xlist], i++, If[x <= xlist[[i]], Break[]]];        Return[ylist[[i]]]        ];     f[z_] := fpiecewise[z, x, y];          LinearModelFit[data, f[z], z];      ListPlot[{{x, % /@ x} // Transpose, data}, Joined -> True]      ![Part1](http://i41.tinypic.com/2ykcg0j.png) # Part 2: Piecewise[] defined function g[z]               x1 = Join[{0.}, x];     g[z_] := Piecewise[       Table[{y[[i]], x1[[i]] < z <= x1[[i + 1]]}, {i, 1, Length[x]}]]     LinearModelFit[data, g[z], z];     ListPlot[{{x, % /@ x} // Transpose, data}, Joined -> True]      ![Part2](http://i44.tinypic.com/23vixvk.png)


title: How can I fill a curve in ParametricPlot3D?

text: I'd like to fill a curve in a `ParametricPlot3D` in the same way as I might with `ListPointPlot3D`; i.e.,               ListPointPlot3D[data, ColorFunction -> "Rainbow", Filling -> Bottom]      I obtained the data numerically, point-by-point, with MATLAB. I have found a parametric expression for $y$ ($y = f(x)$) and I have a function $F(x, y, z)$, but I want to plot $F$ only for the curve $y = f(x)$, i.e., the 3D surface is defined as               Plot3D[x^2 Sin[x] + y^2 Cos[y] - x y, {x, 0, 1}, {y, 0, 1}]      and I want to plot only the specific line of surface which satisfy $y = f(x) = x^2$ using               ParametricPlot3D[{x, x^2, x^2 Sin[x] + y^2 Cos[y] - x y /. y -> x^2}, {x, 0, 1}]      I'd like to add a filling, but I don't know how. When I type `Filling ->`, the _Mathematica_ code editor complains (the text becomes red).


title: How to Output Chi-Squared Statistics when using NonLinearModelFit

text: I am using NonLinearModelFit for some curve fitting and I was wondering if NLM is able to output chi-squared/leastsquared statistics from the best-fit parameters and confidence intervals. From my understanding, NLM uses a least squares algorithm to find the best parameters, so shouldn't there be an associated chi-squared value with the fit? To check that everything was working, I ran the test a thousand times and looked at the distribution of a certain parameter, alpha. Instead of finding a normal distribution however, I found a distribution with 2 peaks. To me, this indicates that: 1 the fitting function is messing up somehow, or 2, that it is choosing a local minimum and not searching for a better place. I have tried increasing the number of iterations so that the algorithm could possibly find a better local minimum, but that was not successful. So I currently think that the algorithm is getting caught up somewhere. So, I was hoping that I could check the chi-squared value for each iteration and see if some fits were better than others. My code is below:               AU = 149597871000;     G = 6.67428*10^-11;     GMsun = 1.32712442099*10^20;     GMjup = GMsun/1047.348644;     dela = 10^-10;     rJup = 5.2 AU;     lambda = AU;     precision = 25;     alphas = {};     Data[dist_] := {SetPrecision[dist, precision],         SetPrecision[         GMsun/dist^2 + (GMjup dist)/(dist^2 + rJup^2)^(3/2) +           RandomReal[NormalDistribution[]] dela, precision]};     Model[dist_, alpha_, jupiter_, sun_, lambda_] :=        SetPrecision[(G sun)/dist^2 (1 + alpha Exp[-dist/lambda]) + (         G jupiter dist)/(dist^2 + rJup^2)^(3/2), precision];     Do[      Dat = Table[Data[x], {x, AU, 100 AU, AU}];      NLM = NonlinearModelFit[        Dat, {Model[dist, alpha, jupiter, sun, lam]}, {{alpha,           10^-7}, {jupiter, GMjup/G}, {sun, GMsun/G}, {lam, 20*AU}}, dist,         Tolerance -> 10^-50, AccuracyGoal -> precision,         WorkingPrecision -> precision, MaxIterations -> 1000];        realAlpha = NLM["ParameterTableEntries"][[1]][[1]];      realLambda = NLM["ParameterTableEntries"][[4]][[1]];      realJupiter = NLM["ParameterTableEntries"][[2]][[1]];      realSun = NLM["ParameterTableEntries"][[3]][[1]];      alphas = Append[alphas, Abs[realAlpha]];      , {i, 1000}]      Here the list alphas contains 1000 best-fit alphas from 1000 artificially created data sets (Note: this takes a while to run). The problem is that almost 20% of the time it outputs alpha ~ 10^-3, which is much too large to make sense. Thank you!


title: Can I create a CDF from Mathematica 7?

text: I am almost sure I remember seeing an online tool on the Wolframs website for creating CDF's for _Mathematica_ users with version 7. Am I right? And if so, where can I find it?


title: How can I superimpose a set of points on a ContourPlot?

text: I am familiar with _Mathematica_ to a certain extent, but its subtleties still elude me. **Currently I am trying to solve the following problem:**   The function $f(x,y)$ is continuous. I know how to create a contourplot of it. I also have a list of points `{{x,y}, ...}` which I would like to insert into my contour plot. **Background:**   I am working on some genetic algorithms and would like to visualize how the population converges to the global optimum. This is why I would like to show the population (or at least the best candidate of each generation) in the contour plot. How could this be done?


title: How to store values indexed by integer partitions for fast access?

text: I have a huge list of values indexed by integer partitions. If I store them simply in a list, then, when I want to access the value corresponding to some particular integer partition, I have to find the index of the given partition in the list of all partitions before I can access the value. This is slow. Is there a way to optimize this? In my particular example, I have values indexed by pairs of partitions of the same integers. The first 4 levels look like this:               chars = {       {{1}},        {{1, 1}, {-1, 1}}, {{1, 1, 1}, {-1, 0, 2}, {1, -1, 1}},        {{1, 1, 1, 1, 1}, {-1, 0, -1, 1, 3}, {0, -1, 2, 0, 2}, {1, 0, -1, -1, 3},         {-1, 1, 1, -1, 1}}     }      Then to access a particular value, I use this function:               maxn = 4;     YDs = Array[IntegerPartitions[#] &, maxn];          findChar[y1_, y2_] := Module[{l1, l2, n1, n2, i1, j1},       l1 = Length[y1];       l2 = Length[y2];       n1 = Sum[y1[[i]], {i, l1}];       n2 = Sum[y2[[i]], {i, l2}];       If[n1 != n2, Return["ERROR"];];       i1 = Position[YDs[[n1]], y1, Heads -> False][[1, 1]];       j1 = Position[YDs[[n2]], y2, Heads -> False][[1, 1]];       Return[chars[[n1, i1, j1]]];     ];      This seems to be a pretty inefficient way, but I don't know how to do it more effectively in Mathematica.


title: Replace Do loop with Nest

text: a1 = {1, 2, 3, 4};     Do[a2 = DeleteCases[a1, x1];       Do[a3 = DeleteCases[a2, x2];        Do[a4 = DeleteCases[a3, x3];         Do[Sow@{x1, x2, x3, x4};          , {x4, a4}]         , {x3, a3}]        , {x2, a2}]       , {x1, a1}] // Reap // Last      I would like replace my code with `Nest`, I have tried this               a1 = {1, 2, 3, 4};     Nest[Table[{i, j}, {i, a1}, {j, DeleteCases[#, i]}]~Flatten~1 &, a1, 3]      but it worked incorrect.


title: Reduce a huge low-rank matrix

text: I have a huge square matrix, with a lot of zero columns and zero rows: $m=\left( \begin{array}{ccccccccc} 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 & 0 \\ 0 & 0 & 0 & 3 & 7 & 9 & 0 & 0 & 0 \\ 0 & 0 & 0 & 4 & 8 & 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 2 & 6 & 3 & 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 & 0 & 0 & 0 & 0 \\ \end{array} \right)$ In general, I don't know where the zero columns (and rows), but when $i$-th row is empty, then $i$-th column is is also zero. My question is: Is there any internal command to delete all zero columns and zero rows? My motivation for this question is: I want to evaluate the eigenvalues of this huge matrix, which is slow. If I can reduce the matrix efficiently, Eigenvalues[] can be sped up.


title: Manipulate syntax

text: I am trying to manipulate a plot of the Bernoulli roots as follows: ![enter image description here](http://i.stack.imgur.com/lNroQ.gif) The following code clearly is not going to work, but I have included it in an effort to illustrate my meaning.               sol = Solve[N[Table[BernoulliB[n, z], {n, 20, 20}] == 0, 10]];     Manipulate[ListPlot[{{Re@z, Im@z} /. sol}], {roots, 1, 100}]      It is the {n, 20, 20} that I think I am having the trouble with - the 20 is obviously the variable I would like to manipulate, and {n, roots, roots} was all I could think of doing. I am also unsure how to format the axes and point sizes so they remain constant throughout the manipulation.


title: Dynamic Updating CreateDialog Problem

text: In this code, one cannot close the dialog window:               {TogglerBar[Dynamic[x], Range[5]], Dynamic[x],  Dynamic[CreateDialog[x]]}      If I use `DynamicModule` this way, the dialog window will not pop up when it was closed and re-chosen some values.               {TogglerBar[Dynamic[y],Range[5]],Dynamic[y],DynamicModule[{y=y},CreateDialog[y]]}      So how to make the created dialog window could be closed and reopen when click to set different values by `TogglerBar`


How to generate characters by a function which works like the Esc + a + ESC               In[24]:= CharacterRange["a","z"]     Out[24]= {a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}      How to batch convert them to Greek Letters just like that done by this way Esc + a + Esc ... something like this, a function works,               In[25]:= CharacterRange["\[Alpha]","\[Zeta]"]     Out[25]= {\[Alpha],\[Beta],\[Gamma],\[Delta],\[CurlyEpsilon],\[Zeta]}          EnglishToGreekRange["a", "z"]      Comes out               {\[Alpha],\[Beta],\[Chi]...}


title: Graphics3D: the box vertices do not coincide with triangle

text: I have drawn a triangle using `Line` graphics primitive and `Graphics3D` function:                Graphics3D[Line[{{1, 0, 0}, {0, 1, 0}, {0, 0, 1}, {1, 0, 0}}],       Axes -> False, Boxed -> True, AspectRatio -> 1]      ![enter image description here](http://i.stack.imgur.com/1TS7y.png) But in the shape I get, the vertices of triangle do not coincide with the vertices of the box, how can I solve this problem?


title: Write a function that returns the logarithmic derivative

text: How can we write a function that if we input an expression f, it returns the log derivative $\frac{1}{f} \frac{df}{dx}$. We have to use a conditional or pattern test so that the function accepts any symbols as input except for lists. I will show all my attempts and I have some questions about why certain ways are wrong and why are they wrong. I am new to Mathematica and still not very familiar about how it works. Here are all my attempts:   1).   In: $f = x^{2};$   In: func[f_] = $\frac{1}{f} f'$   Out: $\frac{(x^{2})'}{x^{2}}$   This attempt is wrong because first we are not using conditional or pattern test. Also, Why by using ' sign cannot differentiate the function? 2).   In: $f = x^{2};$   In: func[f_] := $\frac{1}{f} f'$   Out: No output   Why by using delayed assignment, there is no output? 3).   In: $f = x^{2};$   In: func[f_,x_] = $\frac{1}{f} f'$   Out: $\frac{(x^{2})'}{x^{2}}$   Does adding another argument x_ redundant or does it make any difference? 4).   In: $f = x^{2};$   In: func[f_] = Module[{f}, Switch[f, _Symbol, $\frac{1}{f} f'$]]   Output: $\frac{f$8344'}{f$8344}$   The syntax might not make any sense, but I am struggling to find ways to fix it. And I might have used to _Symbol incorrectly, what is _Symbol after all? Now I am trying to write the function in a less general way.   5).   Now In: $f = x^{2};$   In: func[f_] = $\frac{1}{f} D[f,x]$   Output: $\frac{2}{x}$   This method of course works but if I change the input to f = $y^{2}$, the function will return 0 as output.   One way to solve this is by changing to func[f_] = $\frac{1}{f} D[f,y]$, but I think this is considered as cheating, since we are not really answering the question and meeting the requirements set by the question. What really makes me struggle is to compute the derivative, how can we compute the derivative of the input function with respect to its independent variable. Also, I don't fully understand the Switch condition:   It is mentioned in Mathematica Help, that Switch evaluates $expr_i$, then compares it with each of the $form_i$ in turn, evaluating and returning the $value_i$. What is form and what is value?   Suppose I write the function:   In: f[x_] := Switch[x, x>0, 1, x<=0, 0]   In: {f[5], f[-5], f[x]}   Out: {0,0,0}   Am I using the wrong form? Any detailed helps are greatly appreciated. Thanks!


title: How to get confidence bands of parameters from a fitting procedure?

text: I have done fitting of data points with a given model that has two parameters (A and B), using `NonlinearModelFit`. The result of the fit is the maximum of the likelihood function, aka the best fit, and the best values for parameters A and B, say (A0, B0). On the A-B plot this would be a single point. There is also a standard deviation given for both parameters separately σA and σB. However, the likelihood function should also give a region on A-B diagram, therefore possible values for A and B that give a good fit - the one that is under a certain confidence level, like 68%. This region is not exactly {A-σA, A+σA} × {B-σB, B+σB}. Instead, {A-σA, A+σA} is probably projection of this region on A-axis. How to get the region of A-B dependence with a specified confidence level (.68, .95, .99) coming from the fit?


title: Why doesn't Mathematica plot $n(-1)^n$ with Plot?

text: I was in doubt if this question should be asked in Mathematics.SE or _Mathematica.SE_ , but I've decided this site would be more appropriate, because I think those who read my question here will know about both mathematics and _Mathematica_. I tried to plot $n(-1)^n$ with `Plot`, but it showed nothing. When I tried to plot it with `DiscretePlot`, it worked. Why did that happen?


title: Method used by FindFit

text: Using `FindFit`, _Mathematica_ selects an optimal algorithm when `Automatic` is selected. I'd like to know the name of the method applied to the `FindFit` computation. Is there any option to explain that?


title: How to get Cases to wrap results in an arbitrary head?

text: A number of functions provide for results to be wrapped in an arbitrary head. This is very important in cases where the results should not be evaluated. Take `Level` as an example:               expr = Hold[{2/2, g[8/4], 1/0}];          Level[expr, {-2}, Hold]      > >     Hold[1/2, 1/4, 1/0] >   `Cases` however provides no such parameter, causing undesired evaluation:               Cases[expr, _Times, 3]      > Power::infy: Infinite expression 1/0 encountered. >> >   >   >     {1, 2, ComplexInfinity}  (* failure *) >   How can this behavior be attained?


title: Not FullDefinition for Save. MachineID not Protected?

text: Is there a way to set what symbols's definitions I do not want to store? Consider the following code:               f := $MachineID;     SetDirectory[NotebookDirectory[]];     Save["testm.m", f];          ClearAll@f          << "testm.m"     f      > >     Set::specset: Cannot change the value of special symbol $MachineID. >> >     0000-00000-00001 (*id of storing machine*) >     0000-00000-00002 (*id of getting machine*) >   This happens bacause `testm.m` contains: > >     f := $MachineID >     $MachineID = "0000-00000-00001" >   **Questions:**   * Is there nicer way to avoid this than my approach:              f:= Symbol["MachineID"]       ?   * Is it `Protected` attribute which decides what is going to be stored? Because there is no problem if `f:=SystemID` but:              Attributes[{$SystemID, $MachineID}]      > >     {{Locked, Protected}, {}} >   **Edit** :   * Why `MachineID` is not protected? - **The bounty is founded for this question.**


title: On the order of rules specification

text: I wanted to understand how Mathematica parses function definitions in rules- based programming, so I started with the simple code:               Clear[f];     f[x /; MatchQ[x, {_?NumericQ, _?NumericQ}]] := Total@x;     f[x_] := -1;     f[{1, 2.3}]     f[{4}]      As expected, the output is:               3.3     -1      Then I added another line:               Clear[f];     f[x /; MatchQ[x, {_?NumericQ, _?NumericQ}]] := Total@x;     f[x ;/ MatchQ[x, {_?NumericQ, 0}]] := (2 * x)[[1]];     f[x_] := -1;     f[{1, 2.3}]     f[{1, 0}]     f[{4}]      Interestingly, the output is now:               3.3     1     -1      So the second rule specification did not really override the first rule. But now, if I put that second rule `before` the first rule, like so:               Clear[f];     f[x ;/ MatchQ[x, {_?NumericQ, 0}]] := (2 * x)[[1]];     f[x /; MatchQ[x, {_?NumericQ, _?NumericQ}]] := Total@x;     f[x_] := -1;     f[{1, 2.3}]     f[{1, 0}]     f[{4}]      I get the expected output:               3.3     2     -1      So, I am guessing if I want multiple rules, I should put the more restrictive ones before the general ones. This way, Mathematica will be able to use the first match to execute the appropriate function. But now consider this:               Clear[f];     f[x_] := -1;     f[x /; MatchQ[x, {_?NumericQ, _?NumericQ}]] := Total@x;     f[x ;/ MatchQ[x, {_?NumericQ, 0}]] := (2 * x)[[1]];     f[{1, 2.3}]     f[{1, 0}]     f[{4}]      The most general rule is at the top, yet the output is:               3.3     2     -1      Can someone please explain why Mathematica didn't just see every input as matching `f[x_]` and simply return `-1`? Thanks in advance.


title: Multiple down-values with exactly the same lefthand side

text: I was working on an answer to this question, when I was sidetracked by what I bring up here. I wanted a function, which when given a string representing a binary number, would convert the string to a list of digits. I wanted to reject any invalid strings and to return the function expression unevaluated an invalid string was rejected. I had a lot of trouble debugging the function. My edits to the function body didn't seem have any effect. Finally, in desperation, I got to performing `Clear[bitsToDigits]` before making an edit. This allowed to complete my debugging, but left me very puzzled because I have come to expect edits which don't effect the first argument of a `SetDelayed` not to require clearing the function's identifier. In such cases, I have come to expect evaluating `SetDelayed` to replace the old down-value with the new one. I decided to look at the down-values after making a second definition of now working function, but not to clear before evaluating it.               bitsToDigits[bitstr_String] :=       With[{result =         Module[{valid, bits = Characters[bitstr]},           valid = StringFreeQ[bitstr, Except["0" | "1"]];           If[valid, bits, False, False]]},         result /; result =!= False]          bitsToDigits[bitstr_String] :=       With[{result =                If[StringFreeQ[bitstr, Except["0" | "1"]],                   Module[{bits = Characters[bitstr]}, bits], False, False]},         result /; result =!= False]      I now looked at the down-values               DownValues[bitsToDigits]      To my horror, the result was > >     { >        HoldPattern[bitsToDigits[bitstr_String]] :> >          With[{result = >            Module[{valid, bits = Characters[bitstr]}, >              valid = StringFreeQ[bitstr, Except["0" | "1"]]; >              If[valid, bits, False, False]]}, >            result /; result =!= False], >        HoldPattern[bitsToDigits[bitstr_String]] :> >          With[{result = >                  If[StringFreeQ[bitstr, Except["0" | "1"]], >                    Module[{bits = Characters[bitstr]}, bits], False, > False]}, >            result /; result =!= False] >      } >   The new version of my function will never be executed because the older definition will always match first. This was totally unexpected. Should I have expected this? Is there something wrong with my definitions of `bitsToDigits`? If so, how should I fix them? Or have I found a bug? I have verified that my problem occurs in both V9 and V10 running on OS X. ### update Mr.Wizard has answered my question as originally posted, but I would be keen to learn if there is a way to implement the behavior I want without the distressing side effect, which interferes with my ingrained code development habits.


title: Faster Eigenvalues with lower precision goal

text: I compute all eigenvalues of a large matrix, and I decide that the speed is more important than the precision. Then the question is, can I speed up `Eigenvalues[]` by setting a lower precision goal? For example, consider a real symmetric random $100\times 100$ matrix:                In[1]:=  A = # + Transpose[#] &@RandomReal[{-1, 1}, {100, 100}];      and compute                In[2]:=  Do[Eigenvalues[A], {10}]; // AbsoluteTiming      Out[2]=  {0.019001,Null}      In real computation I may use a matrix much larger than $100\times 100$, and the computation would take much longer time than $0.019$ seconds. I want to speed up the computation. Can I set a lower precision goal, say `3`, so that `Eigenvalues[]` runs fuster? So I tried                In[3]:=  Do[Eigenvalues[SetPrecision[A, 3]], {10}]; // AbsoluteTiming      Out[3]=  {12.358707,Null}      The precision of the results is `3`, but the computation took `12.36` seconds. This is not what I want. Is there a clever way to speed up `Eigenvalues[]` by setting precision goal to be `3`?


title: Quadratic Equations mod p^k

text: As part of a larger program, I need to solve $A x^2+B x+C \equiv 0 \mod p^k$ for prime $p$. Right now I'm doing this by calling `Reduce[A*x^2+B*x+C==M*p^k,{x,M},Integers]` and then parsing this to find what I need (i.e. usually just assigning `C[1]->0` and ignoring `M` results). But when $A$, $B$, $C$, and especially $p^k$ start to get large (e.g. $A,B,C \approx 10^{30}$ and $p^k \approx 10^{70}$), there is quite a lag. Is there a faster way to find solutions for $x \mod p^k$? Thanks!


title: check if the expression is a equation

text: I need to check if the expression is a correct equation with only 1 variable x and without functions, that are not build into Mathematica. For example               Sin[x]==0       is correct equation. And expressions               Sin[x*a]==0, Sin[[x]==0, f[x]==0, Exp[x]=9       are not correct equations.


title: Differential curve geometry Frenet Formula

text: I am using Mathematica for differential geometry studies using Frenet Formulae. The problem is that I need to graph the solution curve r[t]. Suppose the curvature of a curve is k(s) = |s|and the torsion of a curve t(s)(s) = .3. Starting with the initial conditions with T,N, B being i, j, k,I have to graph the solution curve r(t) that has this data. Can anyone suggest me how to go ahead with this? T'(s) = k(s) N(s), N'(s) = - k(s) T(s) + t(s) B(s), B'(s) = - t(s)N(s). Here T, N, B are the unit tangent and unit normal and B is the unit binormal B = T * N


title: Is there a "precedence table" for the canonical Sort ordering?

text: This answer in which I wrote about the Operator Precedence Table was unexpectedly popular.   That got me thinking about similar things, and I am wondering: **Does an "ordering table" exist for the canonical order used by`Sort` and similar functions?**   (`Ordering`, `Order`, `OrderedQ`) It's easy enough to test the ordering of various expressions, but just as the precedence table contains some surprises even for experienced users I'm wondering if the canonical ordering does too? It seems odd if this isn't spelled out clearly somewhere, yet I don't recall seeing such a list. The documentation for `Order` tantalizingly says: > Order uses canonical order as described in the notes for Sort. Yet the documentation for `Sort` is quite basic, as far as I can find, saying only:   * Sort by default orders integers, rational, and approximate real numbers by their numerical values.   * Sort orders complex numbers by their real parts, and in the event of a tie, by the absolute values of their imaginary parts.   * Sort orders symbols by their names, and in the event of a tie, by their contexts.   * Sort usually orders expressions by putting shorter ones first, and then comparing parts in a depth-first manner.   * Sort treats powers and products specially, ordering them to correspond to terms in a polynomial.   * Sort orders strings as in a dictionary, with uppercase versions of letters coming after lowercase ones. Sort places ordinary letters first, followed in order by script, Gothic, double-struck, Greek, and Hebrew. Mathematical operators appear in order of decreasing precedence. This describes how `Sort` treats certain classes of expressions but it doesn't describe the relative ordering of these classes or attempt in any way to be exhaustive.


title: Finding the location of the last day of the month in a list of dates

text: My question differs from earlier questions about getting the eom dates from a list; I want to get the position of those dates so I can get the corresponding values from other lists. My problem seems to boil down to one about how to use `Position` where _pattern_ is a list. It's an ordinary list of about 5000 dates.               dates[[1 ;; 5]]     {{1995, 1, 31}, {1995, 2, 1}, {1995, 2, 2}, {1995, 2, 3}, {1995, 2, 6}}      As I said, I know how to get the eom dates (there are 229), but I can't seem to make `Position` work with a list.               Map[Last, GatherBy[dates, {#[[1]], #[[2]]} &]][[1 ;; 5]]     {{1995, 1, 31}, {1995, 2, 28}, {1995, 3, 31}, {1995, 4, 28}, {1995, 5,31}}      So, here's the kluge. Partition the dates into pairs. Map a function over the list of pairs that returns 1 if the day of the second member is less than the day of the first member, and zero otherwise. Finally, get the position of the members of this list that equal 1.               p = Flatten[Position[If[#[[2,3]]-#[[1, 3]]<0,1,0]&/@ Partition[dates,2,1],1]]     {1, 21, 44, 64, 87, 109, 130, 153, 174, 196, 218, 239,...}      And here is the list of values:               csh[[p]]     {114.141, 115.698, 116.331, 117.328, 119.333, 119.983,...}      It works, but it seems kind of clumsy.


title: Inconsistent results for equivalent converging symbolic integrals

text: I have looked at previous questions and I'm aware that this seems to be a known bug: _Mathematica_ giving inconsistent results for symbolic integrals done in different ways. The origins for the bugs seem to be varied. I'm having a hard time tracking down _where_ Mathematica is going wrong with this particular one, especially since I am explicitly assuming that all my variables ($L$ and $\rho$) are positive. I've played around with the assumptions without any luck. Here's my code:               $Assumptions = {ρ > 0, L > 0};          limits = Sequence[{ux, 0, L}, {vx, 0, L}, {uy, 0, ux}, {vy, 0, vx}]          N1 = Integrate[a1 = Exp[-ρ (ux - uy) (vx - vy)], limits];     N2 = Integrate[a2 = Exp[-ρ (ux - uy) (vx - vy)] (ρ (ux - uy) (vx - vy)), limits];     N3 = Integrate[a3 = Exp[-ρ (ux - uy) (vx - vy)] (ρ (ux - uy) (vx - vy))^2, limits];     N4 = Integrate[a4 = Exp[-ρ (ux - uy) (vx - vy)] (ρ (ux - uy) (vx - vy))^3, limits];          int1 = Integrate[4 ρ (a1 - 7/2 a2 + 2 a3 - 1/4 a4), limits]          int2 =  Simplify[4 ρ (N1 - 7/2 N2 + 2 N3 - 1/4 N4)] // Expand      Apologies for the large expressions but the particular simplifcations only happen when all four integrands are included with the correct factors. By comparing integrands it's easy to see that `int1` and `int2` are the same integrals. But for `int1` I get               (1 - E^(-L^2 ρ)) L^2      whereas for `int2` I get               L^2 - E^(-L^2 ρ) L^2 - (7 L^4 ρ)/4 + 7/2 L^4 ρ Log[L]      I know that the outcome for `int1` is correct whereas that for `int2` is incorrect. Any thoughts would be very welcome.


title: Simplify rearranges equations?

text: I've been using `Simplify/FullSimplify` to simplify some nasty equations, and by and large it does well but sometimes it rearranges equations in an unhelpful way. Here's a simple example. Say `x` is a positive number (standing in for some generally much more complicated factors),               $Assumptions=x>0      I have an equation like               eq = x^2 (a + b - 2 c^2 b) == 0     eq // Simplify      > >     a + b == 2 b c^2 >   But I don't want it to move terms from the `LHS` to the `RHS`, splitting up terms proportional to `b`. I want them grouped together. I can use `Collect` to keep these terms together, but then I have no way of dividing out the `x^2`. I could use `Collect` then divide out the `x^2` manually, but the terms I'm using `x^2` to stand in for are quite unwieldy, and it would be quite laborious to do this case-by-case, especially when `Simplif`y does it right away. **My question** : Is there any simple way to take `eq` and output > >     a + b - 2c^2 b == 0 >     (* or *) >     a + (1-2c^2)b ==0 >   without explicitly specifying that I want to divide out `x^2` (since `Simplify` divides this out automatically)?


title: Digital Elevation Maps (DEM) are Warped yet ReliefPlot renders as a rectangle - how do i join?

text: I downloaded several USGS Digital Elevation Maps (DEM files) corresponding to 12 adjacent areas. Each file Imports[] into _Mathematica_ and I can render the individual `ReliefPlot`s easily. The intent was, however, to create a mosaic by joining the individual images. Unfortunately, each DEM is warped and when I render using `ImageAssemble` there are triangular gaps between each `ReliefPlot`. Does anyone know if there is a simple way of using _Mathematica_ to orthogonalise the tiles so they can be assembled without gaps? It seems like `Import` pads the gaps using a number corresponding to a corner thereby creating an array that can be processed by `ReliefPlot`. I gather the issue stems from fact each tile is a quadrangle defined using UMT coordinates so I'm hoping the Geodesy package will help effect the transformation. However, having looked at the Geodesy functions I can't see the wood for the trees! Is there a simple fix. And is there a tutorial or book for the package?


title: How to create a writable and clearable symbol?

text: I'm trying to create several symbols and assign values to them. Here's what currently appears to work:               Evaluate[Symbol["fdds" <> ToString[10]]] = 1      But there's then another problem: I can't clear it without explicitly saying `fdds10`, i.e. this code               Evaluate[Symbol["fdds" <> ToString[10]]] =.      as well as this               Clear[Evaluate[Symbol["fdds" <> ToString[10]]]]      give errors: the former gives > Unset::usraw: Cannot unset raw object 1. >> and the latter results in > Clear::ssym: 1 is not a symbol or a string. >> How do I create good easily manageable symbols? PS: I know I could use something like `fdds[[10]]` here, but I'm interested in symbol-based solution.


title: Solving a Trigonometric parameter

text: I have a similar case as given before : Solving a Trigonometric function with one parameter Let:               m = 1;     Dx = 100;     ν = 0.25;     b = 1;      and,               λ1 = Sqrt[(((m^2)*(π^2))/a^2) + Sqrt[(n*(m^2)*(π^2))/(Dx*(a^2))]];     λ2 = Sqrt[(-(((m^2)*(π^2))/a^2)) + Sqrt[(n*(m^2)*(π^2))/(Dx*(a^2))]];     ω1 = ((λ1^2) - ν*((m^2) + (π^2))/a^2);     ω2 = ((λ1^2) - ν*((m^2) + (π^2))/a^2);      Now I have the following equation,               2*ω1*ω2 + ((ω1^2) + (ω2^2))*Cosh[λ1*b]*Cos[λ2*b] -        1/(λ1*λ2)*(((λ1^2)*(ω2^2)) - ((λ2^2)*(ω1^2)))*Sinh[λ1*b]*Sin[λ2*b] ==       0      Which is needed to be solved for the smallest Value of `n` as a function of ratio `a/b` Taking a similar solution given previously in the link I try:               solutions =       Table[{a,         Min[n /.           NSolve[2*ω1*ω2 + ((ω1^2) + (ω2^2))*Cosh[λ1*b]*Cos[λ2*b] -               1/(λ1*λ2)*(((λ1^2)*(ω2^2)) - ((λ2^2)*(ω1^2)))*Sinh[λ1*b]*               Sin[λ2*b] == 0 && 0 < n < 10, n]]}, {a, 0.1, 1, 0.1}]          ListLinePlot[solutions]      Which gives me errors               is neither a list of replacement rules nor a valid dispatch table, \     and so cannot be used for replacing. >>      I am stuck with this one, can anyone see why?


title: How do I export a text file with strings on different lines?

text: I would like to `Export` a text file, and use paragraph / ENTER commands to place different strings on different lines. Say we have three strings - str1, str2, and str3. How can we place them on separate lines of a text file? This command -               Export["test.txt", StringJoin[str1, str2, str3]];      Places str1, str2, and str3 on a single line.


title: Custom BoxWhisker Plot

text: I’d like to figure out how I can show my entire dataset overlaid on a box whisker plot.               data = {{0.763983, -1.11426, 1.05153, -0.0369066, 1.1571, 0.834856, 0.146695,     0.100646, 2.69399, 0.425281}, {0.506237, 1.05127, 1.58117,      0.976295, 1.62204, 1.39005, 1.62387, 1.36098, 1.83858,      0.709489}, {-1.62786, 0.947744, 4.50628, 0.444416, 1.30947, 0.60594,     0.890642, 4.04505, 4.57667, 0.781394}}      The following allows me to show Outliers overlaid on the plot. How would I go about overlaying all of the datapoint on the plot?               BoxWhiskerChart[data, {"Notched", {"MedianMarker", Blue}, {"Outliers",      "\[EmptySmallCircle]", Red}},ChartLabels -> {"X", "Y", "Z"}]


title: Testing Credit Usage in Wolfram Programming Cloud

text: I currently have a free WPC account, which I am using for testing purposes. Amongst other things, I want to find out more about how the credit system works, in particular how many credits are used, based on various different operations. However, whenever I try to access the Usage Summary Report in my WPC account I receive the following, unhelpful error message: "Sorry you do not have permission to access this item. Try using a different account." Are free WPC accounts not provisioned with access to usage reports? How does one budget credit usage without such information?


title: Matrix Plot – Little Exercise

text: Hi there, mathematicians. I'm not very good at coding plots in _Mathematica_ , so I was hoping that one of you could help me solve a problem I'm having. I have the following matrix plot:               Z = {Subscript[x, 0], Subscript[x, 1], Subscript[x, 2]}     X = {{0, 8, 12}, {.1, 0, 0}, {0, .2, 0}}      Then I put it in a function as follows:               P[x_] := X^x.Z      I would like _Mathematica_ to display plots such that, whenever x iterates from 1 to 10 in the function, the x1, x2, and x3 from the matrix are respectively plotted in three plots. Can anyone help me? * * * **EDIT: Trying to be more clear** I have the matrix (mat) and the vector (v):               mat = {{0, 8, 12}, {.1, 0, 0}, {0, .2, 0}}     v = {x0, x1, x2}      Then later I define the function for population development, `pD`, taking `t` (for time in days) as its only parameter.               pD[t] = mat^t.v      Now I would like to show the development of the variables $x_1$,$x_2$, and $x_3$ assuming the values 30, 60, 30, respectively. I would do so by making plots of the three functions over the range 1 to 10 days. For each the first plot should display the values of $\{t,pD[t_{x_1}]\}$, the second the values of $\{t,pD[t_{x_2}]\}$, and the third the values of $\{t,pD[t_{x_3}]\}$. I hope this clarifies my question. Sorry for being so unconventional in the first place. However, having worked my eyes blind for quite some time, I presumed that it was anything but difficult to understand. Thanks for your patience! * * * Best regards, Brinck10


title: How can I plot the real and imaginary parts of a complex function given by an implicit equation?

text: My equation is               I e2 s2 w (m1^2 m2 q1 s1^2 s2 + m1 m2^2 q2 s1^2 s2 + m1^2 q1 s1^2 s2 ζ -        m2^2 q2 s1^2 s2 ζ - 2 m1 q1 s1^2 s2 ζ^2 - m2 q1 s1^2 s2 ζ^2 + m1 q2 s1^2 s2 ζ^2 +        q1 s1^2 s2 ζ^3 - q2 s1^2 s2 ζ^3) +      1/w s1 γ ζ^3 (2 I m2^2 q2 s1 s2^2 ζ + 2 I m2 q1 s1 s2^2 ζ^2 -        2 I m2 q2 s1 s2^2 ζ^2 - 2 I q1 s1 s2^2 ζ^3) -      I (m1^2 m2 q1 s1 s2^2 + m1 m2^2 q2 s1 s2^2 - m1^2 q1 s1 s2^2 ζ + m2^2 q2 s1 s2^2 ζ +        m2 q1 s1 s2^2 ζ^2 - m1 q2 s1 s2^2 ζ^2 - 2 m2 q2 s1 s2^2 ζ^2 - q1 s1 s2^2 ζ^3 +        q2 s1 s2^2 ζ^3) (-e1 s1 w + (s1 γ ζ^3)/w) == 0      and               m1 = Sqrt[ζ^2 - I*w/s1]; m2 = Sqrt[ζ^2 - I*w/s2];      The independent variable is `w`. All the other variables are constant except `ζ` (complex number).               q1 = 1; q2 = 0.5; e1 = 1; e2 = 0.8; s1 = 1; s2 = 0.6; γ =1000;      I used `FindRoot` and solved this problem. `FindRoot` gives the solution only for one case of `w`, but I want to plot the graph of `w` and `ζ`. How do I plot `Re[ζ]` vs.`w` and `Im[ζ]` vs. `w`?


title: Obtaining Size Of Graphical Objects

text: I have created a panel, say `Panel[""]`. I want to know its size/dimensions. Is there any built-in function for doing that?


title: Fit text to a path

text: > **Possible Duplicate:**   >  Movable text on a curve This is a common feature among vector-based graphics suites (e.g. Illustrator), so I was wondering how it could be done in Mathematica. Here's an example: ![enter image description here](http://i.stack.imgur.com/vcg4z.png) I'm pretty sure one has to "vectorize the font" first, as demonstrated here under "neat examples," but beyond that, I'm stuck. In Illustrator, one can choose to align the text to the path using the baseline, ascenders, descenders, and also choose various methods of fitting the path to the curve ("rainbow," "skew," "3D ribbon," "stair step," "gravity"), but I would be satisfied with a solution that uses the lowest point in a string of text (i.e. the descender), and uses the "rainbow" style of Illustrator, as is shown in the above example. For simplicity, let's just align the above string ("The quick brown fox jumped over the lazy dog") with the Sin function.


title: Automatic substitution of fractions

text: I have several equations with many variables, and here and there I would like to do a variable substitution. For example, in the equation:               a (b + 42 c / d)      I might want to remap variables _a * b --> p_ and _a * c / d --> q_ in order to get:               p + 42 q       Can _Mathematica_ do this? I tried to play with the `With[]` and `Rule[]` function and the like, but that doesn't seem to produce anything. I can imagine that _Mathematica_ is not capable of doing such a thing, but I thought it would be worth asking. **And the pro question:** And then very much related to this: is there a way to use `With[]` not to set a single variable but to set variable relations, e.g. the sum or product of two variables. So that this:               With[{a * b = 5},  a (b + 42 c / d)] (* This doesn't work*)      would reduce to:               5 + 42 a * c / d


title: Nested Map and Apply

text: There are some other questions on this topic but I could not get an answer from reading them. What I want to do is use `Apply` on some of the arguments of a function, `h`, and then `Map` on another argument. Here is what I attempted:               Map[Apply[{h[#, ##]} &, {a, b}] &, {1, 2}]     (* ===>{{h[a, a, b]}, {h[a, a, b]}} *)      The elements I want to `Map` over never get used. But this is not what I want. I want just               {h[1,a,b],h[2,a,b]}      I could use Table instead of Map but it's slow (slower than just using `Apply` twice) and I was hoping `Map` would be faster. I understand that `Apply` is using both `#` and `##` but I'm not sure what syntax is correct to force the first `Slot` to be used by `Map` instead of `Apply`. EDIT: This is more like what I actually want to do:               Map[Apply[{h1[#, ##],h2[#, ##]} &, {RandomReal[], RandomReal[]}] &, {1, 2}]      So I want output as               {{h1[1, a1,b1], h2[1, a1,b1]},{h1[2, a2,b2], h2[2, a2,b2]}}      where I `a`'s and `b`'s are the random numbers. So to get this, I think the order of `Apply` and `Map` is important.


title: PlotLegends doesn't work on Plot3D-V8.0.0

text: I am trying to plot in 3D and I need to use `PlotLegend`. My code is               Needs["PlotLegends`"]     Evaluate[PlotLegends]     Plot3D[Tanh[H/T], {T, 0, 300}, {H, 0.001, 1},      PlotLabel ->        Style[Framed[         "Energy Dependance on Magnetic Field H and Absolute Temperature \     T"], 13, Red, Background -> Lighter[LightYellow]],       Background -> LightGray,       ColorFunction -> Function[{x, y, z}, Hue[.65 (1 - z)]],       AxesLabel -> {T[kelvin], H[tesla]}, BoundaryStyle -> Thick,       ClippingStyle -> Opacity[0.5], Mesh -> Full,       PlotLegends -> Automatic]      While I use `Needs["PlotLegends`"]` I don't seem to be able to plot a legend. I get an error saying _Plot3D::optx: Unknown option PlotLegends in Plot3D[...]_ How can this be fixed?


title: Programming- cryptography

text: I have defined the following function in _Mathematica_ to get a SET OF `m` SETS (these sets are the codes `{p,q,d,e,n}` for the encryption system `RSA`.):               RSA[m_] :=        Table[          Module[{prime, p, q, k, factors, d, e, n,ans},                 prime = RandomPrime[{2, 10^2}, 2]; p = prime[[1]]; q = prime[[2]];                k = (p - 1)*(q - 1) + 1; factors = FactorInteger[k];                 d = RandomChoice[factors][[1]]; e = k/d; n = p*q;                 ans = {p, q, d, e, n}; ans],         {i, 1, m}];      The problem is that although it is not very probable, these sets can be repeated, and I would like to avoid this case, but I have no idea. I have tried using the _Mathematica_ function `Union`, in which reapeted sets wouldn't be included, but I don't know how to add more in order to get just m elements (sets).


title: A* algorithm for finding shortest path in a graph

text: FindShortestPath finds the shortest path between two vertices in an edge- weighted graph, allowing a choice between the Dijkstra and Bellman-Ford algorithms. In my (limited) understanding, both of these algorithms fall into the breadth-first category. My question is if there are accessible implementations of depth-first shortest path algorithms like A* for edge-weighted graphs in Mathematica. I am aware of the question How to display each step of an A star algorithm?, but before delving into modifying that code so as to work with weighted graphs I wanted to make sure that I don't re-invent the wheel. In fact, I haven't been able to locate an efficient implementation (using fancy data structures etc.) of A* for edge-weighted graphs in _any_ programming language, but that would probably be a question for another site.