$CurrentLink passing down in MathLink SetDelayed functions

I would like to utilize the MathLink option of having each `Install` of my package result in a linking object which I can use to control when and how certain elements are used in the underlying `C` code. However, I have difficulties when implementing Mathematica functions on top of the functions which require the `LinkObject`. Of course I need the `SetDelayed` statement due to variable passing etc. Take for instance the `counter.tm` example:               :Evaluate:      BeginPackage[ "counter`"]          :Begin:     :Function:      AddToCounter     :Pattern:       AddToCounter[$CurrentLink, n_Integer]     :Arguments:     {n}     :ArgumentTypes: {Integer}     :ReturnType:    Integer     :End:          :Evaluate:      EndPackage[ ]      This works great until I define additional functions, take for instance this additional function (it _is_ placed within the `BeginPackage/EndPackage`).               :Evaluate:   MyAddToCounter[$CurrentLink,n_Integer] :=                          Return[AddToCounter[$CurrentLink,n+1]]      However, when calling `MyAddToCounter` I only get the function call as a symbol:               In[2]:= MyAddToCounter[link,20]     Out[2]:= AddToCounter[$CurrentLink, 21]      Why is this?   And how can I preserve the separation of each `LinkObject` to the same package?


How to partition a list into sublists in a similar way to Histogram

I have a list of list as below (I show part of it)               {{1902, 0.4662}, {1903, 0.22443}, {1905, 0.02936}, {1906,        0.02702}, {1908, -0.08354}, {1909, -0.05241}, {1911,        0.02388}, {1912, 0.03738}, {1914, 0.25015}, {1915, 0.2831}, {1917,        0.4415}, {1919, 0.18315}, {1921, 0.2256}, {1923, 0.24132}, {1926,        0.21473}, {1928, 0.29596}, {1930, 0.47693}, {1933, 0.41607}, {1935,        0.22161}, {1937, 0.3322}, {1940, 0.2099}, {1942, 0.23376}, {1944,        0.44114}, {1947, 0.15876}, {1949, 0.43953}, {1951, 0.71407}, {1954,        0.9595}, {1956, 0.59436}, {2000, 0.6832}, {2004, 0.86861}, {2007,        0.48201}, {2011, 0.70796}, {2015, 0.57029}, {2020, 0.61997}, {2026,        0.79266}, {2032, 0.78726}, {2038, 0.83884}}      For example, in {1902,0.4662} "1902" represent time 19:02 and 0.4662 represent the data at time 19:02. **What I want to do is to calculate average of the data in every 5 minutes.** That is from 19:02 to 19:06, from 19:07 to 19:11. **Notice the time step is not evenly distributed.** `Histogram` can naturally count how many of the data are in each interval. I want to partition the list like `Histogram` and then I can calculate average in each interval. And notice that the data may not be in a single day. I can't figure out an elegant way to do this with built-in function. Can somebody help me? Besides I think this is a very simple statistical calculation of data. **I want to know what software could do this easily and directly.** Update: the full data sample is here http://en.textsave.org/VdL with date information


Simple blink comparator for two images

I tried to build a simple 'blink comparator' - where you can click on an image repeatedly to switch between two similar images. (An old-fashioned notion in the days of powerful image processing software, it's true.) I think the problem with what I've done so far is the behaviour of the symbols inside a `DynamicModule`:               image1 = Thumbnail[ExampleData[{"TestImage", "Mandrill"}], 300];     image2 = Thumbnail[        ColorNegate[ExampleData[{"TestImage", "Mandrill"}]], 300];     DynamicModule[{imageList = {image1, image2}},      EventHandler[       Show[        First[imageList],        Graphics[         {          Text[           Style[            "name of First[imageList]]?",             14, White],           ImageDimensions[First[imageList]]/2]          }         ]],       {"MouseDown" :>          {          RotateLeft[imageList],          Beep[]          }        }]]      ![gratuitous mandrill picture](http://i.stack.imgur.com/75B9K.png) The `Beep` confirms the `EventHandler` action, but the image doesn't change.


Appending to sublists using "anchor" values

Say I have a set of lists that look like this:               list = {{{151.335`, 245.102`}, {1, 1}}, {{41.435`, 245.021`}, {2, 2}, {3, 3}},             {{131.048`, 243.364`}, {3, 3}, {56, 56}, {76, 23}}, {{164.911`, 244.039`},               {4, 4}}, {{98.1685`, 239.618`}, {5, 5}}, {{196.333`, 239.212`}, {6, 6}},              {{184.767`, 234.228`}, {7, 7}}, {{213.044`, 234.24`}, {8, 8}},              {{26.6316`, 221.423`}, {9, 9}}};          appendList = {{{3, 3}, {"Yellow", "Red"}, {"Blue", "Majesty"}},                   {{76, 23}, {"White", "Avalanche"}}}      How can I use the first element in each sublist of `appendList` as an anchor to append the next set of elements in place in `list` generating something like the following?:               finalList = {{{151.335`, 245.102`}, {1, 1}}, {{41.435`, 245.021`}, {2, 2}, {3, 3},                   {"Yellow","Red"},{"Blue","Majesty"}}, {{131.048`, 243.364`}, {3, 3},                   {56, 56}, {76, 23},{"White","Avalanche"}}, {{164.911`, 244.039`},                    {4, 4}}, {{98.1685`, 239.618`}, {5, 5}}, {{196.333`, 239.212`},{6,6}},                  {{184.767`, 234.228`}, {7, 7}}, {{213.044`, 234.24`}, {8, 8}},                   {{26.6316`, 221.423`}, {9, 9}}};      After-the-fact question: This is a brief followup which doesn't quite deserve it's own question - how can we only look at the last element in each sublist of `list` to check to see if it matches the "anchor" value at the first position in `appendList`? In other words, where `{{{2, 2}, {"Yellow", "Red"}, {"Blue", "Majesty"}}, {{56, 56}, {"White", "Avalanche"}}}` yields a `finalList = list` since {2,2} and {56,56} are not at the ends of the sublists in `list`?


Stochastic Approximation and Simulation using Running Median

I have a function $$F(X_{t+1},Y_{t}^{med})= \alpha X_{t+1} + (1-\alpha) Y_{t}^{med},$$ where $$Y_{t}^{med} = Median(Y_1, Y_2,... Y_t).$$ Moreover, $Y_1 = X_1$ and $Y_t = F(X_{t},Y_{t-1}^{med})$ $\forall t>1$. Suppose $X_t \sim X$ is a IID random variable following a Beta distribution, $X \sim Beta(2,1)$. I wish to plot the evolution of $Y_{t}^{med}$ over time. Currently, I have: 1) The function:               f[a_, {x_, y_}] := a x + (1 - a) y      2) Generate data. **Here, I don't know how to generate the running median, that is $Y_{t}^{med}$ in Mathematica.**               sim[length_] :=       Module[{rv = RandomVariate[BetaDistribution[2, 1], length], y, yMed},       y[1] = First@rv;       yMed[t_Integer] := yMed[t] = MovingMedian[rv, t];       y[t_Integer] := y[t] = f[0.5, {rv[[t]], yMed[t - 1]}];       yMed /@ Range[length]]      3) Create the plot/graph for 100 iterations, 5 random walks:               ListPlot[Table[sim[100], {5}], PlotRange -> All, Joined -> True,       Frame -> False, AxesOrigin -> {0, 0}, AxesLabel -> {t, Y},       GridLines -> {{}, {2/3}}, GridLinesStyle -> Directive[Gray, Dashed]]


Function that returns the binary string given its index in lexicographic ordering

Index the binary strings in lexicographic order, so that the empty string " " corresponds to 0, the string "0" corresponds to 1, the string "1" to 2, and so on. I want a function that, given a natural number $n\geq0$, returns the binary string with lexicographic index $n$.


What is the most elegant way to display multiple graphs with a common title?

I often seek to display two graphs, side by side, with a common label over them. There is no option for adding a label to `GraphicsRow`, which means, I think, that I need to use `Grid` or `GraphicsGrid` and include a row on top that has `SpanFromLeft` set to allow a graphically defined line of text occupy the entire row. It seems like a lot of work to do something simple. Is there a better solution?


How to use Optional as an omissible parameter in pattern-match?

Below is a function intended to test if an expression is a polynomial in which all the coefficients and exponents are integers:               intPolyQ[Optional[_Integer] +      Plus[Optional[_Integer] x_Symbol^Optional[_Integer] ...], x_] := True;     intPolyQ[___] := False;      It gives unexpected results in some cases. For example,               intPolyQ[#, x] & /@ {x, 2 x, 2 x + 1, 2 x^2 + 3 x, 2 x^2 + 3 x + 1}      gives               {True, True, True, False, True}      which is wrong in the 4th case. Why does this happen? How do I fix it?


Exporting as .PDB extension

I am working with the 3-D coordinates of proteins. The file format I import and modify coordinates of is in the .PDB format, and the string to import is also in this same format. Currently, when I try to export as in "final.pdb", I get: "Export::type: "String cannot be exported to the !(\"PDB\") format." However, when I export with the extension .txt, and use:               Import["final.txt", "PDB"]      The file imports as the protein structure. My question: Is there a way to export using the .PDB extension. Or even force the export. Having the .pdb extension would be much easier for other programs. If there is a way, please let me know.


Differential Equations with Matrices

I'm trying to implement the differential equation of a Cellular Neural Network in _Mathematica_ as seen below:               A = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};        B = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};        u = {{10, 11, 12, 1}, {20, 21, 22, 1}, {66, 77, 88, 1}};     Ioff = 1;          NDSolve[{x'[t] == -x[t] + ListConvolve[A, x[t], 1] + ListConvolve[B, u, 1] + Ioff,     x[0] == u}, x, {t, 0, 2}]      But `NDSolve` returns two errors: > `ListConvolve::kldims:` "The kernel {{1,2,3},{4,5,6},{7,8,9}} and list x[t] > are not both non-empty lists with the same tensor rank." > > `NDSolve::ndfdmc:` Computed derivatives do not have dimensionality > consistent with the initial conditions. I would really appreciate any help since I'm a beginner in _Mathematica_ and I don't know what I'm doing wrong


What do the hashtags represent in the result of Solve, and how should I use them?

There is a function that I'm trying to get the inverse of. My function is a simple polynomial:               Tn[T_] := 4/9 T^3/Tc^2 + 5/9 T      Now I tried to find `T` as a function of `Tn`, for which I used Solve:               sols=Solve[Tn[x] == a, x, Reals]     {{x -> Root[-9 a Tc^2 + 5 Tc^2 #1 + 4 #1^3 &, 1]}}      Plotting it is no problem, which I did by using this:               Tc = 1;     Plot[Evaluate[x /. sols], {a, 0, 1}]      ![enter image description here](http://i.stack.imgur.com/dPE8s.png) But the problem is that I have no idea what the hashtags in the result of Solve denote, and how I should write the function `T(Tn)`. What do the `#`s mean, and how exactly does `T` depend on `Tn`?


How do I work with Root objects?

I want to solve the trigonometric equation : $$(3-\cos 4x )\cdot (\sin x - \cos x ) = 2.$$ I tried               Solve[(3 - Cos[4*x])*(Sin[x] - Cos[x]) == 2, x]      It returns the solutions in terms of `Root` objects yielding also this message : > >     Solve::ifun: Inverse functions are being used by Solve, so some > solutions may not be found; >     use Reduce for complete solution information. >> >   How do I tell _Mathematica_ to do that? How can I solve this equation : $\tan(2x)⋅ \tan(7x) = 1$ ?


How can I obtain absolute result for Root[ # ] symbol

I'm using mathematica 8.0. When I calculate NDSolve`ImplicitRungeKuttaGaussCoefficients[10, Infinity] function, it gives me some symbolic results. I trided //N and //FuıllSimplify operation as in How do I work with Root objects? topic but it gave me only numerical results or some of absolute results, I didn't get all of my results, but i don't want to this. I want to absolute results for my calculation but I couldn't achieve this.For Example the first element of A matrix is :                (322 - 13 Sqrt[70])/3600      , but second element of A matrix is :                    Root[20242937658868661529 + 13567555581406269206400 #1 +         2767290377721440719680000 #1^2 +         187835459850164351232000000 #1^3 +         1303105350315444928000000000 #1^4 -         113922281443839160320000000000 #1^5 +         1236506465399482368000000000000 #1^6 -         5007540613482086400000000000000 #1^7 +         6998115764183040000000000000000 #1^8 &, 1]


What is that Root[...] inside the answer represent?

![enter image description here](http://i.stack.imgur.com/vR9WO.png) So I am encountering this situation, in which mathematica doesn't give me the answer, but in a form of "Root". How do I interpret this ? what is the number after the "&" represent? How should I ask mathematica to evaluate this Root for me? Please don't tell me to use `N[%]`. I have an equation of 4 variables and I don't have numerical value for them. I would like it in symbolic form.


Mathematica returns different results when requested by Reduce, Solve

When I request with Reduce, Mathematica returns:               In[13]:= N[Reduce[X^3-26X+1 == 0,X, Reals]]                                          Out[13]= X == -5.11814 || X == 0.0384637 || X == 5.07968      However, when I request with Solve, it returns three complex roots               In[15]:= N[Solve[X^3-26X+1 == 0,X]]                                                                                -16     Out[15]= {{X -> 5.07968 + 0. I}, {X -> 0.0384637 + 4.44089 10    I},                                  -16     {X -> -5.11814 - 4.44089 10    I}}      I think the different here is the Reals field. However, I'm confused about the correctness of result. Which one should I follow when I want to solve the equations. Thanks


Eigenvalues for large matrices without Root-Solution

I read some other questions and tried to implement the given answers but yet, I did not succeed to find proper solutions for my eigenvalues. I hope someone can show me how to do this for this case, and even larger matrices in the same shape:               mat = {{L - 2*s, -w, s, 0, s, 0}, {w, L, 0, 0, 0, 0},             {s, 0, L - 2*s, -w, s, 0}, {0, 0, L, w, 0, 0},     {s, 0, s, 0, L - 2*s, -w}, {0, 0, 0, 0, L, w}};      I used `FullSimplify[Eigenvalues[mat], Assumptions -> {Element[L, Reals], Element[w, Reals], Element[w, Reals]}]` as well as               Sort[Eigenvalues[mat] // Simplify // N]      with the same results that 4 eigenvalues are written as Root.


Verify "Type" of solution

I've written some _Mathematica_ functions which allow the user to verify if a mathematical function has certain properties. What I'm basically doing is generating "random" functions in respect of certain parameters and then verify if these functions have those properties. So at some point, I solve a system of equations as follows:               sol = Solve[function1 == 0 && function2 == 0, {x, y}, Reals];      Lateron, I use a conditional statement like:               If[Length@sol==1, ...]      In this case, I want to continue if there is exactly 1 solution of the form `{x->value1, y->value2}`. Sometimes, however, the only solution is something like:               {{x -> Root[-8 + 16 #1 + 16 #1^3 + 3 #1^5 &, 1],        y -> -2 - 1/2 Root[-8 + 16 #1 + 16 #1^3 + 3 #1^5 &, 1]^2}}      In this case, my _Mathematica_ function will continue calculating and take minutes for a single function because of the high complexity of the `Solve[...]` return value. Is there a built-in function to determine whether the solution is "explicit", or does someone have a trick for this?


Mathematica won't give eigenvectors but Wolfram Alpha will? What am I doing wrong?

If I ask Mathematica to find the eigenvectors and eigenvalues of the matrix:               mat := {{a, b, c}, {b, d, e}, {c, e, f}}     Assuming[{a > 0, b > 0, c > 0, d > 0, e > 0, f > 0}, Eigenvalues[mat]]     Assuming[{a > 0, b > 0, c > 0, d > 0, e > 0, f > 0}, Eigenvectors[mat]]      If returns stuff like               {Root[c^2 d - 2 b c e + a e^2 + b^2 f -      a d f + (-b^2 - c^2 + a d - e^2 + a f + d f) #1 + (-a - d -         f) #1^2 + #1^3 &, 1],      Root[c^2 d - 2 b c e + a e^2 + b^2 f -      a d f + (-b^2 - c^2 + a d - e^2 + a f + d f) #1 + (-a - d -         f) #1^2 + #1^3 &, 2],      Root[c^2 d - 2 b c e + a e^2 + b^2 f -      a d f + (-b^2 - c^2 + a d - e^2 + a f + d f) #1 + (-a - d -         f) #1^2 + #1^3 &, 3]}      But if I ask Wolfram Alpha: ![enter image description here](http://i.stack.imgur.com/IKI0Q.png) It does it. What am I doing wrong in Mathematica?


How do I interpret the Roots syntax when I am finding the eigenvalues of a matrix

Here is an example of my problem: ![eigenvalues](http://i.stack.imgur.com/8kayB.png) I am somewhat confused by the syntax of this. I am guessing that the #1 is specifying the start of another root? Why then does one of the roots = u + with nothing after the plus? I think if I better grasped what the #1 stood for I might understand. Also, is there a reason that the Root ends with an &? Thanks!


Eigenvalues of a matrix, rhombus/hash sign

I wanted calculate the eigenvalues of                A = {{0, 1, 0, 0}, {a, b, c, 0}, {0, 0, 0, 1}, {d, 0, e, f}}      Then assigned the parameters a value               Eigenvalues[A] /. {a -> 3/4 (1 + 4/3 beta^2), b -> -1/2,      c -> 3/4 (1 - 4/3 beta^2), d -> 3/4 (1 - 4/3 beta^2),      e -> 3/4 (1 + 4/3 beta^2), f -> -1/2}      And I get this: > >     {Root[12 beta^2 + (-3 - 4 beta^2) #1 + (-5 - 8 beta^2) #1^2 + >     4 #1^3 + 4 #1^4 &, 1], >     Root[12 beta^2 + (-3 - 4 beta^2) #1 + (-5 - 8 beta^2) #1^2 + >     4 #1^3 + 4 #1^4 &, 2], >     Root[12 beta^2 + (-3 - 4 beta^2) #1 + (-5 - 8 beta^2) #1^2 + >     4 #1^3 + 4 #1^4 &, 3], >     Root[12 beta^2 + (-3 - 4 beta^2) #1 + (-5 - 8 beta^2) #1^2 + >     4 #1^3 + 4 #1^4 &, 4]} >   what does `#1` means and the `&,1`? why it doesnt calculate with beta like in               Eigenvalues[{{a, b}, {-b, 2 a}}]?


Solve doesn't return all solutions

I got a simple cubic equation as input, but _Mathematica_ does not give all solutions, why is this the case here?               f[α_] := Sqrt[2] α (Δ + 2g^2/Ω(α Conjugate[α]))          Solve[f[α] == 0, α]      > >     {{α -> 0}} >   There should also be the solution where $\alpha \in$ Real, so that $|\alpha|^2 = -\frac{\Delta\Omega}{2g^2}$ under the condition $\Delta\Omega < 0$.


What is the difference between Reduce and Solve?

`Solve` and `Reduce` both can be used for solving equations. Just by working with them, I know there are some differences between them. but that is about all I know, and I want to know what the differences are. Could someone teach me about this?


HarmonicNumber problem

I am looking for all the roots of `HarmonicNumber`, in the domain [-30, 1] and [0, 6000] for the real and imaginary parts, respectively, and where the parameter `n` of `HarmonicNumber` is as high as 200. This problem had been asked before in this question. As I increase the size of the domains where I am looking for roots, the following warnings show up: > FindRoot::jsing: "Encountered a singular Jacobian at the point {x,y} = > {56.9935,171.987}. Try perturbing the initial point(s)." > > FindRoot::lstol: The line search decreased the step size to within tolerance > specified by AccuracyGoal and PrecisionGoal but was unable to find a > sufficient decrease in the merit function. You may need more than > MachinePrecision digits of working precision to meet these tolerances " Could you help me fix this? Or suggest another way to solve this equation. I got the same warnings when I tried to apply another technique as described in this answer Here is the code:               Options[FindRoots2D] = {PlotPoints -> Automatic, MaxRecursion -> Automatic};           FindRoots2D[funcs_, {x_, a_, b_}, {y_, c_, d_}, opts___] := Module[     {fZero, seeds, signs, fy},fy = Compile[{x, y}, Evaluate[funcs[[2]]]];      fZero = Cases[Normal[      ContourPlot[         funcs[[1]] == 0,          {x, a-(b-a)/97, b+(b-a)/103}, {y, c-(d-c)/98, d+(d-c)/102},          Evaluate[FilterRules[{opts}, Options[ContourPlot]]]]],       Line[z_] :> z, Infinity];            seeds = Flatten[(      (signs = Sign[Apply[fy, #1, {1}]];        #1[[1 + Flatten[Position[Rest[signs*RotateRight[signs]], -1]]]]) &      ) /@ fZero, 1];      If[seeds == {}, {},       Select[         Union[({x, y} /.            FindRoot[{funcs[[1]], funcs[[2]]}, {x, #1[[1]]}, {y, #1[[2]]},                Evaluate[FilterRules[{opts}, Options[FindRoot]]]] & ) /@ seeds,             SameTest -> (Norm[#1 - #2] < 10^(-6) & )],          a <= #1[[1]] <= b && c <= #1[[2]] <= d & ]]]     n = 20;     zeros = FindRoots2D[{Re[HarmonicNumber[n, x + I y]], Im[HarmonicNumber[n, x + I y]]}, {x, -30, 1}, {y, 0, 6000}]     mediumSeaGreen = RGBColor[0.235298`, 0.702002`, 0.443098`];     violet = RGBColor[0.559999`, 0.370006`, 0.599994`];     orangeRed = RGBColor[1.`, 0.270608`, 0.`];     ContourPlot[{Re[HarmonicNumber[n, x + I y]] == 0, Im[HarmonicNumber[n, x + I y]] == 0},      {x, -30, 1}, {y, 0, 6000},     MaxRecursion -> 3,ContourStyle -> {Directive[Thick, mediumSeaGreen],     Directive[Thick, violet]},      Epilog -> {PointSize[0.02], orangeRed, Point[zeros]}]      The following was my trial of n=20 and range x={-32,1} and y={0,4000}. n = 20; seeds = findSeeds[myHN[n, x + I y], {x, -32, 1}, {y, 0, 4000}, PlotPoints -> 25, MeshFunctions -> {myHNReImCx[n][#1, #2] &, myHNReImCy[n][#1, #2] &}]; // AbsoluteTiming allfoundzeros = Quiet@myFRC[myHN[n, z], {z, -32, 1 + 4000 I}, seeds.{1, I}]; // AbsoluteTiming uniqueszeros = #[[First@Ordering[Abs@myHN[n, #]]]] & /@ findclusters[allfoundzeros, 10.^-6]; // AbsoluteTiming zeros = Pick[uniqueszeros, With[{zz = Developer`ToPackedArray@N@uniqueszeros}, UnitStep[(#1 - (-32)) (1 - #1) (#2) (4000 - #2)] &[Re[zz], Im[zz], 1]], 1]; // AbsoluteTiming Length[zeros] zeroplot = Graphics[{PointSize[0.0035], Red, Point@Transpose@{Re[zeros], Im[zeros]}}, PlotRange -> {{-32, 1}, {0, 4000}}, AspectRatio -> 1, Frame -> True]


Is it possible to use WolframAlpha servers to evaluate equations in Mathematica v8.0.4?

Is it possible to use WolframAlpha computational power to evaluate equations in Mathematica version 8.0.4? The thing is, it takes ages for my computer to evaluate certain equations. It would be great if I could use WolframAlpha (or something else?) to compute these equations .


The algorithm of ListGraphs[n,m]

I'm not sure if this is a Mathematica problem, math problem or a CS problem, so if this is off-topic please transfer it. In the package `Combinatorica` there is a function `ListGraphs[n,m]` which returns all nonisomorphic undirected graphs with `n` vertices and `m` edges. What algorithm does it use? All I can think of is to enumerate all graphs with `n` vertices and `m` edges brute-force, and check isomorphism for each graph. But I don't think that's effective. Is there a better algorism for this task? Thanks!


Mathematica 9 does not read mathematica 8 ".mx" files

Having written a lot of code on M8, I recently switched to M9 and tried to run the code on M9, the code starts by loading an .mx file written by M8, but M9 wouldn't read the .mx file saying that it was written on another machine. This is a major incompatibility issue between M8 and M9. Fortunately, I kept my M8 installation, so for now, M9 is useless to me. Please a solution.


ClassifierInformation's "ClassPriors" misreporting?

## To the **TLDR** people It seems to me that when you explicitly set `ClassPriors` when running `Classify`, it creates a `ClassifierFunction` that works fine but reports the `Automatic` class priors instead of those explicitly provided. Is this true, intended, buggy, or am I missing something? ## To the **WHYTPPCWCCAPWWDWFY** people _(What Have You Tried/Please Provide Code We Can Copy And Play With/We Don't Work For You)_ Take a `Classify` documentation example               data = {1 -> True, 2 -> True, 3 -> True, 4 -> True, 5 -> False,        6 -> True};          c = Classify[data];      It automatically chose Naive Bayes. Now we check the class priors               ClassifierInformation[c, "ClassPriors"]          (* <|False -> 0.25, True -> 0.75|> *)      Let's see the probabilites for 5               c[5, "Probabilities"]          (* <|False -> 0.341463, True -> 0.658537|> *)      This doesn't change if one explicitly sets the class priors, and this makes sense to me               c[5, "Probabilities",       ClassPriors -> ClassifierInformation[c, "ClassPriors"]]          (* <|False -> 0.341463, True -> 0.658537|> *)      Now, let's custom set other priors at classification time               priors = <|True -> 0.5, False -> 0.5|>;     c2 = Classify[data, ClassPriors -> priors];      The new probabilies lean more towards `False`, makes sense               c2[5, "Probabilities"]     c[5, "Probabilities", ClassPriors -> priors]          (* <|False -> 0.608696, True -> 0.391304|> *)     (* <|False -> 0.608696, True -> 0.391304|> *)      However, `ClassifierInformation` still returns the old priors               ClassifierInformation[c2, "ClassPriors"]          (* <|False -> 0.25, True -> 0.75|> *)      so these 2 now return different results.               c2[5, "Probabilities"]     c2[5, "Probabilities",       ClassPriors -> ClassifierInformation[c2, "ClassPriors"]]          (* <|False -> 0.608696, True -> 0.391304|> *)     (* <|False -> 0.341463, True -> 0.658537|> *)      Am I missing something when I find this weird/buggy?


How to use a scheduled event in a cloud notebook to read data files on a desktop

I don't know even how to attempt this, or if it's possible. I would like to be able to examine conditions, data, status of email server on my work desktop from the programming cloud. I recognize that these are three different things (is an application running? does a file xxx.xls have data for something? are processes connected to the desktop running?). One might be do-able and the others not, so to be specific, I would like to be able to check for data, and maybe start applications on my desktop from the cloud. I this even possible?


PolynomialReduce inconsistent results

I was playing around with gröbner basis and s-polynomials and I fell upon the PolynomialReduce, and I was wondering why it gives different results when I move around the polynomials in its second parameter,               PolynomialReduce[x^2 (x^2 + y) - 1 (x^2 y + 1), {x^2 y + 1, y + x^2, x^4 - 1}, {x, y}]      gives               {{-1, x^2, 0}, 0}      while               PolynomialReduce[ x^2 (x^2 + y) - 1 (x^2 y + 1), {y + x^2, x^2 y + 1, x^4 - 1}, {x, y}]      gives               {{x^2 - y, 0, 0}, -1 + y^2}      which is obviously wrong** as it is very apparent that the coefficients is just x^2 and -1. Can anybody shed some light on this? It's very disturbing and confusing. [edit] **the result might not be wrong, but it does not give the minimal b as per instruced by the documentation http://reference.wolfram.com/language/ref/PolynomialReduce.html


How can I export my learned ClassiferFunction[] and PredictorFunction[]s?

Mathematica 10 provides beautiful high-level machine learning functionality. Sadly, the learned functions once created are rather opaque objects. I need to use them in other projects, so here is my question: **Can I export the neural networks, random forest decision trees, or any other internals of the learned functions for externally use, e.g. can I export a neural net into a standard FANN File format.** PS. My real hope is to use _Mathematica_ **V10** to generate machine-vision convolutional neural networks and then embed them within my clojure, pythons and iOS projects.


What is the most efficient way to add rows and columns to a matrix?

Say I have a matrix m and a vector v.               v = {a[1], a[2], a[3], a[4]};          m={{a[1,1],a[1,2],a[1,3],a[1,4]},        {a[2,1],a[2,2],a[2,3],a[2,4]},        {a[3,1],a[3,2],a[3,3],a[3,4]},        {a[4,1],a[4,2],a[4,3],a[4,4]}};      What is the most efficient way to add v to the rows of m to create...               mrow={{a[1],a[2],a[3],a[4]},           {a[1,1],a[1,2],a[1,3],a[1,4]},           {a[2,1],a[2,2],a[2,3],a[2,4]},           {a[3,1],a[3,2],a[3,3],a[3,4]},           {a[4,1],a[4,2],a[4,3],a[4,4]}}      Likewise, what is the most efficient way to add v to the columns of m to create...               mcol={{a[1],a[1,1],a[1,2],a[1,3],a[1,4]},           {a[2],a[2,1],a[2,2],a[2,3],a[2,4]},           {a[3],a[3,1],a[3,2],a[3,3],a[3,4]},           {a[4],a[4,1],a[4,2],a[4,3],a[4,4]}};      **EDIT** : I've tested some of the suggestions for adding a column with a large matrix and was somewhat surprised by the results.               m = RandomVariate[NormalDistribution[], {1000, 1000}];          v = RandomVariate[NormalDistribution[], 1000];          In[37]:= AbsoluteTiming[Do[MapThread[Prepend, {m, v}], {100}];]          Out[37]= {1.809623, Null}          In[38]:= AbsoluteTiming[Do[Transpose[Prepend[Transpose[m], v]], {100}];]          Out[38]= {2.449231, Null}          In[39]:= AbsoluteTiming[Do[Transpose[Join[Transpose[m], {v}]], {100}];]          Out[39]= {2.271853, Null}


Merge two lists for List3DPlot

I have a two lists: `list1 = {{x1, y1}, {x2, y2}, {x3, y3}, {x4, y4}, {x5, y5}}` and `list2 = {z1, z2, z3, z4, z5}` and I want to make a third one like this `output = {{x1, y1, z1}, {x2, y2, z2}, {x3, y3, z3}, {x4, y4,z4}, {x5, y5, z5}}` What nice command can do the trick? It is to do a `ListPlot3D` with two lists with more than 10000 entries. I tried with `Map` and pure function but it is giving me troubles. Thank you


A Faster way to combine two Lists of different structures into one of a different structure

I have the following two lists (each containing over 500,000 elements). Here is a sample:               lis1 = { {1.86582, 1.70162, 1.25256}, {1.82707, 1.29901, 1.10659},        {1.76547, 1.21544, 1.09433}, {1.18306, 1.28322, 1.75524},        {1.12555, 1.98011, 1.53359}, {1.10584, 1.12299, 1.88411},        {1.83799, 1.5275, 1.76179}, {1.42352, 1.45163, 1.45318},        {1.63669, 1.78145, 1.60307}, {1.61749, 1.44287, 1.57405}      };      and               lis2 = {0.826095, 0.73286, 0.918137, 0.937434, 0.506525,              0.562795, 0.664915, 0.789321, 0.6559, 0.398447}      They both have equal `Length`s. I want to combine both Lists to obtain a new list that looks like this               { {1.86582, 1.70162, 1.25256, 0.826095},      {1.82707, 1.29901, 1.10659, 0.73286},      {1.76547, 1.21544, 1.09433, 0.918137},      {1.18306, 1.28322, 1.75524, 0.937434},      {1.12555, 1.98011, 1.53359, 0.506525},      {1.10584,1.12299, 1.88411, 0.562795},      {1.83799, 1.5275, 1.76179, 0.664915},      {1.42352, 1.45163, 1.45318, 0.789321},      {1.63669, 1.78145,1.60307, 0.6559},      {1.61749, 1.44287, 1.57405, 0.398447} }      That is, each element of the combined list contains the corresponding elements of `lis1` and `lis2`, with the first three elements being from `lis1` and the fourth element from `lis2`. Here is what I did to combine them in this fashion:               Transpose[{lis1, lis2}] //. {{a_, b_, c_}, d_} :> {a, b, c, d}      Is there a faster way to achieve this as my lists are huge ?


Adding columns of data to a matrix

I create a matrix of values using `Table`. Here's my code:               Matrice = Table[N[Spectral[i,j]], {i, 1, 50}, {k, {0.1, 0.2, 0.5, 0.8}}]      so I have a matrix `50x4` where `Spectral` is a function previously defined. I would like to have the `i`s on my first column, thus having a `50x5` matrix. How could I do that?


Nested List Product

I want to apply `Times` on the elements of a list such that:               {2,3,5,7,11,13,17,19} =>      {{2,3,5,7,11,13,17,19},{6,35,143,323},{210,46189},{9699690}}      I wrote this function :               listProduct[list_] :=       Apply[Times, Partition[list, Ceiling[Length[list]/2]]]          Nest[listProduct, {2, 3, 5, 7, 11, 13, 17, 19}, 1]      Using `Nest` at each level generate the desired element but I am having difficulties with combining the results. Also, I want to be able to use each element once computed.


How can I make DensityHistogram obey the lower bound in PlotRange in version 10?

In version 9, `DensityHistogram` worked with `PlotRange` as expected:               SeedRandom[0]     DensityHistogram[      Transpose[{RandomReal[NormalDistribution[], 1000],         RandomReal[NormalDistribution[], 1000]}],      PlotRange -> {{0, 3}, {0, 3}}     ]      ![enter image description here](http://i.stack.imgur.com/nQ1QZ.png) In version 10, the upper bound (3) is obeyed (with some new padding) but the lower bound (0) is ignored: ![enter image description here](http://i.stack.imgur.com/uVaJU.png) How can I make DensityHistogram obey the lower bound in PlotRange?


How do I expand a sum?

I have a problem with _Mathematica_ 's symbolic manipulations. As an example, consider the following expression: $$\sum _{i=1}^n -2 x_i \left(-a x_i-b+y_i\right)=0$$ How do I get _Mathematica_ to expand it into this form: $$-\sum _{i=1}^n x_i y_i +a \sum _{i=1}^n x_i^2+b \sum _{i=1}^n x_i=0$$ What I mean is: what functions do I apply to get the product to expand and the summation operator to distribute?


Efficient code for the Ten True Sentences puzzle

I am trying to solve Ten True Sentences Puzzle. > Take a look at the following sentences: > >   * The number of times the digit 0 appears in this puzzle is **_**. >   * The number of times the digit 1 appears in this puzzle is **_**. >   * The number of times the digit 2 appears in this puzzle is **_**. >   * The number of times the digit 3 appears in this puzzle is **_**. >   * The number of times the digit 4 appears in this puzzle is **_**. >   * The number of times the digit 5 appears in this puzzle is **_**. >   * The number of times the digit 6 appears in this puzzle is **_**. >   * The number of times the digit 7 appears in this puzzle is **_**. >   * The number of times the digit 8 appears in this puzzle is **_**. >   * The number of times the digit 9 appears in this puzzle is **_**. > > > Fill these sentences with digits such that all the sentences holds true. I wrote the following code, but it didn't work.               Do[       If[Tally[Range[0, 9] ~Join~ x][[All, 2]] == x, Print@x],       {x, Tuples[Range[0, 9], 10]}] // AbsoluteTiming      How can I imporve my code? **Updated**               Compile[{},        NestWhile[Join[{1, 7, 3, 2}, RandomInteger[10, 6]] &, Range[0,9],            Tally[Range[0, 9] ~Join~ #][[All, 2]] != # &],         CompilationTarget -> "C", RuntimeOptions -> "Speed"        ][] // AbsoluteTiming


Why is Mathematica treating my text as input?

I have typed in some text input by using Alt-7 to convert everything into text, but why is text still evaluated? Or is there better way to make comments other than (* text here *), because in my text there are numbers and it is also evaluating them too?


FindRoot options

I found an example of `FindRoot` usage that I couldn't find documented. It looks like:               FindRoot[f[x] == 0.4, {x, 0, 1, 0, 1}]      The documentation shows this case `FindRoot[lhs==rhs, {x, xstart, xmin, xmax}]` searches for a solution, stopping the search if x ever gets outside the range. But the example I found has an extra argument. What does it mean? Thanks.


Coloring a set of polygons, each polygon to have a specific color

In addition to my previus post, regarding plotting the surface of a Möbius strip, I now realised, that some of the eigenmodes for a Möbius strip are either oscillations of a scalar field OR a vector field, meaning that not all eigenmodes of this object can be shown in 3D as wobbles in the direction normal to the surface, because the Möbius strip is not orientable, like a cylinder is. Now that I have learned this fact, I have to do the following:   1. Represent all **transversal** oscillations as wobbles in the direction normal to the surface. This means that these are oscillations of a vector field with only one component. This has been succesfully done with the help in my previous question. Here is the solution for the case of a cylinder.   2. I need to represent all the **longitudinal** oscillations as oscillations of a scalar field, which is usually done by showing changes of color on an object, like shown in this example for a cylinder: ![enter image description here](http://i.stack.imgur.com/egcXZ.png) **Problem** I would like to plot 4D data $(x,y,z,F)$ as a set of polygons that have been made using `DelaunayTriangulation[]` of a 2D mesh in 3D using `Graphics3D`for the case of a Möbius strip, where $(x,y,z)$ are the data points and $F$ is the color. In my previous question I noted that `ListSurfacePlot3D` and `ListPlot3D` are not working properly for the case of the Möbius strip. The solution was to plot the strip as a set of polygons, generated by the mesh. A uniformly colored polygon surface looks like this: ![enter image description here](http://i.stack.imgur.com/cc4b3.png) **What I want** I would like to color these polygons with the color equal to the average value of $F$ for the surrounding 3 points. **Here is the provided data and code** Original 2D data of a rectangular $[0,1]\times[0,1]$ membrane:               data2D = Import["http://pastebin.com/raw.php?i=0Liw8F1r", "NB"];      Transformed 4D data parametrised as a Möbius strip with color data as the 4th column:               data4D = Import["http://pastebin.com/raw.php?i=zgrCRiQh", "NB"];      The code to draw the strip without the color data $F$:               tri = First@        Cases[ListDensityPlot[Join[#, {0}] & /@ data2D],          Polygon[idx_] :> idx, Infinity];              Graphics3D[          GraphicsComplex[           data4D[[;; , 1 ;; 3]], {Yellow, EdgeForm[], Polygon /@ tri}],           Boxed -> False, AspectRatio -> 1, BoxRatios -> Automatic,           SphericalRegion -> True,           PlotRange -> 0.9 {{-1, 1}, {-1, 1}, {-0.5, 0.5}}, ImageSize -> Large]      I tried to find some answers before posting the question, but all solutions had either discrete points or smooth plots in 3D, andI need to color the specific polygons. Thank you all for your help, I hope that the problem is clearly stated.


Can this function be numerically integrated

I need to integrate the function, $f(a,b)=-g(a,b) _ln(g(a,b)) = -1/ Pi_ (( (E^(-((a^2 - E^(-t [Gamma]) [Alpha]^2)/( 1 + 2 [Sigma]^2)))) [Pi] ([Sigma]^2) )/((1 + 2 [Sigma]^2) (E^(2 [Alpha]^2) + Cos[[Phi]])) (Exp[ I*(4 b E^(-((t [Gamma])/2)) [Alpha] + [Phi] + 2 [Sigma]^2 [Phi])/(1 + 2 [Sigma]^2)] + Exp[-I*(4 b E^(-((t [Gamma])/2)) [Alpha] + [Phi] + 2 [Sigma]^2 [Phi])/(1 + 2 [Sigma]^2)]) + (( E^(-((b^2 + (a + Sqrt[E^(-t [Gamma])] [Alpha])^2 - (2 [Alpha]^2 + t [Gamma]) (1 + 2 [Sigma]^2))/( 1 + 2 [Sigma]^2)))) [Pi] )/((2 + 1/[Sigma]^2) (E^( 2 [Alpha]^2) + Cos[[Phi]])*E^(t [Gamma])) + (( E^(-((b^2 + (a - Sqrt[E^(-t [Gamma])] [Alpha])^2 - (2 [Alpha]^2 + t [Gamma]) (1 + 2 [Sigma]^2))/( 1 + 2 [Sigma]^2)))) [Pi] )/((2 + 1/[Sigma]^2) (E^( 2 [Alpha]^2) + Cos[[Phi]]) _E^(t [Gamma])))/ Normalization_ (Log[( [Pi] ([Sigma]^2) )/((1 + 2 [Sigma]^2) (E^( 2 [Alpha]^2) + Cos[[Phi]]))] - ( a^2 - E^(-t [Gamma]) [Alpha]^2)/(1 + 2 [Sigma]^2) + Log[(2* Cos[(4 b E^(-((t [Gamma])/2)) [Alpha] + [Phi] + 2 [Sigma]^2 [Phi])/(1 + 2 [Sigma]^2)]) + E^(-((b^2 + 2*a*Sqrt[ E^(-t [Gamma])] [Alpha] - (2 [Alpha]^2 + t [Gamma]) (1 + 2 [Sigma]^2))/(1 + 2 [Sigma]^2)))* E^(-t [Gamma]) + E^(-((b^2 - 2*a*Sqrt[ E^(-t [Gamma])] [Alpha] - (2 [Alpha]^2 + t [Gamma]) (1 + 2 [Sigma]^2))/(1 + 2 [Sigma]^2)))* E^(-t [Gamma])] - Log[Normalization]) where $g(a,b)=$![enter image description here](http://i.stack.imgur.com/m1fEs.png) `a,b` are variables, `I` is a imaginary unit and others are constants having the following values. Normalization= 0.00585175 [Alpha] = 0.8 [Gamma] = 0.005*0.08 [Phi] = 0 [Sigma] = 0.02 t = 0 $f(a,b)$ cannot be analytically integrated, and so I'd like to numerically integrate it. As you can see in $g(a,b)$, $f(a,b)$ is a highly oscillatory function. So I'm using option `"LevinRule"`.               NIntegrate[f, {a, -Infinity, Infinity}, {b, -Infinity, Infinity},       Exclusions -> g == 0, Method -> "LevinRule",       MaxRecursion -> 100], WorkingPrecision -> 60]      The problem is _Mathematica_ says that > >     Numerical integration with "LevinRule" failed. The integration continues >     with Method ->"MultiDimensionalRule" >   The result of the numerical integration with `"MultiDimensionalRule"` is not accurate enough. Anyone knows how I can numerically integrate $f(a,b)$?


Is there a guideline about when to end expressions with semicolons?

Whether for nested `If`s or within scoping constructs like `Module` and `Block`, I never know whether to end the final expression with a semicolon. I know the semicolon suppresses output, but, for example, in a series of nested `If`s, one needs only to semicolon the outermost `If` to suppress output. So, is it better practice to semicolon _everything_ unless output is needed? Or is it better to semicolon _nothing_ until the last point where output is unwanted?


Find all the integer numbers $a$, $b$, $c$, $d$, $e$, $f$, $k$ to this equation have three integer different solutions?

How to find all integer numbers $a$, $b$, $c$, $d$, $e$, $f$, $k$ that belong to interval $[-10,10]$, so that the equation $$\sqrt[3]{a x + b} +\sqrt[3]{c x + d} + \sqrt[3]{e x + f} =k$$ has three different integer solutions? I tried               Reduce[{Root[#^3 - (a x + b) &, 1] + Root[#^3 - (c x + d) &, 1] +          Root[#^3 - (e x + f) &, 1] == k, -10 <= a <= 10, -10 <= b <=         10, -10 <= c <= 10, -10 <= d <= 10, -10 <= e <= 10, -10 <= f <=         10, -10 <= k <= 10}, {a, b, c, d, e, f, k, x}, Integers]      **Update** With $k=0$, we can transform the given equation of the form $$(a+c+e)x + b + d + f = 3\sqrt[3]{(ax + b)(cx+d)(ex+f)}$$ Cubing both sides of the equation:               ClearAll;     f[x_] := (a + c + e) x + b + d + f;     g[x_] := 3 ((a x + b) (c x + d) (e x + f))^(1/3);     Collect[f[x]^3 - g[x]^3, x];     Discriminant[%, x]      Next, we solve for `Discriminant > 0` But I can not get the answer. This is some equations   * $\sqrt[3]{-2 x + 8}+ \sqrt[3]{x + 2} + \sqrt[3]{x - 10}=0$.   * $\sqrt[3]{-2 x + 4}+ \sqrt[3]{x + 6} + \sqrt[3]{x - 10}=0$.   * $\sqrt[3]{-3 x + 9}+ \sqrt[3]{x + 1} + \sqrt[3]{2x - 10}=0$.   * $\sqrt[3]{-6 x + 6}+ \sqrt[3]{4 x + 4} + \sqrt[3]{2x - 10}=0$.


How safe are ReadProtected and Locked symbols?

> **Possible Duplicate:**   >  How to distribute proprietary Mathematica code I suspect that there is a way to expose the down values of such symbols with an attack along these lines:               Unprotect[SetAttributes, Set, Attributes]     SetAttributes[sym_, att_Symbol] /; MemberQ[{Locked, ReadProtected}, att] := Null     SetAttributes[sym_, atts_List] /;  MemberQ[atts, (Locked | ReadProtected)] :=       SetAttributes[sym, DeleteCases[atts, (Locked | ReadProtected)]]     Attributes /: Set[Attributes[sym_], att_Symbol] /;        MemberQ[{Locked, ReadProtected}, att] := Null     Attributes /: Set[Attributes[sym_], atts_List] /;        MemberQ[atts, (Locked | ReadProtected)] :=       SetAttributes[sym, DeleteCases[atts, (Locked | ReadProtected)]]     Protect[SetAttributes, Set, Attributes];      Can anyone recover the down values of this MrE[] function if you load "FindMeEncoded.m" into a fresh kernel?               MrE[x_] := With[{y = "you found me!!!!"}, ToString[x] ~~ ": you can't find me"]     SetAttributes[MrE, ReadProtected]     SetAttributes[MrE, Locked]     Save["FindMe.m", MrE]     Encode["FindMe.m", "FindMeEncoded.m"]


Read/Write protection of script

I have a script file (.m), which I need to distribute for execution. How can I read/write protect it? thanks


Solving an ODE in power series

How do I find a series solution to an ODE? I do not mean taking the Taylor series of an exact solution; I want to solve nasty nonlinear differential equations locally via plug and chug. Surely, that is a built-in option in _Mathematica_.


How to configure two Mathematica in different places with different settings

For some reasons, I should use two language versions _Mathematica_. The most reason is I want to see the comparison of Help page(English version and Chinese version) to improve my English, both are useful.   * [update]However, When I just concentrate on the language of Help page, that problem is nothing, just put english help page in the english version, and chinese help page in the chinese version, open Mathematica by two shortcut, it's OK now, ignore the language of the UI(both Chinese). ## question 1: How to make `FrontEnd` do not show this popup dialogue? ![enter image description here](http://i.stack.imgur.com/kmgok.png) ## question2: I've installed two _Mathematica_ 9 with different language versions. One in Disk D `English` Version One in Disk E `ChineseSimplified` Version How to configure two different settings? # _(Hard point:)_ Because they share the configures, some configure files are stored here in my computer.               "E:\\Users\\Quaternions\\AppData\\Roaming\\Mathematica"     "E:\\Users\\Quaternions\\AppData\\Roaming\\Mathematica\\FrontEnd\\init.m"      How to make the different configures, such as `Language`, `Background` and others. For background color, the value of `Background` is easy to setting. As I've tried, one can add               SetOptions[FrontEndSession,Background->LightBlue]      in some init.m here               "D:\\Program Files\\Wolfram\\Research\\Mathematica\\9.0\\SystemFiles\\Autoload\\PacletManager\\Kernel\\init.m"      or here               "D:\\Program Files\\Wolfram Research\\Mathematica\\9.0\\AddOns\\AutoLoad\\English\\init.m"      And then when open _Mathematica_ in Disk D, the background is LightBlue. When open _Mathematica_ in Disk E, the background will be White ($FrontEnd background value). What's the tough thing? The value of `$Language` So the keypoint of the problem is： How to open _Mathematica_ in Disk D whose `$Language` is English [Help page language is English, and also UI is English], and Open _Mathematica_ in Disk E whose `$Language` is ChineseSimplifed [Help page language is ChineseSimplified and also UI is ChineseSimplified]


Drawing a complete graph of an ego network

I have an ego network (a network of a person (ego) and his friends). It is drawn with the ego at the center surrounded by the friends. It might be possible that all the friends are connected to each other, in which case one can have a complete graph. Mathematica however draws a complete graph with no focal node. How can I make Mathematica draw a complete graph with a center node in it? How can I remove some connections so that it would still be an ego network but not a complete graph? Thanks.


Fast calculation of commute distances on large graphs (i.e. fast computation of the pseudo-inverse of a large Laplacian / Kirchhoff matrix)

I have a large, locally connected and undirected graph $G$ with $\approx 10^4$ vertices and $\approx 10^5$ to $\approx 10^6$ edges. Moreover I can bound the maximum vertex degree as $Q_{max}$. I would like to obtain all pairwise commute times between vertices in two sets $(v_{(a,1)}, ..., v_{(a,M)}) \in V_a$ and $(v_{(b,1)}, ..., v_{(b,N)}) \in V_b$ where $N >> M$, and do this without simulation of the underlying Markov process. To do this I need to compute the Laplacian matrix of $G$ (which is apparently computed using KirchhoffMatrix[G] in Mathematica, and takes about $\approx 50$ milliseconds on an X5690 3.47 GHz Intel Xeon processor), and then to compute its pseudoinverse, which I believe is an $O(n^3)$ operation. My question is - does Mathematica have a nice way of computing the pseudoinverse for a large Laplacian matrix, allowing me to efficiently extract commute times between pairs of vertices? How large can $G$ be? * * * Update - Following from Szabolcs comments, can anyone confirm that the time complexity of PseudoInverse[] is $O(n^3)$?


Is there a keyboard shortcut for Centered Math Cell?

I've been typesetting in mathematica and would like to know if it is possible to use a keyboard shortcut to place a centered math cell or equation symbol aligned math cell in my document without having to use the writing assistant.


Unexpected result from Map

I'm using _Mathematica 8.0_. Is the following output a bug or do I miss something?               f[a_] = 2 a;     Map[f,1+x]      gives $2+2x$ as expected, but               Map[f,x]      results in the output $x$


Determining the RGB values of the default plot color

In Mathematica 7, the default plot color is a purple-like color (although I think it is _not_ `Purple`). Is it possible to use Mathematica to determine the RGB color values of the default plot color? Thanks for your time.


Maximum tuple value

Is there a simple way to make a maximum tuple value (similar to python)? For example, in python               max([ (1,2), (1,3), (3,1), (4,0) ])      returns `(4,0)`, using lexicographic order. If I have a tensor in Mathematica, is there a way to take the max without flattening it? i.e. a way to call               Max[ { {1,2}, {1,3}, {3,1}, {4,0} } ]      so that it returns `{4,0}` instead of `4`?


Determine Functions Given Data Points

Is it possible for Mathematica to solve for f(x,y) = 0 such that {x,y} contains `{{0,0.5}, {1,0.5}, {0.6,0.8}, {0.4,0.2}}` ? Do we need to specify f(x,y) first ? Thank you


Plotting a network or a graph with given coordinates for vertices

I'm new to _Mathematica_ yet have coded a lot in MATLAB. Currently I'm working on a network simulation. My model is implemented in MATLAB, but I need to port it to _Mathematica_. **Here is my question** : Given a graph `g` and coordinates `x` and `y` for each node. I want to plot the network with nodes at the corresponding coordinates. How can this be done? In case you are also used to MATLAB, there is the function `gplot`, which does the job. Is there a similar plotting function in _Mathematica_?


Can you label an array by variables or strings instead of integers?

Is there a way to label an array by a variable instead of an integer? For example calling the array `I[i,j]` with `{i,j} = {x,y,z}` instead of `{i,j} = {1,2,3}`? For example, I might want to label the components of the Inertia tensor by `I[x,x]`, `I[x,y]`.. instead of `I[1,1]`, `I[1,2]`..


BoxWhiskerChart without whiskers

I would like a chart showing the median, 1/4, 3/4 quartiles, without the whiskers or fences. how can I achieve this? I cannot figure out how to turn off both the whiskers and the fences in the result of:               BoxWhiskerChart[RandomVariate[NormalDistribution[0, 1], 100]]      but doing so would do the trick.


Want more vibrant colors in plots

Is it possible to create plots that have vibrant colors like those I create in Python? For instance, take this thread function returning 0 where I used rainbow and here is the temperature gradient: ![enter image description here](http://i.stack.imgur.com/VmXIe.png) Now here is a heat map I created in Python for comparison. ![enter image description here](http://i.stack.imgur.com/uAyax.png)


How to create moving graphics that maintain shape

In the output code for the following graphic:               a = .5;     b = .4;     Subscript[θ, 1] = π/4;     Subscript[θ, 2] = π/4;     Q = 5;     p = 1;     {Slider[Dynamic[Subscript[θ, 2]], {0, 2 π}],       Dynamic[Subscript[θ, 2]],       Dynamic[ListPlot[        Flatten[{Table[{a + p,               b}.{{Cos[Subscript[θ, 2]],                Sin[Subscript[θ, 2]]}, {-Sin[Subscript[θ, 2]],                Cos[Subscript[θ, 2]]}}.{{Cos[Subscript[θ,                 1]], Sin[Subscript[θ,                 1]]}, {-Sin[Subscript[θ, 1]],                Cos[Subscript[θ, 1]]}} + {Q*              Cos[Subscript[θ, 1]],              Q*Sin[Subscript[θ, 1]]}, {a, -.5, .5, .1}],           Table[{a + p, -b}.{{Cos[Subscript[θ, 2]],                Sin[Subscript[θ, 2]]}, {-Sin[Subscript[θ, 2]],                Cos[Subscript[θ, 2]]}}.{{Cos[Subscript[θ,                 1]], Sin[Subscript[θ,                 1]]}, {-Sin[Subscript[θ, 1]],                Cos[Subscript[θ, 1]]}} + {Q*              Cos[Subscript[θ, 1]],              Q*Sin[Subscript[θ, 1]]}, {a, -.5, .5, .1}],           Table[{a + p,               b}.{{Cos[Subscript[θ, 2]],                Sin[Subscript[θ, 2]]}, {-Sin[Subscript[θ, 2]],                Cos[Subscript[θ, 2]]}}.{{Cos[Subscript[θ,                 1]], Sin[Subscript[θ,                 1]]}, {-Sin[Subscript[θ, 1]],                Cos[Subscript[θ, 1]]}} + {Q*              Cos[Subscript[θ, 1]],              Q*Sin[Subscript[θ, 1]]}, {b, -.25, .25, .05}],           Table[{-a + p,               b}.{{Cos[Subscript[θ, 2]],                Sin[Subscript[θ, 2]]}, {-Sin[Subscript[θ, 2]],                Cos[Subscript[θ, 2]]}}.{{Cos[Subscript[θ,                 1]], Sin[Subscript[θ,                 1]]}, {-Sin[Subscript[θ, 1]],                Cos[Subscript[θ, 1]]}} + {Q*              Cos[Subscript[θ, 1]],              Q*Sin[Subscript[θ, 1]]}, {b, -.25, .25, .05}]}, 1]        , PlotRange -> {{-5, 5}, {-6, 6}}]]}      The shape moves as I move the dynamic slider. However, the shape is distorted. I would like to figure out how to maintain the original shape of the rectangle as I move the plots of points around in the circle. How do I do this?


Displaying a locator that moves smoothly and updates some dynamic variables

I want to select a point on a graph and display a function of the coordinates value. Asking here a related question I learned to use Setting. Consider the example, where I display the coordinate `x` and its double `2*x`:               Manipulate[      xp = Dynamic[First[pt]];      z = Setting[2*xp];      Column[{        Style[StringForm["x=`1`, z=`2`", xp, z], Blue, 16],        LocatorPane[Dynamic[pt],         ListPlot[{{0, 0}},          Epilog -> {Red, PointSize[Large], Point[Dynamic[pt]]}          ]]}, Center],      {{pt, {0, 0}}, None}      ]      By clicking on the graph, the value of `x` and `z = 2*x` is correctly displayed above the graph. However, one cannot move the `Locator` smoothly, each point must be clicked! The problem is caused by `Setting`. By removing it, the point can be moved around smoothly, `x` is displayed dynamically but then the `z` is not calculated but displayed as `2 x`. Is it possible to display the value of `z` without loosing the fluency in the point selection? Is there a different way to get the value of `z` without using `Setting`?


Using Wolfram Language without Raspberry Pi

What are the different ways I can start using Wolfram Language even though I dont want to use Raspberry Pi? Are there any convenient ways? I actually have a raspberry pi but I am trying to find alternative workarounds as well.


How is Wolfram Language different than regular Mathematica?

From all I can see there seems to be no difference between "Wolfram Language" and regular Mathematica. Is Wolfram just a marketing rebranding of Mathematica or is there a new capability I am missing?


Plotting: DensityPlot produces artifacts

I am trying to plot the electric potentials of bouncing balls using the following code:               g = 0.1;     Tmax = 100;     n = 6;     pos = RandomReal[{-1, 1}, {n, 2}];     charge = RandomReal[{1, 10}, 10];          sol = NDSolve[         Flatten@Table[{             With[{i = i},                  {(x[i])''[t] == 0,                  (x[i])'[0] == 0,                  (y[i]'')[t] == -g,                  (y[i])'[0] == 0,                  x[i][0] == pos[[i, 1]],                  y[i][0] == pos[[i, 2]],                  WhenEvent[                      y[i][t] < -1, {y[i]'[t] -> -0.95 y[i]'[t],                       y[i][t] -> y[i][t] + 0.05}]                  }              ]      }, {i, 1, n}], Flatten@Table[{x[i], y[i]}, {i, 1, n}], {t, 0, Tmax}, PrecisionGoal -> 2];          Manipulate[Graphics[         Table[             With[{p = Evaluate[                 {x[i][t], y[i][t]} /. First[sol]]},             Disk[p, 0.05]], {i, 1, n}], PlotRange -> 1.05], {t, 0, Tmax}]          PotentialAnimated[x_, y_, t_] :=          Sum[charge[[i]]/             If[Norm[({x, y} - {x[i][t], y[i][t]} /. sol)] > 0.001,                 Norm[({x, y} - {x[i][t], y[i][t]} /. sol)], 0.001],         {i, 1, n}]          Manipulate[         DensityPlot[PotentialAnimated[x, y, t], {x, -1, 1}, {y, -1, 1}], {t, 0, 10}]      This^ last command should plot the potentials in my box caused by the charged balls jumping up and down, but I get an almost fractal looking artifact from my lower left to my upper right corner. Any ideas why this is happening ? // part 2 not directly related but I feel like it would be a waste to start a new question just for this. Im now trying to combine the two plots like this: Manipulate[ Show[{DensityPlot[ PotentialAnimated[x, y, t], {x, -10, 10}, {y, -10, 10}, ColorFunction -> "SunsetColors"], Graphics[ Table[ With[{p = {x[i][t], y[i][t]} /. First[sol]}, {ColorData["TemperatureMap", (charge[[i]] + 10)/20], Disk[p, 0.5]} ] , {i, 1, n}] , PlotRange -> 10.5, Background -> Black]}], {t, 0, Tmax}] for charges ranging from -10 to 10 , but it seems like the colors get "clipped" on the density plot![clipped](http://i.stack.imgur.com/Xl6dq.jpg) how can I fix it so colours near the balls dont just go white. thx for the help so far catadoxas


How to transform a 3D image by an affine transformation matrix

I have a question concerning Image Processing: I have a stack of images, which I can compose to a 3D image using Image3D. Additionally I have a 4x4 affine transformation matrix. I would like to transform the 3D image using my transformation matrix. In 2D this would be possible using ImageTransformation[image, transformationMatrix]               t = AffineTransform[{{{RandomReal[{-0.5, 5}],       RandomReal[{-0.5, 5}]}, {RandomReal[{-0.5, 5}],       RandomReal[{-0.5, 5}]}}, {RandomReal[{0.2, 0.2}],      RandomReal[{-0.2, 0.2}]}}]     ImageTransformation[ExampleData[{"TestImage", "Lena"}], t, PlotRange -> All, Padding -> None]      So this works fine for 2D images, but unfortunately ImageTransformation is not applicable to Image3D-objects. My first attempt was to decompose the matrix into several matrices and transform the image stack in 2 steps:   1. transforming each image of the image stack   2. transpose the image stack and transform with the transformation matrix for the third dimension. As an example I do the following steps for translation:               image3D = Import["ExampleData/CTengine.tiff", "Image3D"]     slices = Image3DSlices[image3D];     translation3D = TranslationTransform[{0.2, 0.1, 0.3}]     translation3D1 = TranslationTransform[{0.2, 0.1}]     translation3D2 = TranslationTransform[{0, 0.3}]     tempimageslices = ImageTransformation[#, translation3D1] & /@ slices;     transposedtempimageeslices =  Image /@ (Transpose[ImageData[#] & /@ tempimageslices]);     tempimageslices2 =   ImageTransformation[#, translation3D2] & /@ transposedtempimageeslices;     final = Image /@ (Transpose[ImageData[#] & /@ tempimageslices2, {2, 1, 3}]);     Image3D[final]      The Steps in this example are:   1. I cut the image into several slices.   2. I split the 4 x 4 transformation matrix "translation3D" into 2 3 x 3 matrices "translation3D1" and "translation3D2".   3. I transform every image in slices using ImageTransformation and the matrix "translation3D1"    4. I transpose the imageData and create new images in the new dimensions   5. I transform the images in the new dimensions using the matrix "translation3D2"   6. I transpose the images in order to have the original ImageDimensions For a translation or a scaling, the two transformation matrices i need, are easy to read from the matrix. The problem I have with this method is that I can't compute the decomposition of an affine transformation matrix. Is there an easy way to decompose the affine transformation or another solution in which the full affine transformation can be used to transform the image stack?


Notebook stops using extra kernels after some time

Have a mathematica .nb job where I've programmed to run on parallel. Everything goes fine for about an hour but after this most kernels just stop being used by the program. I can see this happing in most of my routines. I'll leave a link where most can take a look at the notebook Well, it's in portuguese, but you guys don't have to worry about that...most words are kind of readable.. !![Definitions 1](http://i.stack.imgur.com/34kt6.png) !![Definitions 2](http://i.stack.imgur.com/nxH60.png) !![Routine](http://i.stack.imgur.com/iIikU.png) !![Program Block](http://i.stack.imgur.com/vRU2L.png) https://onedrive.live.com/redir?resid=8F3E863A924D47BC%2114489


Can Eigenvalues[] and Eigenvectors[] be assumed to return the same ordering?

If I do back to back calls of `Eigenvalues[]` and `Eigenvectors[]` can these be assumed to order the values and vectors the same, or is each independent? Related to this is a curiosity about the performance of a pair of calls like this. Are Mathematica optimizations done at an expression level, or if a result from one could help another later (or previous) calculation, is it able to reorder internally and/or make use of previous calculations?


Order of eigenvectors

I have a matrix               A = {{5, 4, 2}, {4, 5, 2}, {2, 2, 2}}      The eigenvalues are `1, 1, 10` and I need to find the eigenvectors. Solving for `1` would result in two eigenvectors. Using _WolframAlpha_ I get `(-1, 0, 2)` and `(-1, 1, 0)` This comes from `x3 = -2 (x1 + x2)` For instance I could have: > >     x1 = 1, x2 = -1, x3 = 0 >   > > or >   >   >     x1 = -1, x2 = 1, x3=0 >   and > >     x1 = 0, x2 = -1, x3 = 2 >   > > or >   >   >     x1=-1, x2=0, x3=2 >   How to properly order those values?


Convert number to exponent form with highest power possible

As a school assignment we have to write a program which solves this issue. Since the program has to run efficient I am wondering what the best way is to approach this issue. Of course there you can just guess and try if it works, but that would not be efficient at all. Could someone push me in the right direction how to solve: n = b ^ e where e is the largest number possible? For example, n = 16 would result in 2 ^ 4 instead of 4 ^ 2.


Forcing contours to close at edge

I have some data that I am plotting with `ListContourPlot` and I would like my contours to be closed at the edge (closing around the high value region). A simple example:               ListContourPlot[{{3, 2, 1, 0}, {2, 1, 1, 0}, {1, 0, 0, 0}, {0, 0, 0, 0}},                      Contours -> {1}, ContourShading -> None, ContourStyle -> Thick]      > ![!\[plot of unclosed > contours\]\(http://i.imgur.com/B8eMa5d.png\)](http://i.stack.imgur.com/L4KLf.png) I know you can add e.g. `BoundaryStyle -> Black`, but it closes the whole region: > ![enter image description here](http://i.stack.imgur.com/WD0Mu.png) Note that I have tried the answer here, but that method changes the plotting method from plotting a matrix to plotting `{x,y,f(x,y)}` values, which has some undesirable results on my (much more complicated than the above example) data.


How to change the appearance of a Cell GroupOpener?

I would like to change the Cell GroupOpener appearance. ![Cell GroupOpener](http://i.stack.imgur.com/VJoPt.png) In the present Mathematica design it is too small and can be missed by a reader unfamiliar with Mma. I know, how to change its color through the OptionInspector. Now, how can I put there something instead of the check-mark that is there at present? For example, a gray triangle that has been there previously, of something more complex, some graphics of my own design **Edit** : To answer the question of Silva below: This is how the Cell GroupOpener looks like at my machine operating on Windows XP, Mma 9.0.1. ![enter image description here](http://i.stack.imgur.com/HjB2Y.png) Now on my other machine with Windows 7 and same Mma version the GroupOpener looks like a tiny check-mark. It is hardly visible and it is more difficult to operate (i.e. to open and close). For example, visually it is difficult to distinguish the closed from the open one. I am sorry, being presently at the machine with the XP I cannot provide an image for the GroupOpener at Win7. Now, it is not too bad, as long as it concerns myself, this or that GroupOpener presentation is it. However, I am creating documents to give away, and need that inexperienced people would easily identify the GroupOpener and easily operate with it. So I would like to be able to control its appearance.


How to export results of an analysis in table format into MS word file

I'm working on a simulation study using Mathematica 8. At the end of the analysis I'll have a matrix of data containing my results (assume for three variables like x,y & z). I used these codes for integrating labels (e.g. x,y & z) into data matrix and creating a table format:               data = Table[Random[], {i, 3}, {j, 3}] (* as an example of data*)     label= {"x","y","z"}     Text@Grid[Insert[data, lab, 1], Frame -> All]      resulting in (I don't know why frames don't appear here but do in Mathematica): \begin{array}{ccc} \text{x} & \text{y} & \text{z} \\\ 0.0047326 & 0.877782 & 0.924523 \\\ 0.188628 & 0.171809 & 0.317739 \\\ 0.775678 & 0.0886559 & 0.336866 \end{array} I wan to how I can export this table into Ms Word as a table not an equation. Any help and idea is appreciated. Thanks, Amin.


Unable to convert $\TeX$ input into mathematica

The input               ToExpression["\\sqrt{x y}", TeXForm]      gives me the `$Failed` output. Maybe my very old computer is the problem, but that's the only command that has caused me problems, and that input is from the tutorials.


Function returning Null along with other unexpected expressions

When I use some function, at the end along with the output I get some NULLs returned that I don't understand the reason for and are highly undesirable. For example, when I define the reversal of list with               ReverseList[ele_List] := Module[{list = List[], i, k = 1},       {For[i = Length[ele], i > 0, {i--, k++}, {AppendTo[list, ele[[i]]]}],        Print[list],        Return[list]}       ]      The output I get                ReverseList[{1, 2, 3, 4, 5}]      is               {5,4,3,2,1} {Null, Null, Return[{5, 4, 3, 2, 1}]}      I am also have a problem with returning the list. Can someone please help me with these two problems?


AR(1) Process first term

I'm trying to generate a very simple AR(1) Process with _Mathematica_ using the `ARProcess[]` function. The process must have the following format: $Y_t = \alpha + \beta Y_{t−1} + ϵ_t$ However, after reading the _Mathematica_ help file and some posts about `ARProcess[]` at MMA.SE, I couldn't find a way to correctly generate the process. I seems that the `ARProcess[]` function cannot deal with the $\alpha$ term of the process. For instance, consider the process described below: $Y_t = 10 + .6Y_{t−1} + ϵ_t$ , where $ϵ_t$ is Normally distributed with mean $0$ and variance $4$ (i.e., $ϵ_t \sim N(0,2)$). If I use `ARProcess[{.6},4]` I get               Mean[ARProcess[{.6}, 4][t]]     Variance[ARProcess[{.6}, 4][t]]      > Out[1]= 0 > > Out[2]= 6.25 which are consistent with an AR(1) process of the form $Y_t = 0 + .6Y_{t−1} + ϵ_t$ I would like to be able to, though the `ARProcess[]` function, calculate the **mean** and the **variance** of the process $Y_t = 10 + .6Y_{t−1} + ϵ_t$ in order to get a **Mean** of $25$ and a **Variance** of $6.25$. Is there any way to achieve this in _Mathematica_?


How does one use StandbyDistribution to model the reliability of an M of N warm standby system when M > 1?

I am modeling the reliability of a system with four units, numbered 1 through 4. The system needs at least two of the four units to be operational. Initially units 1 and 2 are active and units 3 and 4 are in warm standby. If either unit 1 or unit 2 fails, unit 3 becomes active (unless it has already failed while in standby). If a second active unit fails, unit 4 becomes active (again unless it has already failed while in standby). When a unit fails it remains failed. Unit 1 has reliability distribution d1, unit 2 has reliability distribution d2, unit 3 has reliability distribution d3a when active and d3s when in standby, and similarly for unit 4. `StandbyDistribution` handles cases where initially there is only one active unit. However, in `StandbyDistribution[dist1, {..., {distxstandby, distxactive}, ...}, ...]`, it is not at all obvious to me what the expression `dist1` should be for the case I am looking at. At the same time, `BooleanCountingFunction` is well suited for an M of N system where all of the units are active, but there doesn't seem to be any way of specifying that `N - M` units are initially in warm standby. Has anyone successfully dealt with the case I am looking at?


Matrix of given size with unspecified elements

I want to generate a Matrix of given size whose elements are not specified I can use               Array[a, {3, 2}]      to get               {{a[1, 1], a[1, 2]}, {a[2, 1], a[2, 2]}, {a[3, 1], a[3, 2]}}      however i would like to have               {{a[[1, 1]], a[[1, 2]]}, {a[[2, 1]], a[[2, 2]]}, {a[[3, 1]], a[[3, 2]]}}


Where does Mathematica install command line tools on OS X Lion?

I've read the documentation and tutorials on using _Mathematica_ and the kernel from the command line, and all of these materials suggest that I ought to be able to simply type either               $ mathematica      or               $ math      in Terminal, assuming these these commands have been installed in (variously) `/usr/local/bin` or `/usr/bin`. But I get the usual "command not found" error message that results when this is not the case, even though these directories are in my PATH. Where does _Mathematica_ (9.0) really install `mathematica` and `math` on OSX Lion?


How can I check if one expression implies another?

Say I have one expression, for example $x^3-3 + c = y$, and I want to check if it implies another with some set of explicitly stated assumptions. With the previous example, assuming all variables are positive real numbers, we might ask if $x^3-3 + c = y$ implies $c = -x^3 + y$. This example is trivial, but I'd like to do the same where, perhaps, choices can be made about the use of various special functions or identities and there can also be inequalities. Is there something like `ImpliesQ[{exp1,exp2}]`?


Why am I getting an error from MLPutFunction after getting the MathLink from LibraryLink?

Based on the example on the documentation page for `processMathLink`, I've got the following C++ code:               void MathematicaFunctionDescriptor::Register(WolframLibraryData lib_data) const     {         MLINK link = lib_data->getMathLink(lib_data);         Checked(&MLPutFunction, link, "EvalutatePacket", 1, "MLPutFunction(EvaluatePacket, 1) failed");         Checked(&MLPutFunction, link, "Set", 2, "MLPutFunction(Set, 2) failed");         Checked(&MLPutSymbol, link, maFunctionName.c_str(), "MLPutSymbol(" + maFunctionName + ") failed");         Checked(&MLPutFunction, link, "LibraryFunctionLoad", 4, "MLPutFunction(LibraryFunctionLoad, 4) failed");         Checked(&MLPutString, link, "MaCALFrontEnd", "MLPutString(\"MaCALFrontEnd\") failed");         Checked(&MLPutString, link, mgFunctionName.c_str(), "MLPutString(\"" + mgFunctionName + "\") failed");         PutSymbolList(link, input);         Checked(MLPutSymbol, link, output.c_str(), "MLPutSymbol(" + output + ") failed");         int errorCode = lib_data->processMathLink(link);         if (errorCode != 0)             throw GMathematica::CallBackError(errorCode, "Cannot register function " + maFunctionName);         int nextPacket = MLNextPacket(link);         if (nextPacket == RETURNPKT)             MLNewPacket(link);     }      This is called from a function `initializeAll` which catches all exceptions, and converts them into error returns to Mathematica. `Checked` is a simple template function which wraps a call to its first arguement, checking its return status, and throwing an exception with its last argument as a message if the call fails. I've invoked this from Mathematica by:               LibraryFunctionLoad[ "MaCAL", "initializeAll", {}, Integer ]     %[]      The `LibraryFunctionLoad` seems to work; the dll "MaCAL" contains the function "initializeAll", which loads all of the necessary DLLs (about 20) in the correct order, then invokes the wrapper for the above function in the DLL "MaCALFrontEnd". I get back the error message `"MLPutFunction(EvaluatePacket, 1) failed"`. Regretfully, I don't know how to find out why it failed. More generally: I'm trying to execute "LibraryFunctionLoad" for all of my functions, from the C++ code invoked by the first function. (I actually tried this first in `WolframLibrary_initialize`; I moved it to a separate function when this failed, but with no noticeable difference.) Is it possible to do this from `WolframLibrary_initialize`? And is this the correct technique, or is there a better solution? And more generally, is there some good literature, on the net or in the form of a book, which explains how to do these sort of things. The Wolfram documentation is some of the worst I've encountered--they seem to confuse quantity with quality.


FindFaces: how to improve the results of the face recognition feature

In _Mathematica 9_ , the `FindFaces` command offers an easy way to detect faces. In some experiments, I've been getting reasonable results, but I'd like to know if there are ways to improve the success rate. As with the online help example, I thought the 1927 Solvay Conference photograph was a good place to start. You can find it on the Wikimedia here, at 3000 by 2171 pixels.               solvay = Import["http://upload.wikimedia.org/wikipedia/commons/6/6e/Solvay_conference_1927.jpg"];     faces = FindFaces[solvay]      which returns a list of rectangles:               {{{81.5, 1105.5}, {262.5, 1286.5}}, {{133.5, 1038.5}, {231.5, 1136.5}}, ...      Using these to chop out some passport photographs:               passports = ImageTrim[solvay, #] & /@ faces      gives this: ![solvay faces](http://i.stack.imgur.com/KlNI1.png) I can get rid of the images that are too large by using the optional minimum and maximum sizes:               faces1 = FindFaces[solvay, {85, 130}];     passports1 = ImageTrim[solvay, #] & /@ faces1      But it's still not perfect. (The online help example seems to miss more people than I do, but there are no false positives, unlike my interesting collection of masonry people. How would I improve these results? Is `Mathematica`'s built-in function capable of better results, or is it just, well, a toy?


How to extract a consecutive list of substring from a string?

Given a list of strings:               data = {      "2894;Hot Pink;53:09:44;1449714",      "17456;Dark Cyan;19:06:42;6929227",      "5147;Lime;54:11:55;5247632"     }      (Words are separated by `";"`, the number of words in strings are equal. Number of characters in strings are unequal. Number of characterss in words are unequal.) How to extract the $m^{th}$ through $n^{th}$ words, so that e.g. $m=2, n=3$ should return:               {     "Hot Pink;53:09:44",     "Dark Cyan;19:06:42",     "Lime;54:11:55"     }        **UPDATE** Final solution was found for the task.   I like to share it here.               inlist = RandomChoice[     {"7270;Deep Pink;04:14:55;0027354",      "2871;Dark Orchid;54:21:23;1182263",      "4021;Silver;04:00:58;6940040",      "3521;Dark Slate Gray;18:42:43;5828275"},      400000];            delim = ";";     fromWord = 2;     numberOfWords = 2;            from = 2 fromWord - 1;     to = 2 (fromWord + numberOfWords - 1) - 1;     outlist = List /@ StringJoin /@           StringSplit[inlist, delim -> delim][[All, from ;; to]]; // Timing            {0.92, Null}        The honor goes to the very concerned in this task. Every detail of their conception was vital to the solution. Keep'n rocking.


Discrepancy with TakeWhile between RandomInteger result and list on Linux

I have to following code that solves a problem for me. The example that is given to us is as follows: `lst = {1,-2, 3, 4,5,-3, -4, 9,7,0,8}`, predicate = `Positive`. The maximal Predicate-segments of `lst` are `{1}, {3,4,5}, {9,7}`, and `{8}`.               getSegments[lst_,predicate_] :=       Module[{res= {},seg, lstcopy=lst},         While[Length[lstcopy]>0,           seg = TakeWhile[lstcopy,predicate[#]&];           If[Length[seg] > 0,             (* True *)             AppendTo[res,seg];              lstcopy=Drop[lstcopy,Length[seg]],             (* False *)             lstcopy=Drop[lstcopy,Length[TakeWhile[lstcopy,!predicate[#]&]]];            ] (* If *)         ] ;(* While *)         Return[res];       ];      The above code works fine for the following input:               In[1]:= getSegments[RandomInteger[{-100,100},10],Positive]     Out[1]= {{68,13},{59},{16},{41}}          In[2]:= getSegments[RandomInteger[{-100,100},10],Negative]     Out[2]= {{-26},{-77,-60},{-11,-78}}      Yet something very strange happens with the following:               In[3]:= getSegments[RandomInteger[{1,2},10],EvenQ]     Out[3]= {}          In[4]:= getSegments[{1,1,2,2,1,2,2,1,2,2},EvenQ]     Out[4]= {{2,2},{2,2},{2,2}}      This is the same for OddQ. **Why does it treat the RandomInteger result so differently from the list?** The input for `In[4]` is also generated with a call to RandomInteger[{1,2},10]. I did find that `seg` is always empty with the `In[3]` case, while the `False` branch of the `If` takes all the elements in the list. **EDIT** It is of note that I run Mathematica 8 on Linux. The above works fine on Windows versions of Mathematica. **EDIT 2**               In[76]:= getSegments[RandomInteger[{1,2},5],EvenQ] // Trace     Out[76]= {{RandomInteger[{1,2},5],     {1,2,1,2,1}},getSegments[{1,2,1,2,1},EvenQ],SplitBy[{1,2,1,2,1},EvenQ]     [[If[EvenQ[First[{1,2,1,2,1}]],1,2];;All;;2]],     {SplitBy[{1,2,1,2,1},EvenQ],Split[{1,2,1,2,1},EvenQ[#1]===EvenQ[#2]&],     {(EvenQ[#1]===EvenQ[#2]&)[1,2],EvenQ[1]===EvenQ[2],{EvenQ[1],False},     {EvenQ[2],True},False===True,False},{(EvenQ[#1]===EvenQ[#2]&)     [2,1],EvenQ[2]===EvenQ[1],{EvenQ[2],True},     {EvenQ[1],False},True===False,False},{(EvenQ[#1]===EvenQ[#2]&)     [1,2],EvenQ[1]===EvenQ[2],{EvenQ[1],False},     {EvenQ[2],True},False===True,False},{(EvenQ[#1]===EvenQ[#2]&)     [2,1],EvenQ[2]===EvenQ[1],{EvenQ[2],True},     {EvenQ[1],False},True===False,False},{{1},{2},{1},{2},{1}}},     {{{{First[{1,2,1,2,1}],1},EvenQ[1],False},If[False,1,2],2},2;;All;;2},     {{1},{2},{1},{2},{1}}[[2;;All;;2]],{{2},{2}}}      I've trimmed down to problem to the following:               lst = RandomInteger[{1, 2}, 10]     TakeWhile[lst, EvenQ]     TakeWhile[lst, OddQ]      One of the TakeWhile calls should always return some value. Yet they both give an empty list. This works fine on Windows, yet fails on Linux.


Trying to calculate a sum within a module - why is the iterator not creating integers?

Suppose I have the code:               #!/usr/local/bin/MathematicaScript -script     SetOptions[$Output, FormatType -> OutputForm];          foo[bar_?IntegerQ, baz_?IntegerQ] = bar;          M[g_?IntegerQ] = Module[         {sum},         sum = Sum[foo[i, g], {i, 1, 4} ];         N[sum]     ];          Print[M[1]]      Why does this output:               foo[1., 1] + foo[2., 1] + foo[3., 1] + foo[4., 1]      When simply changing the `g` to a `1` as following correctly interprets the iterator as an integer?               #!/usr/local/bin/MathematicaScript -script     SetOptions[$Output, FormatType -> OutputForm];          foo[bar_?IntegerQ, baz_?IntegerQ] = bar;          M[g_?IntegerQ] = Module[         {sum},         sum = Sum[foo[i, 1], {i, 1, 4} ];         N[sum]     ];          Print[M[1]]      This outputs (as expected):               10


Mathematica for linear algebra course?

I'm taking a linear algebra / matrix theory course and we are free to use any software we want, and will be "expected to use MATLAB or an equivalent" for homework. The professor and textbook (Applied Linear Algebra) prefer MATLAB, some students seem to like R, but I'm already familiar with Mathematica and have a student license. Are there any possible limitations of Mathematica to watch out for, if used as a learning device (i.e. not for work or intensive computation) for a linear algebra course? e.g. Are there some operations which the other software packages can do which Mathematica cannot out-of-the-box?


Is there a way to make an interactive plot so one can pan and zoom?

My googling efforts returned nothing so I thought I'd ask here. I often make a ListPlot[] with a huge array, and sometimes it has smaller features that I'd like to take a closer look at, but aren't very visible zoomed all the way out. Obviously I can just change the parameter PlotRange, but that's kind of cumbersome. Ideally, I'd like to be able to select a box around the part I want to zoom in on, and even more ideally maybe use my mousewheel to zoom in on where the cursor is, and be able to "grab" the plot to shift around where I'm looking at, when I'm zoomed in. Most programs that plot things have this functionality, so I'm guessing MM must too. It seems like I might be able to do something similar using Manipulate cleverly (like, at least make sliders to control the zoom and center), but I don't see how to do it easily. Is there any way?


Trouble with CDF on Mac OSX

My problem seems to be very strange. I've created a CDF file and am trying to upload it to a Google site, and I've been almost completely successful! My only problem is that I cannot correctly view/interact with the CDF on my Mac. If I view in Safari, I cannot interact with the CDF, and if I use Firefox I can, but the CDF flashes near the top and bottom. However, if I view the exact same webpage on my desktop (running Windows 7), everything works fine across Firefox and Chrome! It seems that I've narrowed the issue down to spacing. If I take my original `.nb` file and save it as a `.cdf`, I preserve the spacing that I inteded to have, but I encounter the website embedding issues. However, if I run the "deploy as HTML" option, my spacing shrinks and becomes more compact, and my Mac browsers can handle the CDF. Problem is, I want to keep the spacing. Also, I am trying to give the embedded CDF a pixel size of 800x800. Any ideas? The two files can be downloaded from here:   * Spaced webpage   * Compact webpage


Need tips on improving this directed graph

First we define a function that returns the least odd prime factor.               lopf[n_] := FactorInteger[n][[2, 1]]      Then we craft a routine that performs the 3x+1 steps using only primes               t = {};     z = 4;     While[z < 501,      y = Prime[z++];      prev = y;      u = {};      x = y;      While[x >= y,       prev = x;       x = lopf[3 x + 1];       u = AppendTo[u, {DirectedEdge[prev, x]}];       t = AppendTo[t, u];       ]      ]     t = Union[Flatten[t]];      Then we graph it               Graph[t]      ![Mathematica graphics](http://i.stack.imgur.com/SoXZ2.png) How can we structure this graph in a more civilized manner? I would like to have the first 5 primes {7,11,17,13,5} placed vertically down the center of a .pdf page and the remaining primes clustered about them. Also, Is there a way to use a rollover to identify a prime represented by a dot? This would be handy within an interactive document.


Numerically integrating solution obtained from NDSolve method

In the following example, $u(x)$ is found numerically using NDSolve method.                F = 1/1000         h = 12000/1000         d = 10/10         L = 1000         W = 3         phi[x_] :=           Piecewise[{{(1/2)*(1 - Tanh[((L*x)/(d))]),              x <= 1/2}, {(1/2)*(1 + Tanh[((L*(x - L/L))/(d))]), x > 1/2}}]         vE[x_] := x*(1 - x)*4         s = NDSolve[{u''[x] == (h*L*L/(d*d))*phi[x]*phi[x]*u[x] -               F*L*L*(1 - phi[x]), u[-W*d/L] == 0, u[1 + W*d/L] == 0},            u, {x, -W*d/L, 1 + W*d/L}, Method -> "StiffnessSwitching",            WorkingPrecision -> 40, InterpolationOrder -> All]         diff[x_] := (u[x] - vE[x])*(u[x] - vE[x])         Plot[Evaluate[{diff[x]} /. s], {x, W*d/L, 1 - W*d/L},           PlotRange -> All]      Which works perfectly. I need to see what is mean square error between obtained solution and another function $vE(x)$.               sum = 0;     Do[      first = W*d/L;      second = 1 - W*d/L;      {sum = sum + diff[first + (i/100)*(second - first)]},      {i, 0, 100, 1}]     Evaluate[sum]      but this gives only expression but not value. I think this is because $u(x)$ is obtained at discrete points only and is not defined on the points on which I have calculated error. I also tried using integration,               intVal = NIntegrate[({u[x]} /. s - vE[x])*({u[x]} /. s - vE[x]), {x,         W*d/L, 1 - W*d/L}]      but this gives long error message ending with,                "...is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing"      How can I evaluate this integral?


Is there a way to require confirmation for execution of certain cells?

Often I have Notebooks where I generate several images and export them into files. Now when I want to change one image, I'd like to just re-evaluate the complete notebook, however I generally do _not_ want all images to be exported again, but only selected ones. For this, it would be useful if I could make _some_ cells confirmation-only. Ideally it would highlight the cell in question, but that's optional (I can just look at which cell is the first unevaluated). It should however make sure that the cell is visible (because Mathematica dialogs unfortunately tend to _completely_ block the underlying notebook). It should ask me if I want to execute the cell, and if I say no, just skip it and continue at the next cell. Is this possible, and if yes, how? Bonus points if it doesn't trigger when doing Shift-Enter from _within_ the cell in question (because in that case, it's obvious that I want it executed)


How to Solve or LinearSolve $A = I$ matrix equation?

I'd like to solve this equation for $A = B$ where $B = I$, which represents 3 systems of 3 linear equations, for $a, b, c, d, e, f$, without writing `LinearSolve` 3 times. What is a simple way to accomplish this? Input:                  A = {        {a + b, -a + b, a + 2 b},         {c + d, -c + d, c + 2 d},         {e + f, -e + f, e + 2 b}        };     MatrixForm[A]     B = IdentityMatrix[3]     (*want to solve A == B, but probably wrong...*)     M = LinearSolve[A, IdentityMatrix[3]]     MatrixForm[M]


No Syntax Highlighting of Package Functions

Lately, my installation of Mathematica has decided not to highlight any symbols loaded from packages. The picture below is a good representation of this: ![enter image description here](http://i.stack.imgur.com/AJEEY.png) where after loading both `PhysicalConstants`` and `Units`` `BohrRadius`, `Meter`, and `Angstrom` should all be black. Yet, they retain their "unknown symbol" color. This occurs for all packages and is persistent across restarting the front-end and rebooting the entire system. Any suggestions for correcting this? I am running the student version of 8.0.4 on MacOS 10.6.8.