Any solution to system of equations?

I need ANY combination of 8 variables which satisfy:               a+b+c+d+e+f+g+h=0     a^2+b^2+c^2+d^2+e^2+f^2+g^2+h^2=1     a*b+b*c+c*d+d*e+e*f+f*g+g*h+a*h>2/3      Ideally these would be numbers having simple closed forms... If I exchange third restriction with               a*b+b*c+c*d+d*e+e*f+f*g+g*h+a*h=2/3      I get a solution a=b=c=6^(-0.5); e=f=g=-6^(-0.5); d=h=0;


Interactive grid

I would like to create an interactive grid, whereby one number from a grid is selected by the cursor ("3" in the example below), and all other numbers in the grid are highlighted that are related to the chosen number, and each successive number after that. In the example below, "3" is the selected number, and the highlighted numbers are double the previous one. I am not sure whether a loop, or a direct function (in this case, clearly multiplying by powers of 2) would be the best approach - I assume the function-apply approach would be the quickest for large grids. Below is an example: ![enter image description here](http://i.stack.imgur.com/fNXyD.gif) generated with:               m = 10;(*size of the grid*)          premade = Transpose@Partition[Range@100, m];          col[n_] := Table[{n - 0.5, i - 0.5}, {i, 1, m}]          Graphics[{         {Red, Opacity[0.3], Rectangle[{0, 2}, {01, 3}]},       {Red, Opacity[0.3], Rectangle[{0, 5}, {01, 6}]},       {Red, Opacity[0.3], Rectangle[{1, 1}, {02, 2}]},       {Red, Opacity[0.3], Rectangle[{2, 3}, {03, 4}]},       {Red, Opacity[0.3], Rectangle[{4, 7}, {05, 8}]},       {Red, Opacity[0.3], Rectangle[{9, 5}, {10, 6}]},            Table[Text[Style[premade[[#, i]], Large, FontFamily -> "Times"],col[i][[#]]] &          /@ Range@m, {i, 1, m}]},          GridLines -> {Range@m, Range@m}, PlotRange -> {{0, m}, {0, m}},          Axes -> False, Frame -> True,          GridLinesStyle -> Directive[GrayLevel[0.8], Dashed]]      NOTE: All columns will be separate lists.


Mathematica Typing Effect

Here is a Typing Effect in javascript. I could only implement a very simple one:               DynamicModule[{s = ""},      Dynamic[Refresh[        If[Length[s] > 10, s = "", s = s <> "x"],        TrackedSymbols :> {}, UpdateInterval -> 0.5]]]      How can I do that exactly the same?


How to make all numbers equal to one in a Series?

I have many outputs of one-dimensional Series expansions for which I am only interested in the general tending with the variable. For example, I would like to be able to transform something like               3.4235 + (4.22-5.2342 I) a + 7.543 a^6 + O[a]^7      into just               1 + a + a^6 + O[a]^7      etc. I have tried many things, including trying to collect the SeriesCoefficients and reassign them to 1, but I haven't been able to make it work yet. Here's an example of an attempt that isn't yet working (note, if it did work as expected, I would still need to add a simple If[] to exclude assigning SeriesCoefficients or Chop@SeriesCoefficients that are 0 to 1).                clear[test]; test = Series[1/(1 - b x), {x, 0, 4}];      Do[test = ReplaceAll[test, SeriesCoefficient[test, s] -> 3], {s, 0, 4}];      Print@test      Probably a much more efficient solution to this problem would be a more general rule that could be applied to the final output that simply checks the expression for "numbers" and makes them all 1. Surely there is a way to get mathematica to recognize numbers compared to symbols?


Why the result by hand is different from the command "DSolve"?

_**Yesterday,I use the Mathematica to solve a Differential Equation by the command DSolve:_**               DSolve[y''[x] + 2 y'[x] + 5 y[x] == x Cos[x], y[x], x]      > {{y[x] -> E^-x C[2] Cos[2 x] + E^-x C1 Sin[2 x] + 1/200 (-25 Cos[x] Cos[2 x] > + 25 x Cos[x] Cos[2 x] - 3 Cos[2 x] Cos[3 x] + 15 x Cos[2 x] Cos[3 x] - 25 x > Cos[2 x] Sin[x] + 25 x Cos[x] Sin[2 x] + 4 Cos[3 x] Sin[2 x] + 5 x Cos[3 x] > Sin[2 x] - 25 Sin[x] Sin[2 x] + 25 x Sin[x] Sin[2 x] - 4 Cos[2 x] Sin[3 x] - > 5 x Cos[2 x] Sin[3 x] - 3 Sin[2 x] Sin[3 x] + 15 x Sin[2 x] Sin[3 x])}} _**However,I feel the result is very complex.So I caculate it by hand.Below is my process._** **_`Characteristic equation`:_** r^2+2*r+5==0 r1=-1+2 I,r2=-1-2 I **_So the`Nonhomogenerous equation` general solution is:_** E^-x(C1 Cos[2x]+C2 Sin[2x]) **_I use the`Differential Operator method` to caculate the nonhomogenerous particular solution:_** ![Differential Operator method](http://i.stack.imgur.com/ogO9N.png) **_So my question is why the two result is different?Can someone tell me the reason? Thanks sincerely!!_**


Manipulate: After Changing view of a Graphic, the sliders can't be used anymore

I have a new problem: I have exported my program as a cdf standalone. I changed the view of the graphic and now the sliders cant be used anymore. Very strange... Here is a screenshot: ![screenshot](http://i.stack.imgur.com/Sbaj1.png) The orange frame is the reason. The mouse still remains in the graphic. How can I solve this problem?


Why is my PageRank result in Mathematica converging this way?

I am using this technique to find the PR of these 3 pages. It converges to something it shouldn't be. I tried the same iteration in Java and 2 pages come up with 1.333 and the other one as 0.666. Mathematica is calculating something differently. Here's my code:               g = {"Netscape" -> "Amazon", "Netscape" -> "Netscape",         "Amazon" -> "Netscape", "Amazon" -> "Microsoft",         "Microsoft" -> "Amazon"};     pr = PageRankVector[g]     GraphPlot[g,       VertexRenderingFunction -> (Text[          Framed[#2 <> "\n" <>             ToString[pr[[#3]]], {Background -> RGBColor[1, 1, 0.8],             FrameStyle -> RGBColor[0.94, 0.85, 0.36]}], #1] &),       DirectedEdges -> True]


Correlation with missing data

I have two lists, age and score, that I want to find correlation on for 50 people. For some people, the score is blank. Example data:               age={60., 21., 24., 63., 66., 62., 56., 54., 62.,...}     score={720., 880., 980., 820., , 820., 970., 950., 170.,...}      If I simply use DeleteCases to remove the " " from the score list, I change the length and cannot correlate the two lists of different lengths. Suggestions?


White spots in ListDensityPlot

I have a problem with `ListDensityPlot`. I have some data on an irregular grid. I try to plot them with               xStart=0;     xEnd=1000;     yStart=170;     yEnd=270;     ListDensityPlot[data,PlotRange -> {{xStart, xEnd}, {yStart, yEnd}}, FrameTicks -> True,      AspectRatio -> Abs[(yEnd - yStart)/(xEnd - xStart)], PlotRangePadding -> None,        ColorFunction -> (If[#1 === 0 , Black, GrayLevel[Rescale[#1, {0, 1}]]] &),      ColorFunctionScaling -> False, LightingAngle -> None, InterpolationOrder -> 0, ImageSize -> 1000]      In the output I have some ugly white spots: ![picture with white spots](http://i.stack.imgur.com/YJ6Np.png) If I change my plot (setting `xEnd = 230`), the white spots disappear: ![picture with reduced range](http://i.stack.imgur.com/9TGdF.png) So, from my point of view, the white spots are not caused by my data. Somehow Mathematica (I am using 9.0.1) causes them. To solve this problem I am using the following workaround:               ListPlot3D[data, PlotRange -> {{xStart, xEnd/1}, {yStart, yEnd}, All},      BoxRatios -> {1, Abs[(yEnd - yStart)/(xEnd - xStart)], 1},      ColorFunction -> (If[#1 === 0 , Black, GrayLevel[Rescale[#3, {0, 1}]]] &),      ColorFunctionScaling -> True,Mesh -> None, ImageSize -> 1500,      ViewPoint -> {0, 0, Infinity}, InterpolationOrder -> 0, BoundaryStyle -> None]      This gives me a nice output: ![picture without white spots](http://i.stack.imgur.com/YPSAh.png) What can I do that I get the same output with `ListDensityPlot`? At least I need `ListDensityPlot` because changes in the `InterpolationOrder` look there different than in the `ListPlot3D`. There is perhaps a similar question here, but rescaling does not help here. Additionally, my problem is “solved” with `ListPlot3D`, Eli Lansey’s problem not. I would be happy about some help!


Why DSolve giving Inconsistent or redundant transcendental equation on this problem

Kamke's differential equation #574 has a solution, but Mathematica generates an error message as it tries to solve it. It still gives the solution. My question is: What could have caused Mathematica to generate these errors? Trying this on Maple, it gives also the solution shown with no error message. Should Mathematica have generated these error messages?               Clear[f, x, y];     DSolve[f[x - 3/2*D[y[x], x]^2] + D[y[x], x]^3 - y[x] == 0, y[x], x]          (*{{y[x] -> 1/9 (2 Sqrt[6] x Sqrt[x - C[1]] - 2 Sqrt[6] Sqrt[x - C[1]] C[1] + 9           f[C[1]]), y[x] -> 1/9 (-2 Sqrt[6] x Sqrt[x - C[1]] + 2 Sqrt[6] Sqrt[x - C[1]] C[1]      + 9 f[C[1]])}}*)      ![Mathematica graphics](http://i.stack.imgur.com/bh6rU.png) ![Mathematica graphics](http://i.stack.imgur.com/cpELd.png) The Kamke solution is from the textbook: ("Differential Gleichungen" by Kamke, 3rd edition.) ![enter image description here](http://i.stack.imgur.com/KFi4o.jpg)


Why Solve won't work for user-defined function, used for system solving?

I have a list of x-es, that I transform into a list of tx-es. Also tao is my user-defined function that I don't know the parameters of, but I do know the values I get when I put the tx-es in it. And Solve won't get me these parameters.               x = {1, 2, 2.5, 3, 4}     (* {1, 2, 2.5, 3, 4} *)          t[x_] := x*PI/2          tx = {t[x[[1]]], t[x[[2]]], t[x[[3]]], t[x[[4]]], t[x[[5]]]}     (* {PI/2, PI, 1.25 PI, (3 PI)/2, 2 PI} *)          tao[p_] := a + b*Cos[p] + c*Sin[p] + d*Cos[2 p] + e*Sin[2 p]          Solve[{tao[tx[[1]]], tao[tx[[3]]], tao[tx[[3]]], tao[tx[[4]]], tao[tx[[5]]]} == {0, 1, 5, 2, 7},            {a, b, c, d, e}]     (* {} *)


Graphics Function Definition Style (Using SubValues vs. DownValues)

I am going through some of the items in "Modern Differential Geometry of Curves and Surfaces with Mathematica, Third Edition". An example of the style used by these authors is:               piriform[a_, b_][t_] := {a (1 + Sin[t]), b Cos[t] (1 + Sin[t])}          ParametricPlot[Evaluate[piriform[1, 1][t]], {t, 0, 2 Pi}, AspectRatio -> Automatic]      Can someone please explain why they use piriform[a_, b_][t_] as opposed to piriform[a_, b_, t_]? Is there some advantage to the authors' form over the latter form?


Using DateListPlot and Plot

I'm trying to do an example of trig modelling. Very simple, but hoping to use real data. I can get weather data for where I live here, and it makes a pretty reasonable sinusoid                   DateListPlot[      WeatherData["Edmonton",        "MeanTemperature", {{2005, 1, 1}, {2011, 12, 31}, "Month"}],       Joined -> True]      ![weather data](http://i.stack.imgur.com/sFBTh.png) I am looking for a VERY SIMPLE overlay of an actual sine graph, period would be 1 year, I'm guessing the midline would be about 5 degrees, amplitude is about 15 degrees, and phase shift is 0. This is just as much a math question as a Mathematica question. Like I said, I don't need a trig regression, at least not for this example. Just want to illustrate the process to my students, approximate a, b, c and d in the general equation y = a + b sin c(x-d) to show them a transformation of a function to reasonably match this data. If I find a plot that is reasonable, how do I overlay the two graphs? Also, I figured sunrise or sunset times would have been a better source of data, but didn't see anyway to access that from MMA, though I could get it from Alpha. Yes, this is non-math major, non-Mathematica expert , lame question! But help is appreciated. Okay, with help from @b.gatessucks I have made some progress, though I still value any feedback or help. So I get the weather data               data = WeatherData["Edmonton",         "MeanTemperature", {{2005, 1, 1}, {2011, 12, 31}, "Month"}];      changed the list to a numerical form, where the first entry is the number of seconds since Jan. 1 , 1900               newdata1 = {AbsoluteTime[#[[1]]], #[[2]]} & /@ data      I wanted this graph to have more reasonable numbers to use as an example with high school students, so I got the number of seconds up to Jan. 1, 2005 (where my data starts)               t1 = AbsoluteTime[{2005, 1, 1, 0, 0, 0}]       and subtract this from every entry so our time scale now has 0 at Jan. 1, 2005               newdata2 = {#[[1]] - t1, #[[2]]} & /@ newdata1      Now take that and divide by the number of seconds in year since I'd like each 1 on the time axis to represent 1 year               year = 3.154 10^7     newdata3 = {#[[1]]/year, #[[2]]} & /@ newdata2      This gives this plot ![list plot](http://i.stack.imgur.com/724KU.png) Which now lets me write a sin function using "reasonable" numbers. Note, I know this isn't a "fit" , it was intended to be more of a visual exercise in transformations of sine function. ![enter image description here](http://i.stack.imgur.com/TogK1.png)               Show[ListPlot[newdata3, Joined -> True],       Plot[2 + 15 Sin[2 \[Pi] (x - 0.25)], {x, 0, 7}, PlotStyle -> Dashed],       PlotRange -> {{-1, 7}, {-15, 20}}, ImageSize -> 300]


How do I find the best parameter to fit my data if the model is a interpolating function?

Hi I have a question regarding to find the best parameters for my model to fit my data. I have 3 ordinary equation, and I now just picked some parameters (`k1 = 7.32*10^-5; k2 = 8.09*10^-9`) for my ODE. Defined all the constant values:               k1 = 7.32*10^-5;     k2 = 8.09*10^-9;     Da = 1.33*10 - 4;     Nd0 = 0.001;     HR0 = 0.2;     H0908 = 0.004;     x0 = 0.007;      And define the 3 ODE equations:               Equation1908 = {Nd0*          Caf908'[t] == -k1*(Nd0*HR0)/H0908*Caf908[t]*Cbf908[t]/Hf908[t] +           k2*(0.2 - 3*HR0*Cbf908[t]),        HR0*Cbf908'[t] == -3*k1*(Nd0*HR0)/H0908*Caf908[t]*           Cbf908[t]/Hf908[t] + 3*k2*(0.2 - 3*HR0*Cbf908[t]),        H0908*Hf908'[t] ==          3*k1*(Nd0*HR0)/H0908*Caf908[t]*Cbf908[t]/Hf908[t] -           3*k2*(0.2 - 3*HR0*Cbf908[t]),        Caf908[0] == 1, Cbf908[0] == 1, Hf908[0] == 1};      Using `NDSolve`:               BC1908 = NDSolve[       Equation1908, {Caf908[t], Cbf908[t], Hf908[t]}, {t, 0, 1000}]      At the end, I obtained 3 interpolating function, for `Caf908[t]`, `Cbf908[t]`, and `Hf908[t]`... I used the solution (`Caf908[t]`) to fit my data. X-axis (`tfexp0908`) versus y-axis (`fexp0908`):               fexp0908 = .001*{1.009790523`, 0.898335138`, 0.878948419`,          0.830114856`, 0.767123385`, 0.732170062`, 0.672106602`,          0.637589428`, 0.59141947`, 0.523944512`, 0.554584169`,          0.451444203`, 0.396545111`, 0.444125908`, 0.352355452`,          0.272913948`, 0.33877861`, 0.287900412`, 0.276936425`};     tfexp0908 = {0, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 180, 210,         245, 270, 300, 330, 360, 390};      And I obtained a good fit. But I would like to know how I can use _Mathematica_ to obtain the best parameter, `k1` & `k2`, for my model (`Caf908[t]`) and get the best fit to my data. Thank you!


Why can't I remove Orderless from Plus?

I am making some random algebra equations, and I want to have the ordering be random too, such that if my random equation generator makes `x+1`, the output stays `x+1`, without reverting to `1+x`. I have tried `ClearAttributes[Plus, Orderless]`, but it simply did not work - entering `x+1` returns `1+x`. The following sort-of works:               Unprotect[Plus];     Format[Plus[a_, b_]] := ToString@a <> " + " <> ToString@b      But it uses `Unprotect`, converts everything to strings, and also doesn't work when `b` is a fraction (fractions `p/q` are represented as `p\n--\nq`). Is there a nicer way to do this? Also, I plan to convert everything to `TraditionalForm` at the end, so using that to control ordering won't work either.


Why aren't the locators independently enabled/disabled?

I am wondering why the `Enabled` setting for the first locator (point1) overrides the `Enabled` setting for the second locator (point2). Any ideas?               Manipulate[      Graphics[{ {{Arrow[{{0, 0}, point1}]}}, {{Arrow[{{0, 0},         point2}]}}},       Axes -> True, PlotRange -> {{-4, 8}, {-4, 8}}],     {{point1, {-1, 3}}, {-4, -4}, {8, 8}, {.1, .1}, Locator, Enabled -> False},     {{point2, {5, -2}}, {-3, -3}, {6, 6}, {.1, .1}, Locator, Enabled -> True}]      One of the locators should be enabled; the other should be disabled. However, as the picture shows, they are both disabled. I realize I could work around this by using `LocatorPane`, but I'm curious why this doesn't work for individual locators. Am I overlooking something or is this a bug? ![locators](http://i.stack.imgur.com/UNiPK.png)


Fluorescence Correlation Spectroscopy Simulation

I am simulating Fluorescence Correlation Spectroscopy which basically involves tracking the random motion of particles in a box with periodic boundary conditions and then calculating their intensity using a 3D Gaussian function where the particles are at their maximum intensity at the center of the box. Finally, the intensities of the particles are then summed up for each time step. The problem I am having is manipulating a very large list of lists when calculating the intensity of each particle at each time step.               Timing[Clear["Global`*"]       ClearSystemCache[];      n = 10.;      radius = 5.*10.^-9.;      k = 1.38*10.^-23.;      T = 293.;      Eta = 1.*10.^-3.;      d = (k*T)/(6.*\[Pi]*Eta*radius);      Deltat = 500000.;      time = 10.*10.^-6.;      Taud = (Omegar^2./(4.*d));      Omegar = 200.*10.^-9.;      Omegaz = 5.*Omegar;      Io = 1;      boundary = 5.*10.^-6.;      initial = boundary/2.;      step = Sqrt[2.*d*time];      RandomWalk[x_] :=        Accumulate[        Join[{RandomReal[{-initial, initial}, 3]},          RandomVariate[NormalDistribution[0, step], {x, 3}]]];      p = Table[        Mod[RandomWalk[Deltat], boundary, -initial], {i, n}];      particleintensity =        Table[Io*Exp[(-2.*(p[[i, t, 1]]^2. + p[[i, t, 2]]^2.))/Omegar^2. - (2. (p[[i, t,        3]]^2.))/Omegaz^2.], {t, 1, Deltat + 1}, {i, n}];     int = Total[particleintensity, {2}];     ListPlot[int, AxesOrigin -> {0., 0.}, AxesLabel -> {"t", "I"},       PlotRange -> Full, PlotRangeClipping -> False, PlotStyle -> Red]]          {87.2093,"Plot"}      ![Mathematica graphics](http://i.stack.imgur.com/72CgF.png) In the example above, I have 10 particles for 500,000 time steps and it takes a considerable amount of time. The majority of the calculation time occurs at the end when calculating the variable `particleintensity`. I am thinking that there has to be a faster way to do this that utilizes less memory. Any suggestions would be greatly appreciated.


Product of elements within a list

Please Consider :               list={{5,2,6},{2,8,3}}      I need to get the product of all the element within list : As of now I do this :               (#[[1]]*#[[2]]*#[[3]]) & /@ list      Which means I have to manually specify the number of elements within each least and the sublists length has to b equal. How could do this automatically to automatically deal with the following case ?               listA={{5,2,6,3},{2,8,3,4}}     listB={{5,2,6},{2,4}}


Matrix Multiplication Modulo 2

I would like to perform matrix multiplication modulo 2. Hence, instead of the usual: `A.B` I did: > `Inner[#1*#2 &, A, B, Modulus[#1+#2,2]&]` However, it does not work, since `#1+#2` (in the modulus) only adds the first two inputs, whereas, I want it to add all its inputs (like `Plus` does). I want to define a function that just adds up all its inputs, modulo 2 **and it can take in variable number of inputs**. In otherwords, I want to define a `addmod` which takes in variable number of inputs and adds them (modulo 2): > `addmod[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0] = 1`, `addmod[0, 1, 0, 0, 0, 1, 0, > 0, 1, 0, 0] = 1` and so on. Note, the input is not a list here. Hence I cannot say something like: `addmod[list]=Fold[Modulus[Plus[#1+#2,2],2]&,0,list]` I would be happy to get some help on this. Sorry, if i am missing out something basic. Thanks very much.


Saving in Latex

I have already asked this question in another topic, see here. When I save the following notebook code as $\LaTeX$,               In[1]:= DSolve[y'[x] + x y'[x]^2 == 1, y, x]          Out[1]= {{y ->         Function[{x},          C[1] + 1/2 (-2 Sqrt[1 + 4 x] - 2 Log[1 - Sqrt[1 + 4 x]])]}, {y ->         Function[{x},          C[1] + 1/2 (2 Sqrt[1 + 4 x] - 2 Log[1 + Sqrt[1 + 4 x]])]}}      I get this latex code:               %% AMS-LaTeX Created by Wolfram Mathematica 8.0 : www.wolfram.com          \documentclass{article}     \usepackage{amsmath, amssymb, graphics, setspace}     \newcommand{\mathsym}[1]{{}}     \newcommand{\unicode}[1]{{}}     \newcounter{mathematicapage}     \begin{document}     \begin{doublespace}     \noindent\(\pmb{\text{DSolve}[y'[x]+x y'[x]{}^{\wedge}2==1,y,x]}\)     \end{doublespace}     \begin{doublespace}     \noindent\(\left\{\left\{y\to \text{Function}\left[\{x\},C[1]+\frac{1}{2} \left(-2                   \sqrt{1+4 x}-2 \text{Log}\left[1-\sqrt{1+4 x}\right]\right)\right]\right\},\left\{y\to     \text{Function}\left[\{x\},C[1]+\frac{1}{2} \left(2 \sqrt{1+4 x}-2     \text{Log}\left[1+\sqrt{1+4 x}\right]\right)\right]\right\}\right\}\)     \end{doublespace}     \end{document}      I would like to have $$ instead of               \begin{doublespace}     \noindent      i.e., as an ordinary $\TeX$ file.


Optimizing the front end on the Raspberry Pi

Using Mathematica's Front End on the Raspberry Pi is truly a test of one's patience. The most basic of notebooks become unresponsive after seemingly trivial additions to the notebook. Consider the following Cell               Manipulate[       StringJoin["!raspistill -n -t 5", Sequence @@ {         " -w ", ToString@width,          " -h ", ToString@height,         " -ISO ", ToString@ISO              }, " -o -"],      {{width, 600}, 200, 2592, 1},      {{height, 400}, 200, 1944, 1},      {{ISO, 200}, {100, 200, 400, 800}},           ]      As I type this cell, the first several lines get displayed more-or-less as I type. By the time I get to the `{{ISO, 200} ...` portion of the cell, the notebook is fairly unresponsive, the CPU usage has jumped to 100% and I can get ahead of the display by a line or more. I've noticed some marginal increase in responsiveness with these options:               SetOptions[EvaluationNotebook[], "ShowSyntaxStyles" -> False]     SetOptions[EvaluationNotebook[], "ShowCodeAssist" -> False]     $HistoryLength = 0;      If I start a new Cell, the responsiveness goes back to "normal". If I input the same text into a `TextCell`, the display keeps up with my typing. As surreal as it sounds, _writing code into a TextCell and then converting the cell to Input_ is faster than trying to do everything in an Input cell. Does anyone have any suggestions on what other Options may be influencing the performance of Input Cells?


Simple algorithm to find cycles in edge list

I have the edge list of an undirected graph which consists of disjoint "cycles" only. Example:               {{1, 2}, {2, 3}, {3, 4}, {4, 1}, {5, 6}, {6, 7}, {7, 5}}      ![Mathematica graphics](http://i.stack.imgur.com/RCCrE.png) Each vertex has exactly two edges connecting to it. Each cycle has at least three vertices. The vertices are denoted by integers $1..n$. The edge list is given in some random order. The edges appear in random orientations (i.e. `{1,2}` might be given as `{2,1}`) I need to break the graph into cycles and sort the vertices in the order they're connected. For example, if the input is:               {{7, 6}, {5, 6}, {4, 3}, {3, 2}, {4, 1}, {2, 1}, {7, 5}}      then I want the output               { {1, 2, 3, 4},       {5, 6, 7} }      The first sublist corresponds to the tetragon, the second one corresponds to the triangle. The vertices must appear in the order they're connected. Performance requirements: the maximum vertex count is a few thousand---it should run near-instantaneously for an input of this size. An $n \log n$ solution is possible. However, I'm more interested in a concise and elegant solution than a performant one using e.g. `Compile`. Note: while it was easiest to state the problem in terms of graphs, it's not really a graph theoretical problem, so don't feel compelled to use `Graph` unless it's really advantageous. * * * **Clarification:** This question is not (only) about finding connected components. It is about ordering vertices along the cycles. Actually my practical problem is that I have the _edges_ of a polygon in random order and orientation, and I need to sort them so I can use them in `Polygon` and related primitives. A sample dataset can be downloaded using `Import["http://w504215.open.ge.tt/1/files/3XgvcEF/0/blob?download", "WDX"]`.


Close subgroup of cells and keep them closed

Styles can be used to give your calculation a book-like structure; with chapters, sections and paragraphs. Closing those subgroups of cells you don't want to see is then very powerful to create visual order. I use this to keep oversight of my calculation. The cells containing the actual calculations I close, and only the titles and heads are visible. This works well until I evaluate cells. Whenever a result or message is printed, the cells open automatically, and the notebook becomes a mess again. My question is: how can I prevent these cells from opening ? I have some ideas, but I would like to hear if you have any (better) alternatives. This I what can think of:   * Add a semicolon after each line.    * Use Block[{Print}, Expression} to suppress Print statements The side effect of these methods is that no results or messages are printed at all. I would like them to be printed though. At the same time I want to decide my self when to open a cell or not.


Delete the current notebook cell using the keyboard

Is there another way than pressing `Ctrl`+`.` until the whole cell is selected and then pressing `Del`? If this is not built in, can I create some sort of a global macro to do this and bind it to a keyboard shortcut?


Splitting a list at a particular position

Is it possible to split a list into two lists at a specific position? The main list is for example:               data={{xa,ya},{xb,yb},{xc,yc},...,{xz,yz}}.       I want to split this list into two new lists:               data1={{xa,ya},{xb,yb},...,{xi,yi}}       and               data2={{xj,yj},{xk,yk},...,{xz,yz}}       at a specific y-value at position `i`. I was not successful in using `Part`. Maybe there is another possibility?


Using .NET 4.0 from NETLink

Using Mathematica 8, I can check the version of the .NET framework used by `NETLink` as follows:               Needs["NETLink`"]     InstallNet[];     LoadNETType["System.Environment"];     System`Environment`Version@ToString[]      > "2.0.50727.5448" As you can see, it is the old 2.0 framework. However, my machine has version 4.0 of the .NET framework installed. Is there a way to configure Mathematica to use the newer version?


Replacement rule only matches part of expression

I have the result of a calculation (which is too long to mention here) and it gives               -I (t2 - t4) (((Hy vx^2 - Hx vx vy + vz (Hz vy - Hy vz)) Re[Ex] +         Hx vz^2 Re[Ey] - Ey vz^2 Re[Hx] +         vx (Hy vy Re[Ey] - Hz vz Re[Ey] + Ex vy Re[Hx]) +         vy (3 Hx vz Re[Ez] - 3 Ez vz Re[Hx]) + (-Ex vx^2 + Ex vz^2 +         vx (-Ey vy + 3 Ez vz)) Re[Hy] - Ex vy vz Re[Hz] +         vx (-3 Hy vz Re[Ez] + Ey vz Re[Hz]) +         vy^2 Real[I Ey Conjugate[Hx]]))      So, I have the following replacement rule               {f_ x_ + f_ y_ -> f (x + y), f_ x_ - f_ y_ -> f (x - y)}      If I now do               3 Hx Re[Ez] vz - 3 Ez Re[Hx] vz //. {f_ x_ + f_ y_ -> f (x + y), f_ x_ - f_ y_ -> f (x - y)}      This gives me               (3 Hx Re[Ez] - 3 Ez Re[Hx]) vz      If I do the same on the above equation the rule just gives the same thing back to me. What I want is (I have manually manipulated this to give what I want to obtain as requested.)               -I (t2 - t4) (-vx vy Abs[Ex]^2) +        vz^2 (Hx Re[Ey] - Ey Re[Hx]) +         vx vy (Hy Re[Ey] + Ex Re[Hx]) +         vy vz 3 (Hx Re[Ez] - Ez Re[Hx]) +        (-vx^2 + vz^2) (Ex Re[Hy] - Hy Re[Ex])        - vy vx Abs[Hy]^2        - vy vz (Ex Re[Hz] + Hz Re[Ex])        vx vz 3 (Hy Re[Ez] + Ez Re[Hy])        + vx vz (Ey Re[Hz] - Hz Re[Ey]) +         vy^2 Real[I Ey Conjugate[Hx]]      My substitution rules are                replrule1 = {f_ x_ + f_ y_ -> f (x + y), f_ x_ - f_ y_ -> f (x - y)}      replrule2 = a_Complex x_ Re[y_] + b_Complex y_ Re[x_] :>         Abs[a] Real[I x Conjugate[y]] /; a == -b      replrule4 = x_ Re[y_] - y_ Re[x_] -> Real[I x Conjugate[y]]      After that substitution I also want to apply               b_Complex y_ Re[x_] + a_Complex x_ Re[y_] :>  Abs[a] Real[I x Conjugate[y]] /; a == -b      Which has been a previous question of mine here.


Customize startup

Is there a way to personalize the startup? I want, for example, that mathematica starts Maximized (not slightly-less-than-maximized as it usually does) with a notebook (also maximized) with a zoom of 130%. I use mathematica 8.0.4 and windows XP.


How to add periodicity to condition?

Is it possible to set the following function `f[a]`, where `a` can be any real number? > $$ f(\alpha) = \begin{cases} 1 & \text{if } 2\pi n < \alpha < \pi (2n+1) \\ > 2 & \text{if } \pi (2n+1) \le \alpha \le 2\pi (n+1) \end{cases}, \ n \in > \mathbb{Z}\ $$ The issue here is `n` which I want to be substituted consecutively by an integer in order to produce propriate continuous conditions. I guess, it is not the case where `Assumptions` should be used as my attempt underneath doesn't work.               f[a_] := \[Piecewise] {        {1, 2 \[Pi]n < a && a < \[Pi] (2 n + 1)},        {2, \[Pi] (2 n + 1) <= a && a <= 2 \[Pi] (n + 1)}       }, Assumptions -> n \[Element] Integers      Thanks.


How can I overlap image on Graphics3D at a specific position?

I make a `Polygon` with size of {width=0,length=50,height=30}; I want to overlap `Image` on `Polygon` at position {width=0,length=25,height=15}. For this purpose I wrote some code: myImage= ![enter image description here](http://i.stack.imgur.com/6LF9n.jpg)                    Show[Rasterize[Show[Graphics3D[Polygon[{{0, 0, 0}, {0, 0, 30}, {0, 50, 30}, {0, 50, 0}}],                                     Lighting -> {LightBlue}, Boxed -> False                                        ](*Graphi3D is closed here*)                             ](*Show is closed*),                         "Image",Background -> None, ImageSize -> {300,300}                        ](*RasterSize is closed here*),                Graphics[Inset[Image[myImage(*its a variable*), ImageSize -> {50, 50}],Scaled[{25, 15}]]]             ](*Show is closed here*)      After evaluation of the above code I faced two problems   1. Graphics3D is not rotated,   2. `Image`is not overlapped, I want to overlap `Image` at a specific position on `Polygon` and if we have rotated `Polygon` automatically that overlapping `Image` was also rotated.


How to simplify or improve my code (or how to Flatten inside the matrix)?

I believe that it may be simplified, but I have no ideas anymore.. I need to flatten inside each element of array. F.ex. {{1}, 128552, 6, 1} ---> {1, 128552, 6, 1} Input data (Z - requests, t - periods of time):               Z = {{ 1,  3, 3, 7}, {8, 6, 6, 3}, {3, 5, 6, 13},       {15, 15, 9, 4}, {1, 1, 3, 6}, {9, 4, 3,  2}}          t = {{129600, 30240}, {30240, 10080}, {10080, 1440}, {1440, 0}}      I need to generate time of each request, then number of product (1-6), then sort it and give the index number of requst and in the end append 1. My decision:               MapIndexed[Prepend[Append[#, 1], #2] &, Sort[Flatten[Table[Partition[Append[Riffle[     RandomInteger[t[[i]], Z[[j, i]]], j], j], 2], {j, 6}, {i, 4}], 2], #1[[1]] > #2[[1]] &]]      It's part of the answer:               {{{1}, 128559, 3, 1}, {{2}, 128229, 6, 1}, {{3}, 127041, 4, 1},....,{{151}, 34, 3, 1}, {{152}, 18, 4, 1}}      I don't know how to simplify my decision..


How to evaluate the sum using values from the data being input

I have a problem in evaluating a sum using values from data I input. Suppose I have `data = {1, 3, 5, 6, 8}` If I want to evaluate the sum of my data (1+3+5+6+8), I can use the following command:               Sum[x, {x, data}]      And it will give me 23, which is correct. However, I found difficulty if I want to evaluate the sum of Log of each value, such that I have: Log(1) + Log(3) + Log(5) + Log(6) + Log(8). This can be done manually if I type the function one by one, but then it is not efficient if I have 100 values to be calculated. Can anyone help me in solving this problem?


Numerical value of physical constants Mathematica 10

Is there a way to use the physical constants in calculations and have Mathematica 10 figure out the final unit and numerical magnitude? When I try               pcM = N[Quantity[1, "PlanckConstant"]]      I simply get `1\. h` without the numerical value of Planck constant. Subsequently, using this in all further steps, keeps the answer in h and does not work out units. However, if I define the planck constant by hand and use it in a calculation, everything works as expected. I am curious as to why the internally defined constants do not show up with numerical values. Thanks,


Problems with BSplineFunction vs. BSplineSurface

Why are those surfaces different?               cpts = Table[{x, y, RandomReal[{0, 2}]}, {x, 0, 7}, {y, 0, 5}];     surf = BSplineSurface[cpts];     surfFn = BSplineFunction[cpts];               Show[      Plot3D[surfFn[x/7, y/5][[3]], {x, 0, 7}, {y, 0, 5}, Mesh -> None, PlotStyle -> Red,                                                             BoundaryStyle -> Red, BaseStyle -> Thick],      Graphics3D[{EdgeForm[{Blue, Thick}], surf}],       Background -> GrayLevel@.7]      ![enter image description here](http://i.stack.imgur.com/fc3ln.png)


What is an elegant way to aggregate two cash flows

When modeling a swap contract a common operation is to sum up two cash flows producing a resulting cashflow with netted amounts in the highest granularity of the two initial cash flows. What is a practical way to do this?               c1 = Cashflow[Annuity[-765.3, 4, 1/12]]; (*-monthly payments_*)          c2 = Cashflow[Annuity[2357.124, 4, 1/4]]; (*_-quarterly payments_*)          c3 = ? (*_-result is the netted cashflow in monthly granularity_*)      ![A fragment of result modeled with Numbers, with two cash flows in different granularity and the resulting with netted amounts.](http://i.stack.imgur.com/04JhL.jpg)


DateList does not output the correct time, but Date does

I noticed a strange thing when trying the new astronomical data functions in Mathematica 10 on my Raspberry Pi. The `Sunrise` and `Sunset` functions return incorrect times. Then I started to play with time and date functions and I've discovered that `Date` and `DateList` return different results. As a reference, the output of both functions on my main computer:               Column[{Date[], DateList[],$TimeZone}]      > >     {2014,3,31,20,54,59.141095} >     {2014,3,31,20,54,59.141123} >     2. >   But on the Raspberry Pi: > >     {2014,3,31,20,54,49.685639} >     {2014,3,31,19,54,49.778047} >     1. >   Looks like the `$TimeZone` is off, but `Date` ignores it. Let's look at the documentation of the two functions: > Date[] uses whatever date and time have been set on your computer system. It > performs no corrections for time zones, daylight saving time, etc. vs > DateList[] uses whatever date and time have been set on your computer > system. It performs no corrections for time zones, daylight saving time, > etc. So they should return exactly the same output. There's a warning that "Date has been superseded by DateList since Version 6.0" but in this case it actually works better. Why doesn't Mathematica detect the correct time zone and why does `Date` work, but `DateList` doesn't?


How to combine matrix with array without cycles?

I am new to _Mathematica_. And I'm sorry for my English.   I have created a matrix ($6 \times 4$) and an array ($1 \times 4$). I want to get another matrix that will have the first element from the array combined with all the first elements in all the lines. And the second element will be combined with all the second elements in all the lines of the matrix. I have the following data:               Z = {{ 1,  3, 3, 7}, {8, 6, 6, 3}, {3, 5, 6, 13},           {15, 15, 9, 4}, {1, 1, 3, 6}, {9, 4, 3,  2}}          t = {{129600, 30240}, {30240, 10080}, {10080, 1440}, {1440, 0}}      And I'd like to get this: > >     {{{{129600, 30240}, 1}, {{30240, 10080}, 3}, {{10080, 1440}, 3}, {{1440, > 0}, 7}}, >      {{{129600, 30240}, 8}, {{30240, 10080}, 6}, {{10080, 1440}, 6}, {{1440, > 0}, 3}}, >      {{{129600, 30240}, 3}, {{30240, 10080}, 5}, {{10080, 1440}, 6}, {{1440, > 0}, 13}}, >      {{{129600, 30240}, 15}, {{30240, 10080}, 15}, {{10080, 1440}, 9}, > {{1440, 0}, 4}}, >      {{{129600, 30240}, 1}, {{30240, 10080}, 1}, {{10080, 1440}, 3}, {{1440, > 0}, 6}}, >      {{{129600, 30240}, 9}, {{30240, 10080}, 4}, {{10080, 1440}, 3}, {{1440, > 0}, 2}}} >   I've done it with the help of `For`. But it's not so convenient..


Error Function Integral (Erf)

Any idea how to solve analytically this integral               Integrate[(a Erf[a Sqrt[b/(a^2 + b)] c])/(a^2 + b)^(3/2), a]      I tried substitution u=a^2 + b, but it didn't work. I don't need numerical integration or to solve via the few terms of the Taylor expansion. This seems to be very difficult to solve, but maybe somebody has got an idea.


How to show gif animation inside Manipulation in the cloud?

This creates a manipulate object show two static plots,               pic1 = Plot[Sin[x], {x, 0, Pi}];     pic2 = Plot[Cos[x], {x, 0, Pi}];     CloudDeploy[Manipulate[pic, {pic, {pic1 -> "sine", pic2 -> "cosine"}}]]      ![enter image description here](http://i.stack.imgur.com/GlLWE.png) Is it possible to replace the static images above with gif animations, so that it shows different gif animations as I select different buttons? For example, I tried something like               pic1 = Table[Plot[Sin[n x], {x, 0, Pi}], {n, 0, 2, 0.1}];     pic2 = Table[Plot[Cos[n x], {x, 0, Pi}], {n, 0, 2, 0.1}];          CloudDeploy[Manipulate[ExportForm[pic, "gif"], {pic, {pic1 -> "sine", pic2 -> "cosine"}}]]      but it doesn't work. This is what I get from the cloud ![enter image description here](http://i.stack.imgur.com/uzdau.png)


Speeding up a slow indefinite integral

I have found an alternative way to express an old solution:               PwD = (1/(4*Sqrt[Pi])) Integrate[(Exp[-(0.25/t)]/t^1.5)*         Sum[Exp[-((n^2*Pi^2*t)/40000)]              Integrate[                 Exp[-((z^2*Tan[45*Degree]^2 + (200*n - z)^2)/(4*t))] +                  Exp[-((z^2*Tan[45*Degree]^2 + (100 + 200*n - z)^2)/200)],                  {z, -50, Plus[50]}             ], {n, -4, 4}         ], {t, 0, y}       ];      Solving a partial solution, I have:               PwD = (Exp[-(0.25/t)]/t^1.5)*Sum[Exp[-((n^2*Pi^2*t)/40000)]*         Integrate[             Exp[-((z^2*Tan[45*Degree]^2 + (200*n - z)^2)/(4*t))] +              Exp[-((z^2*Tan[45*Degree]^2 + (100 + 200*n - z)^2)/200)],              {z, -50, Plus[50]}         ], {n, -4, 4}     ];      Now, for plotting the indefinite integral in time (`t`) I had used the following codes:               function[y_] := (1/(4 Sqrt[π]))*NIntegrate[PwD, {t, 0.01, y}];     tabulate = Table[{y, function[y]}, {y, 0, 100000, 1}];     finalfunction = Interpolation[tabulate];     LogLogPlot[{finalfunction[y], y*finalfunction'[y]}, {y, 1, 1000000},         PlotRange -> {0.01, 10}, Frame -> True]      I used this same code on other similar solutions and had positive results. But for this specific solution I couldn't get it to work. Or it's seems that would take a very long time for it. Could someone provide an alternative way to help _Mathematica_ along?


GroebnerBasis without specifying variables

All the examples in the Mathematica documentation specify that the syntax for the `GroebnerBasis` command is               GroebnerBasis[{poly1,poly2,...},{x1,x2,...}]      however it does return a result when ran just as               GroebnerBasis[{poly1,poly2,...}]      (although it does put a red caret in at the end, indicating it is missing an expected second parameter). I assume that, in this case, `GroebnerBasis` makes some choice for the variables. My intuition was that it would be `GroebnerBasis[polys] == GroebnerBasis[polys, Variables[polys]]`, but that does not seem to be the case. What is the behavior of the `GroebnerBasis` command without a variable specification?


Assign clipboard object in mathematica when print screen is pressed (windows)

Mathematica runs behind, while another window is selected. When I press print screen, I want mathematica too detect this and call a function with the picture as argument.               Paste[];     Image[%[[1,1,1,1,1,1,1]]]      Returns the screenshot, but I need it to be one command and picture shouldnt be almost destroyed as it happens with the command above. How should I do this?


Problem with Compile Function

I am attempting to `Compile` this function which is used to calculate a elastic collision in two dimensions. The two first coordinates of each list are the position and the last are the velocity of each colliding particle. It should take an argument like:               list={{1,2,3,4},{5,6,7,8}}          cF = Compile[{{list, _Real, 2}},        If[         (list[[2]] - list[[1]])[[{1, 2}]] != {0, 0},          Map[          Flatten[           {#[[1,1 ;; 2]]             + (#[[1,3 ;; 4]].{(#[[1, 2]] - #[[2, 2]]), (#[[2, 1]] - #[[1,1]])}               / Sqrt[(#[[1, 2]] - #[[2, 2]])^2 + (#[[2,1]] - #[[1, 1]])^2]              ) {(#[[1, 2]] - #[[2,2]]), (#[[2, 1]] - #[[1, 1]])}               /Sqrt[(#[[1, 2]] - #[[2, 2]])^2 + (#[[2, 1]] - #[[1,1]])^2]             + (#[[2,3 ;; 4]].(#[[2]] - #[[1]])[[{1, 2}]]               / Sqrt[(#[[2]] - #[[1]])[[1]]^2 + (#[[2]] - #[[1]])[[2]]^2]              ) (#[[2]] - #[[1]])[[{1, 2}]]               /Sqrt[(#[[2]] - #[[1]])[[1]]^2 + (#[[2]] - #[[1]])[[2]]^2]           , (#[[1, 3 ;; 4]].{(#[[1, 2]] - #[[2, 2]]), (#[[2, 1]] - #[[1, 1]])}              / Sqrt[(#[[1, 2]] - #[[2, 2]])^2 + (#[[2, 1]] - #[[1,1]])^2]            ) {(#[[1, 2]] - #[[2, 2]]), (#[[2, 1]] - #[[1, 1]])}              / Sqrt[(#[[1, 2]] - #[[2, 2]])^2 + (#[[2, 1]] - #[[1,1]])^2]             + (#[[2, 3 ;; 4]].(#[[2]] - #[[1]])[[{1, 2}]]               * Sqrt[(#[[2]] - #[[1]])[[1]]^2 + (#[[2]] - #[[1]])[[2]]^2]              ) (#[[2]] - #[[1]])[[{1, 2}]]                   / Sqrt[(#[[2]] - #[[1]])[[1]]^2 + (#[[2]] - #[[1]])[[2]]^2]}          ] &, (* End Flatten *)               {{list[[1]], list[[2]]}, {list[[2]], list[[1]]}}         ], (* End Map; End True branch of If *)         Map[Flatten[{#[[{1, 2}]] + #[[{3, 4}]], #[[{3, 4}]]}] &, list]       ] (* End If *)     ]; (* End Compile*)      However, it throws an error:               Compile::cplist:"Compile`GetElement[System`Private`CompileSymbol[0],System`Private`CompileSymbol[1]][[1,Compile`$5]] should be a tensor of type Integer, Real, or Complex; evaluation will use the uncompiled function."


Error entering equation in DSolve

I entered a command incorrectly as follows:                   DSolve[{y'[x]=y[x]},y[x],x]      I am now experiencing:                   DSolve[{y'[x] == y[x]}, y[x], x]      > During evaluation of In[26]:= DSolve::deqn: Equation or list of equations > expected instead of True in the first argument {True}. >>               (* DSolve[{True},y(x),x] *)      How do I recover from this error. I've tried Clear[y'[x]]. That didn't work. D.


Select a repeated element in a list

I want to select all elements that repeat 4 times in the list. I propose this code               list = {a, a, a, b, c, a, b, b, b, e};          elementsplus4 = Select[list, Count[list, #] == 4 &];      I obtain:               {a, a, a, b, a, b, b, b}      How can I obtain just `{a,b}`


Solve Lagrange multipliers optimization problem

I have two nested solid figure, where $V(a,h,\tau)$ defines the volume and $A(a,h,t)$ defines the surface. The outer solid figure is parametrized in $a_s$,$h_s$ and $t_s$ (they share a common center). Now I raise the Volume of the inner by factor $\alpha$, so $$V(a_s,h_s,t_s) = \alpha V(a,h,t)$$ The first constraint is that the surface $A$ of the inner raised solid figure is constant: $$A(a,h,t) = A(a_s,h_s,t_s)$$ The second constraint is that the enclosed volume of outer and inner solid figure is constant: $$V(a_sl, h_s+d, ts) - V(a_s,h_s,t_s) = V(al, h+d, t) - V(a,h,t)$$ If $\alpha$ gets too big, the surface constraint can not be satisfied any more. So I want to maximize this with respect to $\alpha$. The target function has to be $\alpha V(a,h,t)$. I'm taking the vector derivative in all my parameters (except for $al$, which is the function alipid) and try to solve it symbolically. This runs forever... (several hours by now). Can I check the "progress" somehow? Or is this simply an ill-posed system? **Perhaps I should try to optimize this numerically with some starting values for $a$, $h$ and $t$?** Finding good starting values will be difficult, as the system has lots of solutions.               d = 0.1;     V[a_, h_, tau_] := (Sqrt[3]/2) h (Sqrt[3] a + h/3 tau)^2     A[a_, h_, tau_] :=  3 Sqrt[3] a^2 + 2 a h Sqrt[1 + tau^2] +        h (2 a + Sqrt[3]/3 h tau) Sqrt[4 + tau^2]          alipid[a_, h_, tau_, d_] := a + d Sqrt[3]/         6 ((1 + Sqrt[1 + tau^2] - tau )/(1 + Sqrt[1 + tau^2] + tau ) +          (2 + Sqrt[4 + tau^2] - tau)/(2 + Sqrt[4 + tau^2] + tau))          eqns := {α V[a, h, t] + λ1 (A[as, hs, ts] - A[a, h, t]) +          λ2 (V[alipid[as, hs + d, ts, d], hs + d, ts] - V[as, hs, ts] -          V[alipid[a, h + d, t, d], h + d, t] + V[a, h, t])}     deriv := D[eqns, {{α, as, hs, ts, λ1, λ2}}]     Solve[deriv == 0, {α, as, hs, ts, λ1, λ2}, Reals]


exporting eps figures maintaining the same size

I need to export some (2D) graphs from mathematica in eps format (only, unfortunately). The graphs are of similar nature (plotted from our different functions), and I have used the `PlotRange` option to make all the graphs of equal size (in both `x` and `y` direction). However, while exporting, we get the exported files of slightly unequal size. This creates a problem while putting in some document, as when we scale it to the same size, the font size looks different (which, needless to say are same for everyone). I tried to use the `ImageSize` option, but definitely I am making some mistakes, as I am not getting the graphics ( or to be precise getting a small part of the graphics). So my question is, what is the best way to export all of them in a fixed size, say of 5cm x 4cm? I use version 7. Advanced thanks for any help.


Why does N[Re@f] give complex result?

Consider this code:               BlochΚ[κ_, V0_, z_] :=       MathieuC[MathieuCharacteristicA[κ, 2 V0], 2 V0,  z/2] +        Sign[κ] I MathieuS[MathieuCharacteristicB[κ, 2 V0],          2 V0, z/2]          Block[{$MaxExtraPrecision = 500, ϵ = 10^-10}, N[Re@BlochΚ[-2 + ϵ, -1, -10]]]     Block[{$MaxExtraPrecision = 1000, ϵ = 10^-20}, N[Re@BlochΚ[-2 + ϵ, -1, -10]]]     Block[{$MaxExtraPrecision = 500, ϵ = 10^-10}, N[Re@BlochΚ[-2 + ϵ, -1, -10]]]      On a fresh kernel I get               (*     -0.484175     -0.993753     -1.38778*10^-16+6.17104*10^-9 I     *)      Why I get complex number at the third time even I used `Re` explicitly? And why the results are different for the first and third time? Did I made a stupid mistake or what?


Recurrence relation in a table

I am trying to generate a list of `x`-values for a function using a module, where my `x`-value must increase by 'a' if the term number is even, and by 'y' if it is odd. However, `x[1]` is `0`. For example: $x_1 = 0, x_2 = a, x_3 = a+y, x_4 = 2a+y, x_5 = 2a+2y...$you get the point. I am attempting to use a recurrence relation within an If-clause to generate values of $x_n$. However, my code does not work. My code is:                XValues[counter_] :=          Module[{a, y, xvalues, x},               x[1] -> 0;               xvalues =           Table[x[j] -> If[OddQ[j] == True , x[j - 1] + y, x[j - 1] + a], {j, 2, counter}];               Flatten@{x[1] -> 0, xvalues}       ]      However, if I evaluate the module for a certain number, I get the following:               { x$10387[1] -> 0,        x$10387[2] -> a$10387 + x$10387[1],        x$10387[3] -> y$10387 + x$10387[2],        x$10387[4] -> a$10387 + x$10387[3],        x$10387[5] -> y$10387 + x$10387[4]}      I think it is probably to do with protected variables or something along those lines, but I am not sure. Any ideas would be gratefully received! Thanks. ---------------------EDIT--------------------- Thanks for all the answers! @Teake Nutma I have used your algorithm in a module to generate the values as it seems most appropriate to what I want to do with the `x` values.               XValues[counter_] :=         Module[{xvalues},         xsubstitute[1] = 0;         xsubstitute[i_Integer?EvenQ] :=          xsubstitute[i] = xsubstitute[i - 1] + a;         xsubstitute[i_Integer?OddQ] :=          xsubstitute[i] = xsubstitute[i - 1] + y;         xvalues = Table[xsubstitute[i], {i, 1, counter}]         ]      I now want to replace the `x` value in the `Phi` functions of the equations generated below with the `x` value generated through the XValues module (so a different value of `x` for each 'Eq' generated). This is my attempt so far but it does not appear to work. Any ideas?               simeqs = Table[Eq[j] -> Phi[j] == Phi[j + 1] /. x -> xsubstitute[j]/. eqs , {j, 2*number}];


Formatting a fraction as a mixed number

Is there a command that will take a rational number and rewrite it in a mixed- number-like form? That is, I'd like to apply a command to something like `10/7` and get the result `1 + 3/7` (or `3/7 + 1` would be fine, too). With polynomial division, the `Apart[]` command does the trick pretty well, but I haven't been able to find anything comparable for numbers.


SocialMediaData["Twitter"]: no output

I decided to give the `SocialMediaData` functionality of MMA10 a try but it does not seem to work for Twitter. The first time I call `SocialMediaData[]` I am correctly forwarded to the Twitter website where I can copy my authorization key, but then nothing happens. This is, for example, the output I get for               SocialMediaData["Twitter","FollowerNetwork"]      ![enter image description here](http://i.stack.imgur.com/12iTQ.png) When I enter a wrong authorization key the authorization window keeps reappearing so apparently the key is correct. `SocialMediaData` for Facebook works like it should. **Question: what could be the reason that SocialMediaData does not give any output?**


Using Compile Function Options efficiently

While this gives general pointers, I want inputs on **ground rules** for improved performance of nested/interdependent compiled functions. **sample problem:** `a`, `b`, `c`, and `d` are four supporting compiled functions that interact among themselves and also support the main function `main`, as defined below:               a = Compile[{{p1, _Real}, {p2, _Real}}, Min[p1, p2]];     b = Compile[{{p1, _Real}, {p2, _Real}}, Max[p1, p2]];     c = Compile[{{p1, _Real}, {p2, _Real}}, Min[1, 0.5 + a[p1, p2]/b[p1, p2]],             CompilationOptions -> {"InlineExternalDefinitions" -> True},          RuntimeAttributes -> {Listable},Parallelization -> True];     d = Compile[{{p1, _Real}, {p2, _Real}, {p3, _Real}}, a[Mod[p1, 5] - p2, p3],             CompilationOptions -> {"InlineExternalDefinitions" -> True},          RuntimeAttributes -> {Listable}, Parallelization -> True];          main = Compile[{{aa, _Real, 0}}, Module[{            k1 = RandomReal[10, {10^4, 5}],             k2 = RandomReal[5, {10^4, 5}],             k3 = RandomReal[15, {10^4, 5}]},             aa + b[k1, k2] + c[k2, k3] + d[k1, k2, k3]],             CompilationOptions -> {"InlineExternalDefinitions" -> True}];          Do[main[10],{100}];//AbsoluteTiming      I found that eliminating redundant options for dependent functions can help improve the performance; e.g. Since `a` and `b` are used in `c` and `c` is defined as listable and parallelized, 1) `a` and `b` need not be defined listable and defining them as listable may deteriorate the performance of `c` (using `AbsoluteTiming`) 2) since `a` and `b` are not defined `listable`, they can be inlined in `c` that will further improve performance, compared to using `"InlineExternalDefinitions" -> True` alone. With this understanding I want inputs to help establish ground rules that will enhance the **performance** of main:   1. Which functions need `CompilationOptions -> {"ExpressionOptimization" -> True}, RuntimeOptions -> "Speed"` and why not others?   2. Which functions need `CompilationTarger-> "C"` and why not others?   3. Since `main` calls `b`, `c` and `d` and already has `RuntimeAttributes -> {Listable}, Parallelization -> True`, none of the supporting functions should need to be listable, but it will not work. Why?   4. What else can be done to improve the performance of `main` (I need to use a compiled function in `NMinimizer`) ?


How to use SaveDefinitions when using Rasterized Frames for a ListAnimate?

In another post (Is it possible to prerender animation in Wolfram Mathematica?) I got a good way to prerender frames in order to get a smooth animation using ListAnimate. I need to save the Animation in a CDF document so it can be viewed by people using Wolfram CDF Player and not needing to run cells, so I use SaveDefinitions->True within the ListAnimate command. The problem is, when using rasterized frames, ListAnimate never runs and apparently causes a memory overflow. How can I solve this? I use this code for example (which doesn't run when SaveDefinitions is set to True):               exampleFrames =       Table[        DensityPlot[         Evaluate[          Exp[-((x - Cos[t])^2 + (y - Sin[t])^2)/.025]          ],         {x, -1.5, 1.5}, {y, -1.5, 1.5},         ColorFunction -> GrayLevel,         PlotRange -> All,         PlotPoints -> 30,         Frame -> None,         PlotRangePadding -> None         ],        {t, Pi/50, 2 Pi, Pi/50}        ];          rasterizedFrames = Map[Image, exampleFrames];          ListAnimate[rasterizedFrames, SaveDefinitions -> True]      I need this for my dissertation so any help would be really appreciated.


Efficient Generation of Random Variates from a Copula Distribution

I have a 7-asset portfolio for which I want to simulate daily log-deltas using a Student T copula. The marginal distributions are all either Stable or TsallisQGaussian. Using **NMaximize** , I have already determined that the copula _dof_ = 9. The asset correlation matrix, _corrmat_ , is:               corrmat = {{1., 0.491789, 0.382652, -0.580449, 0.34607, -0.0887926,        0.292343}, {0.491789, 1., 0.475475, -0.713583, 0.364887, -0.112926,        0.372419}, {0.382652, 0.475475, 1., -0.695327, 0.370684, -0.0894264,        0.359768}, {-0.580449, -0.713583, -0.695327, 1., -0.498612,        0.1529, -0.482753}, {0.34607, 0.364887, 0.370684, -0.498612,        1., -0.0433323, 0.291971}, {-0.0887926, -0.112926, -0.0894264,        0.1529, -0.0433323, 1., -0.0954981}, {0.292343, 0.372419,        0.359768, -0.482753, 0.291971, -0.0954981, 1.}}      from which the conditioned VCV matrix, _vcvmat_ , is:               vcvmat = {{0.9586172917, -0.03410852909, -0.2933963066, 0.1208800096,        0.1706880212, 0.1239885803, -0.06784705084}, {-0.03410852909,        0.6979797397,        0.02009209742, -0.001634295474, -0.02837172149, -0.02564790389,        0.01303223508}, {-0.2933963066, 0.02009209742,        0.7314875880, -0.1494059087, -0.3716208429, -0.2204546813,        0.1000107891}, {0.1208800096, -0.001634295474, -0.1494059087,        0.8597301696, 0.1366021203,        0.07930474269, -0.05334637064}, {0.1706880212, -0.02837172149, \     -0.3716208429, 0.1366021203, 1.136447366,        0.2592871862, -0.06289877472}, {0.1239885803, -0.02564790389, \     -0.2204546813, 0.07930474269, 0.2592871862,        1.154068011, -0.02358813328}, {-0.06784705084, 0.01303223508,        0.1000107891, -0.05334637064, -0.06289877472, -0.02358813328,        0.8678362987}}      The respective marginal distributions are:               mda = StableDistribution[1, 1.66576, -0.205451, -0.00149914, 0.00932388]     mdb = TsallisQGaussianDistribution[0.000198498, 0.0124003, 1.43148]     mdc = StableDistribution[1, 1.84146, -0.453362, 0.000669985, 0.00802551]     mdd = TsallisQGaussianDistribution[-0.00129644,0.0112156, 1.52237]     mde = TsallisQGaussianDistribution[0.000625683, 0.0147539, 1.46668]     mdf = StableDistribution[1, 1.45877, 0.253482, 0.000708238, 0.00111962]     mdg = TsallisQGaussianDistribution[0.00064191, 0.0121773, 1.52216]      Given these values, the entire copula expression is:               tCopula = CopulaDistribution[{"MultivariateT", vcvmat, 9},                    {mda, mdb, mdc, mdd, mde, mdf, mdg}];      So far, so good. The problem is the requisite calculation time. Here are the outputs:               In: Timing[x = RandomVariate[tCopula, 100];]     Out: {8.917131, Null}          In: Timing[y = RandomVariate[tCopula, 1000];]     Out: {92.197472, Null}          In: Timing[z = RandomVariate[tCopula, 10000];]     Out: {921.512002, Null}      The computation times are roughly linear, and since 10,000 samples is a bare minimum for meaningful analysis, simulating a mere 7-asset portfolio is at least a fifteen minute proposition. Is there a way to call this simulation more efficiently within _Mathematica_ 9? FWIW, I'm using _Mathematica_ on a Mac, so Finance Platform isn't an option. * * * Sasha, Thanks for taking the time to unbundle all that functionality. For the benefit of anyone else who wants to run the simulation, be aware that Mma threw a non-Hermitian error when I evaluated the _data_ argument the way Sasha initially set it up. I went back and adjusted the machine precision of my VCV matrix, and I created a separate variable, _v2mat_ , for Sasha's expression               vcvmat/KronekerProduct[Sqrt[Diagonal[vcvmat]],Sqrt[Diagonal[vcvmat]]]      Then I evaluated               RandomVariate[MultivariateTDistribution[v2mat, dof], 10^4]      and it worked fine. For purposes of comparison, I reran the original tCopula argument for a 10^4 x 7 set of observations:               In: Timing[data1 = RandomVariate[tCopula, 10000];]     Out: {888.577837, Null}      versus a 10^4 x 7 set of values from Sasha's method:               In: Timing[data2 = Transpose[MapThread[#1[#2]&, {qfs, Transpose[data]}]];]     Out: {4.322776, Null}      Quite a difference. Here's a graphical juxtaposition after running the same Mahalanobis distance multivariate outlier routine on both data sets. ![data1](http://i.stack.imgur.com/yBpLz.jpg) ![data2](http://i.stack.imgur.com/RYIy9.jpg) Not only is Sasha's method much faster, if anything it appears to yield more representative random variates.


Automatically compute r[1] = r1; r[2] = r2; …

I have three variables like this,               r1 = 4;     r2 = 3;     r3 = 1;      and I want to insert them into a function use them in a function definition like so:               f[n_] := r[n] + r[n-1]      So I need to have a function that just duplicates the variable, something like:               r[1] = r1 = 4;     r[2] = r2 = 3;     r[3] = r3 = 1;      Firstly, I thought of doing               r[n_] := r[n]      but that doesn't make much sense. * * * I was wondering if there is some nice way to do this?


Help to solve the equation with RungeKutta method

I need to solve this equation.               v'[t] + v[t] == 1/(1 + Exp[-v[t]])      I tried to solve it using RungeKutta method described in Wolfram tutorial(http://reference.wolfram.com/mathematica/tutorial/NDSolvePlugIns.html#51030643) But, I get some errors. I was wondering if anyone can help me to correct the error. I am still trying to figure it out. Appreciate any help. Thanks.                CRK4[]["Step"[rhs_, h_, t_, x_, xp_]] := Module[{k0, k1, k2, k3},       k0 = h xp;       k1 = h rhs[t + h/2, x + k0/2];       k2 = h rhs[t + h/2, x + k1/2];       k3 = h rhs[t + h, x + k2];       (k0 + 2 k1 + 2 k2 + k3)/6]     CRK4[___]["StepInput"] = {"F"["T", "X"], "H", "T", "X", "XP"};     CRK4[___]["StepOutput"] = "XI";          CRK4[___]["DifferenceOrder"] := 4          CRK4[___]["StepMode"] := Fixed     a = NDSolve[{v'[t] + v[t] == 1/(1 + Exp[-v[t]]), v[0] == 1},        v, {t, 0, 100}, Method -> CRK4]      But, It gives an error. I actually want to plot a graph of V vs t.


Setting an initial value for ListAnimate?

ListAnimate is fairly similar to Manipulate, but while Manipulate has a simple way to request an initial value for the manipulation parameter, I haven't found a way to tell ListAnimate to start with a certain value. Consider a simple example:               ListAnimate[Table[Plot[Sin[p x], {x, -1, 1}], {p, 1, 4}]]        vs.               Manipulate[Plot[Sin[p x], {x, -1, 1}], {p, Range[1, 4]}]        These simple examples seem virtually the same (I didn't bother to change the Manipulate Control to a slider), but in fact, they are different. ListAnimate is essentially pre-compiled. In my research, I want to do something similar with very complex plots which take a long time to produce. Manipulate re- calculates it's arguments when the manipulator is adjusted. We don't notice it here because Sin[p x] is so trivial. But with a complicated plot, it's no good. Conversely, with ListAnimate, it may take 15 minutes or more to run the code, once and for all, and then I can quickly scan through all the output smoothly. I looked through the options for ListAnimate and, for example, I can begin the output paused with ,AnimationRunning -> False. Is there a way to make the animation begin with not the first element but a chosen one? **TL;DR** Make               ListAnimate[Table[Plot[Sin[p x], {x, -1, 1}], {p, 1, 4}], AnimationRunning -> False]        begin with output of Plot[Sin[ **3** x], {x, -1, 1}]


Graphics elements do not line up perfectly in exported PDFs

Graphics elements do not always line up perfectly in exported PDFs using "Save As..." method. Take, for example:                Graphics[{Point[{0, 1}], Line[{{0, 0}, {0, 1}}]}, AspectRatio -> Automatic]      It looks like this on screen: ![](http://i.stack.imgur.com/Nf0uX.png) Notice that the dot isn't centred on the end of the line. Now let's export to PDF (hoping that what we saw displayed in the Mathematica GUI is just a rendering problem). Right click the graphic, and choose Save As... -> PDF. The PDF looks like this when magnified in a viewer: ![](http://i.stack.imgur.com/oTYCz.png) There is clearly a very serious misalignment. Is there a workaround? Note: this seems to be a new problem in version 9. Version 7 and 8 are not affected.


Plotting 2D Data with Categorical Data in One of the Dimensions

I have a 2D data set in the form of:               data={{Category, Integer}, {Category, Integer},{Category, Integer}...}      It is a pretty simple data set with four categories and several hundred rows. I am looking to make a scatterplot of the data resulting in a visualization with four columns of points, one for each category (placing categories on the X-Axis). This should be a very easy plot to produce using:               ListPlot[data]      Mathematica returns a blank plot with no error messages. I have also tried using DistributionChart with the following code:               DistributionChart[data, ChartElementFunction -> "PointDensity"]      Do I need to transform the categorical values to numeric? If I run this in R, it can identify they categories and handle appropriately. Update 1: Here is an example of what I get from R. The data set is movie ratings. It is out of scope for this posting, but I also like the Jitter function in R (as seen in this image) which seems not to have an equivalent function in M9. I usually play with opacity when I have many overlapping data points. ![Movie Ratings Scatter Plot in R](http://i.stack.imgur.com/Fyg4C.png) Update 2: Correct. The data is more accurately written as such:               data = { {{cat1, d11}, {cat2, d12}, {cat3, d13}, {cat4, d14}},  {{cat1, d21} ...}, ...}


Texture[] not working properly with Image AlphaChannel

I recently encountered a problem when combining multiple texture layers in an graphics object when the texture comes from an image with alpha channel. Apparently the alpha channel of the image passed to `Texture[]` as an argument is not represented as it should be in the obtained Graphics object. Instead of delivering true transparent texels I just get non transparent white ones. The same issue applies to usage of `Texture[]` with `Graphics3D`. Here is a simple test case: I first create two images, the second one containing an alpha channel:               layer1 = Image[RandomReal[1, {12, 12, 3}]];     layer2 = SetAlphaChannel[Image[RandomReal[1, {12, 12, 3}]],         Image[Join[ConstantArray[0, {6, 12}], ConstantArray[1, {6, 12}]]]];      Then I lay layer2 on top of layer1 and create a Graphics object of each layer using a Texture on a polygon:               Graphics[{Texture[layer1], Polygon[{{0, 0}, {1, 0}, {1, 1}, {0, 1}}, VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0, 1}}],        Texture[layer2], Polygon[{{0, 0}, {1, 0}, {1, 1}, {0, 1}}, VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0, 1}}]}]      Unfortunately I only get white pixels where layer2 should be transparent. ![enter image description here](http://i.stack.imgur.com/Ep9Ar.jpg) If I just pass the ImageData of layer2 things work, but the rest of the image information is lost (notice the additional blurring):               Graphics[{Texture[layer1], Polygon[{{0, 0}, {1, 0}, {1, 1}, {0, 1}}, VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0, 1}}],        Texture[layer2//ImageData], Polygon[{{0, 0}, {1, 0}, {1, 1}, {0, 1}}, VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0, 1}}]}]      ![enter image description here](http://i.stack.imgur.com/eT0jP.jpg) Is this a bug or am I missing something?


Crank-Nicolson scheme for Schrodinger equation

I try to solve 1D Schrodinger equation with Crank-Nickolson methode. I use atomic units: time < 10^-14 => 413 a.u.t. length 30 * 10^-9 m => 567 Bohr radii               a = 50;      \[Sigma] = a/10;     p[x_, 0] := Exp[-(x^2)/(2 \[Sigma]^2)]; (* граничные условия *)     p[\[PlusMinus]a, t_] := 0; (* н.у. *)     NN = 100;     h = 1/NN;     repl = x -> ((i*6*a)/NN - 3*a);      eq = D[Subscript[p, i][t],      t] == I/2(Subscript[p, i - 1][t] + 2 Subscript[p, i][t] -        Subscript[p, i + 1][t])/h^2(*+D[u[x],x]*Subscript[p,i][t]*)/.      repl;      Table[eq, {i, 0, NN}];     boundary = {Subscript[p, 0][t] == 0,      Subscript[p, NN][t] == 0};      p0[x_] := Exp[-(x^2)/(2 \[Sigma]^2)];      Cauchy = Table[     Subscript[p, i][0] == p0[x] /. repl, {i, 1,      NN - 1}]; (*задача Коши*)     eqns = Join[Table[eq, {i, 1, NN - 1}], boundary,      Cauchy];     sol = NDSolve[N[eqns],      N[Table[Subscript[p, i][t], {i, 0, NN}]], {t, 0, 413}];      and have this error:               NDSolve::mconly: For the method IDA, only machine real code is available. Unable to     continue with complex values or beyond floating-point exceptions. >>      I want to get something like this:               sol = NDSolve[{I D[u[t, x], t] == (-1/2)D[u[t, x], {x, 2}],      u[0., x] == Exp[-(x^2./(2*\[Sigma]^2))], u[t, a] == 0,      u[t, -a] == 0}, u, {t, 0, 4130}, {x, -a, a},(*MaxStepSize->0.01,*)     AccuracyGoal -> 3, PrecisionGoal -> 3];          Animate[Plot[Evaluate[Abs[u[t, x] /. First[sol]]^2], {x, -a, a},      PlotRange -> {0, 1}], {t, 0, 413}]      What's wrong with my code and how to fix it?


Is it possible to get the order of inputs when "overloading" an orderless function?

When working with symbolic matrix operations or other objects which don't have commutative multiplication, it would be nice to not have to constantly switch out times for `NonCommutativeMultiply` (`**`). So I was wondering if there is a way to do something like               matrix /: Times[pre___, a_matrix, post___] :=  NonCommutativeMultiply[pre, a, post]     a = matrix["a"];     b = matrix["b"];      and then have it replaced automatically. However since `Times` is orderless, this doesn't preserve the order. In general, is it impossible to get the order of inputs when doing this kind of "overloading" though upvalues of an orderless function?


Input alias having a place holder which gets selected when the alias is used

If one executes the following code               SetOptions[EvaluationNotebook[], InputAliases -> {"aa" ->       "AFunctionWithAVeryLongName[\!\(\*TagBox[FrameBox[\"input\"],\"Placeholder\"]\)]"}]      the front end will change `ESC`+`a`+`a`+`Esc` into a long expression with a placeholder. I want the placeholder selected after the replacement. If I try to use `SelectionPlaceholder`, instead of `Placeholder`, then a character from `AFunctionWithAVeryLongName` gets selected. If I try to include a tab at the end of the string,               SetOptions[EvaluationNotebook[], InputAliases -> {"aa" ->       "AFunctionWithAVeryLongName[\!\(\*TagBox[FrameBox[\"input\"],\"Placeholder\"]\:0009\)]"}]      the tab goes in literally as a tab character, not a tab command. Also, I want the output to have a string, say "input", in the placeholder. ![enter image description here](http://i.stack.imgur.com/Y9x4E.png)


Numerical error in Mathieu functions

Consider the `MathieuCharacteristicA` function, which is a piecewise function according to the documentation. The discontinuity happens at integer number.               With[{V0 = -1},       Plot[MathieuCharacteristicA[κ, V0], {κ, -2.5, 2.5}]]      ![enter image description here](http://i.stack.imgur.com/yn3nY.png) Consider the point approaching k=2 from the left side , and plot the Mathieu funtions near that point.               ParallelTable[      Plot[Evaluate@        With[{V0 = -1, κ = 2 - ϵ},          Re@MathieuC[MathieuCharacteristicA[κ, V0], V0,            z]], {z, -10, 10}, PlotRange -> All,        ImageSize -> Medium], {ϵ, {10^-8, 15/10*10^-8, 18/10*10^-8,         2*10^-8}}]      ![enter image description here](http://i.stack.imgur.com/ZXDAl.png) We see that from points k=2-10^-8 , k=2-1.5*10^-8 to points k=1.8*^-8, k=2*^-8, there are big discontinouity. **Why does this big discontinuity happen in the Mathieu function** , even we are still away from the piecewise point? **Which result is correct?** Moreover, as I increase the working precision, the results changes. Which results should I trust?               ParallelTable[      Plot[Evaluate@        With[{V0 = -1, κ = 2 - ϵ},          Re@MathieuC[MathieuCharacteristicA[κ, V0], V0,            z]], {z, -10, 10}, PlotRange -> All, ImageSize -> Medium,        WorkingPrecision -> 50], {ϵ, {10^-8, 15/10*10^-8,         18/10*10^-8, 2*10^-8}}]      ![enter image description here](http://i.stack.imgur.com/YYeZ3.png) **Update:** More strange behavior               NLimit[      Re@MathieuC[MathieuCharacteristicA[κ, -1], -1,         0], κ -> 2, Direction -> 1, WorkingPrecision -> 100]     (*      0.000026560352729499428275267693547091828644960849846890155742135607985075453865741662994877041     *)               N[      Table[Re@MathieuC[MathieuCharacteristicA[2 - ϵ, -1], -1,          0], {ϵ, {10^-6, 10^-8, 10^-10, 10^-20, 10^-40, 10^-60,          10^-100}}], 100]     (* \     {9.375519741470728355592491183508603286638427801561870220416306315833951776806837902179623867179198570*10^-6,       9.375519742493871990285719573456924995106820123921565403331967009687923231481580841077469030562191305*10^-8,       9.375519742493974304649207591451232553957148872416907065490732452953108780592926489536671069329119067*10^-10,       9.375519742493974314881667185336397875216528878100913700967589255793432748631135267810942389900367393*10^-20,       9.375519654864253585910474819580416042344587293945440367769556457939085038181962308922619162634748808*10^-40,     1.114388591781733115021002428520876171768008184684161143978162399223107768160400228809114697590700165,     1.114388591781733115021002428520876171768008184684161143978162399223107768160400228809114697590700165} *)      What's the correct limit for k->2 ?


Manipulate store values

Is there a way to store the numerical values from a manipulate function in the form of a table? For example, if the function is               f[x_] := x^2 - 2x      Can one store all the values for each value of `x` in `(0,1)` from `Manipulate[]` other than taking a snapshot?


Finding an optimal overlay of two point clouds

Imagine I have two sets of points:               pointSetPerfect = Flatten[Table[{i, j}, {i, 10, 40, 10}, {j, 10, 40, 10}], 1];          pointSetNoise = Table[pointSetPerfect[[i]] + RandomReal[{-2, 2} - 100], {i, 1, Length[pointSetPerfect]}];          r = RotationTransform[47.5 Degree, {0, 2}];     pointSetNoise = r[pointSetNoise];          ListPlot[{pointSetPerfect, pointSetNoise}]      Without knowing what I did above to generate `pointSetNoise`, I would like to overlay, as best as I can, a set of points on `pointSetNoise` with the same interpoint spacings as in the point set `pointSetPerfect`, and return these coordinates. If necessary, I could also click on the image to specify by eye a (very approximate) 1-to-1 mapping between points in either set. Is there a nice way of doing this in Mathematica v9?


Problem in solving PDE

I have a problem in solving a type of PDE. The actual problem involves diffusion and adsorption in a trench, but here is a simpler example. I have two independent variables $t$ and $x$. There are two dependent variables $y(t,x)$ and $z(t)$. Note that $z$ is a function of $t$ only. `NDSolve` does not accept the problem with the boundary conditions. Running this code               ClearAll["Global`*"];          pdeset = {D[y[t, x], t] == -D[y[t, x], x] + z[t], D[z[t], t] == y[t, 0]};     bc1 = {y[t, 0] == 5, y[0, x] == Cos[x]};     bc2 = {z[0] == 1};          bcAll = Flatten[{bc1, bc2}, 1];          sol = NDSolve[{pdeset, bcAll}, {y, z}, {t, 0, 1}, {x, 0, 1}]      I get the error message saying > >     NDSolve::ndode: Input is not an ordinary differential equation. >   I am using _Mathematica_ 9.0 on Windows 7 64 bit.


Will built-in functions always perform better than parallelized user-defined functions?

(*Here is an comparison*)     data = {};     For[n = 1, n < 10, n++,     t1 = Timing[ParallelSum[1/i^2, {i, 1, n*100000}]];     t2 = Timing[HarmonicNumber[n*100000, 2]];     AppendTo[data, {t1[[1]], t2[[1]]}]]     data      The result is as following which shows the built-in functions always win here.               {{0.432000, 0.192000}, {0.896000, 0.500000}, {1.476000,      0.860000}, {2.228000, 1.236000}, {3.048000, 1.664000}, {3.956000,      2.128000}, {4.920000, 2.540000}, {5.932000, 2.936000}, {7.140000,      3.492000}}      The question is: If we rewrite a built-in function with parallelized functions, e.g. rewrite               HarmonicNumber[n*100000, 2]      as               ParallelSum[1/i^2, {i, 1, n*100000}]      Could we win (in more general case)? If not, then why? And what is the advantage of parallelization? Any help will be appreciated!


EdgeRenderingFunction question

( **Edit 1** : I added this paragraph after the original post, for context) Some context for this question can be found in another post (Problem with EdgeRenderingFunction), which however may be taken off-line because the main problem there turned out to be a rather simple syntax error. In any case, the point is that I am trying to stretch GraphPlot beyond how it is normally used. I need 2 things: (1) different colour edges; and (2) labels on the edges, which in my case indicate the edge multiplicity for that colour. I was able to get this to work for graphs in which there is no more than a single directed edge -- in a given direction -- between two nodes. So, two labelled directed edges in _opposite_ directions between the same 2 nodes works, but two labelled directed edges in the _same_ direction between the same 2 nodes does not currently work. The approach I am using is to build 2-character labels that act as the 3rd argument of the EdgeRenderingFunction option of GraphPlot, such that the first character is the multiplicity of a given edge (and is used as an actual label) whereas the second character is used to specify the colour of the edge. (Original post starts below) I need to be able to draw multiple edges between the same nodes, and in different colours. Whereas this is easily done without labels, if I want each edge also to carry a label then I get an error. First define a graph:               test = {{1 -> 2, "11"}, {2 -> 1, "21"}, {1 -> 3, "31"}, {2 -> 3, "41"},     {2 -> 4, "12"}, {2 -> 4, "21"}, {4 -> 2, "32"}, {4 -> 1, "42"}, 3 -> 4,     3 -> 4, 3 -> 4, 3 -> 4};      I can have as many '3 -> 4' as I want and as many edges will be drawn between Nodes 3 and 4. But the two edges I am trying to draw between Nodes 2 and 4 give an error. The Mathematica documentation has an example where this works. It's in the GraphPlot documentation, under Applications/Finite State Diagrams, so I am puzzled that it does not work here. Note that if I get rid of the second 2 -> 4 rule, i.e. {2 -> 4, "21"}, then this code works fine:               GraphPlot[test,       MultiedgeStyle -> 0.15,       VertexCoordinateRules -> circleLayout[n],       SelfLoopStyle -> .2,       VertexRenderingFunction -> ({Gray, EdgeForm[Black], Disk[#, .06]} &),       EdgeRenderingFunction ->         (If[Intersection[{None}, {#3}] != {},                {RGBColor[0, 0, 0], Thickness[.008], Arrowheads[.07], Arrow[#1, 0.05]},           Switch[Characters[#3][[2]],             "1", {RGBColor[0, 0.6, 0], Thickness[.008], Arrowheads[.07], Arrow[#1, 0.05],                   Inset[Style[Characters[#3][[1]], Black, FontSize -> 16],                          Mean[#1], {0, 0}, Background -> Yellow]},             "2", {RGBColor[1, 0, 1], Thickness[.008], Arrowheads[.07], Arrow[#1, 0.05],                   Inset[Style[Characters[#3][[1]], Black, FontSize -> 16],                          Mean[#1], {0, 0}, Background -> Yellow]}                 ]             ]         &),        PlotStyle -> Thickness[.007],        PlotRange -> {{-1.1, 1.1}, {-1.1, 1.1}}      ]      The error I get is this:                Part 2 of Characters[Network`GraphPlot`wrapper["12"]] does not exist      I paste a jpeg of the output. The nodes are numbered 1-4 counterclockwise from the top. This picture is close to what it is supposed to look like. The only wrong arrow is the black horizontal arrow from Node 2 to Node 4. In place of that there should be two arrows, one green and the other magenta, in the same direction from 2 to 4 and with different labels. ![Labelled_Multiedged_Graph_Error](http://i.stack.imgur.com/QGQHY.jpg) I have shortened the InputForm for the graphical output of the above command (I deleted the intermediate coordinates of all the Arrows) so I could paste it below. I also added blank lines between the instructions for different arrows to make the output easier to interpret.               Graphics[Annotation[{{Thickness[0.007], {RGBColor[0, 0.6, 0],       Thickness[0.008], Arrowheads[0.07], Arrow[{{0., 1.},        {-0.06647942640193483, 0.8537452619157436},         ...       {-0.8537452619157443, 0.0664794264019346}, {-1., 0.}}, 0.05],       Inset[Style["1", GrayLevel[0], FontSize -> 16],        {-0.44451835279238505, 0.4445183527923848}, {0, 0},        Background -> RGBColor[1, 1, 0]]},          {RGBColor[0, 0.6, 0],       Thickness[0.008], Arrowheads[0.07], Arrow[{{0., 1.}, {0.,        -1.}}, 0.05], Inset[Style["3", GrayLevel[0],         FontSize -> 16], {0., 0.}, {0, 0}, Background ->         RGBColor[1, 1, 0]]},          {RGBColor[0, 0.6, 0],       Thickness[0.008], Arrowheads[0.07], Arrow[{{-1., 0.},        {-0.9335205735980654, 0.14625473808425649},         ...       {-0.14625473808425588, 0.9335205735980656}, {0., 1.}}, 0.05],       Inset[Style["2", GrayLevel[0], FontSize -> 16],        {-0.5554816472076151, 0.5554816472076154}, {0, 0},        Background -> RGBColor[1, 1, 0]]},          {RGBColor[0, 0.6, 0],       Thickness[0.008], Arrowheads[0.07], Arrow[{{-1., 0.}, {0.,        -1.}}, 0.05], Inset[Style["4", GrayLevel[0],         FontSize -> 16], {-0.5, -0.5}, {0, 0},        Background -> RGBColor[1, 1, 0]]},          Switch[Characters[Network`GraphPlot`wrapper["12"]][[2]],       "1", {RGBColor[0, 0.6, 0], Thickness[0.008],        Arrowheads[0.07], Arrow[{{-1., 0.}, {-0.7872658355138089,         0.07977531168232177},         ...              {0.7872658355138097, 0.07977531168232133}, {1., 0.}}, 0.05],        Inset[Style[Characters[Network`GraphPlot`wrapper["12"]][[          1]], Black, FontSize -> 16], Mean[{{-1., 0.},          {-0.7872658355138089, 0.07977531168232177},           ...         {0.7872658355138097, 0.07977531168232133}, {1., 0.}}],         {0, 0}, Background -> Yellow]},      "2", {RGBColor[1, 0, 1], Thickness[0.008], Arrowheads[0.07],        Arrow[{{-1., 0.}, {-0.7872658355138089,         0.07977531168232177},         ...        {0.7872658355138097, 0.07977531168232133}, {1., 0.}}, 0.05],        Inset[Style[Characters[Network`GraphPlot`wrapper["12"]][[          1]], Black, FontSize -> 16], Mean[{{-1., 0.},          {-0.7872658355138089, 0.07977531168232177},           ...         {0.7872658355138097, 0.07977531168232133}, {1., 0.}}],         {0, 0}, Background -> Yellow]}],          {RGBColor[0, 0, 0],       Thickness[0.008], Arrowheads[0.07], Arrow[{{-1., 0.}, {1.,        0.}}, 0.05]},          {RGBColor[0, 0, 0], Thickness[0.008],       Arrowheads[0.07], Arrow[{{0., -1.}, {0.06647942640193483,        -0.8537452619157436},        ...       {0.8537452619157443, -0.0664794264019346}, {1., 0.}},        0.05]},          {RGBColor[0, 0, 0], Thickness[0.008],       Arrowheads[0.07], Arrow[{{0., -1.}, {0.08817568578755441,        -0.886631261130288},        ...        {0.8866312611302873, -0.08817568578755464}, {1., 0.}}, 0.05]},           {RGBColor[0, 0, 0], Thickness[0.008], Arrowheads[0.07],       Arrow[{{0., -1.}, {0.11336873886971244,        -0.9118243142124458},        ...        {0.9118243142124456, -0.1133687388697131}, {1., 0.}}, 0.05]},           {RGBColor[0, 0, 0], Thickness[0.008], Arrowheads[0.07],       Arrow[{{0., -1.}, {0.14625473808425649,        -0.9335205735980654},        ...       {0.9335205735980656, -0.14625473808425588}, {1., 0.}},        0.05]},          {RGBColor[1, 0, 1], Thickness[0.008],       Arrowheads[0.07], Arrow[{{1., 0.}, {0.7872658355138089,        -0.07977531168232177},       ...        {-0.7872658355138097, -0.07977531168232133}, {-1., 0.}}, 0.05],       Inset[Style["3", GrayLevel[0], FontSize -> 16],        {-3.392348130799089*^-16, -0.11096329441523041}, {0, 0},        Background -> RGBColor[1, 1, 0]]},          {RGBColor[1, 0, 1],       Thickness[0.008], Arrowheads[0.07], Arrow[{{1., 0.}, {0.,        1.}}, 0.05], Inset[Style["4", GrayLevel[0],         FontSize -> 16], {0.5, 0.5}, {0, 0},        Background -> RGBColor[1, 1, 0]]}},           {Thickness[0.007], {GrayLevel[0.5], EdgeForm[GrayLevel[0]],       Disk[{0., 1.}, 0.06]}, {GrayLevel[0.5],       EdgeForm[GrayLevel[0]], Disk[{-1., 0.}, 0.06]},       {GrayLevel[0.5], EdgeForm[GrayLevel[0]],       Disk[{0., -1.}, 0.06]}, {GrayLevel[0.5],       EdgeForm[GrayLevel[0]], Disk[{1., 0.}, 0.06]}}},       VertexCoordinateRules -> {{0., 1.}, {-1., 0.}, {0., -1.}, {1.,       0.}}], FrameTicks -> None, PlotRange ->       {{-1.1, 1.1}, {-1.1, 1.1}}, PlotRangePadding -> Scaled[0.1],       AspectRatio -> Automatic]      It looks like the presence of two {2 -> 4, "some label"} edges throws off the code above. The error refers to the first one of these, the second one does not appear at all in the InputForm output. In place of the arrow-related objects you can see the Switch structure. I tried making the labels identical (as they are in the Mathematica documentation) and it did not make any difference. Any suggestions? Thanks in advance. **EDIT 2** (after a few days): I have made a small step forward but am still far from the actual solution. Consider this code:               Clear[test];     test = {{1 -> 2, "11"}, {2 -> 1, "21"}, {1 -> 3, "31"}, {2 -> 3, "41"}, {2 -> 4,"12"},            {2 -> 4, "21"}, {4 -> 2, "32"}, {4 -> 1, "42"}, 3 -> 4, 3 -> 4, 3 -> 4, 3->4};          GraphPlot[test,     MultiedgeStyle -> All,     VertexCoordinateRules -> circleLayout[n],     SelfLoopStyle -> .2,     VertexRenderingFunction -> ({Gray, EdgeForm[Black], Disk[#, .06]} &),     EdgeRenderingFunction ->     (     If[Intersection[{None}, {Print[#3]; #3}] != {},             {RGBColor[0, 0, 0], Thickness[.008], Arrowheads[.07], Arrow[#1, 0.05]},             Switch[Characters[If[Depth[#3] > 1, #3[[1]], #3]][[2]],              "1", {RGBColor[0, 0.6, 0], Thickness[.008], Arrowheads[.07], Arrow[#1, 0.05],                 Inset[Style[Characters[If[Depth[#3] > 1, #3[[1]], #3]][[1]],                 Black, FontSize -> 16], Mean[#1], {0, 0}, Background -> Yellow]},              "2", {RGBColor[1, 0, 1], Thickness[.008], Arrowheads[.07], Arrow[#1, 0.05],                 Inset[Style[Characters[If[Depth[#3] > 1, #3[[1]], #3]][[1]],                 Black, FontSize -> 16], Mean[#1], {0, 0}, Background -> Yellow]}                   ]            ]         &),     PlotStyle -> Thickness[.007],     PlotRange -> {{-1.1, 1.1}, {-1.1, 1.1}}     ]      By using Depth[] I was able to extract the label "12" from inside the "Network`Graphplot`wrapper[12]" thing (not sure what to call it). This is great but what worries me is that the label "21" corresponding to the second directed arrow 2 -> 4 has, as before, completely disappeared. The graph looks like this now: ![Labelled_Multiedged_Graph_Error_2](http://i.stack.imgur.com/eNUtp.jpg) The black arrow from 2 to 4 came out black because the label "21" disappeared. I found this rather arcane post http://stackoverflow.com/questions/4091728/tips-for-creating-graph-diagrams that talks about something vaguely related, i.e. "Network`GraphPlotDump`RuleListGraphQ[x_]", but I don't know enough under-the- hood Mathematica to make much sense of it... **Edit 3** : I spent a couple more days on this and could not find a workaround. Although using this as one of the edges almost works: {2 -> 4, {"12","21"}}. I can access the label I want with #3[1] or #3[2]. The problem of course that this is the spec for just one edge and not two as I need. So I don't think this can be a solution unless somebody knows of a way to force a second 2 -> 4 edge. I would like to document that this is indeed a bug, apparently with V9. I paste here the GraphPlot command from one of the examples in the GraphPlot documentation (Examples/Applications/Finite State Diagrams):               GraphPlot[{"start" -> "empty", {"empty" -> "empty", "other"}, {"empty" -> "n", "n"},       {"n" -> "n", "n"}, {"n" -> "empty", "other"}, {"n" -> "na", "a"},      {"na" -> "nan", "n"}, {"na" -> "empty", "other"}, {"nan" -> "na", "a"},      {"nan" -> "na", "a"}, {"nan" -> "nano", "o"}, {"nan" -> "empty", "other"},      {"nano" -> "nano", "any"}}, VertexLabeling -> True, DirectedEdges -> True,       MultiedgeStyle -> 0.3]      The graph that comes out of this has the same "Network`GraphPlot`wrapper[a]" string as the label of one of the "nan"->"na" edges, and none on the second "nan"->"na" edge. That's **different** from what the documentation shows, which is two "a" labels on two separate directed edges between the same two nodes, as we would expect. How can we inform Wolfram? Any hope they will fix it once they know?? Thanks.


Transforming noisy multivariate data

I’ve been racking my brain all afternoon on trying to solve this… I have a set of **noisy** co-ordinate data               data = {{x1,y1,z1}…..{xn,yn,zn}}      that forms an ellipsoid . I’d like to transform the co-ordinate data into a **unit sphere**. As an illustration, my original data is in blue, and I’d like to transform it to the red data. ![transform from blue to red:](http://i.stack.imgur.com/P6MoJ.png) What is the best way to find the transformation coefficients               affine = {{sxx,sxy,sxz}, {syx, syy,syz}, {szx,szy,szz}}      offset = Table[{ox,oy,oz}, {i,1,Length[data]}]        such that:               transform = affine.data + offset       subject to the constraint that               x^2+y^2+z^2 = 1      I assume this requires some kind of least square fit. I can’t figure out how I can get *fit * or _NMinimize_ to make this work. Maybe I am using the wrong functions…. Ideas greatly appreciated…. Thanks, P


How can I solve a set of non-linear equations?

I was wondering whether someone can give me an idea on how I can solve a set of non-linear equations with an unknown exponent This is what I have:   * Known values: N, R   * Unknown values: λ, α, J   * Equations              J = N1 + a*R1^λ       J = N2 + a*R2^λ     J = N3 + a*R3^λ      The α, J, λ should be approximately the same in every equation Additional info The only thing I know according to the author of the paper is that "... by solving the three unknowns J, a, λ with a least-square solution scheme" I know about least-squares, but not how to apply it when the exponent is unknown along with sum of `N`.


Can the CholeskyDecomposition function in Mathematica be made to work on non-symmetric matrices?

The `CholeskyDecomposition[m]` function in _Mathematica_ requires a symmetric and positive definite matrix `m`. For instance, the following works:               In[1]:= m = {{1, 0.5, 0.5}, {0.5, 1, 0.5}, {0.5, 0.5, 1}};          In[2]:= CholeskyDecomposition[m]          Out[2]= {{1., 0.5, 0.5}, {0., 0.866025, 0.288675}, {0., 0., 0.816497}}      However, consider another matrix `m1`               In[3]:= m1 = m; m1[[3, 2]] = 0.5000000000001          Out[3]= 0.5          In[4]:= m1          Out[4]= {{1, 0.5, 0.5}, {0.5, 1, 0.5}, {0.5, 0.5, 1}}      The Cholesky decomposition does not work here:               In[5]:= CholeskyDecomposition[m1]          During evaluation of In[5]:= CholeskyDecomposition::herm: The matrix {{1.,0.5,0.5},{0.5,1.,0.5},{0.5,0.5,1.}} is not Hermitian or real and symmetric. >>          Out[5]= CholeskyDecomposition[{{1, 0.5, 0.5}, {0.5, 1, 0.5}, {0.5,         0.5, 1}}]      Most other matrix based systems use either the lower triangular or upper triangular portion of a matrix when computing the Cholesky decomposition. For example, Eigen, LAPACK and R all do this. MATLAB offers many different versions of its `chol` function and it is possible to use either the upper or lower triangular portion. _Mathematica_ does not offer this functionality. For example, in R we can have               > m3<-matrix(c(1.0, 0.5, 0.5, 0.5, 1.0, 0.5000000000001, 0.5, 0.5, 1.0), 3,3)     > chol(m3)          [,1]      [,2]      [,3]     [1,]    1 0.5000000 0.5000000     [2,]    0 0.8660254 0.2886751     [3,]    0 0.0000000 0.8164966     >       Why is this important? I find that checking for symmetry can be problematic in numerical computations where because of roundoff errors etc, slight asymmetries appear in matrices in iterative computations such as MCMC simulations. In such cases, the checking for symmetry results in the computation getting aborted midway. Is there any way in which one can modify the built in `CholeskyDecomposition` function so that it does not check for symmetry, but aborts if the matrix is not positive definite? Such a modification would still retail all the speed benefits of the underlying LAPACK or MKL functions that _Mathematica_ could be using but will not enforce symmetry.


NDSolve: Couple ODE and PDE

I am trying to numerically solve an equation with NDSolve, where there is a ODE coupled to a PDE, like the following:                   NDSolve[{       Derivative[1, 0][u][t,x] ==         -0.8*u[t, x] - (5.*n[t]*Derivative[0, 1][u][t, x])/(5. + n[t]) + (50.*n[t]^2*Derivative[0, 2][u][t, x])/(5. + n[t])^2,        Derivative[1][n][t] ==         100. - 0.8*n[t] - (0.5*Integrate[u[t, x], {x, 0, 2*Pi}]*n[t])/(5. + n[t]),        u[0, x] == 200.,       n[0] == 50.,       u[t, 0] == u[t, 2*Pi]},      {u, n},      {t, 0., 2.},      {x, 0., 6.28}]      Unfortunately Mathematica tells me `"NDSolve::ndode: Input is not an ordinary differential equation"`. When i change `n[t]` to `n[t,x]` it calculates something, but `n[t,x]` doesn't stay uniform over time, which it should because `n` wasn't a function of `x` in the first place. Would anyone know a way around this?


Create magnified call-out loupe effect on image

I'm trying to create a Mathematica `Manipulate` that generates a graphical call-out using a 'loupe'-style or magnifying glass enlarger - a possible solution is shown in this mock-up: ![loupe](http://i.stack.imgur.com/3UTau.png) The idea is that you can move the focus (a point on the source image, I suppose), and see the enlarged result inside the 'loupe' or magnifying glass. Variable enlargement would be needed as well. It could be a rectangular loupe, I suppose, but circles would be cool. This style of image is generally recommended because it allows people to see details and the context of those details. This is what I've managed to do so far:               m = ImageResize[ExampleData[{"TestImage", "Mandrill"}], 300];     imageData = ImageData[m, DataReversed -> True];     Manipulate[      Grid[       {{         Graphics[{           Raster[imageData, {{0, 0}, ImageDimensions[m]}], Point[pt]},           ImageSize -> ImageDimensions[m]],         Graphics[{Raster[imageData, {{0, 0}, ImageDimensions[m]}],            Disk[pt, 5]}, ImageSize -> ImageDimensions[m]]         }}],      {{pt, {200, 200}}, Locator}]      ![loupe first attempt](http://i.stack.imgur.com/m6eAS.png) The dot in the right image follows the left image. I can't see how to make the circular shape or to make it track the point or to add a magnifying option. Help or clues appreciated! ## Edit I thought all these answers were great and it's a pity I can't accept them all... :( I noticed that with some of the solutions (@szabolcs, @simon) the image seems to be transformed and looks better/smoother than it really is, whereas the other solutions show the pixels themselves. Both approaches are useful in their own way, depending on whether you're trying to point out the pixel structure or the image content.


FrontEndTokens, MathLink, and Serializer.exe

I have been using some basic MathLink programming in my work and wanted to create some more sophisticated MathLink programs. I came across the book "MathLink: Network Programming with Mathematica", which was written around the era of Mathematica version 4, which has some neat interactive gui examples using mathlink, based around a piece of mathlink code created by the author of that book called Serializer.exe. Its essentially a mathlink template program designed to sit in between the kernel and the front end as they communicate so you can modify how that communication works. I can _almost_ run it on my machine, using Mathematica 8, up to one little sticking point that maybe someone can help me with. To give you an idea of whats going on: The starting point is a mathlink template program (compiled using c, as such things are) called Serializer.exe. This program is added as a custom evaluator in mathematica via the "Kernel Configuration Options", and the code is run with that kernel (i.e. it runs through serializer.exe before being sent to the actual kernel.) Then this program spawns a raw mathlink program which is added to the list of evaluators (Options[$FrontEnd,EvaluatorNames]) and tries to set up a mathlink connection between it and the front end. After going through the code step by step, the place where its stuck is a pair of lines of code that look like:               FrontEndExecute[EvaluatorStart[nameofrawMathLinkEvaluator]];     MessageLinkActivate[];      Now MessageLinkActivate[] is a custom function defined in the c code, but it seems that it should be similar to LinkActivate[], the usual math link activation function. Users of mathlink will know that once LinkActivate is called on a kernel, it blocks evaluation until the other end of the program activates as well. The program hangs if the activate is never answered. However, EvaluatorStart is not defined anywhere, and it throws an error message that is does not recognize the packet "EvaluatorStart", and then waits forever for a return linkactivation that never happens. I'll give exact instructions for recreating the error in the comments below, but I should say that the exact same error comes up if EvaluatorStart is changed to a random string of letters- so I'm sure the program really has no definition for EvaluatorStart. I am trying to deduce the right line of code to put here - after some googling, it seems that there is a FrontEnd Token called EvaluatorStart, which would be called something like this:               FrontEndExecute[FrontEndToken[nb,"EvaluatorStart",nameofrawMathLinkEvaluator];     MessageLinkActivate[];      where nb is an argument that must refer to some notebook, which I'm not sure what to put (I tried EvaluationNotebook[] with no luck). Any help would be appreciated on the following questions:   * In Mathematica 4, what did FrontEndExecute[EvaluatorStart[name]] do?    * How could I recreate that functionality in Mathematica 8 or 9?   * Does anyone use serializer.exe with a modern version of mathematica?   * Has anyone else created advanced interactive mathlink programs, like the interactive graphics system featured in "MathLink: Network Programming with Mathematica", with publically available code? Edit: To recreate this would require adding serializer.exe to your mathematica $LaunchDirectory, and then running some very short code in Mathematica. I can provide this file and code if anyone actually wants to help try to solve this.