title: Showing ListLogPlot and redrawing FrameTicks

text: I want to combine two `ListLogPlot` plots. For example               p1 = ListLogPlot[Range@100, Frame -> True]     p2 = ListLogPlot[10^4*Range@100, Frame -> True]      I got               Show[p1, p2, PlotRange -> All]      ![enter image description here](http://i.stack.imgur.com/Msnob.png) By using the ticks of p2, I got               Show[p1, p2, PlotRange -> All, FrameTicks -> (FrameTicks /. p2[[2]])]      ![enter image description here](http://i.stack.imgur.com/6ujxe.png) Both of the results have ticks which only cover a part of the figure. By trying               Show[p1, p2, PlotRange -> All, FrameTicks -> Automatic]      ![enter image description here](http://i.stack.imgur.com/0ZklM.png) I actually got a _wrong_ result with completely wrong ticks. So would there be a way to let `Show` combine the plots and redraw the ticks automatically? Thanks! Some notes: (1) There is a similar post: Scale label problem of multiple ListLogPlot graphs However, it doesn't solve my problem because the two plots here have different scales which are non-overlapping. Thus the problem is not solved simply by ordering the plots or choosing which ticks to use. (2) I could instead do `ListLogPlot[{Range@100, 10^4*Range@100}]`. However, actually each plot command in my realistic case is complicated enough thus it would be easier and more modular for me to draw them separately and combine them afterwards.


title: What is the fastest way to find an integer-valued row echelon form for a matrix with integer entries?

text: Let me begin by saying that this is my first post on StackExchange. I apologize in advance if I unwittingly break any of its unwritten rules of etiquette. Recently, I've been trying to understand an algorithm by coding it into Mathematica. One of the main steps in the algorithm requires me to find a integer-valued row echelon form for a matrix with integer entries. There are several constraints that the input matrices satisfy. The matrices represent sparse underdetermined (never inconsistent or trivial) homogeneous linear systems. The number of columns may only take particular values fixed by the algorithm but, for the purposes of this question, it is enough to know that the number of columns is always much, much larger than the number of rows. The number of rows is also typically somewhat large and it may be the case that some number of rows are duplicates or linear combinations of other rows. Another key point is that the integer entries could generically be quite large. Therefore `Compile` was not an option for me (however if there is some magic way to do multi-precision arithmetic with `Compile` please let me know!). My main motivation for asking this question is that this is the first time that it has actually mattered to me how efficient my Mathematica code is and I am having a very difficult time optimizing my solution attempts. First a word about data structures. I represent my sparse arrays using their rule-based form on a row-by-row basis. As a representative example, consider the following 15 X 100 matrix:               {{{1} -> 1, {21} -> -1, {62} -> -1, {92} -> 1}, {{2} ->      1, {22} -> -1, {64} -> -1, {94} -> 1}, {{3} ->      1, {23} -> -1, {65} -> -1, {95} -> 1}, {{2} ->      1, {22} -> -1, {64} -> -1, {94} -> 1}, {{4} ->      1, {24} -> -1, {67} -> -1, {97} -> 1}, {{5} ->      1, {25} -> -1, {68} -> -1, {98} -> 1}, {{3} ->      1, {23} -> -1, {65} -> -1, {95} -> 1}, {{5} ->      1, {25} -> -1, {68} -> -1, {98} -> 1}, {{6} ->      1, {26} -> -1, {69} -> -1, {99} -> 1}, {{55} -> -2, {56} ->      1987, {62} -> -8, {63} -> -2, {65} -> -4, {66} ->      1987, {72} -> -4, {73} -> -2, {82} -> -4, {95} ->      2}, {{58} -> -2, {59} ->      1987, {64} -> -8, {65} -> -2, {68} -> -4, {69} ->      1987, {74} -> -4, {75} -> -2, {84} -> -4, {98} ->      2}, {{59} -> -2, {60} ->      1987, {65} -> -8, {66} -> -2, {69} -> -4, {70} ->      1987, {75} -> -4, {76} -> -2, {85} -> -4, {99} ->      2}, {{5} -> -2, {6} -> 1987, {13} -> -2, {16} ->      1987, {22} -> -4, {23} -> -2, {32} -> 4, {45} -> -2, {55} ->      4, {56} -> -3974, {62} -> 16, {63} -> 4, {64} -> -8, {65} ->      4, {66} -> -3974, {72} -> 8, {73} -> 4, {82} -> 8, {94} ->      8}, {{8} -> -2, {9} -> 1987, {15} -> -2, {19} ->      1987, {24} -> -4, {25} -> -2, {34} -> 4, {48} -> -2, {58} ->      4, {59} -> -3974, {64} -> 16, {65} -> 4, {67} -> -8, {68} ->      4, {69} -> -3974, {74} -> 8, {75} -> 4, {84} -> 8, {97} ->      8}, {{9} -> -2, {10} -> 1987, {16} -> -2, {20} ->      1987, {25} -> -4, {26} -> -2, {35} -> 4, {49} -> -2, {59} ->      4, {60} -> -3974, {65} -> 16, {66} -> 4, {68} -> -8, {69} ->      4, {70} -> -3974, {75} -> 8, {76} -> 4, {85} -> 8, {98} -> 8}}      My main motivation for using this representation of my data is that it seems to make the implementation of an efficient pivoting strategy incredibly simple. I'm not overly wedded to this choice of data structure and would be happy to switch to something else if it allows for a better solution to the problem. One obvious question is: Why not just use built-in functions? It seems to me that, at least naively, the out-of-the-box solution based on `RowReduce`               IntegerRowEchelon1[L_, n_] := (temp =      DeleteCases[RowReduce[SparseArray[#, n] & /@ L], 0 Range[n]];      Drop[ArrayRules[#], -1] & /@      Expand[(LCM @@ Denominator[Flatten[temp]]) temp])      is overkill in the extreme. First of all, it seems impossible to force `RowReduce` to deliver a row echelon as opposed to a reduced row echelon form. The back-solving step of the elimination process is unnecessary for me and therefore should be avoided. Furthermore, since I am working over the integers, I have to waste time by clearing the denominators and turning the reduced row echelon form that `RowReduce` delivers into an acceptable integer- valued output. So far, however, I haven't been able to improve upon the above solution. The essence of my question to you, the experts, is whether or not I should just go with the ridiculous work-around `IntegerRowEchelon1` or if there is a more natural lower-level solution that would work as fast or faster. There are clearly many computations done by `IntegerRowEchelon1` that could in principle be avoided but, on the other hand, `RowReduce` has undoubtedly been highly optimized by the developers at WRI. So it is not obvious to me whether or not one can do significantly better. Finally, let me share with you two solution attempts which lose to `IntegerRowEchelon1` by factors of roughly 2 and 3 respectively. I tested them both on 1000 15 X 100 matrices with 35% of their entries filled in using `RandomInteger`. The correctness of the output was verified by applying `IntegerRowEchelon1` to both the input and the output. These solution attempts were based on a classical algorithm due to Camille Jordan. Since this algorithm was not widely known until the work of Erwin Bareiss circa 1968 (The original paper, E. H. Bareiss, "Sylvester's Identity and Multistep Integer- Preserving Gaussian Elimination", is googleable (search "Erwin Bareiss Sylvester's Identity", first link) if you want to have a look at it. I also was able to get quite a bit out of the Google Books preview for Chapter 9 of "Algorithms For Computer Algebra" by Geddes et. al. http://books.google.es/books?id=9fOUwkkRxT4C&printsec=frontcover&hl=es&source=gbs_ge_summary_r&cad=0#v=onepage&q&f=false), it is usually called the Bareiss one-step fraction-free Gaussian elimination algorithm. This algorithm is exposited in many textbooks on computer algebra and is probably the simplest one that does what I want. Although I couldn't find an answer in the documentation, I would guess that this algorithm is what Mathematica is using to forward-solve when you select the method "OneStepRowReduction." Needless to say, I tried forcing `RowReduce` to use this method but it appears to make no difference whatsoever, in either the timing or in the output. Of course, I've also considered the possibility that the reason I can't beat Mathematica is that it is using an algorithm more efficient than Bareiss's. For now, I will proceed assuming that Bareiss's algorithm is at least no worse than the algorithm(s) upon which `RowReduce` is ultimately based. For those of you with insider information, any pearls of wisdom you can share about how `RowReduce` actually works would be more than welcome. My first attempt at coding Bareiss's algorithm looks pretty ugly but only loses to `IntegerRowEchelon1` by a factor of about 1.9:               IntegerRowEchelon2[L_] := (Aold = SortBy[L, #[[1, 1, 1]] &];      rnum = Length[Aold]; i = 1; lastpivot = 1; Anew = Aold; flag = 0;      While[i <= rnum - 1,      If[Aold[[i, 1, 1]] =!= Aold[[i + 1, 1, 1]], i++; lastpivot = 1;      Continue[]];      For[a = i + 1, a <= rnum, a++,      If[Aold[[i, All, 1]] =!= Aold[[a, All, 1]],       tempRRi =        Rule[#, 0] & /@         Complement[Aold[[a, All, 1]], Aold[[i, All, 1]]];       tempRRa =        Rule[#, 0] & /@         Complement[Aold[[i, All, 1]], Aold[[a, All, 1]]];       Aold[[a]] = Sort[Join[Aold[[a]], tempRRa]];       Aold[[i]] = Sort[Join[Aold[[i]], tempRRi]];       Anew[[i]] = Aold[[i]];       Anew[[a]] =        If[Aold[[a, 1, 1]] === Aold[[i, 1, 1]], Drop[Aold[[a]], 1],         Aold[[a]]],       Anew[[a]] =        If[Aold[[a, 1, 1]] === Aold[[i, 1, 1]], Drop[Aold[[a]], 1],         Aold[[a]]]];      Which[Aold[[a, 1, 1]] === Aold[[i, 1, 1]],       Anew[[a, 1 ;; Length[Aold[[a]]] - 1, 2]] =        Drop[1/lastpivot (Aold[[i, 1, 2]] Aold[[a,               1 ;; Length[Aold[[a]]], 2]] -            Aold[[i, 1 ;; Length[Aold[[a]]], 2]] Aold[[a, 1, 2]]), 1],       True,       Anew[[a, 1 ;; Length[Aold[[a]]], 2]] =        1/lastpivot Aold[[i, 1, 2]] Aold[[a, 1 ;; Length[Aold[[a]]],           2]]]; If[      Anew[[a, 1 ;; Length[Aold[[a]]] - 1, 2]] =!=        0 Range[Length[Aold[[a]]] - 1],       Anew[[{i, a}]] = DeleteCases[#, {x_} -> 0] & /@ Anew[[{i, a}]];       Aold[[{i, a}]] = DeleteCases[#, {x_} -> 0] & /@ Aold[[{i, a}]],       flag = 1; Anew = Delete[Anew, a]; rnum--; Break[]]];      If[flag == 1, flag = 0; If[i != Anew[[i + 1, 1, 1, 1]], i++];       Aold = Anew; Continue[]]; lastpivot = Aold[[i, 1, 2]]; i++;       Anew = SortBy[Anew, #[[1, 1, 1]] &]; Aold = Anew]; Anew)      I was sure that my second attempt was going to perform much better but it turned out to lose by a factor of about 2.8 to `IntegerRowEchelon1`               IntegerRowEchelon3[L_] :=     (A = SortBy[L /. Rule[{x_}, y_] :> List[x, y], #[[1, 1]] &];      rnum = Length[A]; i = 1; lastpivot = 1;      While[i < rnum,      If[A[[i, 1, 1]] != A[[i + 1, 1, 1]], i++; lastpivot = 1;      Continue[]];      pivotrow = A[[i]]; (activerow = A[[#]];        A[[#]] =         If[Length[#] == 1, {#[[1, 1]], #[[1, 2]]/            lastpivot}, {#[[1, 1]], (#[[1, 2]] + #[[2, 2]])/            lastpivot}] & /@          SplitBy[Sort[           Join[Map[{#[[1]], pivotrow[[1, 2]] #[[2]]} &,              If[activerow[[1, 1]] == pivotrow[[1, 1]],               Drop[activerow, 1], activerow]],             Map[{#[[1]], -If[activerow[[1, 1]] == pivotrow[[1, 1]],                   activerow[[1, 2]], 0] #[[2]]} &,              Drop[pivotrow, 1]]]], #[[1]] &]) & /@ Range[i + 1, rnum];      A = SortBy[      DeleteCases[DeleteCases[A, {_, 0}, {2}], {}], #[[1, 1]] &];       lastpivot = pivotrow[[1, 2]]; rnum = Length[A]; i++];      A /. List[x_, y_] :> Rule[{x}, y])      At least to me,`IntegerRowEchelon3` looks much nicer than `IntegerRowEchelon2`. But it's way slower! This is quite counter-intuitive to me because, in coding `IntegerRowEchelon3`, I made a concerted effort to get rid of as much fluff as possible and be as functional as possible which I thought was "good Mathematica programming style". It was very disappointing to discover that `IntegerRowEchelon3` loses so badly to `IntegerRowEchelon1`. I must admit that I feel a bit lost at this point about issues of performance tuning and look forward to seeing alternative solutions to my problem. To be clear, at the end of the day speed is what matters and I would be more than happy to accept "high-level" solutions that beat `IntegerRowEchelon1` as well.


title: Problems with txt-export under Macintosh

text: I exported data form Mathematica to txt-format on my Mac. When opening the txt-file on a Windows-System the file does not appear as on my Mac (see screenshots). Code: `Export["Example.txt", {{"Test1", 1, 2, 3, 4}, {"Test2", 5, 6, 7, 8}}]` Mathematica Documentation Center says "`Export` uses the line separator convention of the computer system on which Mathematica is being run." How can I generate a txt-file under Mac OS, so that this file can be read correctly under Windows to? BTW: I would like to get rid of the braces, quotation marks and commas within the txt-file. ![enter image description here](http://i.stack.imgur.com/joDw3.jpg) ![Mac Screenshot with code](http://i.stack.imgur.com/Iemh9.png)


title: (Symbolic) LinearSolve is slower/different after upgrading to Mathematica 9

text: Yesterday I upgraded from mathematica 8.0.4.0 to 9.0.1.0. Trying to run the same notebook I used many times before, it takes ages to evaluate a symbolic (linearsolve) expression which before was evaluated in within a minute. It doesn't give the answer within 12 hours, with CPU usage at 25-30%. What could have changed? (I don't want to switch back to the old version, want to fix this). I want to solve:               rhoout = LinearSolve[Mcoeff, out]      Where the (10-by-1) vector is simply:               out = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0}      And the matrix (10-by-9):               Mcoeff = {{1, 0, 0, 0, 1, 0, 0, 0, 1}, {-c21 - c31, 0, -I omge, 0, c12, 0,        I Conjugate[omge], 0, c13}, {0,        I (-dge + dse) - c1/4 - c12/2 - c2/4 - c21/2 - c31/2 - c32/        2, -I omse, 0, 0, 0, 0, I Conjugate[omge],        0}, {-I Conjugate[omge], -I Conjugate[omse], -I dge - c1/4 - c13/2 -         c21/2 - c23/2 - c3/4 - c31/2, 0, 0, 0, 0, 0,        I Conjugate[omge]}, {0, 0,        0, -I (-dge + dse) - c1/4 - c12/2 - c2/4 - c21/2 - c31/2 - c32/2,        0, -I omge, I Conjugate[omse], 0, 0}, {c21, 0, 0,        0, -c12 - c32, -I omse, 0, I Conjugate[omse], c23}, {0, 0,        0, -I Conjugate[omge], -I Conjugate[omse], -I dge - I (-dge + dse) -         c12/2 - c13/2 - c2/4 - c23/2 - c3/4 - c32/2, 0, 0,        I Conjugate[omse]}, {I omge, 0, 0, I omse, 0, 0,        I dge - c1/4 - c13/2 - c21/2 - c23/2 - c3/4 - c31/2,        0, -I omge}, {0, I omge, 0, 0, I omse, 0, 0,        I dge + I (-dge + dse) - c12/2 - c13/2 - c2/4 - c23/2 - c3/4 - c32/        2, -I omse}, {c31, 0, I omge, 0, c32,        I omse, -I Conjugate[omge], -I Conjugate[omse], -c13 - c23}}      EDIT OK, I did install the older version again (Mathematica 8.0.4.0), this is the result (I suppressed the output because it is very large, hence the 'Null' in the answer):               In[51]:= Timing[rhoout = LinearSolve[Mcoeff, out];]          Out[51]= {6.256, Null}      In v9.0.1.0, the exact same command (the same .nb file) does not produce an answer within reasonable time (again, I have let the evaluation run overnight, >12hrs, and there was no result)


title: detecting the radius of an incomplete circle

text: I need your help to detect the radius of the blue circle in images like this: ![Mathematica graphics](http://i.stack.imgur.com/moV5x.png). Reading these questions: 1, 2, 3, I figured that this code taken from @halirutan answer to question n°3 could help:               imga=Import[http://i.stack.imgur.com/moV5x.png];     circle = SelectComponents[     MorphologicalComponents[     LaplacianGaussianFilter[ColorNegate@imga, 2], 0.003`],      "Count", # > 400 &];     Colorize[circle]      And I have this output: ![Mathematica graphics](http://i.stack.imgur.com/s2VJr.png) And now I'm stuck, if the circle were closed it would be simple, how can I find the best circle completing it? Obviously if you have a completely different solution it is fine (for example I thought it could be possible to take only the left semicircle, but I don't know how to do it). Please note that I have to process about 100 images like that so if possible I would need the program to run in a reasonable amount of time and with no manual adjustments. **As a bonus question** : since I have to determine also a possible error on the radius, would it be possible to find the outer and the inner circles? and the eccentricity of the closed figure (if it is possible to close it)? **P.S.** : since I just started working with mathematica for image processing I would also like to know a few good references or books about it. I have read a few mathematica books but none of them treated this argument in detail.


title: What is the simplest way to set the toolbar of a notebook to an image?

text: For custom stylesheets, it's nice to have a graphic banner in the Docked Cell. According to the doc page tutorial/IntroductionToToolbars, this is how you do it, but it seem a bit overkill:               img = Rasterize[        Framed["\tMy Header", Background -> LightBlue, FrameStyle -> White,          ImageSize -> {2000, 30}]];     image = Cell[        BoxData[ToBoxes[           img] /. {(ImageSize -> {___, ___}) -> (ImageSize ->               ImageDimensions[img])}], "DockedCell", CellMargins -> -2,         CellFrameMargins -> {{0, 0}, {0, 0}}];     SetOptions[InputNotebook[], DockedCells -> {image}]


title: Bayesian Inference with Continuous prior distribution

text: Assume that we have a prior distribution for the probability of success as follows.               p = BetaDistribution[6, 14]      which we can graph as this               Plot[Evaluate[PDF[p, k]], {k, 0, 1}]      I would like to use Mathematica to calculate the _posterior_ distribution given that we take a sample and we get 420 successes out of a sample size of 1830. what would be to calculate it and graph it? Regards.


title: Solving an equation with a function defined by an element of a list

text: I have the following piece of code:                   y[x_] := (x - 3)^2 + 2         x[a_] := Sort[Select[x /. NSolve[a == y[x], x], #  ∈ Reals && # > 0 &],Less][[1]]         x[2]          (* 3 *)              xx[a_] := Piecewise[{{x[a], a >= 2}}]         NSolve[xx[a] == 3, a]     (* Part::partw: Part 1 of {} does not exist. >>*)           (* {} *)      So if $a\geq2$ then `x` picks the smallest from the list of $2$ elements and `xx` is just `x` on the domain where `x` is defined. Now I want `NSolve` to return the value of $a$ for which `xx[a]=3`. Why does the above error show up? If I give the input `xx[2]` then I get the output 3 as required, but if I put `xx[2]` in `NSolve` it apparently evaluates `xx[a]` first (rather than immediately putting in numerical values for a), which yields the error. How can I fix this, so that `NSolve` returns the value 2? I tried `Reduce` and `FindRoot` as well, which give the same error. Note: this seems like a huge hassle for such an easy function, but I'm applying it to some more complicated functions which seemed irrelevant to mention here. Edit: apparently the problem lies in the `Select` (and then `Sort`) part, since `NSolve` (and all other equation solvers) first puts in a variable `a`, then computes `x[a]` (so that selecting the positive reals does not make sense since `a` is not yet a number) and only then starts putting in the values of `a`... So the solution would be to create another equation solving function than the ones Mathematica has.


title: Output solutions from large amount of multiple parameters to external files?

text: I have some code that solves an ugly PDE by using the results of another, and outputs the value of the solution between a range $mic \leq r \leq r_{o}$. It looks something like this               (*Constants for these PDEs*)     a = 7.5*10^-7; omega = 3.0138*10^7; Do2 = 2*10^-9; po = 100;     ro = 300*10^-6; k = 1; eo = 100; qm = 10^-4; mic = 1*10^-6; De = 5.5*10^-11;          (*First solver*)     s = Quiet[        NDSolve[{D[Ox[r, t], t] -             Do2*(D[Ox[r, t], r, r] + (2/r)*(D[Ox[r, t], r])) + (a*           omega)*((Ox[r, t])/(Ox[r, t] + k)) == 0, Ox[r, 0] == 0,       Ox[micron, t] == 0, Ox[ro, t] == po},      Ox, {r, mic, ro}, {t, 0, 14400}]];          p = Ox /. First[s];          (*More constants (These are ones we want to parameter sweep)*)     kme = 0.1; kmn = 0; j = 0.02;          (*Output PDE solution set*)     G = Table[        Evaluate[         Eb1[r, 14400] /.           NDSolve[{D[Eb1[r, t], t] -               qm*((kme)/(kme +                      p[r, t])*((p[r, t])/(p[r, t] +                       kmn)) + (1 - (p[r, t])/(p[r, t] + kmn))*j)*               First[Evaluate[                 Ef1[r, t] /.               NDSolve[{D[Ef1[r, t], t] -                   De*(D[Ef1[r, t], r, r] + (2/r)*(D[Ef1[r, t], r])) +                   qm*((kme)/(kme +                      p[r, t])*((p[r, t])/(p[r, t] +                      kmn)) + (1 - (p[r, t])/(p[r, t] + kmn))*j)*                   Ef1[r, t] == 0, Ef1[r, 0] == 0, Ef1[mic, t] == 0,                 Ef1[ro, t] == eo},                Ef1, {r, mic, ro}, {t, 0, 14400}]]] == 0,         Eb1[r, 0] == 0}, Eb1, {r, mic, ro}, {t, 0, 14400}]], {r,      mic, ro, mic}];     Export["testplot.xls", G];      This works well for individual solution sets, but what I really want are the solution sets as $kme$, $kmn$ and $j$ vary; specifically, I want these parameters to vary between the limits of               {kme,0.1,15,0.1} , {kmn,0,15,0.1}, {j,0,1,0.01}      I've tried not declaring $kme,kmn,j$ and then adding the above terms to the table output, but this yields an errors with NDSolve. I tried combatting this using ParametricNDSolve and got errors about too many parameters. I was wondering if there's a more elegant solution, or should I use loops to output to individual files, and how would I go about this? This question has stumped me for two days, and there's simply too many values (150 x 151 x 101 = 2287650 solution sets!)to increment this manually. If anyone has a good solution to this, I'd be very, very grateful if they would outline it. The exported format does not have to be excel; it simply has to be in a file format which I can easily import into MATLAB. Thanks in advance. Apologies if there's an obvious solution I'm missing - I'm self- taught and tend to miss the more elegant approaches!


title: What are the possible security breaches in CDF content?

text: It has been noted on this site before that the free CDF player is notoriously trigger-happy in declaring dynamic content to be "potentially unsafe", and forcing the user to enable dynamic content manually upon opening the CDF. This proceeds through a rather unfriendly banner and a big grey box that covers the content. > This file contains potentially unsafe dynamic content. More details $\gg$ > `Enable Dynamics` ![Unsafe content message](http://i.stack.imgur.com/TpySj.png) To quote István Zachar's answer on his canonical CDF question, just about anything will trigger this warning: > The security issue rises when a function is involved in the dynamic output: > >   * with definitions >   * that changes attributes >   * with options >   * package related functions >   * `ToExpression/MakeExpression` >   * `Compress/Uncompress` > * * * It seems to me that this trigger-happiness does not really serve the spirit of security protection: if _everything_ causes the warning then it does not help to discriminate the truly potentially malicious files. Mostly, though, I'm puzzled as to what a file with that sort of content _could_ do if allowed to roam free. I can understand that compressed content is a no-go, but what on Earth is wrong with a function with options? So, to put this question more precisely:   * What sorts of malicious activity are these restrictions meant to prevent? How (roughly!) would they be achieved?   * More particularly, why is each of the features above a potential security risk?   * Conversely, what are the possible dangers of enabling dynamic content on a file I don't trust completely?   * How does this situation depend on whether one is running the free or Pro CDF Player, the web plugin, or full-blown Mathematica? * * * Edit: After posting this question, I was made aware of List of dangerous functions. This is similar, but many of the functions discussed there are disabled on CDFs, and particularly on the free player. Moreover, functions with definitions and with options are _not_ deemed unsafe in notebooks, so the security thresholds for the two are different, and it is relevant to know what the dangers are in CDFs. What can those notebook-safe classes do in CDFs that renders them a security liability?


title: How to generate a random signal consisting of the specified functions

text: Let's assume that I have some particular signal on the finite time interval which is described by function $f(t)$. It could be, for instance, a rectangular pulse with amplitude $a$ and period T; gaus function with $\sigma$ and $a$ or something else. Now I need to generate a signal which consists from randomly appearing functions $f(t)$ with random parameters (random parameters should be random in some specified range). If $f(t)$ is a rectangular function, generated signal should consist from randomly generated rectangulars appearing on the random moments of time (rectangles should not overlap). Can anyone suggest what is the best way to do it in Mathematica? Example:![rectangles](http://i58.tinypic.com/70usu1.png)


title: Match and replace subexpression

text: I would like to replace the expresion $(n1-1)$ to $z1$ in following:               In[1] := 2*n1*p[n1-1,n2]          Out[1] := 2*(z1+1)*p[z1,n2]      I have tried `Replace`, `ReplaceAll`, `/.`, `//.` but nothing seems to be working. Only part inside $p[n1-1, n2]$ is replaced. Can anyone help me with this?


title: Curve fitting data to model

text: **Example** Assumptions:               ClearAll[m, F, b, \[Omega], \[Delta]]     $Assumptions = x > 0 && m > 0 && F > 0 && b > 0 && \[Omega] > 0 && \[Delta] > 0;      In the following, $m$ is the mass of the mechanical system and $\delta$ is the phaseshift of the system.               m = 0.17869 + 0.01376/3;     \[Delta] = ArcTan[b/(m*(\[Omega]^2 - x^2))*x];      The experimental data:               data = {{0.7123448644,0.00246},{0.7324185582,0.00266},{0.7861292525,0.00328},{0.8523181889,0.00451},{0.9109116735,0.00647},{0.9282727060,0.00760},{0.9906639165,0.0114},{1.025928514,0.0152},{1.051970063,0.0222},{1.079096676,0.0131},{1.105138225,0.00865},{1.149625870,0.00549},{1.170242096,0.00455},{1.220155065,0.00336},{1.256504727,0.00267},{1.351990405,0.00184}};      The fitting function:               A[x_] := F/(m*\[Omega]^2*          Sqrt[   (x - \[Delta])^4                 + ((b/(m*\[Omega]))^2 - 2)*(x - \[Delta])^2                 + 1])      where $F$, $b$, and $\omega$ are parameters connected to the system. Determineing the missing parameters:               FindFit[data, A[x], {F, b, \[Omega]}, x]      > {F -> 0.00584067, b -> 0.972727, [Omega] -> -1.10514}               F = 0.005840667856395345;     b = 0.9727272619465833;     \[Omega] = -1.105138224999997;      Plot of data and the fitting curve:               Show[Plot[A[x], {x, 0.6, 1.5}, PlotRange -> Full], ListPlot[data, PlotStyle -> Red]]      > ![output](http://i.stack.imgur.com/JhB1r.jpg) It is obvious that the fitting is all wrong. How do I get the correct fitting parameters? I know that the fit should give approximately               F = 0.03     b = 0.14     \[Omega] = 12      P.S. I would think that executing the first command would assure that $\omega > 0$ when finding the fitting parameters, but this is obviously not the case.


title: How to input pure function to package?

text: I would like to input a pure function into a custom written package, but am running into a variety of errors. The package I have created is as follows:               BeginPackage["functions`"]          CosCoeff::usage="CosCoeff[m] returns cheb coeffs of order m of Cosine[2 Pi t]";          Begin["`Private`"]          ClearAll["Global`*"]          CosCoeff[m0_]:=     Module[{m=m0},     f[t]=Cos[2 Pi t];     Tn[t] = ChebyshevT[j, 2*t - 1];      wt[t] = 1/Sqrt[t - t^2];           p=Table[Chop[NIntegrate[f[t]*Tn[t]*wt[t], {t, 0, 1}]/(N[Pi]/2.0)], {j, 0, m-1}];     p[[1]]=p[[1]]/2;     p     ]          End[]     EndPackage[]      This package as stated creates a table containing "m" shifted-Chebyshev coefficients for the function `Cos[2 Pi t]`. How can I input any function, say Sin[2 Pi t], instead of writing a different module for every function I need to use?


title: Automatic e-mail/text message when a calculation has finished?

text: Sometimes _Mathematica_ takes quite a while to finish calculations and it would be convenient to be able to move away from the computer while it is working. I was wondering if there is any "clever" hack that can be used purely within _Mathematica_ to e-mail updates on the computation. I can think of a very rough way of getting an update other than actually accessing the machine, which would be by exporting some output to a file in Dropbox. From another machine connected to Dropbox I could see when the file is updated. But this seems to me like a very ugly solution. A less ugly solution would be to write an external script, probably with python, and then have _Mathematica_ run it at some point in the calculation. This would allow for both e-mail and text message updates (using Skype or a similar service and the appropiate python modules). Is there any way to do something similar purely within _Mathematica_?


title: Covariant derivative for symbolic tensors

text: I want to define a "prefix" (D_i) covariant derivative operator CD[] for symbolic tensors in form of a function, i.e. for               $Assumptions={Element[g,Arrays[{3,3},Reals,Symmetric[{1,2}]]]}      also               Element[CD[g],Arrays[{3,3,3},Reals,Symmetric[2,3]]]      should be made an assumption, an additional slot is created on the left. So far the only way I found to make this possible is defining a function               $Assumptions = {Element[v,Vectors[3, Reals]]}          CDdef[a_] := (AppendTo[$Assumptions,          Element[CD[a],Arrays[{3}~Join~TensorDimensions[a]],Reals,            TensorSymmetry[TensorProduct[v, a]]]];           $Assumptions =  DeleteDuplicates[$Assumptions]; CD[a])      and effectively writing all the assumption by hand into $Assumptions. But this could generate a huge list in bigger calculations. All my attempts of the kind               $Assumptions={Element[CD[a_?SomeSymmetryQ],Arrays["one more slot"]]}      to use pattern that are at least valid for all tensors with the same symmetries have failed. Is there any effective way to proceed? Many thanks, Hendrik


Why is Euler's number an uppercase "E" and not a lowercase "e"? Isn't Euler's Number normally expressed with a lowercase "e"?


title: Showing the value a plotted function achieves at the right-most point of the plot domain

text: I'm plotting results from NDSolve, and I'd like to clip them with their value at the point where the line is clipped. So where the curve ends at the edge of the plot, there would be a number indicating the y-value of the curve at that point. If that's not possible or too complicated, how can I include the end value of the plot in the legend? here's my plot command:                   Plot[{     Evaluate[Ca //. {parameters}] //. soln,     Evaluate[Cb //. {parameters}] //. soln,     Evaluate[Cc //. {parameters}] //. soln,     Evaluate[Ci //. {parameters}] //. soln,     Evaluate[Cd //. {parameters}] //. soln,     Evaluate[Ce //. {parameters}] //. soln,     Evaluate[Ch //. {parameters}] //. soln}, {w, 0, 500},      PlotRange -> All,      PlotLegends -> {Subscript[C, methane], Subscript[C, ethane],      Subscript[C, ethylene], Subscript[C, inerts], Subscript[C,      benzene], Subscript[C, naphthalene], Subscript[C, hydrogen]},      AxesLabel -> {"w", "C"}, AspectRatio -> 0.8,      PlotLabel -> "molar concentration vs catalyst weight"]


title: How can I emit a sound only during a mouseover?

text: Emitting a constant sound or note (no interruptions) for a fixed duration is easy, but a dynamic duration, not so easy.


title: Generating all "from n choose k" configurations of a simple list

text: Suppose that I have a 1-D list called `myList`. Here's an example:               myList = {"A", "B", "C", "D"};      I want to write (or find built-in) a function called `getConfigurations` that will return all possible "n choose k" lists. Before I explain what I mean by an "n choose k" list, let me just write down the result I would like to obtain from `getConfigurations` for the list `myList` given above:               getConfigurations[myList]      > >     { >   >       (* configurations when ONE element is chosen: k=1 *) >      {{"A"}, {"B"}, {"C"}, {"D"}}, >   >       (* configurations when TWO elements are chosen: k=2 *) >      {{"A", "B"}, {"A", "C"}, {"A", "D"}, {"B", "C"}, {"B", "D"}, {"C", > "D"}}, >   >       (* configurations when THREE elements are chosen: k=3 *) >      {{"A", "B", "C"}, {"A", "B", "D"}, {"A", "C", "D"}, {"B", "C", "D"}}, >   >       (* configurations when FOUR elements are chosen: k=4 *) >      {{"A", "B", "C", "D"}} >   >      } >   I am not sure what (if anything) this is called in combinatorics, but it reminds me of the binomial coefficient: $${n \choose k} = \frac{n!}{k! (n-k)!}$$ which I remember being called the "n choose k" binomial coefficient. In the example `myList` given above, $n = 4$ because `Length[myList]` is 4. For each value of k ($k = 1, 2, 3, 4$), I want to generate all possible configurations. In my case, order does **_not_** matter, so for example, `{"B", "A"}` is indistinguishable from `{"A", "B"}`. I think that the formula for $n \choose k$ gives the _number_ of configurations. It turns out that $${4 \choose 1} = 4$$ $${4 \choose 2} = 6$$ $${4 \choose 3} = 4$$ $${4 \choose 4} = 1$$ which can be seen from `Table[Binomial[4, k], {k, 1, 4}]`. **_However,_** I don't just want the _number_ of possible configurations for each k; instead, I want to actually generate the configurations themselves. **_Is there a simple and elegant -- or perhaps even built-in -- way to do this?_**


title: Plotting contours plot for f(x,y,z)=c

text: I have the following question: I have a file that has structure:               x1 y1 z1 f1     x2 y2 z2 f2     ...     xn yn zn fn      I can easily visualize it with _Mathematica_ using `ListContourPlot3D`. But could you please tell me how I can plot contour plot for this surface? I mean with these data I have a set of surfaces corresponding to different isovalues (f) and I want to plot intersection between all these surfaces and some certain plane. I tried to Google but didn't get any results. Any help and suggestions are really appreciated. Thanks in advance!


title: Temporarily redirect the output of Print[ ] to a second file

text: I have started using _Mathematica_ to automate file backup operations. The logistics I need make _Mathematica_ a good choice. I am testing and developing the Notebook manually, and `Print` outputs document the operational events. The saved Notebook provides a record of the process for that day. I would like to have an easy way to direct Print output to a separate file, for example, by adding               DirectPrintOutputTo["filename "<>DateList["Year","Month","Day"]<>".txt"]       at the beginning of a Notebook. The advantages of this approach seem obvious. I assume I would need to load my function from a package before calling it. Is something like this this possible? Any suggestions about how to do it? Alternatively, maybe I could write a print function called `PrintTo` that would, on first use, open an output file with the name assigned to `printToFileName`, and I could use the editor to change all the `Print` functions to `PrintTo` functions. Not so fancy, but I think I know how to how to do it. I think that I answered my own question, in the sense that my alternative idea seems straightforward and pretty implementable.


title: What's the best practice for nested local constants?

text: > **Possible Duplicate:**   >  How to avoid nested With[]? I have many situations where I have a constant that is local to a function, with other constants that are computed from it. I see that I can implement this using nested `With` statements, like               leapSeconds = With[{        usnoData =          Import["http://maia.usno.navy.mil/ser7/tai-utc.dat", "Text",           CharacterEncoding -> "UTF8"]},       With[{         lineLength = StringPosition[usnoData, "\n"][[1, 1]],         lsCount = Length[StringCases[usnoData, "\n"]] + 1},        DateList[#] & /@ (StringTake[             usnoData, {2 + #*lineLength, 9 + #*lineLength}] & /@            Range[0, lsCount - 1])]]      but this seems cumbersome. Is there a better way to do this sort of thing (I know that for this example I could dispense with the constants, but assume for the exercise that I do indeed need the constants)? Is nesting `With` statments a reasonable approach, or something I've just come up with by not understanding _Mathematica_ very well?


title: Reuse local variable in declaration within With

text: Considering the richness of Mathematica.SE, I am quite surprised I could not find my answer... I am very sorry if it is a duplicate. Consider the following example:               With[{t1=0,t2=t1},t1+t2] (* -> t1 *)      I thought it would print `0` instead of `t1`. Indeed, a `Trace` gives:                Trace@With[{t1 = 0, t2 = t1}, t1 + t2]      (* {With[{t1=0,t2=t1},t1+t2],0+t1,t1} *)      `t1` stays unevaluated. Considering the complex usage of Hold and such attributes for a Mathematica beginner like me and the documentation that states `With` has attribute `HoldAll`, I tried inserting `Evaluate` at various places, and also tried replacing `With` by `Module` (I admit the difference between `With` and `Module` is not obvious to me), but nothing printed me `0` instead of `t1`. How can I inform Mathematica to evaluate `t2=t1` with `t1` and `t2` declared within `With`? Edit: Thanks to the first comments and answer, some usefull and closely related question and answers can be found here.


title: Local variables whose definitions depend on each other

text: Consider the following (pseudo-)function definition:               f[l_] := Let[{               a = Length[l],               b = First[l],               c = b/a,              }, c*10]      So for instance, `f[{2,3,4,5}]` should output `5`. Currently, I only know variants for `Let` that   * set `a`, `b` and `c` globally (on the first call of `f`) or   * don't allow the definition of `c` because `a` and `b` are not defined. What is the most simple way to define _local_ variables whose definitions may depend on each other (upwards)?


title: FindRoot giving false roots with Bessel Functions

text: I have read in some places about the errors associated with FindRoot, but the closest thing I can find on this website seems to be due to the imaginary unit. I am dealing with what should be a relatively simple function for Mathematica to handle, namely a sum of Bessel functions of the first and modified first kinds. My code is               Zeros[z_] = (BesselJ[0, z] - BesselJ[2, z])*(3*BesselI[1, z] +        BesselI[3, z]) - (BesselI[0, z] +        BesselI[2, z])*(3*BesselJ[1, z] - BesselJ[3, z]);     FindRoot[Zeros[z]==0,{z,1}]      which returns 1.4371. But Zeros[1.4371]=-2.0754. I can also find roots by looking at the graph and basically bisecting by hand. My question is, should I rely on the plot, or the findroot algorithm? I am very familiar with Newton's Method (which is what I think FindRoot uses), but it does not make sense to me how it could guess such an erroneous root; this section of the plot shows none of the typical pitfalls of Newton's method. The second root on the other hand is at ~4.4, which the FindRoot algorithm finds to be 4.77493, which isn't a bad estimate given the slope of the function at this location. So, I guess my question boils down to, should I check (and believe) the plot or the FindRoot algorithm, or perhaps neither?


title: Calling part of a  variable in a user defined function

text: I have defined a function               logicalInputField[i_, fieldSize_, numberOfFields_, enable_,tx_,symbol_] :=     Column[{InputField[Dynamic[tx[[i]]], Number, ImageSize -> fieldSize,      Enabled -> enable, ContinuousAction -> True],       Dynamic[If[TrueQ[tx[[i]] == ""],                             (symbol[[i]] = "Please Enter"),(symbol[[i]] ="Right")                                                                                ]  ]}]       I am calling this function here.               DynamicModule[     {s = {}},      For[i = 1, i <= 3, i++,          With[{i = i},AppendTo[s, logicalInputField[i, {50, 20}, 3, True,{"", "", ""}, {"Please Enter", "Please Enter", "Please Enter"}]]]];          Panel[ Row[s]]]      I want to ask whenever I am not giving tx and symbol as an argument at the time of defining function. and then calling it, it works fine. But, as soon as I enter some value in `InputField` , it gives error message               Set::setps: {, ,} in the part assignment is not a symbol.      Why? How can I call the `Part` of a variable from the user defined function.


title: How to determine the center and radius of a circle given three points in 3D?

text: I was wondering if anyone could give me a hand with this problem I have. I have six points on a plane, and I am trying to determine if they form a circle or not. I know that any three points in 2D can determine a circle as long as the three points don't all lie on the same line. The way I figured that problem was taking two points, finding the line that connects them, finding the midpoint of that segment and then finding a perpendicular to the segment at that point. I do that with two segments and the intersection of the perpendicular lines that I find intersect at the center of the circle. When I follow the steps for the points I have in 3D, _Mathematica_ "gets stuck" when I ask it to find the equation of the line with the slope and the two points I give it (because the points have 3 coordinates and not two like in 2D). Any help is greatly appreciated! Thank you,


title: How to calculate an integral of an expression that is determined numerically (in Mathematica)?

text: First of all, I am fairly new to Mathematica and Stackoverflow, so please feel free to give me any advice whatsoever. I aim to calculate an integral of an expression that has been determined numerically. I will give a simple example: A solution (dependent on some parameter value a) is derived by               Clear[Sol]     Sol[a_] := FindInstance[x^2 == a, x]      and results are fine:               Sol[4]      gives               {{x -> 2}}.      Obviously, this special example could be solved algebraically, but since the set of equalities and inequalities I want to analyse is much more complicated, FindInstance (and therefore numerical evaluation) is the only option I could think of (the results from Reduce are to complicated to be checked by hand and I don't know how to elegantly get results from Reduce in an automated way; if you have recommendations on how to approach the results from Reduce, please let me know). I now aim to calculate the integral of the solution given above and try               In[3]:= NIntegrate[(x /. Sol[a][[1]]), {a, 1, 4}]          During evaluation of In[3]:= FindInstance::exvar: The system contains a nonconstant expression a independent of variables {x}.          During evaluation of In[3]:= ReplaceAll::reps: {x^2==a} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing.          During evaluation of In[3]:= NIntegrate::inumr: The integrand x/.x^2==a has evaluated to non-numerical values for all sampling points in the region with boundaries {{1,4}}.          Out[3]= NIntegrate[x /.Sol[a][[1]], {a, 1, 4}]      To mee, it seems like NIntegrate does not "take a value of `a` and plug it into `Sol`, calculate `Sol[a]` and proceed to the next value of a". Therefore I tried to force Mathematica to evaluate `Sol` with numerical values for `a` using commands like Evaluate, With, Block, Module but was unsuccesful (which might be due to poor understanding of these commands). Thanks for reading and maybe helping me out!


title: How to play with Facebook data inside Mathematica?

text: I saw this post from Wolfram here and I would like to know how to import facebook data into Mathematica.


title: How does FindInstance work?

text: I was asked a question one day: find an integer n such that the first five digits of 5*7^n is 12345. It's very nice that I can quickly write code like this:               Block[{n=1,x=5},       While[RealDigits[x=7.*x][[1,;;5]]!={1,2,3,4,5},n++];       n]//Timing          {55.86399999999998,456370}      It takes less than a minute. Later, I found that using the function `FindInstance` I could find a solution in much less time (but not the minimal solution):               FindInstance[{m+Log[10,1.2345]<Log[10,5.]+n Log[10,7.]<m+Log[10,1.2346],n>0},{m,n},Integers]//Timing          {0.3119999999999869,{{m->12872681,n->15232174}}}      Furthermore, I modified the code to be able to find the minimal solution like this:                NestWhileList[           n/.FindInstance[{m+Log[10,1.2345]<Log[10,5.]+n Log[10,7.]<m+Log[10,1.2346],First@#>n>0},{m,n},Integers]&,           n/.FindInstance[{m+Log[10,1.2345]<Log[10,5.]+n Log[10,7.]<m+Log[10,1.2346],n>0},{m,n},Integers],           #!={}&]//Timing              {11.872000000000007,{{15232174},{15188314},{10277666},{5410878},{2955299},{499720},     {497170},{496660},{496150},{494620},{493090},{492580},{492070},{490540},{490030},{489520},{489010},{478300},{456370},n}}      The time it takes is one fifth of that classic method. So, I found a new way to solve this class of questions (just in Mathematica)? My question is, can this method be used for other questions, and which mathematical method does the function `FindInstance` exactly use?


title: How to compute the Lovász number for the given graph in Mathematica?

text: Here is a graph whose adjacency matrix is               m = {     {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0},      {0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0},      {0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1},      {0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1},      {0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1},      {1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1},      {1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0},      {1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0},      {1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1},      {1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0},      {0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0},      {0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0}     };      then how to compute its Lovász number in _Mathematica_? I think this is a common question. Any help or suggestions will be appreciated! Here are three ways to do the computation, which is the best one to compile in Mathematica and how? 1.Let $G=(V,E)$ be a graph on $n$ vertices. Let $A$ range over all $n*n$ symmetric matrix|symmetric matrices such that $a_{ij}=1$ whenever $i=j$ or $ij∉E$, and let $λ_{max}(A)$ denote the largest eigenvalue of $A$. Then an alternative way of computing the Lovász number of $G$ is as follows: $$ \vartheta(G) = \min_A \lambda_\text{max}(A). $$ 2.The following method is dual to the previous one. Let $B$ range over all $n*n$ symmetric positive semidefinite matrix such that $b_{ij'}=0$ for every $ij ∈ E$ and $Tr(B)=1$. Here $Tr$ denotes trace (the sum of diagonal entries) and $J$ is the $n*n$ matrix of ones. Then $$ \vartheta(G) = \max_B \operatorname{Tr}(BJ). $$ Note that $Tr(BJ)$ is just the sum of all entries of $B$. 3.The Lovász number can be computed also in terms of the complement graph $\bar{G}$. Let $d$ be a unit vector and $V = (v_i | i ∈ V)$ be an orthonormal representation of $\bar{G}$. Then $$ \vartheta(G) = \max_{d,V} \sum_{i \in V} (d^\mathrm{T} v_i)^2. $$ Though PlatoManiac provided a helpful link, that way can not go through on my computer.


I had nice discussions with Leonid and Rojo that got me interested in tail recursion. Tail recursion is not always easy to realize with _Mathematica_ , so it would be nice to have some tools to help with this. The question is the title: What tools can help in realizing tail recursion?


title: How to run an external notebook from another notebook?

text: I have some initialization code for setting up context path, defining globally useful functions in a notebook (which are not suitable for a init.m). I have several notebooks that need to run those initialization code every time their content are used. What code should I put in the other notebooks to run the content of the initialization notebook?


title: ListPlot with labels that appear when the pointer goes over the points

text: I would like to generate a `ListPlot` with labels that appear when the pointer goes over the individual points. Specifically, I have a table of dimensions `{100,3}` and I want to use the first two columns for the plot and the third for the label. Does anyone know how to do that?


title: Manipulate: SetterBar with list of functions

text: From the documentation:               Manipulate[Plot[f[x], {x, 0, 2 Pi}], {f, {Sin, Cos, Tan, Cot}}]      How do I include a function like $1/x$ or $x^2$, etc. in that list? I (unsuccessfully) tried `1/#` and `#^2`.


title: FindMinimum produces error message

text: I'm trying to solve a logistic regression problem using _Mathematica_ -- more to improve my _Mathematica_ skills than to solve the problem as I have already solved it using Octave. The problem I am experiencing is with the FindMinimum function which always returns an error no matter what I do. I have tried it without passing the gradient function and it produces the error: > Encountered a gradient that is effectively zero. If I pass it the gradient function, I get the error: > The gradient is not a vector of real numbers at {θ} = {{{0.}, {0.}, {0.}}}. I've read through other posts with similar problems but none of recommended solutions work for me. Below is the code from my Notebook (I hope you can copy and paste it into your own notebook).               data = {{34.62365962451697`, 78.0246928153624`, 0}, {30.28671076822607`,          43.89499752400101`, 0}, {35.84740876993872`, 72.90219802708364`,          0}, {60.18259938620976`, 86.30855209546826`, 1}, {79.0327360507101`,          75.3443764369103`, 1}, {45.08327747668339`, 56.3163717815305`,          0}, {61.10666453684766`, 96.51142588489624`, 1}, {75.02474556738889`,          46.55401354116538`, 1}, {76.09878670226257`, 87.42056971926803`,          1}, {84.43281996120035`, 43.53339331072109`, 1}, {95.86155507093572`,          38.22527805795094`, 0}, {75.01365838958247`, 30.60326323428011`,          0}, {82.30705337399482`, 76.48196330235604`, 1}, {69.36458875970939`,          97.71869196188608`, 1}, {39.53833914367223`, 76.03681085115882`,          0}, {53.9710521485623`, 89.20735013750205`, 1}, {69.07014406283025`,          52.74046973016765`, 1}, {67.94685547711617`, 46.67857410673128`,          0}, {70.66150955499435`, 92.92713789364831`, 1}, {76.97878372747498`,          47.57596364975532`, 1}, {67.37202754570876`, 42.83843832029179`,          0}, {89.6767757507208`, 65.79936592745237`, 1}, {50.534788289883`,          48.85581152764205`, 0}, {34.21206097786789`, 44.20952859866288`,          0}, {77.9240914545704`, 68.9723599933059`, 1}, {62.27101367004632`,          69.95445795447587`, 1}, {80.1901807509566`, 44.82162893218353`,          1}, {93.114388797442`, 38.80067033713209`, 0}, {61.83020602312595`,          50.25610789244621`, 0}, {38.78580379679423`, 64.99568095539578`, 0}};      Break data into correct matricies               myX = Take[data, All, 2];     myy = Take[data, All, -1];      Categorize rows as 0 or 1               posRows = Flatten[Position[myy, {1}]];     negRows = Flatten[Position[myy, {0}]];      Plot the dataset               resultsPlot =      ListPlot[{Partition[Riffle[myX[[posRows, 1]], myX[[posRows, 2]]], 2],         Partition[Riffle[myX[[negRows, 1]], myX[[negRows, 2]]], 2]},        PlotMarkers -> {"X", "O"}, PlotLegends -> {"Positive", "Negative"},        Frame -> True]      Fill out the X matrix by prepending a column of 1's               myX = PadLeft[myX, {Length[myX], 3}, 1];      Create the working functions Sigmoid function - used to ensure we have a convex function with no local minima               sigmoid[mat_] := 1 /(1 + E^-mat);      Cost function               cost[θ_, X_, y_] := Module[{m, hThetaX},       m = Length[y];       hThetaX = sigmoid[X.θ];       Flatten[1/          m*(-y\[Transpose].Log[hThetaX] - (1 - y)\[Transpose].Log[1 - hThetaX])]       ]      Gradient function               grad[θ_, X_, y_] := Module[{m, hThetaX},       m = Length[y];       hThetaX = sigmoid[X.θ];       Flatten[1/m*(hThetaX - y)\[Transpose].X]       ]      Test the functions               thetaInitial = {{0}, {0}, {0}}          cost[thetaInitial, myX, myy][[1]]     grad[thetaInitial, myX, myy]      > >     Out[105]= 0.693147 >   >     Out[106]= {-0.0333333, -6.63738, -6.82055} >   These are the expected results. Find the values of theta that minimise the cost               FindMinimum[cost[θ, myX, myy][[1]], {θ, thetaInitial}, Gradient -> grad[θ, myX, myy]]      > During evaluation of In[108]:= FindMinimum::nrgnum: The gradient is not a > vector of real numbers at {θ} = {{{0.},{0.},{0.}}}. >> >   >   >     Out[108]= {0.0333333, {θ -> {{0.}, {0.}, {0.}}}} >   ----- EDIT ----- As per requests, I've added the full notebook below in one block to make it easier to copy and paste for testing.               data = {{34.62365962451697`, 78.0246928153624`, 0}, {30.28671076822607`,          43.89499752400101`, 0}, {35.84740876993872`, 72.90219802708364`,          0}, {60.18259938620976`, 86.30855209546826`, 1}, {79.0327360507101`,          75.3443764369103`, 1}, {45.08327747668339`, 56.3163717815305`,          0}, {61.10666453684766`, 96.51142588489624`, 1}, {75.02474556738889`,          46.55401354116538`, 1}, {76.09878670226257`, 87.42056971926803`,          1}, {84.43281996120035`, 43.53339331072109`, 1}, {95.86155507093572`,          38.22527805795094`, 0}, {75.01365838958247`, 30.60326323428011`,          0}, {82.30705337399482`, 76.48196330235604`, 1}, {69.36458875970939`,          97.71869196188608`, 1}, {39.53833914367223`, 76.03681085115882`,          0}, {53.9710521485623`, 89.20735013750205`, 1}, {69.07014406283025`,          52.74046973016765`, 1}, {67.94685547711617`, 46.67857410673128`,          0}, {70.66150955499435`, 92.92713789364831`, 1}, {76.97878372747498`,          47.57596364975532`, 1}, {67.37202754570876`, 42.83843832029179`,          0}, {89.6767757507208`, 65.79936592745237`, 1}, {50.534788289883`,          48.85581152764205`, 0}, {34.21206097786789`, 44.20952859866288`,          0}, {77.9240914545704`, 68.9723599933059`, 1}, {62.27101367004632`,          69.95445795447587`, 1}, {80.1901807509566`, 44.82162893218353`,          1}, {93.114388797442`, 38.80067033713209`, 0}, {61.83020602312595`,          50.25610789244621`, 0}, {38.78580379679423`, 64.99568095539578`, 0}};          myX = Take[data, All, 2];     myy = Take[data, All, -1];          posRows = Flatten[Position[myy, {1}]];     negRows = Flatten[Position[myy, {0}]];          resultsPlot =      ListPlot[{Partition[Riffle[myX[[posRows, 1]], myX[[posRows, 2]]], 2],         Partition[Riffle[myX[[negRows, 1]], myX[[negRows, 2]]], 2]},        PlotMarkers -> {"X", "O"}, PlotLegends -> {"Positive", "Negative"},        Frame -> True]          myX = PadLeft[myX, {Length[myX], 3}, 1];          sigmoid[mat_] := 1 /(1 + E^-mat);          cost[\[Theta]_, X_, y_] := Module[{m, hThetaX},       m = Length[y];       hThetaX = sigmoid[X.\[Theta]];       Flatten[1/          m*(-y\[Transpose].Log[hThetaX] - (1 - y)\[Transpose].Log[1 - hThetaX])]       ]          grad[\[Theta]_, X_, y_] := Module[{m, hThetaX},       m = Length[y];       hThetaX = sigmoid[X.\[Theta]];       Flatten[1/m*(hThetaX - y)\[Transpose].X]       ]          thetaInitial = {0, 0, 0}          cost[thetaInitial, myX, myy][[1]]     grad[thetaInitial, myX, myy]               FindMinimum[cost[\[Theta], myX, myy][[1]], {\[Theta], thetaInitial},       Gradient -> grad[\[Theta], myX, myy]]


title: Simulated Annealing for NMinimize[] always returning the same solution

text: I have a function defined as follows:               fourVertIsoHamilt[x11_, x12_, x13_, x14_, x21_, x22_, x23_, x24_, x31_, x32_, x33_, x34_, x41_, x42_, x43_, x44_] :=        fourVertEnrgy[x11, x12, x13, x14, x21, x22, x23, x24, x31, x32, x33, x34, x41, x42, x43, x44]      + fourVertPenIso[ x12, x21, x22, x23, x24, x32, x33, x34, x44];      Where,               fourVertEnrgy[x11_, x12_, x13_, x14_, x21_, x22_, x23_, x24_, x31_, x32_, x33_, x34_, x41_, x42_, x43_, x44_] :=      1 + 2 x11 x12 + 2 x11 x13 + 2 x11 x14 + 2 x12 x13 + 2 x12 x14 + 2 x13 x14 - x11 - x12 - x13 - x14 +      1 + 2 x21 x22 + 2 x21 x23 + 2 x21 x24 + 2 x22 x23 + 2 x22 x24 + 2 x23 x24 - x21 - x22 - x23 - x24 +      1 + 2 x31 x32 + 2 x31 x33 + 2 x31 x34 + 2 x32 x33 + 2 x32 x34 + 2 x33 x34 - x31 - x32 - x33 - x34 +      1 + 2 x41 x42 + 2 x41 x43 + 2 x41 x44 + 2 x42 x43 + 2 x42 x44 + 2 x43 x44 - x41 - x42 - x43 - x44 +      1 + 2 x11 x21 + 2 x11 x31 + 2 x11 x41 + 2 x21 x31 + 2 x21 x41 + 2 x31 x41 - x11 - x21 - x31 - x41 +      1 + 2 x12 x22 + 2 x12 x32 + 2 x12 x42 + 2 x22 x32 + 2 x22 x42 + 2 x32 x42 - x12 - x22 - x32 - x42 +      1 + 2 x13 x23 + 2 x13 x33 + 2 x13 x43 + 2 x23 x33 + 2 x23 x43 + 2 x33 x43 - x13 - x23 - x33 - x43 +      1 + 2 x14 x24 + 2 x14 x34 + 2 x14 x44 + 2 x24 x34 + 2 x24 x44 + 2 x34 x44 - x14 - x24 - x34 - x44;      and,               fourVertPenIso[ x12_, x21_, x22_, x23_, x24_, x32_, x33_, x34_, x44_] :=      x12 x24 + x12 x34 + x12 x44 + x22 x44 + x32 x44 + x21 x32 + x21 x33 + x21 x34 + x22 x33 + x23 x34;      I would like to minimize it using NMinimize with Simulated Annealing options. So, Mathematica the code is:               NMinimize[{fourVertIsoHamilt[x11, x12, x13, x14, x21, x22, x23, x24, x31, x32, x33, x34, x41, x42, x43, x44],      x11 \[Element] Integers, x12 \[Element] Integers, x13 \[Element] Integers,    x14 \[Element] Integers, x21 \[Element] Integers,    x22 \[Element] Integers, x23 \[Element] Integers,    x24 \[Element] Integers, x31 \[Element] Integers, x32 \[Element] Integers, x33 \[Element] Integers, x34 \[Element] Integers, x41 \[Element] Integers,    x42 \[Element] Integers, x43 \[Element] Integers,    x44 \[Element] Integers,      0 <= x11 <= 1, 0 <= x12 <= 1,    0 <= x13 <= 1, 0 <= x14 <= 1, 0 <= x21 <= 1, 0 <= x22 <= 1,    0 <= x23 <= 1, 0 <= x24 <= 1, 0 <= x31 <= 1, 0 <= x32 <= 1,    0 <= x33 <= 1, 0 <= x34 <= 1, 0 <= x41 <= 1, 0 <= x42 <= 1, 0 <= x43 <= 1, 0 <= x44 <= 1},      {x11, x12, x13, x14, x21, x22, x23, x24, x31, x32, x33, x34, x41, x42, x43, x44},   Method -> "SimulatedAnnealing"]      The global minima is zero which I am getting correctly. The problem is the only configuration my code is suggesting for the global minima is:               x11 -> 0, x12 -> 0, x13 -> 1, x14 -> 0, x21 -> 0, x22 -> 0, x23 -> 0, x24 -> 1, x31 -> 0, x32 -> 1, x33 -> 0, x34 -> 0, x41 -> 1, x42 -> 0, x43 -> 0, x44 -> 0      I repeated 10 times and got the same configuration all the time for the global minima 0. Why isn't my code ever getting other solutions like:               x11-> 0, x22-> 0, x34->1, x43->1


title: Approximate to the speed of Build-In functions

text: In _Mathematica_ , there is a function `PowerMod[a,b,m]`, which computes `a^b mod m`. I will concern only this case: `b = -1, m is a power of a prime, say m = p^N`. When b=-1, the result of `PowerMod[a,-1,m]` is the number `a' such that a*a' = 1 mod m`, i.e the inverse of a in `mod m`. There is a standard way to compute this inverse (when m is a prime power), but I will just give the code. The idea is to use Newton's method (in `p-adic` sense).               pAdicInverse[n_Integer,p_Integer,N_Integer]:=Module[          {stepMax,a,a0,x},          stepMax=Floor[Log2[N]]+1;     a=Mod[n,p^N];     a0=Mod[a,p];     x=PowerMod[a,-1,p];          Do[x=Mod[x*(2-a*x),p^2^i],{i,1,stepMax}];          x=Mod[x,p^N]          ]   /;(PrimeQ[p] && N>=1)      This gives the correct answer, but the build-in `PowerMod[a,-1,p^N]` is 15x faster than the above code. I would like to know how to speed up it. I thought to use something like `Nest` or `Fold`, but I didn't figure it out. The reason is that: In each step of `Do`, it works with different modulo `p^2^i`. Of course I can do it use the same modulo `p^N` all the time, but it will be much slower, even if I use `Nest`. This is not really important, but I wonder how to speed it.


title: Why the Mouse dragging response not as smooth as Locator

text: I am experimenting to use `MouseDragged` eventhandler to change the vertices positions of a triangle, it works, but not as smooth as using Locators. Is this the correct way to handle mouse dragging? Would someone please help to improve the response speed.               DynamicModule[{ pos1 = {1, 0}/2 , pos2 = {1, 1}/2 , pos3 = {-1, 0}/2},      edglst = { 1 <-> 2 , 2 <-> 3 , 3 <-> 1   };       Dynamic@Graph[        { EventHandler[1, {"MouseDragged" :> (pos1 = MousePosition["Graphics"])}],          EventHandler[2, {"MouseDragged" :> (pos2 = MousePosition["Graphics"])}],           EventHandler[3, {"MouseDragged" :> (pos3 = MousePosition["Graphics"])}]} ,        edglst,        VertexCoordinates -> {pos1, pos2, pos3 } ,        VertexSize -> 0.08, VertexLabels -> "Name",        PlotRange -> 1, EdgeStyle -> {Thick}, ImagePadding -> 10]]


title: How to create an ImagePartition type-of-function that generates parts of different sizes

text: Background: I partition images to polygons ( squares ) and color them with VertexColors. I want to use a minimal number of polygons while still showing a clear resemblance of the original image. - Some images need more squares in the centre than along the edges ( i.e. portraits ). I want to create an ImagePartition type-of-function that uses a finer grid closer to the middle of a picture. For example:                1-1 1-2 1-3 1-4 1-5      2-1 .           2-5      3-1 .           3-5      4-1 .           4-5      5-1 5-2 5-3 5-4 5-5      ( 5-by-5 )      The missing part                2-2 2-3 2-4      3-1 3-2 3-3      4-1 4-2 4-3       is replaced with pieces from a 10-by-10 partitioning, i.e. 2-2 by:                3-3 3-4      4-3 4-4      and so on, until 4-3 is replaced with                 7-7 7-8       8-7 8-8       from the 10-by-10 partitioning. Finally 3-2 or ( 5-5, 5-6 / 6-5, 6-6 ) is replaced with the results from a 20-by-20 partitioning.                9-9  9-10  9-11   9-12      10-9 10-10 10-11 10-12      11-9 11-10 11-11 11-12      12-9 12-10 12-11 12-12.      In the case of 6-by-6 partitioning also three levels of partioning are used, in this case 6-by-6, 12-by-12, 24-by-24. And so on. **Question: How to create an alternative ImagePartition function that creates a finer grid closer to the centre of the image. The output lists should be arranged in such a way that it is easy to re-assemble the image from the pieces.**


title: Order of symbols in Graphics labels

text: Do you have any idea how to force an order of Greek letter in the graphics? When I type in               AxesLabel -> {Cost, Δ OverBar[π]}      the order is π Δ. How can I force it to be Δ π?


title: How to work out the parameter in a definite integration which has an exact value while the integration doesn't have an analytical solution?

text: Here is the equation I'm trying to solve:               NIntegrate[1/(E^(1/(λ T)) - 1), {λ, 200, 220}] == 1000      `T` is the parameter I'm trying to work out. I tried to solve it with `InverseFunction[]` but it seemed not to work:               te[ii_] := InverseFunction[NIntegrate[1/(-1 + E^(1/(# λ))), {λ, 200, 220}] &][ii]     Evaluate[te[1000]]      What's wrong with my solution? How to correct it?


title: NDSolve + FindRoot for Bessel Zeros

text: I am trying to use a solution given by Michael E2 in this topic:               Zeros[z_] = (BesselJ[0, z] - BesselJ[2, z])*(3*BesselI[1, z] +        BesselI[3, z]) - (BesselI[0, z] +        BesselI[2, z])*(3*BesselJ[1, z] - BesselJ[3, z]);          (zeros = First @ Last @ Reap @ Quiet @ NDSolve[        {y'[x] == Zeros'[x], y[0] == Zeros[0],          WhenEvent[y[x] == 0, Sow[FindRoot[Zeros[z], {z, x}]]]},         y, {x, 0, 40}, AccuracyGoal -> 1, PrecisionGoal -> 1]) // AbsoluteTiming      -- to find roots for my equation: $$ J_1(a/z)\, Y_0(b/z)-J_0(a/z)\,Y_1(b/z)=0, \quad a=10, \;b=1, $$ but get an error               First::first: "{} has a length of zero and no first element."      The problem is that "y(x)=0" event doesn't happen. I understand that the functions are quite different, so I perform the following: $$ J_1(a/z)\; Y_0(b/z)-J_0(a/z)\; Y_1(b/z)=0 \rightarrow\\ \rightarrow \left( J_1(a\tilde z)\; Y_0(b\tilde z)-J_0(a\tilde z)\; Y_1(b\tilde z) \right)\; e^{-100/\tilde z}=0, ~\tilde z = 1/z $$ to make my function to be more like the original one, but still get the error. Could anyone help, please? My code (I mean, the original code with my function) is below.               Sigma = 1;     xi1 = 10;     Zeros[z_] =        (BesselJ[1, xi1*z]*BesselY[0, Sigma*z] -         BesselJ[0, Sigma*z]*BesselY[1, xi1*z])*Exp[-100/z];     (zeros = First@     Last@Reap@       Quiet@NDSolve[{y'[x] == Zeros'[x], y[0] == Zeros[0],       WhenEvent[y[x] == 0, Sow[FindRoot[Zeros[z], {z, x}]]]},      y, {x, 0, 10}, AccuracyGoal -> 10, PrecisionGoal -> 10]) // AbsoluteTiming


title: Dial control for Manipulate?

text: I'm trying to make a control item in a `Manipulate` that is a simple dial. I'm trying to mimic `Manipulate[theta, {theta, 0, 360}]`, but with a `dial` instead of a `Slider`. I've sort of done this (see code below), but my variable pt doesn't reset to its original value when I hit the `ResetButton`. Any help would be appreciated.               DynamicModule[      {pt = {0.5, 0.5}},      Manipulate[       ArcTan @@ pt,       DynamicModule[        {},        LocatorPane[         Dynamic[pt],         Graphics[          {           Line[{{1.1, 0}, {0, 0}}],           EdgeForm[Thin],           {LightGray, Disk[]},           {Lighter@Lighter@LightGray, Disk[{0, 0}, 0.9]},           Dynamic[Disk[0.7 Normalize[pt], 0.08]]           },          PlotRange -> 1.3,          ImageSize -> 60],         Appearance -> None         ]        ],       AppearanceElements -> "ResetButton"       ]      ]


title: Simplifying polynomials in non-commutative variables

text: I would like to be able to simplify a polynomial in two non commuting variables, the desired result being that in every term one variable occurs to the left of the other variable. An example would be the normal ordering of operators from the Weyl algebra. In addition, I would like to be able to specify the commutation relation as well. Say, if the variables are $a$ and $b$, I would like to specify an equation involving $a$ and $b$ which is equal to zero. For example $ab-ba-1=0$ in the case of the Weyl algebra. I've tried the non commutative multiplication $**$. It appears that this function is simply formal multiplication. I tried inputting $a**b**b$ but it's not even giving me $ab^2$. (2)


title: Mouse cursor very slight difference

text: Mathematica uses a very thin, translucent cursor in Input style cells. But in text style cells Mathematica uses a cursor theme from Windows. How do I make the cursor visible as normal? photos of display: ![enter image description here](http://i.stack.imgur.com/0P0DW.jpg) ![enter image description here](http://i.stack.imgur.com/PoL9N.jpg)


title: Specific Mathematica algorithms, for example LU Decomposition

text: Where I can find detailed information on algorithms used by Mathematica, especially for numerical methods. The Manual doesn't seem to iclude specifics in most cases. For example I get a different LU Decomposition of a matrix using Mathematica's LUDecomposition than when I implement the Crout algorithm, even thought I believed it to be standard and having a unique solution.


title: String encoding issue with Pythonika

text: I use Mathematica and Pythonika to run Python code inside it. And I'm not quite sure what causes my issue: all `unicode` Python objects look like this: `А\\.00л\\.00е\\.00к\\.00с` (instead of `Александр`), i.e. there is an extra symbol after each letter, and thus the string is truncated (its length remains same). At the Pythonika page the author mentioned that unicode is supported, although not well-tested. Anyone experienced this? What are the possible workarounds?


title: Create polygon using edge lengths and area

text: Four-sided convex land plots are usually denoted with edge lengths and area. How do I create a Polygon Object with these parameters in Mathematica ?


title: How to move the axes back in Plot?

text: I'd like to draw some curves using Plot, and I tried follow codes:                Plot[Table[n/Sqrt[\[Pi]] Exp[-n^2 x^2], {n, {3, 5, 7}}], {x, -1, 1},       PlotStyle -> Directive[Black, Thick],       AxesStyle ->       Directive[Arrowheads[0.04], GrayLevel[0.7], Thick, Opacity[1]],      Ticks -> None, PlotRange -> {{-1.2, 1.2}, {-0.7, 4.5}},       AspectRatio -> 1, RegionFunction -> Function[{x}, Abs[x] < 1]]      Then it comes out this: ![enter image description here](http://i.stack.imgur.com/HE9Fa.jpg) Which I confused is that the gray axes are in the front of the black curves(esp. for the x axes). How can I move the axes backward to show my curve well?


title: X-axis obscuring a vector that lies along it

text: I am having the following problem. I am playing with `Manipulate` and I would like to draw a vector overlapping an axis (x-component of a vector), and I would like the vector to be blue. But the axis is in the foreground, therefore I don't see the color. How can I bring the arrow in foreground? Anyone have encountered this? I can post code if it helps.


title: Problems with PlotStyle in mathematica 10

text: **Bug introduced in 9.0** * * * The simplest way to ask is to post the code of what I'm doing:               ListPlot[{Table[x, {x, 1, 10, 1}], Table[x + x^2, {x, 1, 10, 1}]},        PlotMarkers -> None, PlotRange -> All,        PlotStyle -> {        {Thickness[.005], Dashing[{.03, .015}], ColorData[1, 1]},           {Thickness[.0075], ColorData[1, 1]}},       Joined -> True     ]      When I did this in _Mathematica_ 8, the first line was dashed and the second line was a thicker, solid line of the same color: ![enter image description here](http://i.stack.imgur.com/5xU8g.png) Now having upgraded to _Mathematica_ 10 and the second line is also dashed, same as the first: ![enter image description here](http://i.stack.imgur.com/8dlQT.png) It seems that if I leave out an explicit `Dashing[{x,x}]` command, the curve inherits the last dashing style, rather than go back to the default! How do I get the second curve to be solid? More importantly, what has changed in _Mathematica_ 10 that causes this? Obviously, my real task is more complicated than this, but this will reproduce the behavior.


title: Parametric Plot of coupled differential equations

text: I am able to plot a graph of all the differential equations, but I'd like a parametric plot of each individual one. Here is what I have so far.               new = Join[     Table[x[i]''[t] == - x[i][t] +        0.1*(x[i + 1][t] - 2*x[i][t] + x[i - 1][t]), {i, 1,       9}], {x[0]'[t] == -x[0][t], x[10]'[t] == x[9][t], x[0][0] == 0,      x[1][0] == 1}, Table[x[i][0] == 0, {i, 2, 10}],      Table[x[i]'[0] == 1, {i, 1, 9}]];          Solt[i_] = NDSolve[new, Table[x[i][t], {i, 0, 10}], {t, 10}]          Plot[Evaluate[Table[x[i][t], {i, 10}] /. Solt[i_]], {t, 0, 10}]          Table[ParametricPlot[     Evaluate[{x[i][t], x[i]'[t]} /. Solt[i_]], {t, 0, 10}], {i, 1, 10}]      What is wrong with the parametric plot. I've done this one before (without the added forcing term). It won't show up.


title: Changing default window appearance

text: Since every single time I start Mathematica, my first action is aligning the windows properly (Notebook on the left for $2/3$ of the screen, help on the right for the other $1/3$), I was wondering whether this could be done automatically. This is what it looks like: ![enter image description here](http://i.stack.imgur.com/FBM01.png) How could I make Mathematica to use these window positions and sizes by default?


title: GUI Maker? Is there a perhaps drag and drop GUI maker for Mma?

text: IDE's like Borland, Eclipse, and others have ways of making GUI's. Drag and drop is usually the way of it. Then one puts the variables together and links up everything. Mma seems to handle (at least so far) in the GUI development department like Machine language. One had to develop ones own libraries of codes to paste into the existing. Is there a more graphical way of designing GUI's in Mma? Know of anyone working on this? A thought here is the Mma Options menu and many others. Someone wrote all of that code by hand. Seems like a good job for a computer. Drag and drop. Drag a button onto the "screen" and give it a variable name. Drag an Text input field onto the screen and give it a variable name. Drag a DB handler onto the screen (not front end) and link it up. Or perhaps a separate question Linking an Eclipse generated Java Front end, that is GUI to Mma. Probably a JLink question?


title: Quickly editing the stylesheet and saving it

text: I have a private stylesheet I'm using. I edit it by going to the menu Edit->Edit Stylesheet and then clicking on the private stylesheet cell. I can modify whatever I want but it never gets saved. The notebook option Saveable can be set to True (is by default False) but that still doesn't change the fact that in order to save it I can only do it by going to Save AS, and making it replace itself. To do that I have to go to the `$UserBaseDirectory`, SystemFiles, FrontEnd, StyleSheets, not practical... The question is implicit, can you help out?


title: Data acquisition from a Measurement Computing USB device

text: I would like to use **Mathematica 9** for to acquire data from a _Measurement Computing_ (MC) USB-201 analog to digital (and other) device for classroom demonstration. I do not have a budget to buy _LabView_ and link Mathematica with it to accomplish what I would like to. Within Mathematica I have tried using `Manipulate` to see if I can detect a signal (anything) from this board (excited artificially with a variable 0-5V source). So far, I do not see any changes indicating I am communicating with this equipment. Has anyone done something like this? Do I need a driver, and if so, where do I get it? Clearly, I am **not** a DAQ expert. I need someone to speak slowly and distinctly so I can understand them. Thank you.


title: Solving a linear system

text: When I tried to solve the equation below, I got the $4$ errors. Since I am pretty new on _Mathematica_ , I don't know what I did wrong. > > $24x_1+20x_2+16x_3=4$   >  $20x_1+20x_2+19x_3=36$   >  $16x_1+19x_2+38x_3=19$ This system is set to solve in Jacobi method after $40$ iterations. Initial approximation is $x_1(0)=0, x_2(0)=0, x_3(0)=0$. I would appreciate it if someone could recommend other methods that I can use for this system!


title: Manipulate and FileNameSetter don't want to play nice together

text: In a `Manipulate`, one can specific the type of an individual control like so:               Manipulate[v, {v, Red, ColorSetter}]      I tried to do the same with `FileNameSetter`, i.e.               Manipulate[v, {v, "no file chosen", FileNameSetter}]      but that doesn't work, and the control is a slider. I can work around the issue like so:               Manipulate[{v, FileNameSetter[Dynamic[v]]}, {v, "no file chosen"},        ControlType -> None]      but I would rather understand why my second example above doesn’t behave as expected. Do you have any idea?


title: Differential equation of a physical property which can not be below zero

text: A simple question but maybe also interesting for others. I have the simple differential equation:               a'[t] == -r      The quantity a has a physical meaning and can not be below 0. The ODE is of course simple to solve but I don't know how to tell DSolve to restet `a` to `0` if it is below zero. My approach now is to simple manipulate the result:               sol = DSolve[{a'[t] == -r, a[0] == 1}, a[t], t]     solspecial = sol /. r -> 0.1     Table[{t, Max[(a[t] /. solspecial), 0]}, {t, 0, 15}]     ListLinePlot[%, PlotRange -> All, Frame -> True,       FrameLabel -> {"time", "a"}]      ![fig 1](http://i.stack.imgur.com/y8TUZ.png) Is there a better way to do this and already state that `a` can not be below 0 in DSolve or NDSolve? edit: to clarify only negative values are reset to 0 and if `r=Sin[t]` the value should "come back". ![enter image description here](http://i.stack.imgur.com/DScvI.png)


title: make a list based on two other lists

text: I have two lists:               list1={4,6}     list2={1,2}      and I now want a function f that produces               f[list1_,list2_]:={1,1,1,1,2,2,2,2,2,2}      so 4 times the 1 and 6 times the 2. f should be generic so that               3list1={2,3,7}; 3list2={1,2,3}      yields               res={1,1,2,2,2,3,3,3,3,3,3,3}      If you know several ways to do this please provide the fastest one. thanks a lot.


title: Cannot launch MathLink from C

text: I am trying to launch a MathLink from a 64bit C dll that I am building, using the following code:               #include "mathlink.h"          static MLENV ep = (MLENV)0;     static MLINK lp = (MLINK)0;          __declspec(dllexport) int __stdcall init()     {       int err;       char * argv[3];       int success = 1;            argv[0] = "-linklaunch";       argv[1] = "-linkname";       argv[2] = "'\"C:\\Program Files\\Wolfram Research\\Mathematica\\9.0\\MathKernel.exe\" -mathlink'";            ep =  MLInitialize((char *)0);       if(ep == (MLENV)0) success = 0;            lp = MLOpenArgcArgv(ep, 3, argv, &err);            if(lp == (MLINK)0) success = err;            return success;     }      However, when calling this `init()` function, I always get the error code 34, indicating that the specified link protocol is unavailable. I tried specifying a link protocol (SharedMemory,Pipes,...) using the `-linkprotocol` argument for `MLOpenArgcArgv()`, but without any change. Although the error code referes to the link protocol, I also tried different formats for the MathKernel.exe directory (e.g. `\\\\\\\` for backslashes, different quotes, ...), but nothing changed. Using 0 for argc and a null pointer for argv also doesn't change anything. The necessary files for MathLink devices (mlshm64.mlp etc.) are all in their correct place (System32 folder for x64). I can also launch the MathKernel.exe from the command line without problems, and a different C program using MathLink which I'm accessing through the `Install[]` function in Mathematica is running fine on the same computer. My system:   * Win7 x64   * Mathematica 9   * DLL compiled with MinGW x64, using an import library for ml64i3.dll generated with gendef/dlltool (see http://forums.wolfram.com/mathgroup/archive/2012/Jun/msg00323.html) Any ideas what could be causing this error? **Edit** I now got the same code running by compiling it in Visual Studio 2013 as a DLL and linking to the same MathLink DLL - still not sure why compiling in MinGW doesn't work though.


title: Graphics with shapefiles using tooltip

text: I'm trying to write a code that displays an entire shapefile color-coded by one variable, and then as the mouse is moving it shows the local regional area of interest with all its data Got a working code, but it doesn't seem efficient as I'm overlaying two different graphics, one with zero opacity. Is there a better way of implementing the code? (Edit: Using Mathematica 9.0)               data = Import["http://exampledata.wolfram.com/usamap.zip", "Data"][[2]];     {Labels, BlockData} = Map[("LabeledData" /. data) /. Rule[a_, b_] :> # &, {a, b}];     ColorBy = "AREA";     Data4Color = ColorBy /. ("LabeledData" /. data);     Geometry = "Geometry" /. data;     labeled = {Data4Color, Geometry} // Transpose;     gathered = GatherBy[labeled, First@# &];     (* http://mathematica.stackexchange.com/a/20207/8757 *)     InteractiveToolTip =       Table[         Tooltip[Geometry[[i]], {Graphics[Geometry[[i]]],          TableForm[{Labels, BlockData[[All, i]]} // Transpose]}],          {i, Dimensions[Geometry][[1]]}];       h1 = MapIndexed[{ColorData[1] @@ #2, Tooltip[#[[All, 2]], #[[1, 1]]]} &, gathered];     Graphics[{h1, {Opacity[0], InteractiveToolTip}}, ImageSize -> Full]      ![Mathematica graphics](http://i.stack.imgur.com/ahZSd.png)


title: Simplification with assumptions

text: I'm trying to make Mathematica do some simplifications for me. I have the expression               ((1 + s[1]) (-1 + s[2]) )/(-1 + s[1] s[2])      and want to simplify this with the assumption that               s[1]^2==1      (it should simplify to 1+s[1], as can be verified manually) I obviously tried               Simplify[((1 + s[1]) (-1 + s[2]) )/(-1 + s[1] s[2]), s[1]^2 == 1]      to no avail. Is there any way I can persuade Mathematica to do this for me? Edit: Here's the manual simplification: $$ \frac{(1 + s[1]) (-1 + s[2])}{-1 + s[1] s[2]}=\frac{(1 + s[1])(-1+s[1]^{-1})(-1+s[1]s[2])+(-1+s[1]^{-1})+(-1+s[1]s[2]) }{-1 + s[1] s[2]}=\frac{(1 + s[1])((-1+s[1])(-1+s[1]s[2])+(-1+s[1])+(-1+s[1]s[2]))}{-1 + s[1] s[2]}=\frac{(1 + s[1])((-1+s[1])(-1+s[1]s[2])+(-1+s[1])+(-1+s[1]s[2]))}{-1 + s[1] s[2]}=\frac{(1 + s[1])(-1+s[1])((-1+s[1]s[2])+1)+(1+s[1])(-1+s[1]s[2])}{-1 + s[1] s[2]}=\frac{0((-1+s[1]s[2])+1)+(1+s[1])(-1+s[1]s[2])}{-1 + s[1] s[2]}=1+s[1] $$


title: How to use the function ImageCorrelate?

text: ![explanation of Correlate](http://i.stack.imgur.com/S1Ijv.png) I am a beginner in using Mathematica, know little about optics. However, I would like to know how to understand the function `ImageCorrelate`, since the introduction in Mathematica Book is too brief and not quite informative. I've read a solution here, How can I extract data points from a black and white image? But can not understand this ![code](http://i.stack.imgur.com/G1PMe.png)


title: Create a graph from KML file

text: I'm wondering how I can take a .KML (Keyhole Markup Language) file and convert/express it as a graph for use in Mathematica. Even just in general, is it possible to convert a KML file to a graph? I'm hoping to express the US railroad system in the 19th century as a graph using this data: http://railroads.unl.edu/resources/


title: Convert a number to a string to use in plot axes label, but keep the exponent

text: This seems to be a simple, but useful question. I am plotting a basic function:               multiplier = 10^11;     func = 10^-11 x^2;     Plot[func*multiplier, {x, 0, 5},        AxesLabel -> {x, "Distance, \!\(\*SuperscriptBox[\(10\), \(-11\)]\) m"}]      That gives the result I wish to see. Imagine now that I wish not to write the multiplier manually in `AxesLabel` when I change it. The inverse multiplier needs to be converted to a string with an exponent (so as to produce the same final appearance). I have tried the `ToString` function with some parameters. For example:               multiplier = 10^11;     func = 10^-11 x^2;     Plot[func*multiplier, {x, 0, 5},        AxesLabel ->          {x, "Distance, " <> ToString[multiplier^(-1), FormatType -> StandardForm] <> " m"}]      But I get an awful label.   1. Could you think of a solution to this problem?   2. Can anyone think of why conversion to real numbers by "N" is necessary and if not how can it be avoided?


title: CDF with numerous independent manipulate objects

text: I have been working on my senior project that involves the creation of a CDF with multiple `Manipulate`expressions. I need to protect my code so I have been trying to create/encode a package that will run the program. I have gotten the program to work flawlessly as a notebook in MMA, but as a CDF I get shadowing errors. I have 54 functions in the code and many of my functions use the same variables which are changed by the user input. I have tried to put all of the code in a single package then set the initialization of each `Manipulate` to the same package, but I get errors. It seems like I need to have a package for each `Manipulate`, then have a function at the beginning of the program to call each package. I am not sure. Here is a scaled-down version.               Manipulate[dummyFunctionToDefineNullSet[],        Initialization :> (SuccessfulShotsFor = {};)]          <someManipulateObject>            Manipulate[iSSF[],        Initialization :> (         iSSF[] :=           (PopupWindow[               Button[Style[SomeStyle], , Background -> SomeBackground],                Button[                 (ptevent0 :=                    (If[Extract[#, {1}] < 575, {1150, 740} - #, #]) &;                   Show[Image, ImageSize -> {1150, 740}]),                  AppendTo[SuccessfulShotsFor, ptevent0[MousePosition["Graphics"]]],                  Appearance -> Frameless],              WindowTitle -> "Successful Shots For", WindowFrame -> "Normal",              Background -> RGBColor[51/240, 163/240, 220/240],              Editable -> False, TextAlignment -> Center ,              WindowSize -> {1200, 825}, WindowFloating -> False,              WindowMargins -> {{0, Automatic}, {Automatic, 0}}]))]          <someManipulateObject>          Manipulate[      Quiet[dSSF[SuccessfulShotsFor]],       Initialization :> (        dSSF[          SuccessfulShotsFor_] :=             (Check[               ImageCompose[                 SmoothDensityHistogram[SuccessfulShotsFor,                    AspectRatio -> Full, PlotRange -> {{0, 1150}, {0, 740}},                    ColorFunction -> "GreenPinkTones", Frame -> False,                    PlotRangePadding -> 0, ImageSize -> {1150, 740}],                  SomeImage],                "ERROR: no user input"]             Check[              ImageCompose[                ListPlot[SuccessfulShotsFor,                   AspectRatio -> Full, PlotRange -> {{0, 1150}, {0, 740}},                   PlotMarkers -> {SomePlotMarker}, Frame -> False,                   PlotRangePadding -> 0, ImageSize -> {1150, 740},                   Background -> RGBColor[0, 62/240, 5/240], Axes -> False],                 SomeImage],               "ERROR: no user input"]))]          <someManipulateObject>      `SuccessfulShotsFor` has been giving me a ton of trouble. Once in a package, the value (which gets changed by the user input on the second `Manipulate`) takes on a different name which does not get passed on to the third `Manipulate`, which displays the images for the user to copy. I am running these CDFs in _Mathematica_. I read about the `$ContextPath`, and I think that is the where the problem lies, but I am not experienced enough to implement the fix.


title: Importing specific elements from JSON

text: I'm having trouble importing JSON in the way I expect, based on my reading of the documentation. The particular issue I'm having is with importing a specific element, or list of elements. From the doc: > `Import["file.json", "elem"]` imports the specified element from a JSON > file. To test this, I'm trying the following:               In[1]:= Export["out.json", {"x"->42,"y"->17.5}]     Out[1]= out.json      The resulting file looks like:               {"x" : 42,      "y" : 17.5}      Importing the entire file works, returning a list of rules:               In[2]:= Import["out.json"]     Out[2]= {x -> 42, y -> 17.5}      But, importing a specific element fails:               In[3]:= Import["out.json", "x"]     Import::noelem: The Import element "x" is not present when importing as JSON.     Out[3]= $Failed      What am I missing? Perhaps "element" doesn't mean what I think it means?


title: How can I rewrite my game without using Manipulate?

text: **Snake Games**               Module[     {dir = {-1, 0}, x = -1., y = 0., snake = Table[{i, 0}, {i, 0, 4}],     gameover = False,     target = {RandomInteger[17] - 9, RandomInteger[17] - 9},     timecount = 0,     score = 0},     Manipulate[     If[      Mod[timecount, 5] == 0 && u != {-1, -1} && gameover == False,     x = u[[1]];     y = u[[2]];     dir = If[      y >= x,      If[y >= -x, {0, 1}, {-1, 0}],      If[y >= -x, {1, 0}, {0, -1}]      ];      If[       MemberQ[snake,          snake[[1]] + dir] || (snake[[1]] + dir)[[          1]] < -10 || (snake[[1]] + dir)[[1]] >          9 || (snake[[1]] + dir)[[2]] < -10 || (snake[[1]] + dir)[[2]] >          9,       gameover = True;       score = Length[snake] - 5       ];      If[       (snake[[1]] + dir) == target,       target = {RandomInteger[17] - 9, RandomInteger[17] - 9},       snake = Most[snake]       ];      PrependTo[snake, snake[[1]] + dir]      ];     timecount++;     Framed[      Graphics[      If[       False == gameover,       Append[        Table[Rectangle[i, i + {1, 1}], {i, snake}],        Rectangle[target, target + {1, 1}]        ],       {Rectangle[{-10, -10}, {10, 10}],         Text[Style[" Game over! ", FontSize -> 36], {0, 3},          Background -> White],         Text[Style[" Score: ", FontSize -> 24], {0, 0},          Background -> White],         Text[Style[score, FontSize -> 24], {0, -2}, Background -> White]}        ],        Axes -> False, PlotRange -> {{-10, 10}, {-10, 10}},         ImagePadding -> 0        ],       FrameMargins -> 0      ],     {u, {-1, -1}, {1, 1}}, ControlPlacement -> Right     ]     ]      It is not convenient for the user to play this game in the above form. So how can I rewrite it without using `Manipulate`, but using other functions that can provide a better user interface?


title: Figuring when the minute and hour hand coincide on a clock

text: I would like to list all possible times in a 12-hour period, where the hour hand overlaps the minute hand completely. This is really a question about three distinct things - to be done in Mathematica - though only the first of the following points really interests me:   * Finding solutions to an equation with several variables, where each variable has _different_ restrictions on its domain;   * Formatting those solutions in a convenient format;   * Using those solutions to draw the actual clocks! So what we have is two different variables, $h$ and $m$. $h$ is an integer, between $0$ and $11$, and $m$ is a real number, between $0$ and $60$. We want solutions to when $$ 30h - \frac{11m}{2}=0 $$ within those domain restrictions. I have tried using both `Solve` and `Reduce`, but neither seems capable of giving me anything more than conditional expressions. So I would like to find all possible solutions, format them in a nice hour:minute format, and maybe even draw the actual clocks corresponding to these solutions. The formatting and drawing are actually not that hard (though elegant, efficient, and different solutions are certainly welcome); I am truly interested in mixing the domains for $h$ and $m$ above, and getting meaningful answers. Please feel free to tag as you feel appropriate.


title: How can I set a fixed cell height?

text: I did this often in previous versions of the Mathematica notebook front end. I would have a cell with lots of raw data, e.g. a very long list. The list might go on for pages. I would set the cell to have a fixed cell height using the options inspector. I could then drag a little box on the bottom of the cell bracket to show only a small fraction, say, the top three and half lines of the input. (I would cut it off in the middle of a line, showing the top half of the characters in the line, in order to make it clear that only a portion was visible.) I can no longer find this option in Mathematica 8 (Mac OS X). Does anyone know if it may be lurking somewhere else?


title: How do I save the last graphical output of Animate so as to make it the background for the next Animate?

text: I am making an instructional program in which a random number appears and moves across and down into the appropriate bin, landing on top of the existing stack. Then another number appears, repeating the animation sequence until it lands on top of its own stack. When any stack reaches the top, the animation stops and this example of the distribution can be observed. Thus,I wish to combine a sequence of animations, using the output of one to serve as the background to the next. How can I save the final graph of each `Animate` sequence so as to use it for the input of the next? The fact that animations are examples of `Manipulate` complicates matters. `Do` loops, etc. do not work here.


title: Why doesn't the FileNameSetter button work in my DialogInput?

text: I am new to _Mathematica_ , so it's probably a small error but I can't figure it out. Here is the code :               DialogInput[{TextCell["Choose your folder:"], InputField[Dynamic[x]],        FileNameSetter[Dynamic[x], "Directory"],        DefaultButton[DialogReturn[x]]}]      When I click on the browse button, nothing happen. Then, when I click on OK, the file system browsing window appears.


title: Can the general term my recurrence equations be written with Floor or Mod?

text: I want to know the formula for the general term of the following recurrence system. I guess it can be written with `Floor` or `Mod`. How can I find it?               RSolve[{a[n + 5] == a[n] + 6, a[1] == 1, a[2] == 3, a[3] == 2, a[4] == 1, a[5] == 1}, a[n], n]          DiscretePlot[-2 + (6 n)/5 +        2/5 Sqrt[28 + 53/Sqrt[5]]         Sin[(2 n \[Pi])/5 - ArcTan[15/Sqrt[85 + 38 Sqrt[5]]]] +        2/5 Sqrt[28 - 53/Sqrt[5]]         Sin[(4 n \[Pi])/5 - ArcTan[3 Sqrt[5 (85 + 38 Sqrt[5])]]], {n, 1,        20}]      **Updated** I would like to have the formula for the general term without using recursion just as               RecurrenceTable[{y[n + 5] == y[n] + 1,        Sequence @@ Table[y[i] == i, {i, 5}]}, y, {n, 1, 30}]      can be written               n - 4 Floor[(n - 1)/5] /. n -> Range@30


title: Copy TraditionalForm output to TraditionalForm input while keeping formatting

text: When I want to copy a scientific notated number from a TraditionalForm output to an input it formats it in a weird way: ![enter image description here](http://i.stack.imgur.com/yRa83.png) Another thing I want to do is only copy a few number of decimals, and remove the accent (`), at the end: ![enter image description here](http://i.stack.imgur.com/wMPbY.png)


title: Programmatic formatting for Mathematica code - possible?

text: It seems to be both an interesting programming challenge and a very useful practical application to have a Mathematica program which would allow one to pretty-print Mathematica code, so that it is easy to read and understand. Some of the desirable features of such a program:   * Works both on string and box level   * Covers many or most common cases for Mathematica code   * Is robust   * Is customizable   * Is extensible Is this possible?


title: How to catch the "Preemptive" evaluations from within the main loop?

text: When trying to make an optimized version of my `plotRange` fonction I faced a problem of catching the `"Preemptive"` evaluations generated by the FrontEnd from withing the main evaluation loop. Consider the following:               ClearAll["Global`*"]     xr[r__] := (xRange = {r}; None);     yr[r__] := (yRange = {r}; None);     nb = CreateDocument[{Plot[Sin[x], {x, 0, 6 Pi}, Ticks -> {xr, yr}]}];     {xRange, yRange}     Pause[1];     {xRange, yRange}     NotebookClose[nb]      > {xRange, yRange} > > {{-0.392699, 19.2423}, {-1.04167, 1.04167}} One can see that the first evaluation of `{xRange, yRange}` returns undefined symbols because at the moment of its evaluation the functions `xr` and `yr` are still not evaluated via a `"Preemptive"` link by the FrontEnd. But after waiting one second these functions are already evaluated and `xRange`, `yRange` are defined. Because I need these values for further evaluations I need to delay the main loop until the `"Preemptive"` evaluations will be done. (An alternative solution would be to force the FrontEnd to perform its evaluations in the main loop.) One possible way to solve the problem is to initiate a `Dialog` which will wait for the `Return` generated by the FrontEnd. But `"Preemptive"` evaluations go past the `Dialog` and do not allow the return from it (the following code freezes the kernel):               Dialog[xr[r__] := (xRange = {r}; None);      yr[r__] := (yRange = {r}; None; NotebookClose[nb];         Return[{xRange, yRange}]);      nb = CreateDocument[{Plot[Sin[x], {x, 0, 6 Pi},           Ticks -> {xr, yr}]}];]      Is it possible to catch the `"Preemptive"` evaluations from the main loop in some way? ## UPDATE Here is a comparison of my original `Rasterize`-based version and the new `FinishDynamic`-based:               gr = Plot[Sin[x], {x, 0, 6 Pi}];     plotRange[plot : (_Graphics | _Graphics3D)] :=       Quiet@Last@        Last@Reap[          Rasterize[           Show[plot, PlotRangePadding -> None, Axes -> True,             Ticks -> (Sow[{##}] &), DisplayFunction -> Identity],            ImageResolution -> 1]]     Table[plotRange[gr], {100}]; // AbsoluteTiming          plotRange[plot : (_Graphics | _Graphics3D)] :=       Quiet@Last@        Last@Reap[(nb =             CreateDocument[{Show[plot, Axes -> True,                Ticks -> (Sow[{##}] &), PlotRangePadding -> None,                DisplayFunction -> Identity]}, ShowCellBracket -> False,              WindowFrame -> "Frameless", WindowElements -> {},              WindowSize -> 1, Antialiasing -> False, Editable -> False,              Magnification -> 1, Saveable -> False,              WindowClickSelect -> False, WindowFloating -> False,              WindowFrameElements -> {}, WindowMovable -> False,              WindowSelected -> False, WindowTitle -> ""];           FinishDynamic[]; NotebookClose[nb])]     Table[plotRange[gr], {100}]; // AbsoluteTiming      > {2.828125, Null} > > {8.406250, Null} The original `Rasterize`-based version is 3 times faster.