title: Why does Expand not work within a function?

text: I'm writing this fairly simple function:               hermite[0, x] = 1;     hermite[1, x] = 2 x;     hermite[n_, x_] := (       hermite[n, x] = 2 x*hermite[n - 1, x] - 2 (n - 1) hermite[n - 2, x];       Expand[hermite[n, x]]       )      But the `Expand` command is ignored. Yet, when I do               Expand[hermite[10, x]]      The result is expanded like I wish. Why is it not working when I put the same command inside a function? I'd like to do it in the function; it would be cleaner.


title: How can I import images from a Microsoft SQLServer database?

text: I have a table with binary data (images) in Microsoft SQlServer. I want to import that data and convert it into `Image` format. I wrote the following code, but it's not working.               (* demoSqlConn points to connectionId in between MM and DB and Images       points to Table name in Db *)     binarydata = SQLSelect[demoSqlConn, "Images"];     convertedData = FromCharacterCode[binarydata[[1, 1]]];     image=ImportString[convertedData, "JPEG"]      After evaluating this code, I get the following error: > The front end encountered an error while processing a "NotebookPredictions" > packet. For testing purposes, I evaluated `binarydata` separately. It returns a list like {{FFD8FFE000104A46494600010201006000600000FFEE000E41646F6265006400000\ 00001FFE1135D4578696600004D4D002A0000000800070132000200000014000000620\ 13B000200000007000000764746000300000001000400004749000300000001003F000\ 09C9D00010000000E00000000EA1C00070000080C00000000876900040000000100000\ 07D000000E7323030393A30333A31322031333A34363A343200436F726269730000059\ 003000200000014000000BF9004000200000014000000D392910002000000033534000\ 0929200020000000335340000EA1C0007000007B40000000000000000323030383A303\ 33A31342031333A35393A323600323030383A30333A31342031333A35393A323600000\ 5010300030000000100060000011A00050000000100....}}. So, I'm getting the data, the problem is converting it.


title: How to show wireframes on imported Object / Mesh (.obj file)

text: I've managed to import a Wavefront (.obj) file and store it in a variable like so:               model = Import[         "/path_to_object/my.obj",          "Graphics3D",          Lighting -> {             {"Ambient", RGBColor[{0.212, 0.168, 0.2}]},             {"Directional", RGBColor[{0.8, 0., 0.}], ImageScaled[{2, 0, 2}]},             {"Directional", RGBColor[{0., 0.8, 0.}], ImageScaled[{2, 2, 2}]},             {"Directional", RGBColor[{0., 0., 0.8}], ImageScaled[{0, 2, 2}]}         }     ]      The output shows no black edges that you would normally see with `Graphics3D` objects, sort of like a "wireframe overlay". I've tried to call the `Graphics3D` function on `model` in this way:               Graphics3D[{AbsoluteThickness[2], AbsoluteDashing[{5, 5}], model}]      But I get the error:               Graphics is not a Graphics3D primitive or directive.      I've also tried adding more arguments to the `Import` function but I get the error:               Import::argt: Import called with 3 arguments; 1 or 2 arguments are expected.      Any ideas on how this can be accomplished? I saw that there is the command `Mesh->All`, but because I'm not that well versed with Mathematica yet, I don't know exactly how to apply a `Mesh` command to an imported `Graphics3D` object.


title: Efficient matrix multiplication

text: I have a list of vectors vecs={vec1,vec2,...,vecN} where veci is a list with length N. Now I have a matrix N*N called mat. I would like to efficiently get all the numbers veci.mat.veci for i=1 to N in a list. How do I do it?


title: Move the Animation Controls in a Manipulate Slider

text: Quick formatting question: How can I move the animation controls for a slider from underneath it to say, on the side? For example, I have this: ![Slider Bars](http://i.imgur.com/KIlAZ6Y.jpg) But I would like all of those controls to be on the right side of each slider, instead of underneath the slider. And actually, if there is a way to just have an input field for the value of each variable, that would great too! I know you can set Appearance -> "Labeled" but this does not allow you to change the value, only observe it. Thanks!


title: Autocomplete not working on Mma9 on Linux

text: I started using Mathematica 9 on Ubuntu 12.10 and, sometimes, autocomplete doesn't work. The suggestions window shows up for just a fraction of second, and quickly disappears. Do you have any idea on how I can sold this problem? Thanks in advance!


title: How can I efficiently and uniformly sample the set of vertices a fixed edge-wise distance away from a chosen vertex?

text: I have a large graph $G$, which may be either directed or undirected. How would I use `DepthFirstScan[]` or `BreadthFirstScan[]` to efficiently and uniformly sample the set of vertices a fixed shortest distance of $D$ away from some vertex $v_i \in V$?


title: NDSolve complains about missing derivatives of dependent variables in Mathematica 9

text: In _Mathematica_ 8               NDSolve[{x[t] == 1, x[0] == 1}, x[t], {t, 0, 10}]      solves fine and returns               {{x[t]->InterpolatingFunction[{{0.,10.}},<>][t]}}      while _Mathematica_ 9 raises > NDSolve::derivs: No derivatives of dependent variables were found in the > equations. NDSolve is designed to solve differential or differential > algebraic equations. Use NSolve or FindRoot to numerically solve algebraic > equations. >> I get the point, but is there maybe a way to restore the old behavior via `NDSolve`'s options system?


title: Problem with working precision

text: I have tried to resolve the problem of the following link How can I solve precision problem I can tell the problem described in that link shortly here, It's no mater how many precision is there after decimal(.) the result should be 2 or 3 precision after decimal as per user requirement.e.g               N[10/3]     3      Output should be as per user wish precision as 2.               3.33     3.00      There I found `NumberForm[]` function as a solution, since the `NumberForm[]` function is wrap up the result, I can't get the result as number out of it. I tried like this               NumberForm[N[10/3],{4,2}]     NumberForm[3, {4, 2}]      Output am getting is               3.33     3.00      But when I try to do further operation, it's not computing               NumberForm[N[10/3], {4, 2}] + 1     NumberForm[3, {4, 2}] + 1      Output               1+3.33     1+3.00      I tried other way also which follows               ToExpression[ToString[NumberForm[3, {4, 2}]]]      OutPut               3.      but I need output as 3.00. Help me to find the solution.


title: build and estimate a time series process

text: I want to generate an EGARCH process. My problem is that I do not see how to create new processes beyond those available. The process itself is : $$\epsilon(t) = \sigma(t) \eta(t)$$ $$\log(\sigma(t)^2 ) = w + b\log(\sigma(t-1)^2) + c\eta(t-1) + d \lvert\eta(t-1)\rvert$$ Notice that I want to use `RandomFunction` to generate the simulated values. Then I'd like to estimate it using the `EstimatedProcess` to estimate the parameters. I want to experiment with false models..


title: Performance of numerical optimization with triple integral

text: I'm trying to solve a numerical optimisation that looks something like this:               Joint[X_, Y_, Z_] := PDF[MultinormalDistribution[{0, 0, 0}, {{1, 1/2, 1/2}, {1/2, 1, 1/2}, {1/2, 1/2, 1}}], {X, Y, Z}]          Cond[z_] := ConditionalMultinormalDistribution[MultinormalDistribution[{0, 0}, {{1, 1/2}, {1/2, 1}}], {z}, {2}]          zstar[y_?NumberQ] := z /. FindRoot[1 - CDF[Cond[z], y] == .3, {z, y - 0.1}]          cap[y1_?NumberQ, y2_?NumberQ] := (1/2)*SurvivalFunction[BinormalDistribution[{0, 0}, {1, 1}, (1/2)], {y1, zstar[y1]}] + (1/2)*SurvivalFunction[BinormalDistribution[{0, 0}, {1, 1}, 1/2], {y2, zstar[y2]}]          q[y_?NumberQ] := NIntegrate[X*Joint[X, Y, Z] , {X, -∞, ∞}, {Y, y, ∞}, {Z, zstar[y], ∞}]          NMaximize[{(1/2)*q[y1] + (1/2)*q[y2], cap[y1, y2] == .1}, {t1, t2}]      The definition of `ConditionalMultinormalDistribution` follows this post This numerical optmization problem is computationally very expensive and I would like to improve its performance


title: Issue with ListDensityPlot when using logarithmic scale

text: I have got some frequency response data from a speaker measured with different incident angles between speaker and microphone taken in an anechoic chamber. The data can be found here. The whole experiment consists of measurement series at 5 different angles which are `{0°, 30°, 60°, 90°, 180°}` ![plot of measurement series](http://i.stack.imgur.com/E3DoZ.jpg) I individually import (and save them in a variable) with:                importlist[path_] :=       ToExpression @ Partition[Flatten @ Drop[Import[path, "Words"] , 2], 2]      and process them (downsampling and rearranging) with the following functions to get a list suitable for `ListDensityPlot`               downsampleFunction[list_, n_, pos_] :=      Downsample[pos @ Transpose @ list, n]          combineFunction[list_, angle_, downsampleBy_] :=      Thread[{downsampleFunction[list, downsampleBy, First], angle,      downsampleFunction[list, downsampleBy, Last] }]           listcombineFunction[listoflists_, listofangles_, downsampleBy_] :=      Flatten[Table[     combineFunction[listoflists[[i]], listofangles[[i]],      downsampleBy ], {i, 1, Length@listoflists}], 1]      If now plotted with something like               ListDensityPlot[     listcombineFunction[     {list0FR, list30FR, list60FR, list90FR, list180FR},      {0°, 30°, 60°, 90°, 180°}, 1000]]      I get a nice looking plot but in linear scale. Since this is frequency response data (and I would like to show that directivity is a matter that becomes (more) relevant at higher frequencies) I would rather prefer a logarithmic frequency (horizontal) axis. If I change my processing functions by adding a `Log10@` in front of my frequency range data like done here:               combineFunction2[list_, angle_, downsampleBy_] :=      Thread[{Log10 @ downsampleFunction[list, downsampleBy, First], angle,      downsampleFunction[list, downsampleBy, Last] }]           listcombineFunction2[listoflists_, listofangles_, downsampleBy_] :=      Flatten[Table[     combineFunction2[listoflists[[i]], listofangles[[i]],      downsampleBy ], {i, 1, Length@listoflists}], 1]      and plot the results I get a ugly graphics glitch (I guess some interpolation issue due to the accelerated changes forced by the logarithm?). An example with corrected ticks and different styling options: ![example image](http://i.stack.imgur.com/fHdTq.jpg) P.S.: I noticed another glitch concerning the 45° rotated frame labels. Does anybody know a fix for the behaviour? If I try the same code with another example the font looks somewhat thinner but not as aliased as in the sample picture above. Example for "desired" behaviour:                LogLinearPlot[Log10[x], {x, 1, 1000},       FrameTicks -> {Flatten[      Table[{d 10^e, Rotate[d 10^e, 45 Degree]}, {e, Floor[Log[10, 35]],      Ceiling[Log[10, 22000]]}, {d, 1, 5, 1}], 1], Automatic},       Frame -> True, ImageSize -> 600]


title: How can I export graph as PDF with metadata such as Title and Author fields

text: I want to export figure from Mathematica in PDF format. Also I want to include Author and Title fields into the PDF. For example, to include Author field, I use the following code:               pp = Plot[{x^2}, {x, -1, 1}]     Export["plot-example.pdf", pp, "Author" -> "Dmitry"]      However, when I open generated PDF file in PDF viewer, the "Author" field is not filled. How should I specify Export call to include Author and Title fields in the generating PDF file?


title: Is there any way to automatically evaluate selection in new window or new notebook?

text: Sometimes when you have long code you need to check some part of this code. the way I am using currently is to selected the part that I want and then copy it to new notebook and then evaluate it there. this process becomes annoying when repeated several times. is there a better way to automatically evaluate selection in new notebook without need to go through copy paste procedure? **Update :** Thanks to halirutan for his suggestions. But one of my concerns is to evaluate selection within the cell in to another window. For example: ![enter image description here](http://i.stack.imgur.com/blSaS.jpg) how to evaluate the selection without manually copy and paste. If the cell itself contain long content, then the only way to debug the cell is be copying part by part and pasting into another notebook and evaluate as a whole new cell.


title: Why does Part behave like it transposes lists?

text: From the documentation of `Part`: > `Part[expr,i,j,...]` is equivalent to `expr[[i]][[j]]...` So I would expect that, if `t = Table[i + 3 j, {j, 0, 2}, {i, 1, 3}]`, i.e. t = $\begin{pmatrix}1&2&3\\\4&5&6\\\7&8&9\end{pmatrix}$,               t[[1;;2]][[1]]     (* {1, 2, 3} *)       would be equivalent to               Part[t, 1 ;; 2, 1]     (* {1, 4} *)      but it's not...


title: How to display the support supp(f) of a piecewise function z = f(x,y)?

text: I'm wondering how to display the support $\mathrm{supp}(f)$ of a piecewise surface $z = f(x,y)$. As an example, let's consider the following piecewise function (and plot it):               f[x_, y_] = Piecewise[{{1, 0 <= x <= 1 && 0 <= y <= 1}}];     g[x_, y_] = Integrate[f[x - t, y - t], {t, 0, 1}];     Plot3D[g[x, y], {x, -0.5, 2.5}, {y, -0.5, 2.5}, PlotRange -> Full]      ![enter image description here](http://i.stack.imgur.com/Gasp5.png) My first thought was to use a contour plot for this purpose, such as               ContourPlot[g[x, y] == .05, {x, -0.5, 2.5}, {y, -0.5, 2.5}]      ![enter image description here](http://i.stack.imgur.com/0qT6M.png) But this is of course only an approximation of the support. How do I display the actual support of my piecewise function? ### Edit The proposed solution in the comments below works great, the result looks as follows: ![enter image description here](http://i.stack.imgur.com/oubOk.png)


title: Why won't Parallelize speed up my code?

text: What reasons are there that can cause parallelized Mathematica code not to run with full performance?


title: Shared variable impacting speed?

text: I am using a shared variable as a progress indicator ( via `SetSharedVariable[counter]` and then `Dynamic[counter]`), to keep track of a parallel computation. However, there seems to be a massive overhead just because I ask ParallelTable to increment the counter:               AbsoluteTiming[ParallelTable[(counter++; myCompiledFunction),{i,1000}];]          (* {6.580984, Null} *)      But the same exact computation without the counter is about 50 times faster:               AbsoluteTiming[ParallelTable[myCompiledFunction,{i,1000}];]          (* {0.129618, Null} *)      Does anybody know why, and if there is a solution? Note: this does not happen if I use `Table`, but then I cannot take advantage of all my cores.


title: How to avoid unpacking from Language`ExtendedFullDefinition

text: Consider this code:               LaunchKernels[];     On["Packing"]          a = RandomReal[{0., 1.}, {64, 30000}];          ParallelMap[Fourier, a]; // AbsoluteTiming      > Developer`FromPackedArray::unpack: Unpacking array in call to > Language`ExtendedFullDefinition. Developer`FromPackedArray::unpack: > Unpacking array in call to MemberQ. >>               (*{1.853567, Null}*)          Map[Fourier, a]; // AbsoluteTiming      > Developer`FromPackedArray::punpackl1: Unpacking array with dimensions > {64,30000} to level 1.               (*{0.289122, Null}*)      How to avoid the unpacking and get some speedup by parallelization? **Update** By avoiding the `MemberQ` unpack (`fix` function copied from here), we can get about 2X speedup, but still slower than the non-parallel version :               memberQ[list_, form_] := Or @@ (MatchQ[#, form] & /@ list)     ClearAll[fix]     SetAttributes[fix, HoldAll]     fix[expr_] := Block[{MemberQ = memberQ}, expr]          fix@ParallelMap[Fourier, a]; // AbsoluteTiming      > Developer`FromPackedArray::unpack: Unpacking array in call to > Language`ExtendedFullDefinition. >>               (*{0.564126, Null}*)      **Update 2** Using the `ParallelTable` can eliminate unpacking and can actually get speedup first run               fix[        ParallelTable[         Fourier[a[[n]]], {n, 1, Length[a]}]]; // AbsoluteTiming     (*{0.215288, Null}*)      second run               fix[        ParallelTable[         Fourier[a[[n]]], {n, 1, Length[a]}]]; // AbsoluteTiming     (*{0.092006, Null}*)      Questions:   1. What is this `Language`ExtendedFullDefinition` and why I always get this warning? How to avoid unpacking from it? I'm using version 9.   2. Can you give more evidence on "Fourier is so fast that you loose any time you gain in the overhead of parallelism"?   3. If the slow is because of parallel over head, why `ParallelTable` is 5X faster than `ParallelMap`? Thanks a lot!


title: Function pattern to support listed and non-listed arguments

text: I often want to write functions that take as an argument either a) a rule or b) a list of rules. As an example, when using `Replace` with just one rule, it does not matter whether you give it as a list or not:               Replace[Range[10], 7->"seven", {1}]     Replace[Range[10], {7->"seven"}, {1}]      will both work as expected. Now, if I wanted to set this up, I would use the listed form throughout the function body, and add a second function pattern to actually rewrite the non- listed Rule into a List:               Replace[expr_, rules_Rule, levelspec_] := Replace[expr, {rules}, levelspec]     Replace[expr_, rules_List, levelspec_] := the function body...      Is there a way to write a pattern which matches both forms and returns the listed one? It is, of course, not too hard to write the function body in a way that it supports both forms. But actually I would like to have it done in the pattern already, so I will not have to take special care of it and can easily extend existing functions to support this feature.


title: ParallelEvaluate: Evaluation Rules and Increment

text: I'm trying to understand how `ParallelEvaluate` works, considering the two following snippets:               count = 1;       SetSharedVariable[count];       ParallelEvaluate[count++]        > >     Out[320]= {1, 2, 3} >   Whereas if I do:               count = 1;       SetSharedVariable[count];       ParallelEvaluate[count = count + 1]        > >     Out[329]= {2, 2, 2} >   The output, as seen above, is quite different. The first case is mostly from the docs for SetSharedVariable. My confusion is because in the docs for the increment operator, the statements `k++` and `k = k+1` are mentioned to be the same. Therefore, could someone please explain why the parallel kernels treat the two situations differently?


title: how to store output of a function in a table for future use

text: I am new to _Mathematica_ and if this is a simple query - please excuse me for the same. I am trying to solve a equation which is a function of two variables. From the solution, I need to store the values of two variables, satisfying this equation into a table to be used for further calculation. The code is as given below :               Remove[Global]          x = 2 r Cos[v + u + γ] - r Cos [(2 v) + u + γ]        (*x coordinate*)     Nxu = D[x, u]     Nxv = D[x, v]     Nx = Nxu Nxv                                          (*normal to x*)          y = 2 r Sin[v + u + γ] - r  Sin[(2 v) + u + γ]        (*y coordinate*)     Nyu = D[y, u]     Nyv = D[y, v]     Ny = Nyu Nyv                                          (*normal to y*)          z = p u                                               (*z coordinate*)     Nzu = D[z, u]     Nzv = D[z, v]     Nz = Nzu Nzv                                          (*normal to z*)          re = 27.5     r = 16.5     g = ArcCos[((5 r^2) - (re^2))/(4 r^2)]     p = 108/(2 π)     γ = 45° 2 Pi / 360     A = 50 + r     γc = 46° 2 Pi / 360          Equation of meshing      EM [u_, v_] = Simplify[(A - x + p Cot[γc]) Nz + (A Cot[γc]) Ny + z Nx ]          ug[thet_] := With[{u = thet}, NSolve[EM[u, v] == 0 && 0 <= v <= g, v, Reals]]     Map[ug, Range[0, 2 Pi, 0.01]]


title: Why FullSimplify doesn't work here?

text: Since the emphasis of this question is on finding a workaround, I decided to post this question with an emphasis on the _explanation_ of the behavior of Mathematica. The Bessel function satisfies the following identity: $$J_{-n}(z)=(-1)^n J_n(z),\qquad n\in\mathbb Z$$ Accordingly:               In[2]:= FullSimplify[(-1)^n*BesselJ[n, z] == BesselJ[-n, z], n ∈ Integers]     Out[2]= True      However:               In[3]:= FullSimplify[(-1)^n*BesselJ[n, z] - BesselJ[-n, z], n ∈ Integers]     Out[3]= -BesselJ[-n, z] + (-1)^n BesselJ[n, z]    (*result expected : 0*)      doesn't work as expected. Some workarounds were suggested in the previous question, such as using `ToString` as the `ComplexityFunction` (in this answer):               FullSimplify[(-1)^n*BesselJ[n, z] - BesselJ[-n, z],  n ∈ Integers,                   ComplexityFunction -> (StringLength @ ToString @ # &)]      My question is: Why `FullSimplify` with no specified option value for `ComplexityFunction` (thus using the default `LeafCount`) doesn't simplify $J_{-n}(z) - (-1)^n J_n(z)$ to zero (with $n\in\mathbb Z$)?


title: How to generate a random binary tree with a given number of vertices and with a given shape, namely compact or elongated

text: I tried to generate a random binary tree with a `Table` of `RandomInteger` and to give a shape with a `LayerSizeFunction`, but the degree of the node equal to 2 is not respected. I try also by `KaryTree`, but I'm not able to do it. The folloing figures show an example of network compact and elongated, with 60 vertices, respectively: ![This one is an example of compacted tree](http://i.stack.imgur.com/apqzy.jpg) ![This one is an example of elongated tree](http://i.stack.imgur.com/fbf2B.jpg) Here is my attempt:               SeedRandom@0     TreePlot[Table[i -> RandomInteger[{0, i - 1}], {i, 1, 20}],        MultiedgeStyle -> None, SelfLoopStyle -> None,        LayerSizeFunction -> (1 # &)]      ![Mathematica graphics](http://i.stack.imgur.com/ZR2Y3.png)


title: Why is ^^ff not the same as ^^ToExpression["ff"]?

text: I want to convert a hexadecimal string to a decimal (base 10) number:               16^^ff     16^^ToExpression["ff"]      The 1st line returns the correct answer of 255, while the 2nd line gives an error. Why doesn't it work?


title: Implementing a function which generalizes the merging step in merge sort

text: One of the key steps in merge sort is the merging step. Given two sorted lists               sorted1={2,6,10,13,16,17,19};     sorted2={1,3,4,5,7,8,9,11,12,14,15,18,20};      of integers, we want to produce a new list as follows:   1. Start with an empty list `acc`.   2. Compare the first elements of `sorted1` and `sorted2`. Append the smaller one to `acc`.   3. Remove the element used in step 2 from either `sorted1` or `sorted2`.   4. If neither `sorted1` nor `sorted2` is empty, go to step 2. Otherwise append the remaining list to `acc` and output the value of `acc`. Applying this process to `sorted1` and `sorted2`, we get               acc={1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}      _Added in response to Rojo's question: We can carry out this procedure even if the two lists are not pre-sorted. So`list1` and `list2` below are not assumed to be sorted._ If there were a built-in function `MergeList` which carries out this process, it would probably take three arguments `list1`, `list2`, and `f`. Here `f` is a Boolean function of two arguments used to decide which element to pick. In the case of merge sort, `f = LessEqual`. I feel that `MergeList` is a fundamental list operation, so **Question 1: Is there such a built-in function or one very close to that?** If I were to write such a function in Scheme, I would use a recursive definition equivalent to the following:               MergeList[list1_,{},f_,acc_:{}]:=Join[acc,list1];     MergeList[{},list2_,f_,acc_:{}]:=Join[acc,list2];     MergeList[list1_,list2_,f_,acc_:{}]:=      If[       f@@First/@{list1,list2},       MergeList[Rest[list1],list2,f,Append[acc,First[list1]]],       MergeList[list1,Rest[list2],f,Append[acc,First[list2]]]      ]      _Sample output with unsorted lists:_               In[2]:= MergeList[{2,5,1},{3,6,4},LessEqual]     Out[2]= {2,3,5,1,6,4}      My impression is that recursive solutions tend to be inefficient in Mathematica, so **Question 2: What would be a better way to implement`MergeList`?** If you have tips about converting loops into their functional equivalents, feel free to mention them as well.


title: Modular arithmetic - efficiently calculating the remainders of factorials

text: When working on this question regarding the divisibility of the sum of factorials, I decided to write some code to test "small values" of the problem using the following code.               f[p_] := Total[Mod[#!, p] & /@ Range[p - 1]];     Table[Mod[f@Prime@i, Prime@i], {i, 1, 500}]      Basically, what the code does is sum up all the factorials $$1!+2!+3!+\dots+(p-1)!$$ and find the remainder modulo $p$, for prime $p$. Unfortunately, my code as written takes a very long time to run. Checking the first 500 primes takes 88.280966 seconds on my computer, but checking the first 2000 primes took me about 4 hours. Is there any way to improve the code, or is it already the best we can do? As for optimizations not involving the code, I used Wilson's Theorem, which states that for all primes $p$, $$(p-1)!\equiv-1 \bmod p$$ Using the above theorem, we can modify the code as follows.               h[p_] := Total@Flatten[{Mod[#!, p], PowerMod[(# - 1)!*(-1)^(#), -1, p]} & /@ Range[(p - 1)/2]];     Table[Mod[h@Prime@i, Prime@i], {i, 1, 500}]      This is considerably faster than the previous code, since checking the first 500 primes takes only 25.896166 seconds. However, checking the first 2000 primes still takes an inordinately long time.


title: How to approximate a given WAV file with trigonometric series?

text: I'd like (together with a few people) to prepare a presentation about Fourier series for middle/high school students. I thought it might be quite cool to play a violin sound from, say, a WAV file, then approximate it by the first one, two, three etc. terms of the corresponding Fourier series. Assuming that I have the WAV file (and it is just one note with known frequency), how could I do this? This can be distilled to two problems: (1) transforming WAV to a list of data (and that is the easy part) and (2) finding the Fourier series of the function, whose sample is that list. AFAIK, `FourierSeries` expects a function and not a list, and it seems that `Fourier` won't help me here. I could transform the list into a function by writing a function doing, say, linear interpolation of the data in the list by hand, but this seems overly complicated. Any ideas?


title: Adding and subtracting from elements in a list

text: I'm trying to solve an aparently simple problem. Given a list of length `n`, `{a1,b1,c1,d1...}` I want to perform two simple operations, and form a new list from each one: `{a1+1,b1-1,c1,d1...}`, `{a1,b1+1,c1-1,d1...}`, `{a1,b1,c1+1,d1-1...}` and so on, and `{a1-1,b1+1,c1,d1...}` and so on. The list elements must not be greater or less than certain values after the addition or substraction. In `{a1+1,b1-1,c1,d1...}`, `{a1,b1+1,c1-1,d1...}`, `{a1,b1,c1+1,d1-1...}` each element must be constrained: `a1<max` and `b1>0`, `b1<max` and `c1>0`, etc. Using this lists I finally use the original list and the `n` new lists to get a list of the form: `{Join[list,new1],Join[list,new2],...}` To solve this problem I wrote a code that although works, takes a very long time to calculate for several sets of list `{{a1,b1,c1,d1...}, {a2,b2,c2,d2...}...}`. Here I post an example using only a list with two sublists, with four elements each one: `{{1, 2, 0, 2}, {2, 2, 1, 1}}`               lst1 = {{1, 2, 0, 2}, {2, 2, 1, 1}};     dim = Partition[Range[Length@First@lst1], 2, 1];     list = li[]; (*to save the "composed" lists*)          (lst = #;     lst2 = Partition[lst, 2, 1];          lst31 = MapThread[If[#1 < 2 && #2 > 0, {#1 + 1, #2 - 1}, {#1, #2}] &,Transpose@lst2];     lst41 = Union@MapThread[ReplacePart[lst, {#1[[1]]-> #2[[1]], #1[[2]]-> #2[[2]]}]&, {dim,lst31}];          lst32 = MapThread[If[#1 > 0 && #2 < 2, {#1 - 1, #2 + 1}, {#1, #2}]&,Transpose@lst2];     lst42 = Union@MapThread[ReplacePart[lst, {#1[[1]]-> #2[[1]], #1[[2]]-> #2[[2]]}]&, {dim, lst32}];          lst61 = Join[lst, #] & /@ lst41;     lst62 = Join[lst, #] & /@ lst42;     lst6 = Union@Join[lst61, lst62];     list = li[list, lst6];     ) & /@ lst1;          list = List @@ Flatten@list      Any advice to improve the performance of the code would be greatly appreciated! **Edit** Based on comments, I tried to explain better the second part of my problem giving a numerical example. **Edit 2** I have added a more precise description about the constraints of the elements of the lists.


title: Get value for a variable from user inside a module

text: I am writing a module. When I run the module, I want it to ask for a variable, like I can in other programing languages such as C++ or Python. For example, in C++:               int i;     cout << "Please enter an integer value: ";     cin >> i;      I want something similar to the above in _Mathematica_.


title: How to take input from user?

text: Since I'm new to _Mathematica_ I want to have a Notebook which takes inputs from user and returns average of the inputs entered and plots it on x-y coordinate. How can I do this?


title: How to display operations on list elements

text: When applying some arithmetic operation on two lists, I'd like to display the actual operations between the elements of each list. For example, `{1, 1} + {1, -1}` would display `{1 + 1, 1 - 1}`. With simple operations, I could just use `Trace` and pick out the part with the right form:               Trace[{1, 1} + {1, -1}, {_Plus, _Plus}]     (* {{1+1,1-1}} *)      However, this becomes really cumbersome in more complex operations. Even worse, some operations don't even show element-by-element operations within `Trace`.               Trace[{{1, 2}, {3, 4}}.{{5, 6}, {7, 8}}]     (* {{{1,2},{3,4}}.{{5,6},{7,8}},{{19,22},{43,50}}} *)      This is what I actually want to display: ![Mathematica graphics](http://i.stack.imgur.com/zyOrJ.png) Of course I could programmatically display the element operation of the matrix multiplication above, but I have to do the same for every other matrix operations. * * * **My question is:** Is there a straightforward way to display operations on elements of two lists? Please feel free to add your own examples and make it as general as you want to.


title: how to write string to file without Quotation mark

text: I am trying to Write String to file, something like this:               Write["test.txt", "This is a test"];      when I opened the file I found that the string was written with the Quotation mark " like this: "This is a test" how can I write only the string text? **Note:** "This is a test" is part of matrix and I can't manually type it like this:               Write["test.txt", This is a test];


title: NDSolve problem with matrix valued function

text: I got a strange problem when using `NDSolve` to solve a matrix value function               σ[t] = {{σx[t], σxy[t]}, {σyx[t], σy[t]}}      when I try to solve it in a compact form. Here is the initialization code:               Clear[t]     F = {{1, t}, {0, 1}};     LL = D[F, t].Inverse[F];      DD = 1/2 (LL + Transpose[LL]);     WW = 1/2 (LL - Transpose[LL]);     U = MatrixPower[Transpose[F].F, 1/2];     R = F.Inverse[U];     Ω = Simplify[D[R, t].Transpose[R]];     λ = 1;     μ = 1;      Now Ω is a 2 x 2 matrix with variable t. When I directly specify the form of σ, and I can get the problem solved:               σ = ({{σx[t], σxy[t]},{σyx[t], σy[t]}});     sol = NDSolve[{         D[σ, t] == (λ*Tr[DD])*IdentityMatrix[2] + 2 μ*DD + Ω.σ + σ.Transpose[Ω],         (σ /. t -> 0) == ({{0, 0}, {0, 0}})       },      {σx, σy, σxy, σyx},      {t, 0, 5}]      However, if I try to define `{σx[t], σxy[t]},{σyx[t], σy[t]}}` as a single `σ[t]`, which is more elegant, there will be problem:               Clear[σ];     func[X_?ArrayQ] := (λ*Tr[DD])*IdentityMatrix[2] + 2 μ*DD + Ω.X + X.Transpose[Ω];     sol = NDSolve[{         D[σ[t], t] == func[σ][t]],          σ[0] == ({{0, 0},{0, 0}})       }, σ, {t, 0, 5}]      The problem lays in the fact that the variable t in matrix Ω is not treated as the same as the t inside the `NDSolve`. Can you help me fix this?


title: multiple sequential definitions, defining own set function

text: I want to define a function for doing multiple definitions, where I apply the same function `f` to all values, and definitions are done not at the same time but after each other. A simple example: the function I want is `multiDef`, where               multiDef[{{a, 1}, {b, 2}, {c, a}}, f]      should be identical to the sequence of assignments               a = f[1];     b = f[2];     c = f[a];      A simple attempt, with slightly different syntax, is               multiDef[list1_List, list2_List, fct_] /; Length[list1] == Length[list2] :=        list1 = fct /@ list2      Aside from the different syntax the problem here is that it will not set `c` to `f[f[1]]`, but to `f[a]` (or to `f[5]` if we had `a = 5` before running this).


title: Specifying parameters for the Ticks option

text: I'm trying to use `Ticks` option with `ListLinePlot` to put ticks at 1, 2, 3, 4, 5, 6, and 7 on the x-axis the points and at 1, 2, 3, 4, and 5 on the y-axis, but all I get is 1 on the y-axis.               Ticks->{{1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}}


title: Generate Random 3D Network using GraphPlot3D and loop

text: Instead of writing all this out I want to do the same thing with a loop and be able to manipulate n and k. The idea is to create a randomly generated network where n is the number of nodes and k is the number of connections between each node. I've gotten close using `While` and `Table` but haven't quite figured out how to make it work. Any suggestions?               Manipulate[          GraphPlot3D[{1 -> RandomInteger[{1, n}],             1 -> RandomInteger[{1, n}], 1 -> RandomInteger[{1, n}],              1 -> RandomInteger[{1, n}], 1 -> RandomInteger[{1, n}],              1 -> RandomInteger[{1, n}], 1 -> RandomInteger[{1, n}],              1 -> RandomInteger[{1, n}], 1 -> RandomInteger[{1, n}],             2 -> RandomInteger[{1, n}], 2 -> RandomInteger[{1, n}],              2 -> RandomInteger[{1, n}], 2 -> RandomInteger[{1, n}],              2 -> RandomInteger[{1, n}], 2 -> RandomInteger[{1, n}],              2 -> RandomInteger[{1, n}], 2 -> RandomInteger[{1, n}],             3 -> RandomInteger[{1, n}], 3 -> RandomInteger[{1, n}],              3 -> RandomInteger[{1, n}], 3 -> RandomInteger[{1, n}],              3 -> RandomInteger[{1, n}], 3 -> RandomInteger[{1, n}],              3 -> RandomInteger[{1, n}], 3 -> RandomInteger[{1, n}],             4 -> RandomInteger[{1, n}], 4 -> RandomInteger[{1, n}],              4 -> RandomInteger[{1, n}], 4 -> RandomInteger[{1, n}],              4 -> RandomInteger[{1, n}], 4 -> RandomInteger[{1, n}],              4 -> RandomInteger[{1, n}], 4 -> RandomInteger[{1, n}],             5 -> RandomInteger[{1, n}], 5 -> RandomInteger[{1, n}],              5 -> RandomInteger[{1, n}], 5 -> RandomInteger[{1, n}],              5 -> RandomInteger[{1, n}], 5 -> RandomInteger[{1, n}],              5 -> RandomInteger[{1, n}], 5 -> RandomInteger[{1, n}],             6 -> RandomInteger[{1, n}], 6 -> RandomInteger[{1, n}],              6 -> RandomInteger[{1, n}], 6 -> RandomInteger[{1, n}],              6 -> RandomInteger[{1, n}], 6 -> RandomInteger[{1, n}],              6 -> RandomInteger[{1, n}], 6 -> RandomInteger[{1, n}],             7 -> RandomInteger[{1, n}], 7 -> RandomInteger[{1, n}],              7 -> RandomInteger[{1, n}], 7 -> RandomInteger[{1, n}],              7 -> RandomInteger[{1, n}], 7 -> RandomInteger[{1, n}],              7 -> RandomInteger[{1, n}], 7 -> RandomInteger[{1, n}],              7 -> RandomInteger[{1, n}],             8 -> RandomInteger[{1, n}], 8 -> RandomInteger[{1, n}],              8 -> RandomInteger[{1, n}], 8 -> RandomInteger[{1, n}],              8 -> RandomInteger[{1, n}], 8 -> RandomInteger[{1, n}],              8 -> RandomInteger[{1, n}], 8 -> RandomInteger[{1, n}]      },         VertexRenderingFunction -> ({White, EdgeForm[Black], Sphere[#, .1],        Black, Text[#2, #1]} &), Boxed -> False], {n, 1, 8, 1}, {k, 1, 8, 1}]


title: Patternmatching sets

text: **How to match set-patterns against sets?** A set (in the mathematical sense) is a list of elements without repetition and order of elements does not matter. For example, we have a pattern set `{3, 1}` that should match sets `{1, 3}`, `{1, 2, 3}`, `{1, 2, 3, 4}` and so on. Note, that the list-length of the pattern is not relevant: any set that contains elements 3 and 1 should match the pattern. So far, this is simple subset testing - but there are two problems:   1. Since order **does** matter for the patternmatcher, one has to write e.g. `Cases[sets, {___, 3, ___, 1, ____}|{___, 1, ___, 3, ____}]` which causes a combinatorial expansion for an increasing number of element-wise matches. Thus I used `MemberQ` instead of structural patterns.   2. I would like to use more complicated patterns, like: "Find all sets that contain 1 and 3 but not 2!". I have a working solution, but it is neither effective nor elegant in my opinion. It involves a Boolean description of the pattern (`And` to include all listed elements, `Or` to include any listed element, `Not` to exclude an element), but I am not sure it is the right way to do it. The function simply wraps each element that apperas in the pattern into `MemberQ`, so the Boolean expression translates to a logical combination of `MemberQ` and `Not@MemberQ` calls.               setCases[sets_List, patt_] := Module[{elem = Union @@ sets},        Cases[sets, _?((patt /. x_ /; MemberQ[elem, x] :> MemberQ[#, x]) &), {1}]        ];      Define a list of sets, and a list of patterns for testing:               sets = Subsets[{1, 2, 3, 4}];          patterns = {1, \[Not] 1, 1 \[And] \[Not] 2, 1 \[Or] \[Not] 2,         1 \[Or] 2 \[Or] 3, 1 \[And] 2 \[And] 3,         1 \[And] \[Not] 2 \[And] \[Not] 3, 1 \[Or] (2 \[And] \[Not] 3),         1 \[And] \[Not] (2 \[And] 3), 1 \[And] \[Not] (2 \[Or] 3),         1 \[And] \[Not] (2 \[Or] (3 \[And] \[Not] 4)),        \[Not] 1 \[And] \[Not] 2 \[And] \[Not] 3 \[And] \[Not] 4}          Grid[{#, setCases[sets, #]} & /@ patterns, Alignment -> Left,       Background -> {None, {{LightGray, White}}}, Spacings -> {1, 1}] // TraditionalForm      ![Mathematica graphics](http://i.stack.imgur.com/EXFC7.png) Let's examine one case closer, by displaying the ultimate pattern that is tested:               (1 \[Or] 2) \[And] \[Not] 3 /. x_Integer :> MemberQ[#, x]      > >     (MemberQ[#1, 1] & || (MemberQ[#1, 2] &)) && ! (MemberQ[#1, 3] &) >   As one can see, the function is far from being economic: alternatives could have been gathered under one `MemberQ` (`MemberQ[#, 1]& || MemberQ[#, 2]&` is equivalent to `MemberQ[#, 1|2]&`) and I think that `Except` should be used as well, though have no idea how. I am interested in robust, fast solutions. **Note** : Do NOT try to simplify the logical patterns, as:               Simplify[And[1, 2]] ==> 2     Simplify[And[0, 1]] ==> False


title: Coloring Bifurcation Diagram

text: I have the following Pitchfork bifurcation:               f[x_, r_] := r x - x^3      I was able to find some nice code on this site to draw up the Logistic Map. I have the following snippet (maybe there is a better solution) to draw the bifurcation diagram, but was wondering if it can be colored to represent the stable from unstable branches? ( saved the file, then modified it). We have three stable branches and one unstable branch. The unstable branch is [0, +r], see: ![enter image description here](http://i.stack.imgur.com/0pqFu.png) Is there a way to show the three branches as a solid blue line and the unstable branch as a dashed red line? Also, can we label the axes as $r$ and $x$, and the branches as stable and unstable? Here is the code snippet that drew the above bifurcation diagram (is there an easier way).                  CClear[NotComplexQ];        NotComplexQ[c_Complex] := False;        NotComplexQ[c_] := True            CartProd[l_] := Outer[List, l[[1]], l[[2]]]            ArreglaLista[l_] := Select[Map[(x /. #) &, Flatten[l]], NotComplexQ]           Points = Flatten[        Map[CartProd,         Table[{{r}, ArreglaLista[NSolve[f[x, r] == 0, x]]}, {r, -1, 2,         0.05}]], 2]           ListPlot[Points]


title: Power series with decimal and arbitrary powers

text: Is there a way to make Mathematica do a series of the form:                Series[ E^{\beta}$ , {x, 0, 1}]      I have noticed that                Series[E^x^(1/2), {x, 0, 1}]      work but                Series[E^x^(.5), {x, 0, 1}]      does not. Thanks for the help. EDIT: I have tried things like                 Assuming[{\bet>0},Series[ E^{\beta}$ , {x, 0, 1}]]      which hasn't helped.


I'm re-implementing some tools previously implemented in Java in Wolfram Language. Is there any metadata-holding mechanisms in Mathematica programming similar to Java annotations?


title: iterating piecewise linear maps on [0,1]

text: I have been trying to make code work for iterating piecewise linear maps on the unit interval in Mathematica to compare with MATLAB and Maple. Tent and logistic maps are easy to implement but Bernoulli and other non-traditional maps have been difficult (at least for me). I wish to investigate histograms of the invariant densities of map iterations for non periodic orbits.


title: Histogram of runs

text: What I would like to do is generate a histogram of the consecutive time spent under a level. For example if the level I was interested in was 1.0 and I had this data;               {{{2010, 1, 1, 6, 15, 0.}, 0.04375}, {{2010, 1, 1, 6, 30, 0.},0.04375},      {{2010, 1, 1, 6, 45, 0.},0.04375}, {{2010, 1, 1, 7, 0, 0.},5},     {{2010, 1, 1, 7, 15, 0.}, 0.5},{2010, 1, 1, 7, 30, 0.}, 5}}}      I would get a histogram containing two values, 45 (7:00am - 6:15am) and 15 (7:30am - 7:15am) minutes. Any help would be appreciated.


title: NIntegrate Error-Estimate Question

text: When I do some complicated 4-dimensional integral numerically, _Mathematica_ tells me its estimate for the value of the integral, and its estimate for the value of the error in the calculation. The integrand:               Integrand[x_, y_, z_, Ekb_] := Sqrt[-4.14195`*^-29 +1.38065`*^-29 Ekb + (1.7055100000000003`*^-29 2.71828`^(-((2.76817`*^8 ((0.986286` x + 0.165048` y)^2 + z^2))/(1.` + 4707.27` (-0.165048` x + 0.986286` y)^2))))/(1.` + 4707.27` (-0.165048` x +0.986286` y)^2) + (2.4364400000000005`*^-29 2.71828`^(-((2.76817`*^8 ((0.986286` x -0.165048` y)^2 + z^2))/(1.` + 4707.27` (0.165048` x + 0.986286` y)^2))))/(1.` + 4707.27`(0.165048` x + 0.986286` y)^2)]/(1.` + 2.71828`^(7.2429699999999995`*^28 (-2.7613`*^-29 + 1.38065`*^-29 Ekb)))      The Integration:               Re@NIntegrate[Integrand[x,y,z,Ekb],{x,-9.53853 10^(-5),9.53853 10^(-5)},{y,-57 10^(-5),57 10^(-5)},{z,-4.37824 10^(-5),4.37824 10^(-5)},{Ekb,0,7*3/17},Method ->     {"GlobalAdaptive", Method -> "MultiDimensionalRule", "MaxErrorIncreases" -> 100}]      It puts out the error message: > NIntegrate::eincr: The global error of the strategy GlobalAdaptive has > increased more than 100 times. The global error is expected to decrease > monotonically after a number of integrand evaluations. Suspect one of the > following: the working precision is insufficient for the specified precision > goal; the integrand is highly oscillatory or it is not a (piecewise) smooth > function; or the true value of the integral is 0. Increasing the value of > the GlobalAdaptive option MaxErrorIncreases might lead to a convergent > numerical integration. NIntegrate obtained 1.51764*10^-27+7.31069*10^-26 I > and 1.0039003041591675`*^-28 for the integral and error estimates. >> Should this be interpreted as (1.51764*10^-27+7.31069*10^-26 I) ± 1.0039003041591675`*^-28,   or   (1.51764*10^-27+7.31069*10^-26 I) ± 5.0195*10^-29 ?


title: What are the differences between library call back functions and WolframCompileLibrary macros?

text: I'm trying to use LibraryLink in Mathematica, and come across some problems. Consider if we have a `MTensor m1` which contains a one dimensional double array, and I want to get the data of that array. I come across two methods. One is to use library callback functions `libData->MTensor_getRealData(m1)` as shown here , the other is use the micros `MTensor_getRealDataMacro(m1)` in the `WolframCompileLibrary.h file` as shown here. What are the differences between them? Does the library call back functions are slower then the macro since they need to "call back" to Mathematica?


title: Establish connection with RLink and Rtools

text: Has anyone gotten _RLink_ to work with _Rtools_ (or even tried)? If so a simple step-by-step would be much appreciated ! When attempting to access any _Rtools_ functionality through _RLink_ I get: > The following R error was encountered: Error in system(cmd, intern = \ > !verbose) : 'C:/Program' not found Background: I'm trying to get data in and out of the _RStan_ package with _Mathematica_ (mostly because _Mathematica_ is the program I've used most for manipulating data and the more I can do in _Mathematica_ the less time I'll have to spend learning how to manipulate the data in _R_ ) and _Rtools_ is required for _RStan_. Thanks for the responses- Some new info in response to the comments: I installed R 2.15.3 (since version 3 doesn't work with RLink in Windows yet) Then:               InstallR["RHomeLocation" -> "C:\\Program Files\\R\\R-2.15.3"]      And that works for the basic RLink functionality. Through the R command line, I got the required packages installed. Then restart Mathematica, and check to make sure the packages are installed (which they are) and accessible - at least at the level that `REvaluate["library(Rcpp)"]` and `REvaluate["library(rstan)"]` both seem to work - returning a list of the loaded libraries. But then either running the "hello world" example from https://github.com/stan-dev/rstan/wiki/RStan-Getting-Started or trying to use any of the rstan commands results in the above error. Any further thoughts?


title: Creating simple table

text: How do I create a table like this? I find it very hard to create the zero-row and zero-column. ![The table](http://i.stack.imgur.com/ySDiv.png) Edit: I am looking for a solution where a formula eg. Table or something else is being used. I can already create the table manually.


title: How to declare a function that uses local variables of a module outside this module?

text: I have the following code               Module[{f,x=0},     f[t_] := x + t;     ..........;     ...f[1]...;     ..........;     ]      My aim is to put the declaration of the function `f` outside the module.


title: Inverting a function in a certain region

text: `InverseFunction` works well for globally invertible functions, like               f = 2*# + 2 &;     InverseFunction[f]      > >     1/2 (-2 + #1) & >   However, how would one for example find the inverse of $f(x)=x^2$ around $(x,f(x))=(1,1)$? My _Mathematica (8.0.4)_ gives me a warning about multivalued inverses in this case, as well as the result $-\sqrt{x}$, which is not the branch that I'm looking for:               f = #^2 &     InverseFunction[f]      > >     #1^2 & >   >     InverseFunction::ifun: >       Inverse functions are being used. Values may be lost for multivalued > inverses. >> >   >     -Sqrt[#1] & >   So: How can I specify the neighbourhood a function should be inverted on?


title: Finding the InverseFunction of a polynomial function restricted to an interval

text: I want to calculate the inverse of               f[x_] := 1/2 - (x (4 x^2 - 9))/12 /; -1/2 <= x <= 1/2      `f[x]` is monotonic inside $-0.5 < x <= 0.5$, but I don't know how to calculate its inverse.


title: Maximum of NDSolve output. Problem with interpolating function

text: I solve a NonLinear PDE and get a solution (which for other reasons I put into a vector): SolVec1[1][[2]][x,t], where x and t are the indipendent variables. Now, I would like to get a distribution of the maximum of the solution vs time. I tried two different things, but the most intuitive and quick doesn't work. 1) A For loop to fill the function of the maxima >>> works but takes very long.               For[it = 0, it <= T, it++,             MAX1[it] = First[Maximize[SolVec1[[1]][[2]][x, it], 0 <= x <= L , x]];           ]      2) Defining a function MAX1[t] of time, and then plot it >>> doesn't work.               MAX1[t_] := First[Maximize[SolVec1[[1]][[2]][x, t],      0 <= x <= L , x]];           Plot[Evaluate[MAX1[t]], {t, 0, T}, PlotRange -> All,       AxesLabel -> {"t", "Max[\[Theta]]"}, Frame -> True,       PlotLabel -> "Max[\[Theta]](t), A=0"]          NMaximize::nnum: The function value -InterpolatingFunction[{{0.,10.},{0.,15.}},{3,10,1,     {25,228},{6,4},0,0,0,0},<<1>>,{Developer`PackedArrayForm,{<<1>>},{<<1>>}},     {Automatic,Automatic}][<<1>>] is not a number at {x} = {6.52468}. >>      Edit: SolVec1[1][[2]] is the solution coming out from a call of NDSolve.               u[\[Lambda]_, \[Omega]_, v_, \[Alpha]a_, aa_, A_] = -(1/(1 + \[Lambda]^2*(aa + A E ^-\[Phi][x, t])*Sin[2*\[Theta][x, t]]^2))*((aa + A E ^-\[Phi][x, t])*\[Lambda]*\[Omega]*\!\(\*SuperscriptBox["\[Theta]", TagBox[RowBox[{"(", RowBox[{"1", ",", "0"}], ")"}],Derivative],MultilineFunction->None]\)[x, t]^2*Sin[2*\[Theta][x, t]]*      Sin[\[Theta][x, t]]^2 -       2*(aa + A E ^-\[Phi][x, t])*v*\[Phi][x, t]^2*\!\(\*SuperscriptBox["\[Theta]", TagBox[RowBox[{"(", RowBox[{"1", ",", "0"}], ")"}],Derivative],MultilineFunction->None]\)[x, t]*      Sin[\[Theta][x, t]] + (aa +          A E ^-\[Phi][x, t])*\[Alpha]a*\[Phi][x, t]^2*       Sin[2*\[Theta][x, t]] + \!\(\*SuperscriptBox["\[Phi]", TagBox[RowBox[{"(", RowBox[{"1", ",", "0"}], ")"}],Derivative],MultilineFunction->None]\)[x, t]*      Cos[\[Theta][x,          t]]*(\[Omega] - \[Lambda]*\[Omega]*Cos[2*\[Theta][x, t]]));               eqn1[\[Lambda]_, w_, v_, \[Alpha]a_, a_, A_] := \!\(\*SubscriptBox[\(\[PartialD]\), \(t\)]\ \(\[Theta][x, t]\)\) - (\!\(\*SuperscriptBox["\[Theta]", TagBox[RowBox[{"(", RowBox[{"2", ",", "0"}], ")"}],Derivative],MultilineFunction->None]\)[x,        t] (1 - w Cos[\[Theta][x, t]]^2) (a + A E^\[Phi][x, t]) +      1/2*(a + A E^\[Phi][x, t]) w \!\(\*SuperscriptBox["\[Theta]", TagBox[RowBox[{"(", RowBox[{"1", ",", "0"}], ")"}],Derivative],MultilineFunction->None]\)[x, t]^2 Sin[2 \[Theta][x, t]] - \[Phi][x,        t] (a + A E^-\[Phi][x, t]) v \!\(\*SuperscriptBox["\[Theta]", TagBox[RowBox[{"(", RowBox[{"1", ",", "0"}], ")"}],Derivative],MultilineFunction->None]\)[x, t] Sin[\[Theta][x, t]] -      u[\[Lambda], w, v, \[Alpha]a, a,        A] (1 - \[Lambda] Cos[2 \[Theta][x, t]]) + (a +         A E^\[Phi][x, t]) w \!\(\*SuperscriptBox["\[Phi]", TagBox[RowBox[{"(", RowBox[{"1", ",", "0"}], ")"}],Derivative],MultilineFunction->None]\)[x, t] Cos[\[Theta][x, t]]);               eqn2[\[Lambda]_, w_, v_, \[Alpha]a_, a_, A_] := \!\(\*SubscriptBox[\(\[PartialD]\), (t\)]\ \(\[Phi][x, t]\)\) - \!\(\*SubscriptBox[\(\[PartialD]\), \(x\)]\ \((v \((a +\*StyleBox["A",FontSize->10]\*StyleBox[" ",FontSize->10]\*SuperscriptBox[StyleBox["E",FontSize->10], RowBox[{"-", RowBox[{"\[Phi]", "[", RowBox[{"x", ",", "t"}], "]"}]}]])\) SuperscriptBox[\(\[Phi][x, t]\), \(2\)] Sin[\[Theta][x,          t]] + \((DD \((1 - \[Xi]\ \*SuperscriptBox[\(Sin[\[Theta][x, t]]\), \(2\)])\) - w\ \*SuperscriptBox[\(Cos[\[Theta][x, t]]\), \(2\)])\)\ *\((a + \*StyleBox["A",FontSize->10]\*StyleBox[" ",FontSize->10]\*SuperscriptBox[StyleBox["E",FontSize->10], RowBox[{"\[Phi]", "[", RowBox[{"x", ",", "t"}], "]"}]])\)*\ \*SuperscriptBox["\[Phi]", TagBox[RowBox[{"(", RowBox[{"1", ",", "0"}], ")"}],Derivative],MultilineFunction->None][x, t] + \[Lambda]\ u[\[Lambda], w,         v, \[Alpha]a, a, A]\ Sin[\[Theta][x, t]]\ Sin[        2\ \[Theta][x, t]])\)\);                     sol1 = {\[Theta], \[Phi]} /. First[NDSolve[{       eqn1[\[Lambda], w, \[Beta], \[Alpha]j, 1, 0] == 0,       eqn2[\[Lambda], w, \[Beta], \[Alpha]j, 1, 0] == 0,       \[Theta][0, t] == 0,       \[Theta][L, t] == 0,       \[Theta][x, 0] == First[InitialMode[x, 1, 0.5]],          \!\(\*SuperscriptBox["\[Phi]", TagBox[RowBox[{"(", RowBox[{"1", ",", "0"}], ")"}],Derivative],MultilineFunction->None]\)[0, t] == 0,          \!\(\*SuperscriptBox["\[Phi]", TagBox[RowBox[{"(", RowBox[{"1", ",", "0"}], ")"}],Derivative],MultilineFunction->None]\)[L, t] == 0,       \[Phi][x, 0] == Last[InitialMode[x, 1, 0.5]]},      {\[Theta], \[Phi]}, {x, 0,        L}, {t, 0, T}, AccuracyGoal -> 4, PrecisionGoal -> 5]] ;          SolVec1[[i]] = {sol1[[1]], sol1[[2]]};      Plotting at the point ($x\simeq6.525$), nothing special happens:                In[124]:= Plot[SolVec1[[1]][[2]][6.5246780797402835`, t], {t, 0, T}, PlotRange ->All]      ![enter image description here](http://i.stack.imgur.com/lpoXV.png)


title: Questions regarding DictionaryLookup of Mathematica

text: **a.** Make a function `longest[lang_]` that gives the length of the longest word in the dictionary of lang. You should get `longest["French"]=25` For this part, I have `lang = DictionaryLookup[All];`   `longest[lang_] := Max[StringLength[lang]]` But this isn't working. **b.** Now give a list with entries `{language,longest[language]}`. `Table[{lang[[i]], Length[DictionaryLookup[{lang[[i]], All}]]}, {i, 1, Length[lang]}]` Again not working **c.** Make a function `lonegestwords[lang_]` that gives the output `{longest[lang],lang,longwords}` where `longwords` is the list of the words of longest length in lang. I tried `longestwords[lang_] := {longest[lang], lang, Select[DictionaryLookup[{lang, All}], StringLength[#] == longest[lang] &]}` **d.** Now get the list with entries `longestwords[lang]` for all languages and sort it in descending order by the longest word. I know that I have to use `Sort[longestwords[lang],#2[[1]]<#1[[1]]&]` But since I don't have the function, I can't do it.


title: Rotating perspective of an image in the z axis

text: A purely recreational question, but one I hoped the community would find interesting enough to suggest a way to approach it. Let me preface this question with the admission that I have done nothing to date with Mathematica's image processing or any other program's image processing. I don't even take photos. I have an photo of a wall mural: ![mural](http://i.stack.imgur.com/DOGOB.jpg) taken at an angle of approximately 40 degrees to its center. The mural no longer exists so I can't rephotograph it. I'd like to process this image so that I would get an image as if I had a perspective perpendicular to the center (or approximate center) of the mural. One could think of it as say anchoring the right edge of the image and then pulling the left edge forward. Or think of it as the plane of the white wall having an x and y axis with the origin at the center of the image, then I want to rotate the image in the z axis. I've reviewed Mathematica's image processing functions. I hoped I'd find an obvious way to do this, perhaps using the Morphological Analysis capabilities, but everything appears 2D oriented. I recognize the difficulty of the problem. Rotating the perspective would require everything to the left of the y axis to enlarge relative to its distance from the y axis while simultaneously doing the inverse to the right of the axis. 3D plots do this inherently, which is why I thought one ought to be able to do this. `ImageData[] and RotationTransform[]` seem likely candidates to do this. The documentation show how to create a `TransformationFunction[]`: ![enter image description here](http://i.stack.imgur.com/wCkBd.png) The ideas to do this exist, but I haven't found an example of this applied to an image in the way I want to do it. In the end, I only want the colors of the mural on a white background, like a poster image, I don't need the lighting or the floor or gradations of color. Solid colors for each of the elements would work fine. Doing these things seems relatively straightforward and should reduce the size of a raster file or the amount of data one needs to process and move around. Can anyone direct me towards any examples or even documentation on how to approach this? P.S., Can everyone see the wolf in the mural? * * * I wanted to show what I got to with Vitaliy Kaurov's solution:                t = FindGeometricTransform[{{1924.19`, 880.846`}, {154.761`,           1200.69`}, {190.872`, 189.582`}, {1893.24`,           297.914`}}, {{1924.19`, 880.846`}, {175.395`,           1283.22`}, {175.395`, 571.325`}, {1893.24`, 297.914`}},         "Transformation" -> "Perspective"];          ImagePerspectiveTransformation[image, t[[2]], 1000, DataRange -> Full,        PlotRange -> All];     ImageTake[%, {100, 480}, {120, 965}];     ImageAdjust[Lighter[Lighter[%]], 0.85]      ![enter image description here](http://i.stack.imgur.com/7dJw6.png) This gets me closer to what I hoped than I imagined possible. Given that the original artist constructed the mural as a collage from rectangular sheets of paper, most of which have gone trapezoidalish I still need to twist the image to restore some of what original photo and image processing has skewed. If I figure it out in a reasonable time I'll post the final image. Thanks to all.


title: How to extract a variable names (not values) from a list of transformation rules?

text: I am trying to extract variable names from a list of transformation rules `mapping = {var1 -> 'val1', var2 -> 'val2' }`. Variables `var1` and `var2` are already defined in my notebook: ` var1 = 'init-val1'; var2 = 'init-val2'; ` When I try to evaluate `Extract[mapping, {1,1}, HoldForm]`, I get `'init- val1'`, instead of `var1`. What am I doing wrong? Why is `var1` getting evaluated despite the explicit `HoldForm` wrapper? How can I fix the problem?


title: Why does Mathematica use [[ ]] notation for array indexing?

text: I am confused by why _Mathematica_ uses `[[3]]` to get the 3rd element, or `[[i,j]` to get the i,j-th element of a 2D array. This seems counter-intuitive. Is this main reason for this to separate array- indexing from function calls? i.e. where I see:               f[3, 4] <-- this is currently function call     f[[3, 4]] <-- f is a 2D array, and we're accessing 3,4-th element      **Question** : Given that Mathematica knows the type of the arguments, can't it infer:   * if we're dealing with a function, apply arguments   * if the object is an array, index it? Thus, why do we need separate `[[ ]]` notation for array indexing?


title: Convex optimization

text: I am playing with some Compressed Sensing (think single pixel camera) applications and would like to have a Mathematica equivalent of a Matlab package call Convex Optimization (CVX). Specifically, I am solving an underdetermined, constrained, L1Norm minimization problem. I have been using NMinimize, but it very slow compared to the Matlab code written by a colleague. I don’t want to give him the pleasure of thinking Matlab is superior. I am sure that the long run times are due to my poor programing skills. The solution is sparse but I do not know how to add that as an additional constraint. Anyway, seems I can’t find a good reference for compressed sensing in Mathematica. Any suggestions would be great!


title: Optimizing a rank 3 tensor

text: Assume we have the following elements \begin{equation} F_i{}^j \;and\; S_{ij}{}^k, \end{equation} which represent the components of tensorial objects of ranks 2 and 3 respectively, with Complex coefficients. Let the components of $F$ be given by $F_1{}^j$ = \begin{matrix} 0 \\\ -x-iy \\\ -i(-1+x^2+2ixy-y^2+z^2)/2z \\\ (1-x^2-2ixy+y^2+z^2)/2z \end{matrix} $F_2{}^j$ = \begin{matrix} x+iy \\\ 0\\\ (1-x^2-2ixy+y^2+z^2)/2z\\\ i(-1+x^2+2ixy-y^2+z^2)/2z \end{matrix} $F_3{}^j$ = \begin{matrix} i(-1+x^2+2ixy-y^2+z^2)/2z\\\ -(1-x^2-2ixy+y^2+z^2)/2z \\\ 0\\\ -x-iy \end{matrix} $F_4{}^j$ = \begin{matrix} -(1-x^2-2ixy+y^2+z^2)/2z\\\ -i(-1+x^2+2ixy-y^2+z^2)/2z\\\ x+iy\\\ 0 \end{matrix} ($j=1,2,3,4$). We would like to solve for the components of $S$ if they satisfy the following equation \begin{equation} S_{li}{}^jF_k{}^l-S_{lk}{}^jF_i{}^l=0, \end{equation} where $l$ is summed over, all the indices run from 1 to 4, and $S$ is symmetric in the lower indices. Would it be possible to write a code that find the components of $S$? The code provided in my previous question Solving antisymmetric tensorial equation would work well for simple examples of $F$, but not for the example we have here.


title: Replace values of a list containing words and numbers

text: I'm trying to import some data in a .txt file which contains numbers and words. I import a list which consists of four rows of measured data acquired with an oscilloscope, but the acquisition program puts units in every measured value. Here's an example:               data={{-1.1000u s,-120.00m V,-1.1000u s,8.0000 V},           {-1.0800u s,-120.00m V,-1.0800u s,8.0000 V},           {-60.000n s,-40.000m V,-60.000n s,8.0000 V},           {-40.000n s,-40.000m V,-40.000n s,8.0000 V},           {-20.000n s,-32.000m V,-20.000n s,8.0000 V},           {0.0000 s,-32.000m V,0.0000 s,8.0000 V}}      I would like to know if there's any way I can turn the above list into something more like this:               newdata={{-1.1000,-0.12000,-1.1000,8.0000},              {-0.060000,-0.040000,-0.060000,8.0000},              {-0.040000,-0.040.000,-0.040000,8.0000},              {-0.020000,-0.032000,-0.020.000,8.0000},              {0.0000,-0.032000,0.0000,8.0000}}      I'll appreciate any ideas. Thanks.


title: How to make Eigensystem in version 10 produce the same results as version 9

text: The Eigensystem in version 10 seems to give slightly different results as in version 9:               Hmtx={{12.375, -0.06250000000000006 - 8.834874115176436*^-18*I, -1.1548235516929313*^-17 - 4.417437057588218*^-18*I, 7.507272729062478*^-19 + 2.4295903816735198*^-17*I, 3.5296840598063115*^-17 - 4.417437057588218*^-18*I, 6.284659706684547*^-19 - 2.6504622345529306*^-17*I, -1.2338675571278232*^-17 - 2.208718528794109*^-18*I, -4.6634340043469916*^-18 - 1.1043592643970545*^-18*I, 5.9846202809437726*^-18 - 1.8774107494749925*^-17*I, -5.0917886236526596*^-17 - 3.6443855725102797*^-17*I, -1.7364763179227213*^-17 + 5.2457065058860084*^-17*I}, {-0.06250000000000006 + 8.834874115176436*^-18*I, 7.875, -0.06250000000000006 - 8.834874115176436*^-18*I, -1.1548235516929313*^-17 - 4.417437057588218*^-18*I, 7.507272729062478*^-19 + 2.4295903816735198*^-17*I, 3.5296840598063115*^-17 - 4.417437057588218*^-18*I, 6.284659706684547*^-19 - 2.6504622345529306*^-17*I, -1.2338675571278232*^-17 - 2.208718528794109*^-18*I, -4.6634340043469916*^-18 - 1.1043592643970545*^-18*I, 5.9846202809437726*^-18 - 1.8774107494749925*^-17*I, -5.0917886236526596*^-17 - 3.6443855725102797*^-17*I}, {-1.1548235516929313*^-17 + 4.417437057588218*^-18*I, -0.06250000000000006 + 8.834874115176436*^-18*I, 4.375, -0.06250000000000006 - 8.834874115176436*^-18*I, -1.1548235516929313*^-17 - 4.417437057588218*^-18*I, 7.507272729062478*^-19 + 2.4295903816735198*^-17*I, 3.5296840598063115*^-17 - 4.417437057588218*^-18*I, 6.284659706684547*^-19 - 2.6504622345529306*^-17*I, -1.2338675571278232*^-17 - 2.208718528794109*^-18*I, -4.6634340043469916*^-18 - 1.1043592643970545*^-18*I, 5.9846202809437726*^-18 - 1.8774107494749925*^-17*I}, {7.507272729062478*^-19 - 2.4295903816735198*^-17*I, -1.1548235516929313*^-17 + 4.417437057588218*^-18*I, -0.06250000000000006 + 8.834874115176436*^-18*I, 1.8749999999999998, -0.06250000000000006 - 8.834874115176436*^-18*I, -1.1548235516929313*^-17 - 4.417437057588218*^-18*I, 7.507272729062478*^-19 + 2.4295903816735198*^-17*I, 3.5296840598063115*^-17 - 4.417437057588218*^-18*I, 6.284659706684547*^-19 - 2.6504622345529306*^-17*I, -1.2338675571278232*^-17 - 2.208718528794109*^-18*I, -4.6634340043469916*^-18 - 1.1043592643970545*^-18*I}, {3.5296840598063115*^-17 + 4.417437057588218*^-18*I, 7.507272729062478*^-19 - 2.4295903816735198*^-17*I, -1.1548235516929313*^-17 + 4.417437057588218*^-18*I, -0.06250000000000006 + 8.834874115176436*^-18*I, 0.3749999999999999, -0.06250000000000006 - 8.834874115176436*^-18*I, -1.1548235516929313*^-17 - 4.417437057588218*^-18*I, 7.507272729062478*^-19 + 2.4295903816735198*^-17*I, 3.5296840598063115*^-17 - 4.417437057588218*^-18*I, 6.284659706684547*^-19 - 2.6504622345529306*^-17*I, -1.2338675571278232*^-17 - 2.208718528794109*^-18*I}, {6.284659706684547*^-19 + 2.6504622345529306*^-17*I, 3.5296840598063115*^-17 + 4.417437057588218*^-18*I, 7.507272729062478*^-19 - 2.4295903816735198*^-17*I, -1.1548235516929313*^-17 + 4.417437057588218*^-18*I, -0.06250000000000006 + 8.834874115176436*^-18*I, -0.12500000000000014, -0.06250000000000006 - 8.834874115176436*^-18*I, -1.1548235516929313*^-17 - 4.417437057588218*^-18*I, 7.507272729062478*^-19 + 2.4295903816735198*^-17*I, 3.5296840598063115*^-17 - 4.417437057588218*^-18*I, 6.284659706684547*^-19 - 2.6504622345529306*^-17*I}, {-1.2338675571278232*^-17 + 2.208718528794109*^-18*I, 6.284659706684547*^-19 + 2.6504622345529306*^-17*I, 3.5296840598063115*^-17 + 4.417437057588218*^-18*I, 7.507272729062478*^-19 - 2.4295903816735198*^-17*I, -1.1548235516929313*^-17 + 4.417437057588218*^-18*I, -0.06250000000000006 + 8.834874115176436*^-18*I, 0.3749999999999999, -0.06250000000000006 - 8.834874115176436*^-18*I, -1.1548235516929313*^-17 - 4.417437057588218*^-18*I, 7.507272729062478*^-19 + 2.4295903816735198*^-17*I, 3.5296840598063115*^-17 - 4.417437057588218*^-18*I}, {-4.6634340043469916*^-18 + 1.1043592643970545*^-18*I, -1.2338675571278232*^-17 + 2.208718528794109*^-18*I, 6.284659706684547*^-19 + 2.6504622345529306*^-17*I, 3.5296840598063115*^-17 + 4.417437057588218*^-18*I, 7.507272729062478*^-19 - 2.4295903816735198*^-17*I, -1.1548235516929313*^-17 + 4.417437057588218*^-18*I, -0.06250000000000006 + 8.834874115176436*^-18*I, 1.8749999999999998, -0.06250000000000006 - 8.834874115176436*^-18*I, -1.1548235516929313*^-17 - 4.417437057588218*^-18*I, 7.507272729062478*^-19 + 2.4295903816735198*^-17*I}, {5.9846202809437726*^-18 + 1.8774107494749925*^-17*I, -4.6634340043469916*^-18 + 1.1043592643970545*^-18*I, -1.2338675571278232*^-17 + 2.208718528794109*^-18*I, 6.284659706684547*^-19 + 2.6504622345529306*^-17*I, 3.5296840598063115*^-17 + 4.417437057588218*^-18*I, 7.507272729062478*^-19 - 2.4295903816735198*^-17*I, -1.1548235516929313*^-17 + 4.417437057588218*^-18*I, -0.06250000000000006 + 8.834874115176436*^-18*I, 4.375, -0.06250000000000006 - 8.834874115176436*^-18*I, -1.1548235516929313*^-17 - 4.417437057588218*^-18*I}, {-5.0917886236526596*^-17 + 3.6443855725102797*^-17*I, 5.9846202809437726*^-18 + 1.8774107494749925*^-17*I, -4.6634340043469916*^-18 + 1.1043592643970545*^-18*I, -1.2338675571278232*^-17 + 2.208718528794109*^-18*I, 6.284659706684547*^-19 + 2.6504622345529306*^-17*I, 3.5296840598063115*^-17 + 4.417437057588218*^-18*I, 7.507272729062478*^-19 - 2.4295903816735198*^-17*I, -1.1548235516929313*^-17 + 4.417437057588218*^-18*I, -0.06250000000000006 + 8.834874115176436*^-18*I, 7.875, -0.06250000000000006 - 8.834874115176436*^-18*I}, {-1.7364763179227213*^-17 - 5.2457065058860084*^-17*I, -5.0917886236526596*^-17 + 3.6443855725102797*^-17*I, 5.9846202809437726*^-18 + 1.8774107494749925*^-17*I, -4.6634340043469916*^-18 + 1.1043592643970545*^-18*I, -1.2338675571278232*^-17 + 2.208718528794109*^-18*I, 6.284659706684547*^-19 + 2.6504622345529306*^-17*I, 3.5296840598063115*^-17 + 4.417437057588218*^-18*I, 7.507272729062478*^-19 - 2.4295903816735198*^-17*I, -1.1548235516929313*^-17 + 4.417437057588218*^-18*I, -0.06250000000000006 + 8.834874115176436*^-18*I, 12.375}};          {vals, vecs} = Eigensystem[Hmtx];     vals     vecs[[1]]      in version 9 I get: eigenvalue               (*     {12.3759, 12.3759, 7.87525, 7.87525, 4.37545, 4.37545, 1.87605, 1.87604, 0.387613, 0.372399, -0.140221}     *)      first eigenvector               (*     {-0.000534641 + 0.00179264 I, 7.42495*10^-6 - 0.0000248957 I, -5.80038*10^-8 + 1.94486*10^-7 I,  3.45242*10^-10 - 1.15759*10^-9 I, -1.71049*10^-12 +  6.02886*10^-12 I, -1.68042*10^-11 - 3.01451*10^-14 I,  3.36278*10^-9 + 1.56589*10^-16 I, -6.45683*10^-7 + 1.38957*10^-18 I, 0.00010848 - 5.32021*10^-19 I, -0.0138864 -  1.97975*10^-18 I, 0.999902}     *)      in version 10 I get: eigenvalue               (*     {12.3759 - 1.02031*10^-15 I, 12.3759 - 9.91618*10^-29 I, 7.87525 - 8.85813*10^-16 I, 7.87525 - 4.21836*10^-20 I,  4.37545 + 8.4819*10^-17 I, 4.37545 + 8.48193*10^-17 I, 1.87605 - 9.81335*10^-20 I, 1.87604 - 9.81346*10^-20 I,  0.387613 - 1.396*10^-22 I,  0.372399 - 1.40297*10^-22 I, -0.140221 - 1.24838*10^-24 I}     *)      first eigenvector               (*     {-0.00639256 + 0.0131895 I,  0.0000887781 - 0.000183172 I, -6.93536*10^-7 + 1.43094*10^-6 I,  4.12798*10^-9 - 8.51706*10^-9 I, -2.14113*10^-11 +   4.43576*10^-11 I, -1.67039*10^-11 - 2.21781*10^-13 I,  3.36242*10^-9 + 1.15472*10^-15 I, -6.45615*10^-7 + 1.42743*10^-17 I,  0.000108469 - 7.67751*10^-17 I, -0.0138849 - 4.92661*10^-16 I,  0.999796 + 0. I}     *)      How can I make version 10 produce the same results as version 9? How can I know which method is used in version 9? I tried to set the `Method` options in version 10 but still unable to get an agreement. **Edit** I agree that the comments are all right, that they are both correct results. I'm curious what's the change in the "internal mechanism", method, etc, so that it produce different correct results. I use this Eigensystem in calculating some quantum mechanic problem called high harmonic generation, which is very sensitive to small errors in the results. In theory , an overall phase change should not effect my results, but after upgrading to version 10, the noise floor in my results increase more then one order of magnitude. I'm trying to see why that happens, and this is my first stop. Mathematica is now a language, I guess I would expect to have exactly the same results if I update the "compiler", or at least I should know why the results are different.


title: Context Sensitive Formatting for a Table

text: Suppose I am calculating the correlation of a a set of vectors.               Correlation[RandomReal[1, {5,5}]]      I would like to display the output using TableForm or Grid and use either Style or Background to highlight the entries that exceed some threshold (say > .5 and < -.5) I found How can I add row and column header images to my TableForm output? which highlights the minimum in each row using:                   TableForm[With[{min = Min[#]}, # /. min -> Style[min, Red]] & /@ data,      TableHeadings -> {ConstantArray[lena, 3], ConstantArray[lena, 9]}]      Can someone help me adapt this for my purpose? Edit: Of course I can do it this way:                data = RandomReal[1,{5,5}];      cors = Round[Correlation[data], .01];      Table[Style[cors[[i, j]],       If[Abs[cors[[i, j]]] > .35, Red, Black]], {i, 1, 5}, {j, 1, 5}] // TableForm      but I would like to understand how to do it in one line Edit #2: Here is the inelegant solution I came up with:                cors = Correlation[RandomReal[1, {5, 5}]];      headers = Table["Header " <> ToString[j], {j, 1, 5}];      backs = Table[ If[cors[[i, j]] > .35, {i + 1, j + 1} -> Green,       If[cors[[i, j]] < -.35, {i + 1, j + 1} -> Red]], {i, 1,       Length[cors]}, {j, 1, Length[cors]}] // Flatten;           Grid[MapThread[Prepend[#2, #1] &, {Join[{""}, headers], Prepend[     (Round[cors, .01]), headers]}],       Background -> {LightGray, LightGray, backs}, Frame -> All]      Which produces ![enter image description here](http://i.stack.imgur.com/QZu34.jpg)


title: Why is Dataset upset by division by zero?

text: Consider this example:               ds = Dataset@Transpose[<|"a" -> {1, 2, 3, 4, 3, 2, 1}, "b" -> {6, 5, 4, 3, 2, 1, 0}|>, AllowedHeads -> All]      ![Mathematica graphics](http://i.stack.imgur.com/1xM43.png) Now say I need to work with the ratios of these two values. This works fine:               ds[;;-2, #a/#b &]      ![Mathematica graphics](http://i.stack.imgur.com/xiozu.png) But this fails:               ds[All, #a/#b &]      ![Mathematica graphics](http://i.stack.imgur.com/pJpS6.png) It would be easier for me to just get a result with some ComplexInfinities. Does the operation fail by desgin or oversight? Is there a workaround? Should I just use               ds[All, Quiet[#a/#b] &]      all the time or is there a more general solution? `Off[General::infy]` doesn't prevent this from failing, though the failure message can't be displayed properly.


title: error when defining a compiled function with ReplacePart

text: I always have difficulty in writing a non-trivial compiled function. I'm using _Mathematica_ 9\. Please see the following code               Clear[longtermCompiled];      longtermCompiled =       Compile[{{M, _Real, 2}},        Module[{len = Length[M]},         ReplacePart[Transpose[M] - IdentityMatrix[len], {len, i_} -> Table[1, {len}]]]];      where `M` is expected to be a matrix (two-dimensional). Upon executing the above definition, it complained:               ReplacePart::argrx: ReplacePart called with 2 arguments; 3 arguments are expected.      I don't understand this error message, because the following code works without any problems:               Clear[longtermX];      longtermX[M_] :=       Module[{len = Length[M]},        ReplacePart[Transpose[M] - IdentityMatrix[len], {len, i_} -> Table[1, {len}]]];      What's wrong?


title: pointer like operations in mathematica and evaluation control

text: I would like to create a data structure of the type "header[pointer]" where pointer would point to a list. I will shown on an example how I'd like this to work, and where the problems are.               In[1]:= pointer = Unique[storage];     Out[1]= storage$113      So far so good. Now I want to assign some values to the storage               In[3]:= Evaluate[pointer] = {v1, v2, v3}     Out[1]={v1,v2,v3}      Evaluate is needed in order to enforce evaluation of the left hand side of the assignment. The pointer has not been touched/changed which is good:               In: Trace[pointer]     Out: {pointer, storage$113, {v1,v2,v3}}      it still points to the storage, which in turn points to the list with the actual data. Yet, now it starts evaluating to something beyond storage$113. This will turn up later as the main problem. Now I'd like to have something like header[storage$113] as a wrapper to pass this around functions, and here the problems start. If one tries               In: header[pointer]     Out: header[{v1,v2,v3}]      the pointer evaluates down to the values. Thus we get bust since pointer evaluates way to much. If one tries               In: SetAttributes[header, HoldAll]      to prevent its evaluation one gets, alas, that it evaluates too little:               In: header[pointer]     Out: header[pointer]      I found a way               In: header[tmp] /. tmp -> Trace[pointer][[2]]     Out: header[storage$113]      that finally does the trick. I really do not understand why this works, actually. Trace[pointer][[2]] should also evaluate down to values v1, v2, ... This implementation might be problematic for several reasons: Trace might come up with a rather long list, and I just need the second element of it! Another problem, I suppose that the output of the Trace command might change dynamically depending on whether one puts in some extra definitions. I suppose that this is theoretically possible. Another way would be to issue header[pointer] command while pointer is still unspecified as               pointer = Unique[storage];     object = header @@ {pointer}     ... fix storage here...      but this forces me to do something I potentially might not want to do. For example, what if the command object = header... has to come at the end for whatever reasons? Anyway, I feel these both constructs looks very fragile I think and I'd like to understand how to controll these things better. Are there better ways?


title: How to connect to remote kernels inside home router?

text: How to use remote kernels inside a home router? My router has the demilitarized zone (DMZ) feature, which can expose my computer to the internet, and should be able to work, but I can't figure out how to setup the connection command in Mathematica to make it work.


title: Question on operator: // N

text: I've seen a notebook with the following:               FullSimplify[      Solve[{eq1, eq2, eq3, eq4, eq5, eq6, eq7, eq8, eq9, eq10, eq11, eq12},            {hbbbf, hbcf, hbbcr, hbcc, hbvbf, hbbc, hsbbf, hssd, hsvbf, hsf, hsbr, hsc}      ]     ][[1]] // N      I searched the _Mathemtatica_ help documentation for `//` and it seems to be a postfix operator. On the other hand `N` seems to be a way to specify the precision of a numerical value. What does the `[[1]] // N` mean? Thanks.


title: How to find all data points within closed curve

text: I want to find all data points inside curve as given below:               data = RandomReal[{-1, 1}, {200, 2}];     ParametricPlot[{Sin[u], Sin[2 u]}, {u, 0, 2 Pi},       Epilog -> {Red, Point[data]}]      Short solution is preferable Thanks.


title: Difference in two codes

text: When I check the following for the Fibonacci sequence, there is no problem:               α := (1 + Sqrt[5])/2;     M := 59793;          g[t_] := Denominator[FromContinuedFraction[ContinuedFraction[N[Log[α]/Log[5]], t]]];     δ := Log[α]/Log[5];     μ := -1/2;          Abs[Round[N[μ, 20]*g[12]] - N[μ, 20]*g[12]] -          M*Abs[(Round[N[δ, 20]*g[12]] - N[δ, 20]*g[12])]      > Out[80]= 0.4419847132 But when I tried to adapt it to the Tribonacci sequence, it does not give the correct result.                a := 1/3 (1 + (19 - 3 Sqrt[33])^(1/3) + (19 + 3 Sqrt[33])^(1/3))          a1 := (a - 1)/(4 a - 6)      w[t_] := Denominator[FromContinuedFraction[ContinuedFraction[Log[a]/Log[5], t]]]        S := 12*(10^13)                  e := Log[a1]/Log[5]         f := Log[a]/Log[5]           Abs[(Round[N[e, 100]*w[33]] - N[e, 100]*w[33])] -       Expand[S]*Abs[(Round[N [f, 100]*w[33]] - N[f, 100]*w[33])]      > Out[107]= \ > -0.0011766892841599426027968279324940525950672232471234884904296672047\ 564 Theoretically, the output should be nearly `0.498`. What is the problem in my code? I could not see it.


title: How do I get a list of unique random integers? Avoiding numbers being drawn twice

text: I am trying to get a set of random integers for which I used the function `RandomInteger[{1, 50}, 5]`. That way, however, there is the chance to get doubles such as `{46, 7, 9, 39, 39}`. How do I avoid numbers being drawn twice? Thank you very much for your help Sincerely


title: Animation of Differential Equations from NDSolve with ParametricPlot3D and Evaluate

text: I have a system of differential equations (referred to as "s") and use `NDSolve` to obtain the solution. I substitute the interpolated functions for the original functions in order to represent the trajectories of two objects in 3 dimensions. Here is the system that I am working with: **(I added this as an edit after I got some feedback that some more information about what I was attempting to animate would be useful )**               sysstars = {((sx[t]^2 + sy[t]^2 + sz[t]^2)^(3/2))*(1 +            2*(mstar1/mstar2) + (mstar1/mstar2)^2)*sx''[t] ==         g*mstar2*(-sx[t]), ((sx[t]^2 + sy[t]^2 + sz[t]^2)^(3/2))*(1 +            2*(mstar1/mstar2) + (mstar1/mstar2)^2)*sy''[t] ==         g*mstar2*(-sy[t]), ((sx[t]^2 + sy[t]^2 + sz[t]^2)^(3/2))*(1 +            2*(mstar1/mstar2) + (mstar1/mstar2)^2)*sz''[t] ==         g*mstar2*(-sz[t]), sx[0] == tpostar1[[1]], sy[0] == tpostar1[[2]],        sz[0] == tpostar1[[3]], sx'[0] == v0com1[[1]],        sy'[0] == v0com1[[2]],        sz'[0] ==         v0com1[[3]], ((qx[t]^2 + qy[t]^2 + qz[t]^2)^(3/2))*(1 +            2*(mstar2/mstar1) + (mstar2/mstar1)^2)*qx''[t] ==         g*mstar1*(-qx[t]), ((qx[t]^2 + qy[t]^2 + qz[t]^2)^(3/2))*(1 +            2*(mstar2/mstar1) + (mstar2/mstar1)^2)*qy''[t] ==         g*mstar2*(-qy[t]), ((qx[t]^2 + qy[t]^2 + qz[t]^2)^(3/2))*(1 +            2*(mstar2/mstar1) + (mstar2/mstar1)^2)*qz''[t] ==         g*mstar2*(-qz[t]), qx[0] == tpostar2[[1]], qy[0] == tpostar2[[2]],        qz[0] == tpostar2[[3]], qx'[0] == v0com2[[1]],        qy'[0] == v0com2[[2]], qz'[0] == v0com2[[3]]}          s = NDSolve[       sysstars, {sx[t], sy[t], sz[t], qx[t], qy[t], qz[t]}, {t, 0,         8*10^7}, MaxSteps -> 10^8]        **And here is how I am plotting them:**               ParametricPlot3D[      Evaluate[{sx[t], sy[t], sz[t], qx[t], qy[t], qz[t]} /. s, {t, 0,         10^7}], PlotRange -> All]     ParametricPlot3D[      Evaluate[{qx[t] + comx[t], qy[t] + comy[t], qz[t] + comz[t],          sx[t] + comx[t], sy[t] + comy[t], sz[t] + comz[t]} /. s, {t, 0,         3*10^7}], PlotRange -> All,]      **(The second Parametric Plot above is where the center of mass vector is added back to show the system from outside the center of mass inertial frame. So the first one plots two objects on initial trajectories that then go into orbit around the center of mass, with the center of mass treated as static)** The results of this are good - static lines in 3D, with the sensible paths. Now, I would like to animate this so that, say two spheres, move as a function of t. I have tried a few on-line suggestions using `Manipulate[Show[...`, but without success so far. I believe that the difficulty may relate to the use of Evaluate inside `ParametricPlot3D` \- in conjunction with the animation techniques. It does not seem possible to get rid of `Evaluate` with `ParamatricPlot3D`, and still get `ParametricPlot3D` to work with the interpolated functions which get substituted to generate the representation. There must be a way to do this in _Mathematica_ \- the program is way to good not to have a good way to do such an obvious thing with solutions, but I am stumped. Suggestions greatly appreciated (after too many hours) ! Delphi


title: Plot, HoldAll and the color problem

text: I have a similar problem as posted in Difference in Plot when using Evaluate vs when not using Evaluate, however due to a numerical evaluation I cannot use `Evaluated->True` as a `Plot[]` option. Her a small example which gives errors:               f[y_, a_] := NIntegrate[y^2 + x, {x, 0, a}];     Plot[Table[f[y, a], {a, 1, 3}], {y, 0, 3}, Evaluated -> True]      The desired output should be equal to               Plot[{f[y, 1],f[y, 2],f[y, 3]}, {y, 0, 3}, Evaluated -> True]      How can I fix this example ?


title: Polynomial expectations of generic distributions

text: **Summary** _Polynomial expectations depend only moments and cross moments of a multivariate distribution. I would like to use`Expectation` to compute polynomial expectations for generic distribution of which only the necessary moments are specified._ **Some details** I would like to compute polynomial exectations with the function `Expectation` for variables distributed according to a generic distribution. Here is a toy example:               In[139]:= ClearAll[myDist]          myDist /: Moment[myDist[mu_, var_], 1] := mu     myDist /: Moment[myDist[mu_, var_], 2] := Moment[myDist[mu, var], 1]^2 + var     myDist /: Moment[myDist[0, var_], 4] :=       Cumulant[myDist[0, var], 4] + 2 Moment[myDist[0, var], 2]     myDist /: Moment[myDist[0, var_], 3] := 0      This few lines provide enough information about the distribution `myDist` so that Mathematica can compute               In[144]:= Expectation[2 x^2, x \[Distributed] myDist[0, s^2], Method -> "Moment"]     Expectation[2 x^4, x \[Distributed] myDist[0, s^2], Method -> "Moment"]          Out[144]= 2 s^2          Out[145]= 2 (2 s^2 + Cumulant[myDist[0, s^2], 4])      I would like to carry out similar calculations with several random variables. For example.               In[147]:= ClearAll[a, b, x, y]     Expectation[      a x + b y, {x \[Distributed] myDist[0, s^2],        y \[Distributed] myDist[0, s^2]}, Method -> "Moment"]     Expectation[(a x + b y)^2, {x \[Distributed] myDist[0, s^2],        y \[Distributed] myDist[0, s^2]}, Method -> "Moment"]          Out[148]= Expectation[      a x + b y, {x \[Distributed] myDist[0, s^2],        y \[Distributed] myDist[0, s^2]}, Method -> "Moment"]          Out[149]= Expectation[(a x + b y)^2, {x \[Distributed] myDist[0, s^2],        y \[Distributed] myDist[0, s^2]}, Method -> "Moment"]      In this case Mathematica doesn't carry out the computation, even though it has all the information to do so. Namely   1. `x` and `y` are independent (this is implied in the specification `{x\[Distributed]myDist[0,s^2],y\[Distributed]myDist[0,s^2]}`, according to the definition of `Expectation`);   2. the result is completely determined by the first and second moment of `x` and `y` (Provided).  One of the problems is that `Expectation` doesn't know (or it is pre-emped by some other rule or evaluation)               In[153]:= Expectation[       a x + b y, {x \[Distributed] myDist[0, s^2],         y \[Distributed] myDist[0, s^2]}, Method -> "Moment"] ===           a Expectation[x, x \[Distributed] myDist[0, s^2], Method -> "Moment"] +        b Expectation[y, y \[Distributed] myDist[0, s^2], Method -> "Moment"]          Out[153]= False      Notice that all-is-well when the distribution is one that Mathematica knows               In[166]:= Expectation[      a x + b y, {x \[Distributed] NormalDistribution[0, s^2],        y \[Distributed] NormalDistribution[0, s^2]}, Method -> "Moment"]          Out[166]= 0      One possible solution is to define an operator such as `myExpectation` that knows/uses linearity properties of the mathematical expectation, but I would rather not reinvent the wheel and leverage the power of the built in symbol `Expectation` (for example specializing a result to one of the built in distributions) as well as the ease with it deals with higher momenta and cumulants. I tried (with no success)   1. using `ProductDistribution[{myDist[], 2}]` instead of ` {x\[Distributed]myDist[0,s^2],y\[Distributed]myDist[0,s^2]}`;   2. definiting a generic distribution as suggested (here) with the symbol `ProbabilityDistribution`. In this case the delayed `UpValues` for the moments cannot be set. Indeed                myDist2[mu_, var_] =      ProbabilityDistribution[myDistPDF[x, mu, var], {x, -Infinity, Infinity}]     myDist2 /: Moment[myDist[mu_, var_], 1] := mu          Out[164]= ProbabilityDistribution[      myDistPDF[\[FormalX], mu, var], {\[FormalX], -\[Infinity], \[Infinity]}]          During evaluation of In[164]:= TagSetDelayed::tagnf: Tag myDist2 not found in Moment[ProbabilityDistribution[myDistPDF[\[FormalX],mu_,var_],{\[FormalX],-\[Infinity],\[Infinity]}],1]. >>          Out[165]= $Failed      If a `HoldPattern` the left-hand-side of the moment delayed assignment, the command executes with no error, but it the information won't be used by `Expectation`. The reason for this is that `Expectation` first evaluates its arguments and `myDist2` evaluated to               ProbabilityDistribution[myDistPDF[\[FormalX],mu,var],{\[FormalX],-\[Infinity],\[Infinity]}]      and the upvalues of `myDist` are from then on "invisible" to `Expectation`. Some related question on how to define an arbitrary distributions are here and here.


title: Word Squares and Beyond

text: A word square is a set of words which, when placed in a grid, read the same horizontally and vertically. For example, the following is an English word square of order 5:               F A C E D     A L I V E     C I V I L     E V I C T     D E L T A      A word cube is an extension of this idea into three dimensions. For example, here are the slices of a word cube of order 4:               H A N D    A R E A    N E T S    D A S H     A R E A    R E A L    E A R L    A L L Y     N E T S    E A R L    T R I O    S L O P     D A S H    A L L Y    S L O P    H Y P E      Imagine stacking these squares vertically to form a cube; then notice how each the nth vertical slice is the same as the nth horizontal slice, and both are word squares. This idea can be extended into word hypercubes, but for simplicity, let's keep the dimensions to 2 or 3. How can we use Mathematica to generate word squares and word cubes? This is a difficult combinatorics question, so I'm only looking for a function which can generate word squares and word cubes of small order in a reasonable amount of time.


title: Animation of 2 Differential Equations - 1 Independent Variable

text: I have effectively 1 differential equation that had to be broken up into 2 (max number of steps reached). I have gotten the solutions for both using NDSolve and have plotted each together. Now, I am trying to animate this solution using Manipulate for each differential equation and then use Show to plot the two together. Ideally, Manipulate would then go through the independent variable (starts at beginning of domain from first interpolating function and goes to end of domain of the second interpolating function) that commands both solutions producing a continuous plot. Unfortunately, Show will not combine these two - I am getting two graphs next to one another. How can I achieve the result I desire? Thanks in advance for any help. I have spent days trying to figure out how to do this - even attempting quite unsuccessfully to extract results and put into a data table.               g1 = NDSolve[{r'[ϕ] == Sin[ArcCot[2/r[ϕ]]]*Sqrt[6 - r[ϕ]^2 - 1/r[ϕ]^2],  r[0] == 1}, r, {ϕ, 0, 4}]     g2 = NDSolve[{r'[ϕ] == -Sin[ArcCot[2/r[ϕ]]]* Sqrt[6 - r[ϕ]^2 - 1/r[ϕ]^2],                   r[ 1.7775896893621104`] == 2.41421},                   r, {ϕ, 1.7775896893621104`, 5}]     v1 = RevolutionPlot3D[x^2, {x, 0, 3}, PlotStyle -> Opacity[0.4], Mesh -> None]     w1 = Manipulate[       ParametricPlot3D[        Evaluate[{1/r[ϕ] Cos[ϕ], 1/r[ϕ] Sin[ϕ], 1/r[ϕ]^2} /. g1], {ϕ, 0.000001, a},         PlotRange -> {{-3, 3}, {-3, 3}, {0, 3}}, PlotStyle -> Thick,         Evaluated -> True], {a, 0.0, 1.7775640272780204}]     w2 = Manipulate[       ParametricPlot3D[        Evaluate[{1/r[ϕ] Cos[ϕ], 1/r[ϕ] Sin[ϕ], 1/r[ϕ]^2} /. g2], {ϕ, 1.77758968936211, a},         PlotRange -> {{-3, 3}, {-3, 3}, {0, 3}}, PlotStyle -> Thick,         Evaluated -> True], {a, 1.7775896893621104, 4.925661999190314}]     Show[v1, w1, w2]


title: Generating a position lookup function for an arbitrary list of integers

text: In my code, I generate a list of integers called `numlist`. Here is an example `numlist`:               numlist = Sort[Table[RandomInteger[{1, 100}], {3}]]      which gives, for example, the output: > {17, 74, 96} I would like to write a function `generateFun` that, using `numlist` as input, generates the following function `myfun`:               myfun[int_Integer] := Which[       int == 17, 1,       int == 74, 2,       int == 96, 3       ]      In other words, `myfun` takes an integer and returns the position of that integer in `numlist`. `numlist` is created at the beginning of the code and does not change during a given execution; however, a new execution will in general create a new list of integers `numlist`. The length of `numlist` varies (it is not guaranteed to be 3), although this fact is not present in the minimal working example that I gave above. I could bypass `generateFun` and simply use this function `myfun2`:               myfun2[int_Integer, numlist_] := First[First[Position[numlist, int]]]      which returns the position of `int_` in `numlist_`. However, since I will need to call the function (`myfun` or `myfun2`) _many_ times (~1,000,000 times), I think that calling `Position` every time may be quite expensive -- since `numlist`, once generated, does not change during the execution. Do you have any advice on how I can generate the `Which` expression automatically from `numlist`?


title: Thread[] seems to reset changes made with Manipulate[]

text: Recently I have been working on group theory and I have found checking for associativity for specific Cayley tables to be rather tedious so I wrote a program to do it for me. Most of the time I would make the Cayley tables first and then run the program to check if it is associative. However, I recently decided to put it all together into one `Manipulate[]` to speed up my productivity. By doing so though, things got a little glitchy. The problem I am having is with creating the rules. I think I managed to narrowed it down to one line of code(?) and so below is my code _without_ the actual function for checking associativity, only the part which seems to make the program to malfunction.               alphabet = "IABCDEFGHJKLMNOPQRSTUVWXYZ";          Manipulate[     aList = StringJoin[#] & /@Tuples[Table[StringTake[alphabet, {n}], {n, letters}], {2}];      bList = Table["I",{letters},{letters}];      rules = Thread[aList -> Flatten[bList]]; (*If I comment out this line everything works fine*)     Row[{Grid[     Prepend[Map[Flatten[#] &,        Transpose[{Table[StringTake[alphabet, {n}], {n, letters}],          Table[With[{n = n, m = m},            PopupMenu[Dynamic[bList[[n, m]]],             Table[StringTake[alphabet, {o}], {o, letters}]]], {n,            letters}, {m, letters}]}]],       Prepend[Table[StringTake[alphabet, {n}], {n, letters}], ""]],      Dividers -> {2 -> True, 2 -> True}], Spacer[50],      Dynamic[bList]}], {letters, 1, 8, 1}]      When I run this program and set a value for a particular element in the grid; `bList` will update, but quickly switch back to it's initial state. However if I remove               rules = Thread[aList -> Flatten[bList]];      the value changes as it should. I tried placing `Dynamic[]` in various places without success. I'm not sure how to proceed, so any help on how to fix the problem would be greatly appreciated.


title: Problems with log-log histograms

text: I'm using a custom function to create Log-Log Histograms of my data. It uses the CustomTicks` package (in LevelScheme, http://scidraw.nd.edu/levelscheme/) to display Log Ticks.               Needs["CustomTicks`"];          domainSizesHistogram[data_List,opts:OptionsPattern[]]:=         Module[{},(         Histogram[             Log[10,data],             {-0.05,5.05,0.1},             "LogCount",             opts,             AxesLabel->{"Basin of attraction", "Number of attractors"},             PlotRange->{Automatic,{-1,9}},             Ticks->{CustomTicks`LogTicks[0,5],Automatic}         ]     )]      It's got to be Log-Log because my simulations produce highly varied output and I would like to generate histograms to quickly compare the output of different runs. Although the function generally works fine, it sometimes produces incorrect histograms.               data1 = {32, 20, 63, 234, 12, 50, 1, 332, 11, 210, 116, 88, 11, 68, 194, 202, \     11, 46, 116, 3, 41, 236, 41, 9, 23,      48, 3, 52, 72, 20, 10, 9, 191, 52, 148, 50, 15, 105, 92, 130, 50, \     12, 244, 131, 159, 55, 189, 161, 83,      17, 22, 7, 36, 51, 15, 132, 130, 42, 6, 51, 79, 39, 10, 4, 32, 13, \     63, 83, 68, 28, 8, 1, 48, 44, 144, 28,      4, 19, 19, 54, 71, 276, 32, 39, 1, 20, 38, 72, 64, 60, 3, 93, 28, \     17, 56, 50, 7, 41, 3, 39, 11, 4, 30,      49, 58, 7, 87, 15, 10, 13, 4, 51, 8, 6, 42, 21, 67, 8, 14, 19, 4, \     2, 49, 56, 15, 3, 58, 11, 5, 15, 5, 4,      1, 27, 9, 34, 41, 3, 13, 14, 48, 69, 5, 38, 26, 8, 31, 23, 2, 21, \     28, 22, 28, 40, 14, 1, 14, 19, 1, 1,      19, 8, 3, 35, 3, 61, 1, 18, 23, 21, 25, 28, 42, 5, 2, 11, 9, 3, 2, \     1, 50, 56, 13, 9, 14, 5, 19, 2, 2, 12,      67, 6, 11, 1, 14, 7, 73, 23, 11, 2, 4, 10, 10, 3, 2, 8, 12, 4, 12, \     1, 8, 43, 6, 10, 15, 7, 6, 9, 9, 17,      4, 6, 9, 2, 7, 9, 4, 2, 3, 25, 7, 2, 18, 4, 5, 13, 1, 16, 5, 13, \     25, 9, 13, 13, 2, 5, 3, 2, 2, 3, 10, 8,      32, 12, 4, 5, 14, 6, 2, 6, 26, 4, 15, 10, 3, 11, 10, 8, 5, 6, 3, \     6, 2, 12, 3, 2, 7, 19, 14, 21, 6, 13, 2,      21, 3, 5, 1, 3, 6, 4, 2, 15, 2, 11, 6, 12, 2, 2, 10, 1, 14, 2, 5, \     1, 2, 1, 3, 2, 3, 2, 2, 1, 5, 2, 4, 7,      7, 6, 4, 2, 2, 13, 12, 4, 10, 5, 2, 2, 3, 7, 4, 1, 8, 4, 2, 4, 3, \     8, 4, 1, 2, 1, 6, 1, 1, 5, 1, 6, 8, 6,      3, 4, 6, 2, 1, 1, 1, 1, 2, 10, 1, 2, 3, 3, 5, 5, 8, 4, 1, 3, 1, 1, \     5, 2, 1, 6, 4, 2, 4, 6, 1, 5, 3, 4, 1,      6, 4, 2, 2, 2, 1, 1, 2, 1, 4, 5, 2, 3, 5, 4, 2, 2, 2, 3, 2, 1, 2, \     1, 1, 4, 2, 2, 2, 1, 3, 1, 1, 3, 3, 3,      1, 3, 3, 1, 1, 5, 1, 1, 2, 1, 2, 2, 1, 1, 1, 1, 2, 1, 3, 1, 1, 1, \     5, 1, 2, 3, 2, 3, 1, 3, 1, 1, 2, 1, 2,      1, 1, 4, 1, 2, 1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 3, 1, 2, 2, 1, 1, \     1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1,      1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \     2, 1, 1, 1, 1};          data2 = {2655, 72, 3862, 2414, 577, 307, 21, 38, 8, 41, 4, 1};      `domainSizesHistogram[data1]` produces a normal histogram: ![Histogram of data1](http://i.stack.imgur.com/WUBNA.png) But `domainSizesHistogram[data2]` gives a histogram where the axes are all messed up: ![enter image description here](http://i.stack.imgur.com/VoJmK.png) How can I fix the function to always produce a histogram with the same axes? I already tried to set a hard `PlotRange` for both axes, but this didn't produce the right results either. Some of my fixes seemed to produce the right axes, but then the bars would float above the horizontal axis. Any help would be appriciated. **Edit:** After adding `AxesOrigin->{-0.05,-1}` to the function, a lot of problem were solved. However, now I get floating bars in some cases. data3 = {4535, 5465}; And `domainSizesHistogram[data3]` produces this: ![Histogram of data3](http://i.stack.imgur.com/LidbO.png)


title: Find intersecting rectangles groups

text: I've a list of rectangles in the form               {index, {centerX, centerY}, {width, height}}      I want to find intersecting rectangles list. I want to obtain a list on the form               {{indx...indy},{indt...indz}...}      Every element of this list is a list of rectangles that have at least an intersection in common, with transitive property: if rectangle 1 intersects rectangle 2 that intersect rectangle 3, these are a part of the same group. If I've this situation in the image below, my intersecting list should be               {{1,2,10},{6},{7,5},{3},{4,8,9}}      (element order is not important). How can I accomplish this? ![enter image description here](http://i.stack.imgur.com/iIKTw.png) EDIT: There's a real sample data, with two groups and an isolated rectangle:               obj2 = {        {1, {0, 0}, {1, 1}},        {2, {0.5, 0.5}, {1, 1}},        {3, {3, 2}, {0.5, 0.6}},        {4, {1.2, 0.5}, {0.5, 0.6}},        {5, {2, -0.3}, {0.4, 0.4}},        {6, {2.1, -0.4}, {0.3, 0.4}}        };