title: Complex result for Real vectors in VectorAngle

text: I was expecting a real angle using VectorAngle when passing real valued vectors, however I obtained a complex angle.               VectorAngle[{-2.7432000000000016`, 0.`, 0.`},{2.743199999999973`, 0.`, 0.`}]      returns               3.14159 - 2.10734*10^-8 I      I was expecting 3.14159 (pi) as this is essentially a half circle. My guess is the precision of the numbers results in the imaginary portion. 3 possible solutions are:   * using Round[result,10^-7], which works for this case, but future cases might have an imaginary part larger than 10^-8    * using Re[result], a better solution. Interestingly, using Round on the vectors to some sufficiently small value results in an exact solution. For example I rounded to the nearest 10^-100 and got the exact value of pi Going forward I'll probably just take the real part of the result, but is this the expected behavior in Mathematica for this function?


title: Get rid of "Testing Notebook" toolbar

text: I was messing around with different styles and tried the MUnit style. I converted back to Standard Report but I still see the toolbar for testing notebook. Is there a way to get rid of it? ![Want to get rid of this "toolbar"](http://i.stack.imgur.com/m8W1p.png)


title: Solving a system of nonlinear equations?

text: I'm relatively new to using Mathematica so I'm not sure if this is really even possible, but I figured it may be worth a try. In my Physical Chemistry class today, we were learning about acid/base equilibria, and for one particular problem it came to a point where we had a system of 6 unknowns in 7 equations, however these were nonlinear equations so simple calculator tools and matrices wouldn't be sufficient to calculate them. So I thought perhaps Mathematica would be powerful enough to be able to write a script of some sort to be able to solve them. The equations in question are as follows. Typically these variables are actually concentrations of some compound, but I've just replaced them with letters to make it simple: 1: x + y = 2z + a + b 2: x + c = 2(z + a) 3: 276 = (x^2)(z) 4: 5.7x10^-10 = [(y)(c)]/(x) 5: 9.8x10^-13 = [(b)(a)]/(z) 6: 9.25 = -log(y) 7: 1x10^-14 = y + c and we need to solve for x, y, z, a, b, and c. Can this really be done in a simple way? Thanks for any input!


title: Row-Reduced-Echelon-Form with Equation Parameters for Consistent Systems

text: I often do row-reduced-echelon-form (RREF) calculations that involve parameters using the _RowReduce_ command. Most times, I want to know which parameters make the system consistent. For example:                RowReduce[{{1, 2, 3, a}, {4, 5, 6, a^2}, {7, 8, 9, a^3}}]      Mathematica reduces this to its lowest form, which results in an inconsistent system because the last row is {0,0,0,1}. However, if you look at the details of the the steps it takes (using WA with rref {{1, 2, 3, a}, {4, 5, 6, a^2}, {7, 8, 9, a^3}}), it shows the point where you could see that choosing $a = 0$ or $a = 1$ would produce a consistent system with infinite solutions. Either of these values for $a$ makes the last row of the rref {0,0,0,0}. Is there a way to get Mathematica to show this reduction without losing that important fact or to state which values of the parameters make the system consistent? Maybe I should be using a different command or approach. It is also interesting that rref is able to successfully find the result for this two parameter example:                RowReduce[{{a, b, 1, 1},{1, a b, 1, b},{1, b, b, 1}}]


title: How to programmatically remove menu items

text: I would like to do the opposite of what is described here. So rather than add a menu item I would like to programmatically remove one (or more). So given a knowledge of the structure of the menu *.tr file ![enter image description here](http://i.stack.imgur.com/MKQAu.png) ...I am looking for something like `RemoveMenuCommands` such that if I wanted to remove **Format > Clear Formatting** I could enter something like this:               FrontEndExecute[RemoveMenuCommands[{"Format", "Clear Formatting"}]]      Does anyone have any thoughts?


title: What's wrong with my graph input?

text: So I saw this picture on my book and it was left as an exercise to figure out. ![enter image description here](http://i.stack.imgur.com/vbtyD.png) This is what I have so far, but I'm not sure where I went wrong.                Plot[{t^3 - t}, {t, -1, 1}, PlotStyle -> Blue, Exclusions -> {t == 1},Exclusions -> {t == -1}, Exclusions -> {s == 2/(3*Sqrt[3])},Exclusions -> {s == -2/(3*Sqrt[3])}, ExclusionsStyle -> {Pink}]             I think somewhere I should use Epilog for that red dot, but with my original input incorrect, I cannot go any further.


title: How to be faster at making a frequency list of increasing steps

text: I want to find propabilities of having a sequence in a list, by using frequencies. The case is that you will bet on an increase when the last event had an increased and bet on derease when the last event had a decrease. This is what I found. But I want to do it faster an with more a lot more data               imput = {395.13, 395.24, 391.25, 394.76, 395.15, 394.9, 396.31,        394.46, 394.8, 396.28, 397.66, 396.86, 394.48, 396.4, 396.14,        396.62, 395.58, 391.69, 387.08, 384.91, 388.26, 386.84, 384.7,        381.6, 377.44, 375.98, 380.49, 379.66, 385.17, 388.34}               growth = Ratios[imput] - 1      > >     {0.000278389, -0.0100951, 0.00897125, 0.000987942, -0.000632671, >      0.00357052, -0.00466806, 0.000861938, 0.00374873, 0.00348239, >     -0.00201177, -0.00599708, 0.00486717, -0.000655903, 0.00121169, >     -0.00262216, -0.00983366, -0.0117695, -0.00560608, 0.00870333, >     -0.00365734, -0.005532, -0.00805823, -0.0109015, -0.00386816, >     0.0119953, -0.0021814, 0.014513, 0.00823013} >   (I delete zeros, so I have a smooth list, but it is not necessary)               sign = Sign[growth]      > >     {1, -1, 1, 1, -1, 1, -1, 1, 1, 1, -1, -1, 1, -1, 1, -1, -1, -1, -1, >     1, -1, -1, -1, -1, -1, 1, -1, 1, 1} >                 direction = Drop[Prepend[sign, 0]*Append[sign, 0], -1]      > >     {0, -1, -1, 1, -1, -1, -1, -1, 1, 1, -1, 1, -1, -1, -1, -1, 1, 1, 1, >     -1, -1, 1, 1, 1, 1, -1, -1, -1, 1} >   (this is to see when we where right. the first time there is no prediction so we where wrong either way. The second time predicted an increase, since 380.49 was bigger then 375.98 and the last event had an increase, but returned a decrease (379.66). So the second time we lost. etc)               row = Quiet[       RecurrenceTable[{a[day + 1] ==           If[Part[Drop[direction, 1], day] > 0.5,            a[day] + Part[Drop[sign, 1], day], Part[Drop[sign, 1], day]],          a[1] == Part[sign, 1]}, a, {day, 1, Length[Drop[sign, 1]]}],        Part::pspec]      > >     {1, -1, 1, 2, -1, 1, -1, 1, 2, 3, -1, -2, 1, -1, 1, -1, -2, -3, -4, >     1, -1, -2, -3, -4, -5, 1, -1, 1} >   (I am not proud of this formula, so I hope someone has an easyer way for doing this. This finds the length of a sequence increase or decrease in a row. Where "-2" means the second decrease in a row.)               frequencyRow = Table[Count[row, Part[row, n]], {n, Length[row]}]          {9, 8, 9, 2, 8, 9, 8, 9, 2, 1, 8, 3, 9, 8, 9, 8, 3, 2, 2, 9, 8, 3, 2,      2, 1, 9, 8, 9}      (where this is the secon formula i dont like, which shows the frequency of the amount of times it increases or decreases on the places of the bet)               chanceRow = Round[frequencyRow/Length[row], 0.01]      > >     {0.32, 0.29, 0.32, 0.07, 0.29, 0.32, 0.29, 0.32, 0.07, 0.04, 0.29, >     0.11, 0.32, 0.29, 0.32, 0.29, 0.11, 0.07, 0.07, 0.32, 0.29, 0.11, >     0.07, 0.07, 0.04, 0.32, 0.29, 0.32} >   (where this is the chance of the event) Please help me polishing this, it does not matter if it is a totally different way as long as it is easier or fast, because I just really don't like the recurrence table (since I want to upgrade this project to a function like `chanceRow[x1_,x2_,x3_]:=` and the recurrence table then gets slow or shows errors)


title: Density map strange mapping of color

text: I tried to convince _Mathematica_ 8 to plot a density map of a function: $$f(x,y) = \frac{2(x^2 - y^2)-1}{(x^2 + y^2)^2}$$ with color scheme called "TemperatureMap". At $x = \pm 1$, $y = 0$ it's completely correct, but at $y = \pm 1$, $x = 0$, it shows white color, where, in fact, it should be blue. I'm only interested in the region $x^2 + y^2 > 1$, so I added the command: `ColorFunctionScaling -> False` and manually rescaled my function to take values only between 0 and 1: $$g(x,y) = \frac14 (3+f(x,y))$$ as I know where the maxima and minima occur in the region I'm interested in. The plot is even more strange, leaving almost no blue and, of course, at $x = 0, y = \pm 1$ it's white. Whole input I used was (PlotPoints so I can get higher quality plot, Exclusions so I can see where's the boundary of region I'm interested in):               DensityPlot[(3 + 2*(x^2 - y^2)/(x^2 + y^2)^2 - 1/(x^2 + y^2)^2)/       4, {x, -3, 3}, {y, -3, 3}, PlotPoints -> 100,       ColorFunction -> "TemperatureMap", Exclusions -> {x^2 + y^2 == 1},       ColorFunctionScaling -> True]      ![Mathematica graphics](http://i.stack.imgur.com/3SdZj.png) I expected a similar density map to the second image on this page. Instead the space approximately $(y/1.2)^2 + x^2 < 1$ is white. The region left of the white part is not exactly an ellipse, it looks like a ladyfinger. Where did I make a mistake? I tried to plot a constant function 0 and 1 while `ColorFunctionScaling` being false and it correctly showed whole plot blue and red respectively. I don't have the slightest clue what went wrong. I'd appreciate any help.


title: To write an array by varying two variables

text: I have a equation G=2X+Y, Now i changed X and Y together from 1 to 10 . I got various values Of G. I have done this by using Table command ,Now I want to plot a graph between G and X, i could not find any command to plot this.can you help me


title: Testing Equality Expression?

text: Even if in               Graph[{1 -> 2}] == Graph[{1 \[DirectedEdge] 2}]      the answer is `True` ; but why MMA doesn't show the result of the following expression?Neither `True` nor `False`.What is the reason?               {1 -> 2} == {1 \[DirectedEdge] 2}


title: Time approximation of decrypting RSA algorithm

text: I've written a function that encrypts a text using the RSA algorithm. It then decrypts it using prime factorization, and takes the time it took to decrypt it and puts it in a vector together with the length of the N variable in the RSA algorithm. I do this with a length of N from 28 to 61. I can then plot this is a graph, and try to estimate how long it would take to prime factorize an N length of 100 or larger. My problem is that I can find no suitable way to fit my values into a graph that then makes a reasonable approximation of the time it would take for say an N of the length of 100. I am using `Fit` and `FindFit`, but all of my results either end up negative for `Length[N] = 100`, or they end up something like 2 years, which is not a reasonable answer. These are my values with the length of N at index 1 and then the time in seconds at index 2.               {{28, 0.016}, {29, 0.}, {32, 0.062}, {33, 0.063}, {36, 0.062}, {37,        0.109}, {40, 0.187}, {42, 0.265}, {43, 0.281}, {45, 0.858}, {48,        4.04}, {50, 4.805}, {52, 7.941}, {54, 12.512}, {54, 11.497}, {57,        19.952}, {60, 103.803}, {61, 102.009}}      I can plot it as follows:               plot = ListPlot[TidN, PlotStyle -> Red];     a1 = a /. FindFit[TidN, a*b^x, {a, b }, x]     b1 = b /. FindFit[TidN, a*b^x, {a, b }, x]     modelplot = Plot[a1*b1^x, {x, 32, 100}, AxesLabel -> {x, y},        PlotRange -> {{20, 70}, {0, 50}}];     Show[modelplot, plot]      This results in the following: ![enter image description here](http://i.imgur.com/ISwEk.jpg) I then try to estimate the time it would take to factorize the length of an N of 100, like this:               a1*b1^100/(3600*24*365)      This gives the result in years, which isn't reasonable at all. It should, I believe, be more close to 100 years:               0.628951      How can I plot this better, and how can I find a function that estimates large numbers more easily? I can of course let my computer run and gather more data points from which I can establish a better function perhaps, but should this really be necessary since I already have 18 points to start from?


title: How do I avoid vector variables being treated as scalars in the course of replacements?

text: I often work with a mixture of symbolic and concrete values as I develop teaching materials. I introduce variables symbolically and then need to instantiate them to specific values while continuing to use the original variables. My `i` represents a vector `{1, 0, 0}` but I don't want to replace `i` with `{1, 0, 0}` _everywhere_ , just when convenient. Thus I lit upon the idea of using replacement rules rather than definitions. But things didn't work out too well:               {a, a + b} //. {a -> 4 i, b -> {0, -2, 2}, i -> {1, 0, 0}}     (* output: {{4, 0, 0}, {{4, 0, 0}, {2, -2, -2}, {6, 2, 2}}} *)      while I wanted this result instead:               {a /. {a -> 4 i}, (a /. {a -> 4 i}) + b} //. {b -> {0, -2, 2}, i -> {1, 0, 0}}     (* output: {{4, 0, 0}, {4, -2, 2}} *)      I now understand that `4 i` is treated as a constant in rewriting `a + b`:               {a, a + b} /. {a -> 4 i, b -> {0, -2, 2}}     (* output: {4 i, {4 i, -2 + 4 i, 2 + 4 i}} *)      I could attempt to control the substitution order by doing something like               {a, a + b} //. ({a -> 4 i, b -> {0, -2, 2}} /. i -> {1, 0, 0}) //. {i -> {1, 0, 0}}     (* output: {{4, 0, 0}, {4, -2, 2}} *)      But this is not very robust and won't work if substitutions are nested more deeply. I can prevent premature application of the problematic rule using conditions e.g.               {a, a + b} //. {a :> 4 i /; i ∈ Vectors[v], b -> {0, -2, 2}, i -> {1, 0, 0}}      But then the rule never gets used as the RHS of the rule is never rewritten. I don't really want to recast all the vector operators I might need following the example of this answer; this seems like overkill.   But I do already use a wrapper `bv[i]` which prints as `UnderBar[i]`. Can anyone suggest a lightweight solution? Could I make `Plus`, `Times` etc. (temporarily) _un_ -listable? BTW This issue is flagged in the documentation for `Assuming`, which does not help in this situation as `Plus` just goes ahead and uses its `Listable` attribute:               Assuming[v ∈ Vectors[2], v + {1, 2}]     (* output: {1 + v, 2 + v} *)


title: How can I make many runs of a simulation and plot all the results with one expression evaluation?

text: I have many cells, starting with this first cell:               mcRun = 20;     randomWalk[n_] := RandomVariate[NormalDistribution[0, 1], n];           RandVar = Table[randomWalk[5], {mcRun}];     Length[RandVar]      MatrixForm[RandVar[[1 ;; 10]]] (* only display first 10 *)     ListPlot[RandVar]      Then later in a 2nd cell:               CorRandVar = RandVar * 10;      Still later in a 3rd cell:               InvCor = CDF[NormalDistribution[], CorRandVar];      And there are many more cells that depend on the value of the initial parameter `mcRun` that I defined in the first cell. At the moment I use 'Evaluate Notebook' to get my results. I wait for one 'Evaluate Notebook' to complete, note down the result from running with `mcRun = 20` (20 monte carlo simulations), edit `mcRun = 20` to another value and repeat. So how could I automate what 'Evaluate Notebook' does and plot, for example, `InvCor` (or any function/value) as a function of the input parameter `mcRun`, say, from 20 to 20,000? ? Or better, how could I incorporate my simulation into a `Manipulate` to add interactivity?


title: How can Mathematica be used to detect an area surrounded by the most lines?

text: I have an array of lines that produce random shapes. These lines define edge boundaries from an array that I would like to use to reconstruct the main feature of the array. Can Mathematica find the points where most of these lines cross, and then define the largest area(s) inside these crossing points? I assume this will give me the main area(s) of the array to look at as in the example plot image. These lines are boundary lines and crossing too many reduces the accuracy of the area plot. There are 4 lines creating most boundaries. The first of those 4 is the line used in the plot below               lines={{{900., 703.449}, {590.556, 0.}}, {{900., 475.145}, {651.23, 0.}}, {{900., 286.849},      {660.333, 0.}}, {{900., 503.578}, {178.177,0.}}, {{0., 707.111}, {900., 689.133}}, {{231.482, 1093.}, {302.527, 0.}}, {{853.322, 1093.}, {568.821, 0.}}, {{513.461, 1093.},     {411.662, 0.}}, {{900., 521.686}, {514.729, 0.}}, {{280.141, 1093.}, {248.479, 0.}}, {{0., 183.582},      {900., 312.065}}, {{0., 648.073}, {900., 682.241}}, {{0.,110.149}, {900., 507.127}}, {{0., 402.186},      {900., 389.603}}, {{900., 605.326}, {324.743, 0.}}, {{706.587, 1093.}, {720.777, 0.}}, {{900., 86.9532},      {769.336, 0.}}, {{900., 539.768}, {610.491, 0.}}, {{900., 464.134}, {113.723, 0.}}, {{900.,428.16},      {47.3056, 0.}}, {{0., 1000.61}, {900., 988.023}}, {{316.911, 1093.}, {889.171, 0.}}, {{0., 337.878},      {900., 399.087}}, {{0., 492.562}, {900., 451.191}}, {{0.,344.122}, {900., 272.07}}, {{0., 151.791},      {900., 369.811}}, {{502.51, 1093.}, {352.038, 0.}}, {{0., 136.204}, {900.,460.163}}, {{177.623, 1093.}, {404.553, 0.}}, {{900., 234.416}, {665.35, 0.}}, {{900., 679.326}, {446.947, 0.}}, {{900., 1089.37}, {312.902, 0.}}, {{0., 652.435}, {900., 207.253}}, {{900.,115.841}, {712.418, 0.}}, {{900., 806.604}, {220.582, 0.}}, {{0., 783.297}, {900., 616.042}}, {{0., 1055.81}, {900., 938.313}}, {{300.376, 1093.}, {156.573, 0.}}, {{684.328, 1093.},      {770.733, 0.}}, {{0., 679.389}, {900., 733.378}}, {{900.,135.671}, {751.702, 0.}}, {{0., 1052.08},      {900., 822.61}}, {{900., 544.556}, {246.914, 0.}}, {{900., 879.237}, {32.7302, 1093.}}, {{0., 972.41},      {900., 956.231}}, {{0., 1026.6}, {900., 857.481}}, {{619.175, 1093.}, {818.911, 0.}}, {{0., 9.58286},      {900., 624.196}}, {{626.404, 1093.}, {555.359, 0.}}, {{772.244, 1093.}, {419.036, 0.}}, {{355.762, 1093.},      {105.964, 0.}}, {{900., 107.987}, {588.194, 1093.}}, {{806.666, 1093.}, {318.024, 0.}}, {{0., 86.1212},      {900., 760.554}}, {{279.164, 1093.}, {358.983, 0.}}, {{0., 27.23}, {900., 260.535}}, {{0., 169.335},      {900., 228.737}}, {{491.48, 1093.}, {96.8161, 0.}}, {{0., 404.323}, {900., 470.951}}, {{900., 681.523},      {342.039, 0.}}, {{732.078, 1093.}, {671.987, 0.}}, {{610.656, 1093.}, {406.405, 0.}}, {{0., 1069.95},      {900.,163.635}}, {{112.851, 1093.}, {397.351, 0.}}, {{0., 72.2908}, {900., 65.1008}}, {{644.998, 1093.},      {702.9, 0.}}, {{900., 720.816}, {203.947, 0.}}, {{549.162, 1093.}, {374.145, 0.}}, {{446.497, 1093.},      {434.49, 0.}}, {{0., 42.0853}, {900., 106.906}}, {{0., 743.122}, {900., 596.242}}, {{0.,630.275},      {900., 744.118}}, {{39.5396, 1093.}, {449.074, 0.}}};      ![Result Showing Largest Bounded Area](http://i.stack.imgur.com/aJZKD.jpg) Thanks for your help!


title: Savitzky-Golay Filter to smooth noisy data

text: I do have noisy data and want to smooth them by a Savitzky-Golay filter because I want to keep the magnitude of the signal. a) Is there a ready-to-use Filter available for that? b) what are appropriate values for m (the half width) and for the coefficients for 3000-4000 data points? Example data: data


title: 1D Random Walk variant

text: I am making a notebook that is a variation to the traditional 1d random walk problem. The normal 1D random walk can be simulated easily by               Map[Accumulate, {RandomChoice[{-1, 1}, {100}]}] // Flatten      > {1, 2, 3, 4, 5, 4, 3, 4, 5, 6, 5, 6, 7, 6, 7, 6, 5, 6, 7, 8, 7, 8, 9, 8, 7, > 8, 9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 1, 2, 3, 4, 5, 4, 3, 4, 5, 6, 7, 8, 7, 6, > 5, 4, 3, 2, 1, 2, 1, 0, 1, 0, -1, 0, -1, 0, -1, 0, 1, 0, -1, -2, -1, -2, -3, > -2, -1, 0, -1, -2, -1, 0, 1, 0, 1, 0, -1, 0, -1, -2, -1, -2, -1, 0, -1, 0, > 1, 0, 1, 0, 1, 2} As shown, this returns a list of positions along the x-axis for each of the 100 steps. However, instead of choosing a set number of steps, I would like to discontinue the walk when a certain points is reached. This, of course, would make the length of the list of locations vary between each run as it will take a different number of steps to reach x = 10, for instance. How can I do this (without a For loop)?


title: Random number generation with specific distribution

text: I am writing a program for solving the shortest path in travelling salesman problem, with a twist that there are multiple salesmen who partition the cities among themselves, thus creating two part problem, namely partitioning the graph among the salesmen and solving the salesman problem for each partition. I am using mathematica for this, at the moment. I am using genetic programming, IE. I generate random partitions combined with order of travel and then I breed the solution so that I weight the better solution more, thus allowing all solutions to be included and the diversity to stay good. The actual breeding itself is quite a complex procedure, but that is a question for another forum and another time. I have alpha version and it works, amazingly, but it is so slow. This would, hopefully, end in commercial use (a start-up firm asked me to look at this), so I need to speed it up before making the program more complex. I figured with small benchmarking that one problem is the generation of a random number that is needed in breeding. This breeding happens tens of thousands of times, but I tested my method randomNumber thus:               Timing[Do[randomNumber[50], {128}]]     {1.263, Null}          Timing[Do[randomNumber[50], {256}]]     {2.199, Null}      This is intolerable. So, I ask, what distribution I should use and how? I would like it to be discrete, generate numbers between 1 and some larger n, so that $\sum_{i=1}^n P(i) = 1$ and the probabilities to have the property $P(1)>P(2)>P(3)\cdots P(n)$ and I would also like to be able to control how fast the probabilities get smaller. At the moment I use this monstrosity:               randomNumber[n_] := (Floor[InverseFunction[HarmonicNumber, 1, 2][RandomReal[] HarmonicNumber[n, 1/3], 1/3]] // N) + 1      This has all the properties described above, I can even control the slope by changing the numbers in `HarmonicNumber[n, 1/3], 1/3]]`. But this method is too slow. I am clearly thinking too complex here. Any suggestions?


title: Efficient GeometricBrownianMotionProcess Monte Carlo simulation

text: Following the answers in this post, I'm trying to implement something similar. If the GBM stays inside the corridor `[L, U]` between predefined times it should return `1` otherwise `0`. I wrote the following code:               MC[X_, t_, Ti_, per_, L_, U_, r_, s_, n_, prob_] :=        Module[{data = 0, data1, data2, value, j},         data =            RandomFunction[GeometricBrownianMotionProcess[r, s, X],            {0, Ti[[Length[Ti]]] + per, .01}, n];         value = 0;         For[j = 1, j <= n, j++,           data1 = Table[Select[#, #[[1]] >= Ti[[i]] && #[[1]] <= (Ti[[i]] + per) &] & /@              {data["Paths"][[j]]}, {i, 1, Length[Ti]}];           data2 = Flatten[data1, 2];           value +=              If[Max[Table[data2[[i]][[2]], {i, 1, Length[data2]}]] <= U &&                 Min[Table[data2[[i]][[2]], {i, 1, Length[data2]}]] >= L,               1, 0]];         N[1/n*value]];          MC[100, 0, {1, 2}, 1, 80, 120, 0.01, 0.15, 100, prob]      If the GBM stays inside `[80,120]` between the times `[1,2]` and `[2,3]`, `value` should be `1` otherwise `0`. Now this code works, but it is really slow. For instance for 10,000 simulations it takes about 10 minutes. Is there a way to improve this? I also want to calculate the probability that the GBM breaches the corridor between two discrete simulations. For example, if $\mathbb{P}[X_t,X_{t+1},L,U]=prob[\cdots]$ and $\mathbb{P}>0.5$, I want to set `value` to `0`. In short, I'm looking for a way to apply a certain function `prob` to every simulated value inside my corridor. Is there a way to do this without a loop? Can someone can give me a hint on how to do this in an efficient way? * * * thank you for your answer. Yes I'm trying to price a corridor option and the function `prob` I mentioned should account for the penetration probability. But I want to get the value of the option if there are more corridor periods than one. To visualize what I mean consider the slightly altered plot you provided:               Module[{S0 = 100, r = 0.01, \[Sigma] = 0.15, L = 80, U = 120,       T = 1, \[CapitalDelta]t = 0.01, nTimes = 100, nPaths = 10,       seed = 123, drift, diff, times, paths, containedPaths, PathToLine},      SeedRandom[seed];     times = Range[0, T, \[CapitalDelta]t];     PathToLine[path_] := Line[Transpose[{times, path}]];          {drift, diff} = {Exp[(r - \[Sigma]^2/2) \[CapitalDelta]t],       diff = \[Sigma] Sqrt[\[CapitalDelta]t]};          paths = Table[GBMPathCompiled[S0, drift, diff, nTimes], {nPaths}];     containedPaths = Select[paths, (And[Max[#] < U, Min[#] > L]) &];     Graphics[{PathToLine /@ paths,  {Red, Line[{{0.2, L}, {0.4, L}}],      Line[{{0.8, L}, {1, L}}], Line[{{0.2, U}, {0.4, U}}],      Line[{{0.8, U}, {1, U}}]}}, Axes -> Automatic,      AspectRatio -> 0.25]]      So the corridor should be active just between certain times $[T_i,T_i+per]$, where $T_i$ are the starting times and $per$ the length of the period. For the example above, this would be `Ti={0.2,0.8}` and `per=


title: Choosing a solution to plot

text: I'm solving a system of equations that gives me three solutions and then plot a series of solutions depending on a parameter. The problem is that I have to choose different solutions depending on parameters. For each combination of parameters the only one solution which makes physical sence - such solution is positive and always less then parameter P0. I guess the right solution is the minimal positive solution. In the proposed sample code the right solutions plotted in the first and third plot between 0 and 0.05 (parameter P0 = 0.1) How can I put all good solutions in a single plot automatically ? ![enter image description here](http://i.stack.imgur.com/6G0fi.jpg)               Quiet[solution =        Solve[{K1*P*M == PaM, K2*PaM*P == PMP, K3*PaM == PM,       P0 == P + PaM + PM + 2*PMP, r*P0 == M + PaM + PM + PMP}, {P, M,       PaM, PM, PMP}]];          Rmax = 5;     Rmin = 0.01;     K1 = 11;     K3 = 102;     P0 = 0.1;     K2values = {1, 10, 100, 1000, 10000, 100000, 1000000};     colors = ColorData[22, "ColorList"];          SetOptions[ParametricPlot, PlotStyle -> (Directive[#, AbsoluteThickness[3]] & /@ colors), AspectRatio -> 0.7, AxesLabel -> {"R", "v"}, PlotRange -> {{0, 5}, {-0.05, 0.2}}];     SetOptions[Graphics, ImageSize -> Large];          Plot1 = ParametricPlot[Evaluate[     Table[{{r, Re[PMP /. solution[[1]]]}}, {K2, K2values}]], {r, Rmin,      Rmax}, PlotLabel -> "Solution 1"] ;     Plot2 = ParametricPlot[Evaluate[     Table[{{r, Re[PMP /. solution[[2]]]}}, {K2, K2values}]], {r, Rmin,      Rmax}, PlotLabel -> "Solution 2"] ;     Plot3 = ParametricPlot[Evaluate[     Table[{{r, Re[PMP /. solution[[3]]]}}, {K2, K2values}]], {r, Rmin,      Rmax}, PlotLabel -> "Solution 3"] ;          GraphicsGrid[{{Graphics[Plot1], Graphics[Plot2], Graphics[Plot3], Column[K2values, Background -> colors]}}, Frame -> None]


title: Playing with Matrix falling code in Mathematica

text: I was trying to create a Matrix falling code image with Mathematica. Here is my code:               mcolors=Blend[{{0.00,Darker[Green,0.7]},{0.90,Darker@Green},{0.90,Lighter[Green]},{1.00,Lighter[Green,0.9]}},#]&;     (*DensityPlot[x,{x,0,1},{y,0,1},ColorFunction\[Rule]mcolors,ColorFunctionScaling\[Rule]False,AspectRatio\[Rule]0.2]*)          stringColum[n_,opacity_]:=Module[{letters,fallingCode},            letters=MapIndexed[Text@Style[#1,mcolors[#2[[1]]/n],Opacity[opacity],Bold,14,FontFamily->"Courier"]&,FromCharacterCode/@RandomInteger[{48,90},n]];              fallingCode=Column[         letters         ,Background->None         ,Spacings->-0.4         ,Alignment->Center       ]     ]          layer1=Graphics[Table[Inset[stringColum[RandomInteger[{1,30}],1.0],Scaled[{i,RandomReal[{0.7,1}]}],Top],{i,0.000,1,0.05}],PlotRange->All];     layer2=Graphics[Table[Inset[stringColum[RandomInteger[{1,30}],0.4],Scaled[{i,RandomReal[{0.7,1}]}],Top],{i,0.025,1,0.05}],PlotRange->All];          Show[layer1,layer2,AspectRatio->1,Background-> Black,ImageSize-> {600,500}]      Where I get as result images like this: ![enter image description here](http://i.stack.imgur.com/ZEiGw.png) Not very exciting when compared to this one: ![enter image description here](http://i.stack.imgur.com/g4Jvw.png) **How can I improve that?** Some itens that I see.   1. I see a blur that I don't know as to reproduce using `Blur`, for different layers.   2. The letter are not just A to Z letters.   3. The columns space are not linear.   4. I don't like the way I handler all the code. It's sound to complex in Graphics part.


title: Subdividing a polygon , equivalent fractions

text: I see that I was a real "doofus" here and my original question was flawed. You can't divide a polygon like you can a circle or a rectangle, except in special cases... I should have seen that right away, as always, I learn so much connecting with users here.... I can still use the solutions that are being posted, but limit the divisions to special cases... sorry for the poorly thought out question.... I'm working with a grade 7 student and going over fractions.... it's always fractions... I have a simple demonstration that shows fractions, and then emphasizes equivalent fractions by subdividing the pieces.                Manipulate[           Graphics[{             Flatten[{Red,           Disk[{0, 0}, 1, {(# - 1)   2 \[Pi]/divs,  #  2 \[Pi]/divs}] & /@            Range[pieces]}],             {Thickness[0.005], Circle[]},             {Thickness[0.005],          Line /@ Table[{{0, 0}, {Cos[i], Sin[i]}}, {i, 0, 2 \[Pi],             2 \[Pi]/divs}]},             {Thickness[0.001],          Line /@ Table[{{0, 0}, {Cos[i], Sin[i]}}, {i, 0, 2 \[Pi],             2 \[Pi]/(mult divs)}]}},       ImageSize -> 600],           {{divs, 2, "divisions"}, 2,  10, 1, ControlPlacement -> Left},      {{pieces, 1, "pieces"}, 1,  divs, 1, ControlPlacement -> Left},      {{mult, 1, "multiplier"}, 1, 10, 1, ControlPlacement -> Left}      ]      ![pie in pieces](http://i.stack.imgur.com/ieItg.png) Same idea with rectangles                    Manipulate[      Graphics[{             {Pink, Rectangle [{0, 0}, {60, pieces 100/divs}]},             {Thickness[0.005],          Line[{{0, 0}, {60, 0}, {60, 100}, {0, 100}, {0, 0}}]},             {Thickness[0.005],          Line /@ Table[{{0, i 100/divs}, {60, i 100/divs}}   , {i, 1,             divs}]},             {Thickness[0.001],          Line /@ Table[{{i 60/divs2, 0}, { i 60/divs2, 100}}   , {i, 1,             divs2}]}                  }, ImageSize -> 500],      {{divs, 2, "vertical"}, 1, 10, 1, ControlPlacement -> Left},      {{divs2, 1, "horizontal"}, 1, 10, 1, ControlPlacement -> Left},      {pieces, 1, divs, 1, ControlPlacement -> Left}      ]      ![rectangle pieces](http://i.stack.imgur.com/fL7xo.png) Okay, my polygon demonstration is sort of working, but way out of my depth here... if I "subdivide" the polygon to show equivalent fractions, I'd need to find points on the polygon, but the "easy" points are on the enclosing circle.               Manipulate[Module[{perimeter, spokes, shaded, minispokes},            perimeter =         Line[Table[{Cos[i], Sin[i]}, {i, 0, 2 \[Pi], 2 \[Pi]/divs}]];       spokes =         Line /@ Table[{{0, 0}, {Cos[i], Sin[i]}}, {i, 0, 2 \[Pi],            2 \[Pi]/divs}];       minispokes =         Line /@ Table[{{0, 0}, {Cos[i], Sin[i]}}, {i, 0, 2 \[Pi],            2 \[Pi]/(mult divs)}];       shaded = {Green,          Polygon[Flatten[{ {{0, 0}},             Table[{Cos[i], Sin[i]}, {i, 0, pieces 2 \[Pi]/divs,               2 \[Pi]/divs}], {{0, 0}}}, 1]]};       Graphics[{shaded, {Thickness[0.005], perimeter,           spokes}, {Thickness[0.001], minispokes}}, ImageSize -> 500,         PlotRange -> {{-1, 1}, {-1, 1}}]       ],      {{divs, 5, "sides"}, 1, 12, 1, ControlPlacement -> Left},      {{pieces, 1, "pieces"}, 1, divs, 1, ControlPlacement -> Left},      {{mult, 1, "multiplier"}, 1, 10, 1, ControlPlacement -> Left}      ]      ![polygon pieces](http://i.stack.imgur.com/ByjUL.png) Hopefully my problem makes sense. How would I create those subdivision lines so the endpoints are on the polygon, not on the circle? I'd welcome any suggestions, feedback, etc. Tom


title: Restoring the 1-to-1 correspondence between elements in two lists, where one list is used as a guide to prune elements from the other

text: when we wish to use one list to select items from another using something like `Pick`, writing the following code, for example, causes us to lose the 1-to-1 correspondence between items in the two lists:               dataArray = {"A","B","C","D","E","F","G"};     testArray = {0.223,0.3,1.2,0.44,4,0.24449,1.01};     dataArray = Pick[dataArray, #>= 1 &/@ testArray];          output = {"C", "E", "G"}      Without having to make a copy of anything, how do we safely prune items from, here `testArray`, to restore the previous 1-to-1 correspondence between elements in `testArray` and elements in `dataArray`? For example, if `B` in `dataArray` corresponds to `0.3` in `testArray` (based on its index), it should again do so after the `Pick` pruning step.


title: How to make an index optional?

text: Can I define a relation between variables, such that the expression will also be evaluated (then assuming all indices are equal) when no index is given? $$ x_i + y_j = \delta_{ij} \stackrel{Mathematica\ recognizes \ then\ that}{\Rightarrow} x + y = \delta_{ii} = 1 $$ $$$$ $$$$ _INITIAL QUESTION WAS:_ I define a relation for the annihilation and creation operator $a_i$ and $a_j$ like this $$[a_i, a_j^\dagger] = \delta_{ij}.$$ The commutator can be defined with the Quantum Notation package. I want to make the index ($i$, resp. $j$) **optional** , such that Mathematica recognizes that $$[a, a^\dagger] =1,$$ i.e. it assumes $i=j$ if no index is given. Is there a way to do this?


title: ItoProcess for coupled SDEs

text: I am trying to create an ItoProcess from the following system of SDEs: $\begin{bmatrix} \mathrm d x\\\\\mathrm d y\end{bmatrix} = \begin{bmatrix} 0 & 1\\\ 0 & \theta\end{bmatrix} \begin{bmatrix} x\\\ y\end{bmatrix} + \begin{bmatrix} \mathrm 0 \\\\\sigma\end{bmatrix}\mathrm d W(t)$ Looking at the documentation, I do not see how I could accomplish that. Is it possible to do in Mathematica? If so, how?


title: Discrete ColorData scheme with n colors?

text: I am trying to visualize a problem I am working on. For this, I need $n$ distinct colors which are preferably easy to distinguish. (Obviously, the higher the $n$ is, the harder it is to distinguish the colors.) I was using the `ColorData["index","ColorList"]`. However, through a crash of my procedure, I found out that the number of colors in the schemes is limited. The documentation on different `ColorList`s is not very extensive, so with simple loop I found out that the maximum number of colors in a scheme ranges from $4$ to $21$. It is however not straightforward to see how many colors are in each scheme. Note, for $n = 5$ it is not optimal to use selection of $21$ colors. For given $n$, is there a simple way to get color sheme with $n$ easy to distinguish colors?


title: Why does not BarLegend accept user-defined color function?

text: I encountered a really strange problem with `BarLegend`. Say you have a user- defined color function:               cf[z_]:=RGBColor[RandomReal[z, 3]]      When you want to use it in `BarLegend` as below:               BarLegend[{cf, {1, 10}}]      Mathematica will generate a blank bar shown as below: ![enter image description here](http://i.stack.imgur.com/dy1pX.jpg) However, after I change the function head in `BarLegend` to a pure function:               BarLegend[{cf[#]&, {1, 10}}]      Mathematica can give desired result. I cannot figure out why Mathematica doesn't accept user-defined color function. Could anyone please give a clue?


title: SyntaxInformation cannot reproduce syntax coloring of Block

text: Is there any way to have the same syntax coloring with `SyntaxInformation` that `Block` has?               SyntaxInformation[func] = {"ArgumentsPattern" -> {{__}, _},                             "LocalVariables" -> {"Solve", {1, Infinity}}};     func[vars : {__}, body_] := {};      After evaluating the above definition, the following two lines have different coloring:               func[{parameter, variable, constant = 0}, parameter + variable + constant]          Block[{parameter, variable, constant = 0}, parameter + variable + constant]      ![Mathematica graphics](http://i.stack.imgur.com/CsS5y.png) As you can notice, any local variable with an initial value is not highlighted as local. I use the default syntax coloring, no changes were applied. `SyntaxInformation` accepts the following values: `{"Table", "Solve", "Integrate", "Limit", "Plot", "Manipulate"}` none of which produces the same behaviour as `Block` does. Perhaps someone knows about an undocumented option value?


title: Solving Stochastic differential equation

text: How do I solve the following simple stochastic differential equation: $$ m x''[t] + \Gamma x'[t] + k x[t] = \sqrt[]{2 kb T/\Gamma)} \eta[t] $$ here $\eta[t]$ is brownian motion , i.e. Wiener process. The equation describes the stochastic motion of a particle in a harmonic potential. I am new to stochastic calculus and almost know nothing. From fiddling around with _Mathematica_ in the last two days I figured that in general the OrnsteinUhlenbeckProcess can be used to simulate $x[t]$. The values are (converting everything in MKS) $$ kb = 1.3806488 * 10 ^{-23}; (*Boltzmanns Constnat*) $$ $$ T = 350.; (*K*); $$ $$ r = 70.*10^{-9}; (*70 nm*); $$ $$ \rho = (2./1000)*100^3; (*Density Of the Particle = 2 gm/cc*) $$ $$ k = (50.*1000*2 \pi )^2 m; (* k = m \Omega^2. Resonant Frequency = 50KHz) $$ $$ m = 4./3 \pi r^3 \rho; (*mass Of The Particle*) $$ $$ \Gamma = 2 \pi 10^{-2}; $$ these are the values I am using.


title: Error using Solve on Matrix Multiplication

text: I am trying to make a function the will find that value of $x$ in the following equation: $x.a=b$ all values of $x, a, b$ are matrices. The dimensions of $x$ are unknown, but $a$ and $b$ have the same dimensions of $n*8$ where $n$ depends on the matrix used in the function I am to understand that the dimensions of $x$ are going to be $n*n$ so that the shapes of the matrix are compatible in the equation. The functions arguments are simply $a$ and $b$, and I tried setting it up as follows:               GetValueOfX[a_,b_] := Solve[x.a==b,x]      But when I try put in values for $a$ and $b$, I get the following error:               Solve::nsmet : This system cannot be solved with the methods available to Solve.       I am very confused by this, is it telling me there are an infinite number of outcomes (I googled the error and this was a common cause) or is this kind of Matrix Multiplication incompatible with Solve as it does not know the dimensions of $x$. And more importantly, is there always going to be an answer? The values I tested were: $a=\begin{matrix}116&101&115&116&105&110&103&44\\\32&116&101&115&116&105&110&103\end{matrix}$ $b=\begin{matrix}114&117&110&110&105&110&103&44\\\32&114&117&110&110&105&110&103\end{matrix}$ P.S. if you want to know, those matrices are the character codes of a phrase and that is how I got them.


title: How to test if any set of pairs contains elements of other list? no matter order of elements

text: I want to detect if a set of pairs, for example a={{2,5},{6,3},{1,4},{8,7}} contains a given pair, for example tabu={{4,1},{2,6}} but don´t be relevant the order inside pair (pair {i,j} is equal to {j,i}), so in this case.... YES!!! "a has an element of tabu. That´s the only target. So, Are there any function to do this directly? * * * I was thinking in a variable Tabustatus=TRue if the big contains any pair of tabu, or tabustatus=False if not contais. Ordering previously the pairs for avoid the sort issue(no matter) any similar to:               a = {{1, 2}, {4, 3}, {3, 2}, {5, 2}};     tabu = {{2, 6}, {4, 1}};     asortg = Table[Sort[a[[i]], Greater], {i, 1, Length[a]}];     asortl = Table[Sort[a[[i]], Less], {i, 1, Length[a]}];     tabusortg = Table[Sort[tabu[[i]], Greater], {i, 1, Length[tabu]}];     tabusortl = Table[Sort[tabu[[i]], Less], {i, 1, Length[tabu]}];     Print["a...........", a];     Print["a - Greater.", asortg];     Print["a - Less....", asortl];     Print["----------------------"];     Print["tabu...........", tabu];     Print["tabu - Greater.", tabusortg];     Print["tabu - Less.....", tabusortl];     Print["----------------------"];     tabustatus = False;     Do[Do[Print["i..", i, "  j..", j];If[asortl[[i]] == tabusortl[[j]], Print[asortl[[i]], " - ", tabusortl[[j]]]; tabustatus = True; Break[], False]; If[tabustatus == True, Break[]], {i, 1, Length[asortl]}]; If[tabustatus == True, Break[]], {j, 1, Length[tabu]}];     Print["Tabu Status...", tabustatus];      In this case, I would need to add any Breaks[] to exit If... Do...Do... without continue searching,... since one time one is found,... TABUSTATUS=TRUE, We don´t need to continue searching. Any faster and less tedious alternative?


title: Passing a joined list of symbols for Module or Block to treat as its own local symbols

text: ### The Question I'd like to write a function which itself takes a list of symbols, _e.g._               Foo[{x, y, z}]      to pass to `Module` within, but with additional localized symbols, _e.g._               Foo[list_, expr_] := Module[Join[list, {a, b, c}], ...]      In other words, I'd like `Foo[{x, y, z}]` to behave like               Module[{x, y, z, a, b, c}, ...]      ##   ### To show what I've tried, though all in vain... I started without the `Join`:               ClearAll[x, y, z, a, b, c, Foo];     x = 7;     Foo[vars_] := Module[vars, x = 43];     Foo[{x, y, z}];     x      which returned, understandably,               Module::lvsym: "Local variable specification {7,y,z} contains 7, which is not a symbol or an assignment to a symbol."      I added `SetAttributes`,               ClearAll[x, y, z, a, b, c, Foo];     x = 7;     SetAttributes[Foo, HoldAll];     Foo[vars_] := Module[vars, x = 43];     Foo[{x, y, z}];     x      which returned the desired result, `43`, _i.e._ unchanged by the assignment within the `Module`. Now, including a `Join`,               ClearAll[x, y, z, a, b, c, Foo];     x = 7;     SetAttributes[Foo, HoldAll];     Foo[vars_] := Module[Join[vars, {a, b, c}], x = 43];     Foo[{x, y, z}];     x      I got,               Module::lvlist: "Local variable specification Join[{x,y,z},{a,b,c}] is not a List."      As I understand, the `Join` didn't evaluate because `Module` itself must be putting a `Hold` attribute on (at least, if not more than) its first argument. So, reading that `Evaluate` > effectively overrides the `HoldFirst` attribute, and causes the first > argument to be evaluated, I tried               ClearAll[x, y, z, a, b, c, Foo];     x = 7;     SetAttributes[Foo, HoldAll];     Foo[vars_] := Module[Evaluate[Join[vars, {a, b, c}]], x = 43];     Foo[{x, y, z}];     x      which returned               Module::lvsym: "Local variable specification {7,y,z,a,b,c} contains 7, which is not a symbol or an assignment to a symbol."      I'm a bit confused as to why `x` interpolated, _i.e._ why the `Hold` attribute didn't persist. I guess the `Hold` attribute only "carries" the argument, unevaluated, into the function, but doesn't hold the argument beyond? Okay, then should I `Hold` the list again?               ClearAll[x, y, z, a, b, c, Foo];     x = 7;     SetAttributes[Foo, HoldAll];     Foo[vars_] := Module[Evaluate[Join[Hold[vars], {a, b, c}]], x = 43];     Foo[{x, y, z}];     x      This resulted in:               Join::heads: Heads Hold and List at positions 1 and 2 are expected to be the same.          Module::lvlist: "Local variable specification Join[Hold[{x,y,z}],{a,b,c}] is not a List."      I made sure to read both Evaluation and Non-Standard Evaluation, but unfortunately these didn't (seem to) help me understand what's happening. I tried `Unevaluated` and `Defer` just to try, but the results weren't different. I saw a Google Groups thread where the solution seemed to be somehow converting the symbols to strings, then back via `Symbol`, but I thought there must be a better way... * * * ### Background @SjoerdCdeVries, in short, I'm trying to write a sort of a `While` loop that makes certain convenient symbols (both functions and variables) available to use within (and only within) the looping expression, and also displaying certain results of the loop afterwards. The motivation is sort-of-explained in the "Background" section of Is there anything like a C pointer (or returning a reference) in $Mathematica$?; I'm writing a tool that users (mostly familiar with `C`, only) can use to prototype ideas for analyzing time-series data. I have a more specific use-case example (in code), but I've decided not to share this unless requested--this post is long enough already.


title: Find size of vertex image relative to the graph coordinate system

text: I am trying to define a graph using my own `VertexShapeFunction` with an `ActionMenu` button being the vertex and a custom `EdgeShapeFunction` defining the edges as arrows. My problem is that I am unable to get the arrows to finish exactly at the border of the `ActionMenu` as it is when I leave `EdgeShapeFunction` to `Automatic`. The coordinates and relative size of the `ActionMenu` button depends on the number of vertices and their layout, so I cannot compute once the coordinates and hardcode them in my definition of the `EdgeShapeFunction`. I was wondering if there is a function or a way to get the relative size to the graph coordinate system of the `ActionMenu` button or some dimensions. Here is an image of what I am trying to get: as seen from the image, the arrows are ending just before they reach the vertex: ![picture](http://i.stack.imgur.com/XFT3w.jpg) Here is part of the code:               ef[el_, __] := {Blue,        Which[First[el][[1]] < Last[el][[1]],         Arrow[{First[el], First[el] + {Last[el][[1]] - 0.5, 0},           Last[el] - {0.5, 0}, Last[el] - {0.400, 0}}],             First[el][[1]] >= Last[el][[1]],         Arrow[{First[el], First[el] + {1.5, 0}, First[el] + {1.5, -0.5},           Last[el] + {-1.5, -0.5 + First[el][[2]] - Last[el][[2]]},           Last[el] - {1.5, 0}, Last[el] - {0.400, 0}}]]}          g = Graph[{1 \[DirectedEdge] 2, 3 \[DirectedEdge] 2},         VertexShapeFunction -> (Inset[            ActionMenu[             icon, {"Print" :> Print[#2]}], #] &),         EdgeShapeFunction -> ef,         VertexLabelStyle -> Directive[Italic, 20]];


title: How to see which arguments are passed into a function

text: It is often that one wonders which arguments are evaluated before being passed into a function. I would like to know if it is possible to see which argumets are being passed into a function without recoding the function, that is, outside of the function. I know that one could try with the Trace command, but it always puzzles me whether the output one really sees reflects what is being sent into the function prior to its evaluation. I suppose, that the key issue is being able to draw a clear line, and say, "yes, these expressions are being fed into the function, and, aha, these evaluations are done in the function". Is there a generic way of doing this without recoding the function (that is, one could put a bunch of print statements in the definition of the function)? For example, I might want to know which arguments are actually passed to a built-in Mathematica function (which one cannot recode) and might need to know what is done with these arguments within the function code. I suppose that the Trace command could be used, but I never figured out how.


title: How to show multiple images with a for loop

text: I wrote a simple application(I put the code in the end) to detect the parallel line pairs in the following picture: ![enter image description here](http://i.stack.imgur.com/OsyKp.jpg) It returned three pairs of parallel line:               {{{{584., 222.175}, {39.6747, 0.}}, {{0., 377.639}, {390.613, 472.}}},      {{{0., 403.894}, {306.413, 0.}}, {{0., 336.953}, {238.095, 0.}}},      {{{584., 186.489}, {127.104, 0.}}, {{0., 377.639}, {390.613, 472.}}}}      And then I want to show every result individually. Here's the way I output the result, where img is the test picture and parLines is the detected parallel line pairs.               For[i = 1, i <= Length[parLines], i++,     Show[img, Graphics[{Thick, Orange, Line /@ parLines[[i]]}]]]      I expected it to output several images and a pair of parallel lines on each. The number of images depend on the number of pairs of parallel line. However, it didn't draw anything. But if I printed them one by one, it worked fine.               Show[img, Graphics[{Thick, Orange, Line /@ parLines[[1]]}]]      ![enter image description here](http://i.stack.imgur.com/Eviow.png)               Show[img, Graphics[{Thick, Orange, Line /@ parLines[[2]]}]]      ![enter image description here](http://i.stack.imgur.com/lKdvM.png)               Show[img, Graphics[{Thick, Orange, Line /@ parLines[[3]]}]]      ![enter image description here](http://i.stack.imgur.com/T1Wwg.png) I can't understand where the problem is. Thanks for any help. * * * Here's the code:               img = Import["http://www.zechini.it/webtv/upload/book.jpg"];     edge = DeleteBorderComponents[EdgeDetect[img]];     lines = ImageLines[edge, 0.1];          NumofLines = Length[lines];     flag = False;     parLines = {};     For[i = 1, i <= NumofLines, i++,       For[j = i + 1, j <= NumofLines, j++,         line1 = lines[[i]];         line2 = lines[[j]];         vec1 = line1[[1]] - line1[[2]];         vec2 = line2[[1]] - line2[[2]];         para = 1 - ArcCos[Abs[(vec1.vec2)/Norm[vec1]/Norm[vec2]]]/(Pi/2);         If[para > 0.9, flag = True; AppendTo[parLines, {line1, line2}];];         ];       ];          If[flag == True,      For[i = 1, i <= Length[parLines], i++,       Show[img, Graphics[{Thick, Orange, Line /@ parLines[[i]]}]]],       Print["Cannot detect parallel line"]]


title: Incorrect behaviour of Locator inside Show?

text: Why doesn't `Locator` behave correctly in the following code?               BezierPoint[t_, cps_] := Block[{tt},        tt = {(1 - t)^3, 3 t (1 - t)^2, 3 t^2 (1 - t), t^3};        Sum[cps[[i]]*tt[[i]], {i, 1, 4}]        ];          DiskBezierRadius[t_, ri_] := Block[{tt},        tt = {(1 - t)^3, 3 t (1 - t)^2, 3 t^2 (1 - t), t^3};        Sum[ri[[i]] tt[[i]], {i, 1, 4}]        ];          ControlPoints = {{100, 100}, {100, 300}, {300, 200}, {300,          100}};     ControlRadii = {50, 50, 20, 20};     Dynamic[Show[       ParametricPlot[BezierPoint[t, ControlPoints], {t, 0, 1}],       Graphics[        Table[p = BezierPoint[t, ControlPoints]; {Text[t, p],           Circle[p, 5]}, {t, 0, 1, 0.1}]],       Graphics[        {         Line[ControlPoints[[1 ;; 2]]],         Line[ControlPoints[[3 ;; 4]]],         Blue,         Locator[Dynamic[ControlPoints[[1]]]],         Locator[Dynamic[ControlPoints[[2]]]],         Locator[ControlPoints[[3]]],         Locator[ControlPoints[[4]]]         }        ],       Axes -> None, AspectRatio -> Automatic,       PlotRange -> {{0, 400}, {0, 400}}       ]]     Dynamic[ControlPoints[[1]]]      ![enter image description here](http://i.stack.imgur.com/hwauF.jpg) If I wrap into `Dynamic` two locators (as in code above) then I have both locators dragged by mouse. I mean if I drag one locator, then both locator move. I can't drag only one locator. If I wrap only one (second) locator, then it can be dragged alone.


title: How can I define a 3d-body through different views?

text: In one of the maths blogs I follow I stumbled upon the following question: The bottom, side, and front views of an object are shown below: ![enter image description here](http://i.stack.imgur.com/Rd5S3.png) How would the object look in three dimensions? **My question**   Is it possible to use these views and construct a 3d body out of them that you can then turn in space with Mathematica?


title: How can I make this more efficient/why doesn't my naive solution speed things up?

text: I'm computing a certain power series (up to some number of terms), and I figured I should try to speed up the computation as much as I can. The series is defined as follows: Let $f$ be a Laurent polynomial (EDIT: with integer coefficients) in two variables $x,y$, then $S=\sum_{m\ge 0} const(f^m)t^m$, where "$const(-)$" is the constant term. Naively, we could try               ConstantTerm[function_]:=Coefficient[Coefficient[function,x,0],y,0];     S[function_,order_]:=Sum[ConstantTerm[function^m]t^m,{m,0,order}]      but this seems stupid as the expensive part is computing powers of the polynomial, and this approach repeats that computation for each term instead of taking advantage of the result of the previous term. I tried to do a classical loop construction with `While`, doing something like `tmpfunction=tmpfunction*function` at each step (I won't show the whole thing, because it clearly is barking up the wrong tree), but there was absolutely no appreciable difference in execution time, even for high orders. 1) What is going on here? Does _Mathematica_ do some secret tricks to optimize the naive construction while executing? Is the overhead of manipulating counting variables in the loop big enough to offset the expense of computing the $f^m$? 2) How can it be made more efficient, if at all?


title: Enumerate the 1-factors (perfect matchings) of $K_n$

text: ## Introduction I would like to enumerate the 1-factors, or (near-)perfect matchings, of the complete graph _K n_. The adjacency list representation for _K n_ is basically { ( _x_ , _y_ ) | 1 ≤ _x_ < _y_ ≤ _n_ }. For example, in the case of _K 3_ = `{{1, 2}, {1, 3}, {2, 3}}`, the near- perfect matchings would be   `{{{1, 2}}, {{1, 3}}, {{2, 3}}}`. For _K 4_ = `{{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}}`, the perfect matchings would be `{{{1, 2}, {3, 4}}, {{1, 3}, {2, 4}}, {{1, 4}, {2, 3}}}`. Here's a nifty little illustration of this inspired by an example from the documentation: ![Nifty](http://i.stack.imgur.com/PKtBW.png) The number of 1-factors of _K n_ is given by the odd double factorial: _n_!! if _n_ is odd, and ( _n_ – 1)!! if _n_ is even. See how this function grows (as the even double factorial) compared to _n_! below:               n        1       2       3       4       5       6       7       8       9      10     n!!      1       1       3       3      15      15     105     105     945     945     n!       1       2       6      24     120     720    5040   40320  362880 3628800          n!/n!!   1       2       2       8       8      48      48     384     384    3840      (For the sake of brevity, I am ignoring parity when using the _n_!! notation in the row headers.) ## Attempt My current solution generates the _n_! permutations, partitions each into pairs, and filters them.               p[n_] := Partition[#, 2] & /@ Permutations[Range[n]];     one[p_] := Select[p, OrderedQ @ # && And @@ OrderedQ /@ # &];     two[p_] := Select[p, # === Intersection@(Intersection /@ #) &];      Solution `one` filters the permutations by requiring each element and each of its contents be sorted.   Solution `two` does the same thing by exploiting the fact that order is ignored in sets. The first solution can be a magnitude faster than the second solution:               With[{n = 9}, TableForm[Table[        With[{ptemp = p[i]},         tone = one@ptemp // Timing // First;         ttwo = two@ptemp // Timing // First;         {tone, ttwo, ttwo/tone}]        , {i, n}],        TableHeadings -> {Range[n], {"one", "two", "one faster by"}}]]                        one         two         one faster by     1   0.000017    0.000011    0.6     2   0.000013    0.000019    1.     3   0.000025    0.000037    1.5     4   0.000066    0.000186    2.8     5   0.000520    0.001044    2.01     6   0.001274    0.007714    6.05     7   0.010958    0.047812    4.363     8   0.065019    0.446901    6.873     9   0.572954    3.941633    6.8795      ## Question How can achieve this without doing _n_!! times as much work generating all the permutations?


title: How can I save both the plot and the legend together?

text: In this example, How can I punt the Legend INSIDE the graph. Because when I save the graph, only save the graph BUT not save the legend.               Expr1 = -2 p + 1     Expr2 = 2 p - 1     Expr3 = p - 1/2     Plot[{Expr1, Expr2, Expr3}, {p, 0, 1},      BaseStyle -> AbsoluteThickness[4],       PlotLegends ->        LineLegend["Expressions", BaseStyle -> AbsoluteThickness[4]]]     Solve[Expr1 == Expr2, p]      Another question. How can I insert the solution in the las line, too INSIDE the graph? Here you can see the result ![http://img534.imageshack.us/img534/8941/for0.png](http://i.stack.imgur.com/Ojl68.png)


title: Selecting index position of data from a table that is less than a certain value

text: I have a table of numbers with a few thousand entries, and I'm trying to find the first index that is less than a particular value. An example of the table I'm working on is as follows:               dr = {6.34152*10^8, 6.32076*10^8, 6.29998*10^8, 6.27921*10^8, 6.25843*10^8, 6.23765*10^8, ...}      What I'm trying to do is find the first entry that is less than `5.77*10^8`. I've tried the following:               SOIdr = Position[dr, First[dr] < 5.77*10^8]      But have had no luck thus far. Any help would be appreciated, thanks guys.


title: Problems with formatting a bar chart

text: I am trying to create a financial dashboard using _Mathematica_. I am having trouble formatting the axes ticks to show whole numbers. Further, when I hover over one of the chart elements, it is displayed in scientific notation. I have attached the code and an image.               Manipulate[       sql = StringJoin[         "select Right(Period,2) as [Period], SUM(Revenue) as [Revenue] ",          " from PRSummaryCMF where Month >=  ", ToString[a],          " and Year =  ", ToString[b], " group by Period order by Period"];       n = SQLExecute[conn, sql];       BarChart[n[[All, 2]],          ChartLabels -> {n[[All, 1]]},          ChartStyle -> "Pastel" ,          BarSpacing -> Automatic],        {{b, 2010, "Year"}, {2010, 2011, 2012, 2013}, ControlType -> Setter},        {{a, "01", "Period"},          {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"},          ControlType -> Setter,  Appearance -> "Labeled"},       ContentSize -> 500]      ![Output Image](http://i.stack.imgur.com/CmCv6.jpg)


title: using index notation for finite differences

text: I am interested in deriving finite difference equations, which means I have to play around with indexed quantities. For example, for a 2D function f(x,y), I could discretize it on a grid with grid points (i,j) and a typical finite difference model might give: f(i,j)-g(i,j) = a(i,j)f(i+1,j)-b(i,j)f(i,j)+c(i,j)f(i+1,j+1) where I know g,a,b and c. I might want to do things like rearrange the above for f(i+1,j+1), or find an expression for f(i+n,j) for arbitrary n, or find coefficients of f(i,j) etc. I might also want to use simultaneous equations like this. What's the best way of representing this kind of maths so that I can perform these manipulations? Thanks, Mark * * * Edit: Here's a simple example. If I have two difference equations: f[i,j]=fold[i,j]+a*( g[i+1,j]-g[i-1,j] ) and g[i,j]=gold[i,j]+b*( f[i,j+1]-f[i,j-1] ) in the functions f and g, where fold,gold,a and b are known. Then I would like to be able to solve these for g[i,j] in terms of the knowns and g at other indices eg. g[i+1,j]. To do this on paper, I use the first equation to give me expressions for f[i,j+1] and f[i,j-1] and then insert these into the RHS of the bottom equation. Then I would like to extract coefficients of things like g[i+1,j+1] from the final expression for g[i,j]. How can I do that in Mathematica?


title: Passing function as argument

text: I've been mucking around with passing functions as arguments to other functions and via trial and error seem to have something that works. I was wondering if someone could have a quick look at some simple example code and let me know if this method is sound or if there are some things that I am overlooking. Cheers...               Clear[mother];     mother[] :=      Module[{f},       f[x_, y_, z_] := x + y + z;       child[f]     ]          Clear[child];     child[functionArgument_] :=       Module[{},        functionArgument[1, 2, 3]     ]


title: No Speedup Compiled Function in FindMinimum

text: The problem: I would like to minimize an objective function with respect to 12 variables. Minimization should be executed as fast as possible. Compiling the objective function increases the execution speed of the objective function but does not improve minimization speed. 1) Setup   * The Function is written in the following form: FUNCTIONSYSTEMPART1 = Function[{time, c1, c2, rho, YY}, Evaluate[WORKINGSYSTEMPART1[[time]]]];   * In order to Speed up the process, I have compiled the objective function COMPILEDSYSTEMPART1 = Compile[{{time, _Integer, 0}, {c1, _Real, 0}, {c2, _Real, 0}, {rho,_Real, 0}, {YY, _Real, 1}}, Evaluate[WORKINGSYSTEMPART1[[time]]]]; Note that the arguments time, c1 ,c2 and rho given as numerics. WORKINGSYSTEMPART1[[time]] represents the objective function. The only unknown variables are stored in YY which is a 12x1 Array. 2) Execution of Objective Function is much faster if the objective function is compiled:               In[400]:= AbsoluteTiming[     Do[FUNCTIONSYSTEMPART1[time, 1, 1, 0.55, ConstantArray[3, 12]], {j, 1, 100000}]]     Out[400]= {8.2444715, Null}          In[401]:= AbsoluteTiming[     Do[COMPILEDSYSTEMPART1[time, 1, 1, 0.55, ConstantArray[3, 12]], {j, 1, 100000}]]     Out[401]= {0.3740214, Null}      3) The Speedup is not preserved when the Minimization Function is called.               AbsoluteTiming[     Quiet[FindMinimum[FUNCTIONSYSTEMPART1[time, 1, 1, 0.55, Z], S, WorkingPrecision -> \[CapitalXi]0]]]     {0.3300188, ... }          AbsoluteTiming[     Quiet[FindMinimum[COMPILEDSYSTEMPART1[time, 1, 1, 0.55, Z], S, WorkingPrecision -> \[CapitalXi]0]]]     {0.3310190, ... }      Question: How is it possible that the speedup (attained by compiling the objective function) is lost?


title: Perspective transformation of a 2d streamplot

text: I have a two-dimensional streamline plot from a fluid dynamics simulation. I am wondering: is it possible to somehow allow Mathematica to treat the streamline plot as a plane in three-dimensional plot so that I can apply a camera perspective transformation to the resulting three-dimensional plot? To provide a bit more information, I have three-dimensional scenes (an example of which is shown below) for which I am running fluid dynamics simulations. As a result of these simulations, I obtain a series of two-dimensional windflow velocity fields, which are cross-sections of the true three-dimensional windflow velocity fields. These fields quantify the direction and speed of the wind through the environment subject to the geometry constraints of the scene and some user-defined parameters and boundary conditions. ![A three-dimensional scene in 3DS Max.  A red plane has been inserted to provide the desired perspective for the planar streamline plot.](http://i.stack.imgur.com/D9ijN.jpg) For visualization purposes, I'm interested in transforming and overlaying one or more of the two-dimensional streamline plots of the velocity fields onto my three-dimensional scene such that the two-dimensional streamline plot takes the place of the red plane in the image below. Although I could simply rasterize the streamline plot, treat it as a texture for the plane, and render the scene in 3DS Max, I'm hoping to overlay the streamline plots as vector graphics. Addendum: As per Yves' suggestion, I have supplied a subsampled version of the windflow velocity field that I am using for my plots. Using his wonderful script, I am able to take a two-dimensional streamline plot and rotate/scale it as if it was a three-dimensional plot.               data = {{{1, 1}, {1.0, 0.0}}, {{11, 1}, {0.971194, 0.0}}, {{21, 1}, {0.963011, 0.0}}, {{31, 1}, {0.993688, 0.0}}, {{41, 1}, {1.023889, 0.0}}, {{51, 1}, {1.024193, 0.0}}, {{61, 1}, {1.010802, 0.0}}, {{71, 1}, {1.032089, 0.0}}, {{81, 1}, {1.026697, 0.0}}, {{91, 1}, {0.987981, 0.0}}, {{101, 1}, {1.025693, 0.0}}, {{111, 1}, {1.105825, 0.0}}, {{121, 1}, {1.098795, 0.0}}, {{131, 1}, {1.065537, 0.0}}, {{141, 1}, {1.012451, 0.0}}, {{151, 1}, {1.0, 0.0}}, {{1, 11}, {1.0, -0.083697}}, {{11, 11}, {0.932164, -0.106793}}, {{21, 11}, {0.925340, -0.192984}}, {{31, 11}, {1.122307, -0.187170}}, {{41, 11}, {1.161864, 0.085156}}, {{51, 11}, {0.976324, 0.115229}}, {{61, 11}, {0.978851, 0.035055}}, {{71, 11}, {1.049432, -0.030869}}, {{81, 11}, {0.936428, 0.062604}}, {{91, 11}, {0.912342, -0.146168}}, {{101, 11}, {1.147333, -0.143745}}, {{111, 11}, {1.166712, 0.127165}}, {{121, 11}, {1.041843, 0.129961}}, {{131, 11}, {1.045287, 0.083479}}, {{141, 11}, {0.994206, 0.122328}}, {{151, 11}, {1.0, 0.132739}}, {{1, 21}, {1.0, -0.023829}}, {{11, 21}, {0.890156, -0.030084}}, {{21, 21}, {0.674394, -0.050241}}, {{31, 21}, {0.0, 0.0}}, {{41, 21}, {0.658960, -0.210046}}, {{51, 21}, {0.716182, 0.091213}}, {{61, 21}, {0.472093, -0.225292}}, {{71, 21}, {0.732020, 0.265153}}, {{81, 21}, {0.843532, 0.369957}}, {{91, 21}, {0.279971, -0.348445}}, {{101, 21}, {0.963035, -0.753370}}, {{111, 21}, {1.002857, 0.538380}}, {{121, 21}, {0.756004, 0.204065}}, {{131, 21}, {0.806599, -0.138649}}, {{141, 21}, {0.913204,  0.279003}}, {{151, 21}, {1.0, 0.159432}}, {{1, 31}, {1.0, 0.044899}}, {{11, 31}, {0.908289, 0.060171}}, {{21, 31}, {0.856098, 0.122421}}, {{31, 31}, {0.762294, 0.042601}}, {{41, 31}, {0.0, 0.0}}, {{51, 31}, {-0.438033, 0.780580}}, {{61, 31}, {0.382021, -0.726038}}, {{71, 31}, {0.550500, -0.113628}}, {{81, 31}, {0.860478, 0.363810}}, {{91, 31}, {1.373814, -0.269792}}, {{101, 31}, {0.153576, -0.482892}}, {{111, 31}, {0.113453, 0.274464}}, {{121, 31}, {0.286391, 0.307524}}, {{131, 31}, {0.275092, -0.174137}}, {{141, 31}, {0.651551, -0.053446}}, {{151, 31}, {1.0, 0.028982}}, {{1, 41}, {1.0, 0.091944}}, {{11, 41}, {0.942248, 0.107845}}, {{21, 41}, {0.914909, 0.147823}}, {{31, 41}, {0.914062, 0.226842}}, {{41, 41}, {1.090780, 0.280458}}, {{51, 41}, {1.423264, 0.011814}}, {{61, 41}, {1.084930, -0.364051}}, {{71, 41}, {0.899861, -0.177124}}, {{81, 41}, {0.992899, -0.106340}}, {{91, 41}, {1.136605, -0.039446}}, {{101, 41}, {0.830366, 0.086879}}, {{111, 41}, {0.653521, 0.119604}}, {{121, 41}, {0.862727, 0.513709}}, {{131, 41}, {1.041204, -0.599559}}, {{141, 41}, {0.911816, -0.171321}}, {{151, 41}, {1.0, -0.089802}}, {{1, 51}, {1.0, 0.0}}, {{11, 51}, {0.972851, 0.0}}, {{21, 51}, {0.958161, 0.0}}, {{31, 51}, {0.956957, 0.0}}, {{41, 51}, {1.008198, 0.0}}, {{51, 51}, {1.082196, 0.0}}, {{61, 51}, {1.119506, 0.0}}, {{71, 51}, {1.011644, 0.0}}, {{81, 51}, {0.905500, 0.0}}, {{91, 51}, {0.811638, 0.0}}, {{101, 51}, {0.953396, 0.0}}, {{111, 51}, {0.978083, 0.0}}, {{121, 51}, {1.166181, 0.0}}, {{131, 51}, {1.289609, 0.0}}, {{141, 51}, {1.066669, 0.0}}, {{151, 51}, {1.0, 0.0}}};      `ListStreamPlot[data, StreamPoints -> Fine][[1]] /. Arrow[pts_] :> Arrow[{#[[1]], 0, #[[2]]} & /@ pts] // Graphics3D` ![A three-dimensional streamline plot in Mathematica](http://i.stack.imgur.com/72jin.png) The only remaining question that I have is: how can I change the camera perspective parameters of the plot? Specifically, I would like change the perspective of the three-dimensional streamline plot such that the bounding box around the plot takes the shape of a trapezoid and the streamline trajectories are modified accordingly. I am aware that Graphics3D has `ViewAngle`, `ViewPoint`, and `ViewVector` options, but I am unsure as to how to use them in the context of Yves' script.


title: Combining lists

text: How can I combine               list1={{x1,y1},{x2,y2},{x3,y3}}       and               list2={{x4,y4},{x5,y5}}       to               list={{x1,y1},{x2,y2},{x3,y3},{x4,y4},{x5,y5}}      ?


title: Verify Harmonic Addition Theorem with Mathematica

text: I've calculated the harmonic addition theorem and would just like to check my result with _Mathematica_. However,               a Exp[I (ω t + ϕ1)] + b Exp[I (ω t + ϕ2)] ==      Sqrt[a^2 + b^2 + 2 a b Cos[ϕ1 - ϕ2]] Exp[     I (ω t + ArcTan[(a Sin[ϕ1] + b Sin[ϕ2])/(a Cos[ϕ1] +      b Cos[ϕ2])])] && Element[{a, b, ϕ1, ϕ2, ω, t}, Reals]      does not evaluate to True, Reduce does not work either. Numerically, it seems to be true on a 10^-15 level:               init = a Exp[I (ω t + ϕ1)] +  b Exp[I (ω t + ϕ2)]     /. {a -> 3, b -> 5, ϕ1 -> 0, ϕ2 -> π/3, ω -> 1}          sum = Sqrt[a^2 + b^2 + 2 a b Cos[ϕ1 - ϕ2]] Exp[I (ω t +      ArcTan[(a Sin[ϕ1] + b Sin[ϕ2])/(a Cos[ϕ1] + b Cos[ϕ2])])]     /. {a -> 3, b -> 5, ϕ1 -> 0, ϕ2 -> π/3, ω -> 1}          Plot[Re[init - sum], {t, -30, 30}]     Plot[Im[init - sum], {t, -30, 30}]      What should I be doing better / what's the point I am missing?


title: Make a slider controlling a generated character's code value

text: If I execute the following code:               char = 97;     Slider[Dynamic@ToExpression@FromCharacterCode@char, {0, 5}]      the slider will fail to change the value of `a`. How do you make this work, when the expression has to be generated with `FromCharacterCode` or similar? **Note:**               ToExpression@FromCharacterCode@97 == a


title: How can I recover the source code from cdf file?

text: by a mistake I have deleted the nb file by which the CDF was generated. All required definitions were in one cell. If I remember the code looked like this:               Grid[{{Button[..],..},        Dynamic[ ParametricPlot[..,Initialization:>{functions definitions}]]]      and later I selected the output cell and saved the selection by: `File > CDF Export > Standalone`. I can open the CDF in a text editor but it is highly unreadable and is difficult to extract all the math commands.


title: Different calculation of median and quartiles, bug in BoxWhiskerChart?

text: When you plot a dataset with `BoxWhiskerChart` passing over the box in the plot with your mouse pointer shows some specifics about the dataset (min and max values, 1/4, 1/2, and 3/4 quartiles). However, if you use `Quartiles` or `Median` to calculate those values, they do not correspond. The values displayed by `BoxWhiskerChart` are different. Does anyone have an explanation or is it simply a bug? Is it system specific (here 8.0.1 on OSX 10.6.8)?               data = RandomVariate[NormalDistribution[0, 1], 20]     BoxWhiskerChart[data]     Quartiles[data]     Median[data]


title: How do I make Mathematica copy a cell after I re-evaluate it?

text: When I edit a cell in the notebook and re-evaluate it, it "overwrites" the input and the output of the previous edit. I want it to copy my edited version to the bottom or something and give me a separate output, not overwriting the old results or old input.


title: What compilers are "suitable" for CompilationTarget->"C"?

text: The documentation for CompilationTarget says, "if you do not have a suitable C compiler then you will not be able to set CompilationTarget to C". Well at this time, I don't have a compiler installed on either of my computers running Windows XP, or Windows 7. Is it safe to say that any compiler that will run with my OS will be "suitable"? If it isn't that simple, can you recommend a compiler?


title: How to get different items in a list to interact to get a result?

text: I have two lists, for example (the real lists are much longer):               list1 = {1, 2, 3, 4, 5, 6, 7};     list2 = {9, 10, 11, 12, 13, 14, 15};      I want to create a single list by adding together different elements from different places in each list. For example, > list3 = (list1i+1 \+ list1i-1) * (list2i+1 \+ list2i-1) where $i$ is the location of the number in the list, e.g. in `list2`, 12 would be $i=4$. I realize the first and last entries in `list3` would either be wrong or non-existent. For example, the 2nd item in `list3` would be $(3+1)(11+9)$ and the 3rd item would be $(4+2)(12+10)$. I hope that makes sense and I appreciate any help.


title: How to plot function over interval returned by Reduce[]

text: Let $f(x) = (x^2 + 1) / x$. I need to plot the function for the values of $x$ in which the square of the function is larger than 4, and its cube is smaller than 64. So I used `Reduce` like this:               Reduce[((x^2 + 1)/x)^2 > 4 && ((x^2 + 1)/x)^3 < 64, x, Reals]      Now I am having problems plotting this. I need to use `Plot` to display the function on the specific interval, but I do not know how to input the result from `Reduce` (which may be union of intervals) in `Plot` in order to draw the function only for those values of $x$. Could anyone assist?


title: Workbench, Deployed Application Missing Documentation from Referenced Projects

text: I am starting to use Wolfram Workbench 2.0 to consolidate a project and take advantage of subversion to keep track of my ongoing updates and changes. The project is compartmentalized into 5 individual Mathematica Application projects, one of which I have set up to have the property that it references the other 4. The compartmentalization is very handy for organization and deploying Project A so that it includes the others makes sharing the application very easy, with one exception. I have found that the only obvious consequence of setting the property of Project A to reference Projects B, C .. etc is that when you Deploy the application of Project A to an archive, the referenced projects are included in the .zip. Everything, that is, except for the Documentation for each referenced project. I have documentation built for every project, and each individual project deploys with Documentation just fine. I can't think of why the Documentation would be excluded for each Referenced project, is this intended behavior?


title: Graphics updating from inside double-Fold-iteration within Manipulate

text: Normally, when using `Manipulate[expr, controls, options]`, the graphics updating should be carried out at the very end of expr. But now I encounter a situation where the graphics result is evaluated at each step inside a double-`Fold`-iteration. Yes I can still adopt the method mentioned above and write following code,               DynamicModule[{g},      Manipulate[       Module[{a},        Fold[(           k = #2;           Fold[(a = #2; g = v[a, k]; Pause[.05]) &, {}, Range[5]]          ) &, {}, Range[15]];        Dynamic@g       ],      {{k, 1}, ControlType -> None},      TrackedSymbols :> {},      SynchronousUpdating -> Automatic,      Initialization :> (v[a_, k_] := Plot[Sin[x (a + k x)], {x, 0, 6}])]     ]      But the problem is that I will have to first wait for the double-`Fold`-evaluation to complete and only after this can I see the updates in a queued sequence. The code I used here is but an over-simplified example and the actual code will take much longer time for computation. I wonder if it is possible to do the graphics updating at every iteration step when `v[a, k]` is evaluated?


title: Why Refine does not simplify Cos[2*Pi*FractionalPart[1/2*(i + j + k)]] to $(-1)^{i+j+k}$?

text: I am obtaining in Mathematica:               Cos[2*Pi*FractionalPart[1/2*(i + j + k)]]      We know that for $i, j, k$ being positive integers this expression after simplification should give: $$ (-1)^{i+j+k} $$ I would like to know why the one of the solutions proposed for this similar question:                Refine[Cos[2*Pi*FractionalPart[1/2*(i + j + k)]],          Assumptions -> {Element[{i, j, k}, Integers], i > 0, j > 0, k > 0}]      did not work for this case?


title: 2D Cellular Automaton: Initial conditions

text: I'm trying to write in Mathematica for a 20x20 grid, with 100 colours, with 4 neighbours. I want the initial conditions to be a 20x20 matrix consisting mainly of zeros.               CellularAutomaton[{100 (4 (100 - 1) + 1), {100, 1}, {1, 1}},      MatrixForm[Table[RandomInteger[], {20}, {20}]], 1]      Apparently init is not in the right form?


title: Connect to remote Ms-sql Database

text: I can connect to the local `Database`(installed in my system) from `Mathematica` via               SQLConnection[JDBC["Microsoft SQL Server(jTDS)", "localhost:1433/TestDatbase"],      "Catalog" -> Automatic, "Description" -> None, "Name" -> "DemoSql",      "Password" -> "test", "Properties" -> {}, "ReadOnly" -> False,      "RelativePath" -> False, "TransactionIsolationLevel" -> "ReadUncommitted",      "UseConnectionPool" -> False, "Username" -> "DemoLogin", "Version" -> 2.]      But When I try to connect to remote database I can't. I have following details               Sever Name: xxxx7ezff6.database.windows.net     User Name: xxxxxxxx     password: password     Database: AdventureWorks2012      I can see this remote database in my SQL Server Management Studio(SSMS) by using server name, user name and password. But I don't know how can I connect to this remote database from Mathematica. I tried like this               SQLConnection[JDBC["Microsoft SQL Server(jTDS)",      "xxxx7ezff6.database.windows.net:1433/AdventureWorks2012"],      "Catalog" -> Automatic, "Description" -> None, "Name" -> "AdvTest",      "Password" -> "password", "Properties" -> {}, "ReadOnly" -> False,      "RelativePath" -> False, "TransactionIsolationLevel" -> "ReadUncommitted",      "UseConnectionPool" -> False, "Username" -> "xxxxxxxx", "Version" -> 2.]      It's end up with error. I think there is problem with hostname and port, But I don't have these details. How can I connect to this remote database? Note: I don't have IP address as well. The port Number I have given here has been set by `mathematica` as default. I tried without port number as well, but no use.


title: How can I set default size for some characters

text: ![Mathematica graphics](http://i.stack.imgur.com/ZNXEw.png) `Alt`+`+` could adjust the size, but how to store the satisfactory size? For example: Each time I type `|`, its size is (I assume) 12. How to make its effect like adding `StyleBox["|", FontSize->18]`?


title: Error while exporting to Excel with named sheets

text: Using Mathematica v9.0.1 This example is from the docs:               data1 = Table[{t, 9.8*t^2}, {t, 0, 3, .1}];     data2 = Table[{t, 9.8*t^2}, {t, 0, 5, .2}];     Export["datasets.xlsx", "Sheets" -> {"Experiment 1" -> data1,                                           "Experiment 2" -> data2}, "Rules"]      Returns: > JLink`Java::argxs: The static method System`Convert`ExcelDump`write was > called with an incorrect number or type of arguments. The arguments, shown > here in a list, were {XLSX,C:\Documents and > Settings\xxx\datasets.xlsx,{Experiment 1,Experiment > 2},{{{0.,0.},{0.1,0.098},<<27>>,{2.9,82.418},{3.,88.2}},{<<1>>}},{{{Null}}},{{{}}},Author->Created > by Wolfram Mathematica 9.0 : www.wolfram.com}. While the following:               Export["datasets.xlsx", {data1, data2}]      works OK, but I need sheet names. Any idea?


title: How to keep labels inside the box in BarChart3D

text: The following code               BarChart3D[      Map[Labeled[#, Text[Style[#, Black, Opacity[1.], Bold, 20]],          Above] &, {{1, 0, 2}, {0, 0, 2}, {2, 1, 0}, {0, 2, 1}}, {2}],       ChartLayout -> "Grid", BarSpacing -> Large,      ChartElements -> Graphics3D[Cylinder[]],      ChartStyle -> Directive[Opacity[0.3]],       AxesLabel -> {None, None, None},      Ticks -> {None, None, {0, 1, 2}},      ChartLabels -> {Placed[{"O", "E", "R", "N"}, Axis], {"D", "N", "A"}},      ViewPoint -> {1.3`, -2.4`, 2.`}]      Works an place labels near axis. And what's interesting is that as you move the box, i.e. change the ViewPoint, with your mouse, the labels change accordingly. ![Mathematica graphics](http://i.stack.imgur.com/5SBcH.png) So, there is something happening at the UI level with that positioning; and I couldn't find an option to place labels that worked for longer text. I need this ![Mathematica graphics](http://i.stack.imgur.com/mBlZE.png) to have labels properly placed. The chart labels are:               ....     ChartLabels -> {        Placed[{"Osteo", "Ewing", "Rhabdo", "Neuro"},  Axis],        {"Dele", "Norm", "Ampl"}}     ....      So, how to tell _Mathematica_ to place labels on `Axis` but aligned properly? **Note:** `Placed[...,Axis]` is the default; so I put it above just in case that rings a bell to someone.


title: ImageLines Segmented options

text: I have tried utilising the ImageLines function, and its accompanying Segmented setting. However, the segmentation doesn't appear to allow for its variables to be fine tuned, at least not according to the official documentation. For example, one may wish to restrict the segmentation to segments with lengths within a certain range, or to change the threshold below which two segments are detected instead of one. How would one do so, assuming that the Segmented setting can be fine-tuned, and if it cannot, what method would be recommended in order to achieve the aims stated above?


title: ListPlot under conditions

text: I have a data file containing several columns and thousands lines of data. Below I present a small portion of it, in order to express my issue:               -0.54      0.09   -.3983969954588588E-02   0.2776322403476376E+00   0.5000000000000000E+05   0.1217096235496098E-13    0     -0.53     -0.03   -.3220837268589903E+00   0.7636149973371797E-02   0.1000000000000000E+04   0.7161538340416553E+00    0     -0.52      0.12   0.4319398001406393E+00   0.3046084462020560E-01   0.5000000000000000E+05   0.2227502533766236E-13    0     -0.51     -0.17   0.4596503785112276E+00   0.1788976667427210E+00   0.1000000000000000E+04   0.4171435790075386E+00    0     -0.12     -0.34   0.5787213420082925E+00   -.9322804977650871E+00   0.5910000000000000E+01   0.5147520415218694E+00    2     -0.12      0.13   0.5730427588243323E+00   0.9338351799657055E+00   0.1128500000000000E+03   0.7609604604284203E-06    1     -0.12      0.50   0.7396872499032718E+00   -.8091545263006905E+00   0.2137430000000000E+04   0.2962964572602038E-14    2     -0.09      0.05   0.6996863847044283E+00   0.8430535062986785E+00   0.2116400000000000E+03   0.3193612197737323E-08    1      The first two columns correspond to the coordinates $x$ and $y$, the next three columns are completely unrelated to this question, sixth column gives the value of a quantity $f$, while the last column shows a signal $s$, which can take only three integer values (0,1,2). What I want, is to plot the first two columns at the $(x,y)$ plane, using `ListPlot` but assign a specific color to each point (dot) according to the values of the last two columns. In particular, using FORTRAN notation, the conditions are:               IF(f.GT.1d-4.AND.s.EQ.0) ---> orange color     IF(f.LE.1d-4.AND.s.EQ.0) ---> red color     IF(f.GT.1d-4.AND.(s.EQ.1.OR.s.EQ.2) ---> green color     IF(f.LE.1d-4.AND.(s.EQ.1.OR.s.EQ.2) ---> blue color      I know, that I could write a simple FORTRAN code reading my data file and use the conditions to spit it into four different files. However, since this is only needed for plotting the data, I suppose that Mathematica can perform `ListPlot` under conditions, thus saving me disk space occupied by unnecessary extra files. Many thanks in advance. **EDIT** Following @Nasser's approach and rearranging a little bit the colors, this is the final product ![image](http://i.stack.imgur.com/kbP4F.jpg) The complete data file can be downloaded here data.


title: Split matrix by all-zero columns

text: Below is my input:               mat = {{0, 0, 0, 0, 0, 1}, {1, 0, 0, 1, 0, 1}, {0, 1, 0, 0, 0, 0}, {0,          0, 0, 0, 0, 1}, {1, 1, 0, 1, 0, 0}, {0, 0, 0, 1, 0, 1}};      $\quad\quad\left( \begin{array}{cccccc} 0 & 0 & 0 & 0 & 0 & 1 \\\ 1 & 0 & 0 & 1 & 0 & 1 \\\ 0 & 1 & 0 & 0 & 0 & 0 \\\ 0 & 0 & 0 & 0 & 0 & 1 \\\ 1 & 1 & 0 & 1 & 0 & 0 \\\ 0 & 0 & 0 & 1 & 0 & 1 \\\ \end{array} \right) $ I would like to split this matrix by the columns with all-zeros, and in the process remove those columns from the matrix. Expected output below: ![output](http://i.stack.imgur.com/JfVRk.png)


title: Truncate a fractional value to particular number of bits?

text: If I have a fractional value, how can I truncate (not round) that to a certain number of bits, like 8? For example, for Pi 3.141569265359... the fractional part is 0.141569265359...               NumberForm[BaseForm[FractionalPart[N[Pi]],2],8]          0.00100100001111110110101010001      But this is giving me 8 decimal digits of PI in base 2. What I want is 8 binary digits in base 2.


title: Insert large amount of data in HSQL

text: I create HSQL database with one table               Needs["DatabaseLink`"]     dbLocation="c:\\work\\hsqlTest\\";     dbName="testDB";     dbServer=SQLServerLaunch[{dbName->dbLocation}]     dbConnectionObject=JDBC["HSQL(Server)","localhost/"<>dbName];     dbConnection=OpenSQLConnection[dbConnectionObject,"Name"->dbName,"Username"->"sa"];      But inserting large amount of data produce different errors with different insert. For example:               data=RandomReal[{-10,10},{500000,1}];     SQLInsert[dbConnection,"TestTableDouble",{"c1"},data];      produce error: JDBC::error: connection exception: connection failure: java.lang.OutOfMemoryError: GC overhead limit exceeded >> or > JDBC::error: GC overhead limit exceeded >> How can I avoid this error? PS: some inserts do not produce error **Add:** With SQLite I have the same problem, but with inserting `1000000` rows


title: Tracing a path on a polar coordinate grid

text: I attempt to trace the path of a point when shift-dragged on a polar coordinate as shown on the picture below. But I only managed to snap the point to the grid. Insight on how to accomplish this? Any help would be much appreciated.               VPOS = {1, 1};     oVPOS = {1, 1};          angle[p_] := (       ang = ArcTan[Abs@p[[2]]/Abs@p[[1]] // N ];       Which[p[[1]] >= 0 && p[[2]] >= 0 , Return[ang ],        p[[1]] < 0 && p[[2]] >= 0 , Return[Pi - ang ],        p[[1]] < 0 && p[[2]] < 0 , Return[-Pi + ang ],        p[[1]] >= 0 && p[[2]] < 0 , Return[-ang ]         ];)           cnt[p_] := (       d = Round@EuclideanDistance[{0, 0}, p];       the2 = Abs@Ceiling[ArcTan[p[[2]]/p[[1]]]/(Pi/12)];       Return[{Sign[p[[1]]] d Cos[the2*Pi/12 ], Sign[p[[2]]] d Sin[the2 *Pi/12 ]}];)          cnt2[p_] := (       od = Round@EuclideanDistance[{0, 0}, oVPOS];       othe2 = Ceiling[angle[oVPOS]/(Pi/12) ] ;            d = EuclideanDistance[{0, 0}, p];       the2 = angle[p];            dd = Round@d;       dthe2 =   Ceiling[the2/(Pi/12)];            Dthe = Abs[od*(  the2 - othe2) ] ;       Dd = Abs[ d - od];       If[Dthe > Dd,        Return[{  dd Cos[ the2],  dd Sin[ the2 ]}],        Return[{  d Cos[dthe2*Pi/12],  d Sin[dthe2*Pi/12]} ]         ]       )          grids[min_, max_] :=        Join[Range[Ceiling[min], Floor[max]],         Table[{j + 1, Lighter@Lighter@Lighter@Lighter@Green}, {j,           Round[min], Round[max - 1], 1}]];          DynamicModule[{pnt = {1, 1} },       EventHandler[         Dynamic@Graphics[           {PointSize[Large], Red, Point[cnt2[VPOS]]},           Axes -> True,           GridLines -> grids,           PlotRange -> {{-10, 10}, {-10, 10}},           Prolog -> {             Lighter @ Lighter @ Blue,             Table[Circle[{0, 0}, r], {r, 1, 14}],             Table[Line[{{-15 Cos[the], -15 Sin[the]},                          {15 Cos[the], 15 Sin[the]}}],              {the, 0, Pi, Pi/12}]}],       {"MouseDragged" :> (         oVPOS=VPOS;         VPOS = MousePosition["Graphics"])}]]      This is what my code produces: ![plot achieved](http://i.stack.imgur.com/P6dW6.png) This is what I want to see: ![plot wanted](http://i.stack.imgur.com/IVQl0.gif)


title: Read C-formatted hexadecimal numbers?

text: I have a lot of 32-bit numbers in hexadecimal symbolized as they are in C (for example, 0x1230abde). How can easily read these in Mathematica?


title: Proper way to deal with lists and map

text: So, I wanted to do something that I assumed would be really simple. Given two lists, $A = \\{a_1, a_2, ...\\}, B = \\{ ... \\}$, I wanted to take a function $f(a, b)$ and generate a list with $\\{ f(a_1, b_1), f(a_1, b_2), ... \\}$, i.e. just the cartesian product. Of course, it's really easy, in principal, to do this:               f[#1, #2] & @@@ Outer[List, {a1, a2, a3}, {b1, b2}]      The annoyance comes in when the elements are themselves lists. In this case, everything breaks. Ridiculous things start happening. There is a "trivial" solution; just use dummy variables in the above statement, and replace it in with what I want later. But to me this seems fundamentally wrong somehow. Surely it should be possible to work with lists of arbitrary type; and not have to "protect" your mapping functions from lists of lists. Any thoughts? Am I missing some fundamental strategy here? \-- Edit: To elaborate more, I'm actually trying to make the following work:               dim = 2; (* Say *)     Table[       SomeFunc[dim, g, op, #] & /@          Subsets[Range[dim], {i}], {i, 1, dim}     ]      `op` previously was a single matrix; but now I need it to be a list of matricies. That is so say, I want to run "SomeFunc" for each matrix in that list, and also each of the results that come from the `Subset` function (note, of course, that `Subsets` returns lists.)


title: Problems with Symbolic summation over unknown values

text: I'm having some real trouble with _Mathematica_ wrongly evaluating various symbolic sums at the moment. I have this function: $$h_{ij}(x) = \binom{j-1}{i-1}-\sum_{r=0}^{j-x-n-(k+1)/2-1}\binom{r+x+n+(1-k)/2}{i-k}\binom{j-r- x-n-5/2+k/2}{k-2}$$ and I use it in the following double summation: $$\sum_{1\leq s<t\leq2x+2n+1}h_{is}(x)h_{jt}(x)-h_{it}(x)h_{js}(x)$$ and I want to know what this summation is as a polynomial in $x$. The values $i,j,k,n$ are all integers, and it can be assumed that $x>0$. Here is my _Mathematica_ input for $h(x)$ (with a slight change of variable in the summand):               h[i_, j_, k_, x_, n_] :=       (Binomial[j - 1, i - 1] -        2*Sum[Binomial[r + i - k, i - k]*Binomial[j - i - r + k - 2, k - 2],        {r, x + n + (k + 1)/2 + 1 - i, j - i}])      and here is my code for the double summation:               summ[i_, j_, k_, x_, n_] :=      Sum[h[i, s, k, x, n]*h[j, t, k, x, n] - h[i, t, k, x, n]*h[j, s, k, x, n],       {t, 2, 2*x + 2*n + 1}, {s, 1, t - 1}]      Now the thing that is really bothering me is a discrepency between evaluating these functions where $x$ is undetermined. I know from other calculations that when $x=1,i=1,j=3,k=3$ and $n=2$, the function `summ` should return 96, which it does. However if leave $x$ undetermined I get the following output:               summ[1,3,3,x,2]      > >     1/3 (x + 2) (x + 3) (2 x + 5)^2   >   Which gives 196 when $x=1$, which is a) in disagreement with my other calculations; and b) in disagreement with _Mathematica_ 's answer for when I specify $x=1$. Please can someone help me understand why this happens? It's driving me up the wall.


title: Functions of two arguments

text: I am pretty weak on the notion of pure functions, etc. I found a clean solution to my problem so in a sense I've already answered my own question but I don't feel I'm on terra firma. I wanted to take a random sample from a list of lists with a different sample size for each list in the list of lists. I did the following which is clean and readable by the cognoscenti. I'll probably have trouble understanding this in a year. Comments and/or suggestions of better ways will be appreciated.               listoflists = {{1, 2, 3, 4}, {5, 6, 7}, {8, 9}, {10, 11, 12, 13}};          samplesizes = {2, 3, 1, 3};          out=Apply[RandomSample, Transpose[{listoflists, samplesizes}], {1}]


title: How do I feed data points into an equation to solve NUMERICALLY?

text: I start with this equation and solve it numerically for $z(x,y)$ in the range $1 < x < 5$ and $1 < y < 5$: $$ \frac{3}{xyz} - 2x - 3y - 5z = 0 $$ Then using the data points of $z$ above, I want to solve for this special condition: $$ x + y + z = 0 $$ Then I want to plot a graph of $y(x)$. Everything must be done numerically.               eqn1 = 3/(x y z) - 2 x - 3 y - 5 z   == 3     ContourPlot3D[Evaluate[eqn1], {x, 1, 5}, {y, 1, 5}, {z, 0, -5}]          fulldomain =        Table[z /. Solve[eqn1, z, Method -> Reduce], {x, 1, 5, 1}, {y, 1, 5,          1}] ;          eqn2 = x + y + z  == 0                special =       Table[y /. Solve[eqn2 /. fulldomain, y, Method -> Reduce], {x, 1, 5,         1}]          ifun = Interpolation[special]     Plot[ifun[x], {x, 1, 5}, Epilog -> Map[Point, special]]


title: Entering scientific notation in an InputField

text: I am trying to make an InputField for numeric input, but               InputField[Dynamic[num],Number]      Does not allow the user to type `1.3*^-13` or `1.3*10^-13`, for example. The characters are simply disallowed in the field. I tried               InputField[Dynamic[num],Expression]      which allows `1.3*10^-13` but does not allow the `1.3*^-13` shorthand. The `*^` simply disappears when I type the `-`. Further exploration shows that it the shorthand entry does work with positive exponents like `1.3*^6`. So, my workaround is to use `Expression` and to remember to use explicit scientific notation whenever I have a negative exponent, but allowing an `Expression` in an `InputField` is always a dangerous proposition. Is there any way to get this to work with `Number`?


title: Better way to plot multiple discrete PDFs?

text: I often find myself trying to plot multiple PDFs for my courses. I find the default tools available to me are lacking and/or cumbersome. After readings some suggestions here, I have come up with the following code to plot 3 instances of the Binomial Distribution. I'm hoping this will prove useful to others (perhaps even myself). I'm also wondering if folks can improve on this.               n = 12;     plist = {1/6, 1/3, 2/3};     colorList = {Magenta, Blue, Green};     Plot[Evaluate[       Map[PDF[BinomialDistribution[n, #], Floor[k]] &,         plist]], {k, -0.001, n + 0.001},      Exclusions -> None,      PlotStyle -> Map[{Thick, #} &, colorList],      PlotLegends -> plist,      Frame -> {True, True, False, False},      FrameTicks -> {Table[i, {i, 0 , n, 2}], Automatic},      FrameLabel -> {"Successes k", "Probability"}]      Here's the output ![plot of multiple histograms](http://i.stack.imgur.com/7Pwt8.png)