title: Identify which cell uses most memory in front-end

text: Even though the mathematica front-end is much more robust than it used to be, everyone must have noticed that when a few 3D graphics are involved, the front-end produces very large notebooks which are more difficult to manage. I am aware of the option to rasterise 3D plots using Image                Plot3D[Sin[1/x 1/y],{x,0,1},{y,0,1},PlotPoints -> 200]//Image[#,ImageResolution-> 300]&      which produces a file of 1.2 MB versus one of 11 MB (without the Image). I am looking for a method to identify within a given notebook which graphics outputs use most memory on the front-end (and potentially disc space when the notebook is saved), in order to rasterize these outputs. Ideally I would rather not rasterize all plots as the interactivity is useful. Note that this question differs from my previous question about identifying which outputs use most kernel memory when stored in Out[] variables. **Question**   1. How to identify which cells use most memory on the front-end in a given notebook?   2. Possibly automate the process of rasterising those cells? May be there is a front end setup to tell it to not produce interactive plots?


title: Exporting a dashed plot with a color gradient to a vector graphics format ruins the dashing

text: When exporting a dashed plot with a color gradient to a vector graphics format such as EPS or PDF, the dashing is partly ruined. For example, this command:               Plot[x^2, {x, -2, 2}, PlotStyle -> Directive[Dashed, Thick], ColorFunction -> Hue]      Creates the following plot: ![A dashed plot with a color gradient exported to png](http://i.stack.imgur.com/c1NnJm.png) However, when exporting the plot to EPS or PDF, I get this plot (notice the ruined dashing, especially near the vertex of the parabola): ![A dashed plot with a color gradient exported to eps](http://i.stack.imgur.com/Zxy9Dm.png)   * **~~Am I doing something wrong, or is this a bug?~~**   * **~~If~~ it is a bug, is there a workaround?** I am using Mathematica version 8.0.4.0 ( _edit:_ on Win7 64bit) **Edit:** I got an email from wolfram support, which I understand confirms this is a bug. Until they fix it, any workarounds which properly export the plot as _vector graphics_ are welcome.


title: How do I make NotebookEvaluate work inside Button?

text: The following creates a button to select a notebook to run. When the button is pressed it seems that Mathematica finds the notebook but cannot evaluate it. The following error occurs > Could not process unknown packet "1"               Button["run file 1",           NotebookEvaluate[           "/../file1.nb"]]      This occurs under Mathematica 8 on all platforms. Any help greatly appreciated, Christina


title: Plotting with NDSolve`StateData`

text: This question is a continuation of this. As answered by J.M., I am able to iterate a solution. However, I am unable to plot it. I am sure that this has to do with my inability to understand how the plot routine works and I can't seem to figure it out:               state = First[       NDSolve`ProcessEquations[{D[u[t, x], t] == D[u[t, x], x, x],          u[0, x] == 0, u[t, 0] == Sin[t], u[t, 5] == 0}, u, t, {x, 0, 5}]]          NDSolve`Iterate[state, 5]     NDSolve`ProcessSolutions[state, "Forward"]          Plot3D[      Evaluate[u[t, x] /. NDSolve`ProcessSolutions[state, "Forward"]],      {t,0,2},      {x, 0, 5}      ]      gives me a blank plot with no curves. What am I doing wrong? I can't omit `{t, 0, 2}` as that would give me an error.


title: How do I compute sidereal time and JD?

text: There was once a package that provided a wide range of functions for computing astronomical information. This package now appears to be out of date; but as near as I can tell, many of the useful functions it provided have not been replicated in `AstronomicalData`. Are there, for example, functions I can use to compute sidereal time, or Julian Date (JD)?


title: Efficient way to perform elementary integration step with NDSolve internal method

text: I'm trying to tweak the `NDSolve` function to perform one elementary integration step (using some explicitly selected stepping algorithm via `Method` option). Such a possibility is crucial for me, since after each performed step I'd like to check for some condition and modify state vector, then continue the integration. To the best of my knowledge such an operation is not possible with the 'pure' `NDSolve`, therefore I'm looking for an alternative solution. So far, I managed to come up with the following solution (please note that the order of a method is selected to mimic the case with a lot of internal steps, this is equivalent to the higher order and longer integration period - `tmax`):               eq = {{x''[t] == -x[t], x[0] == 0, x'[0] == 1}, x, t};     tmax = 1;     method = {"ExplicitRungeKutta", "DifferenceOrder" -> 2};          Block[{state, options, timer},       options = {MaxSteps -> Infinity, Method -> method};       state = First@NDSolve`ProcessEquations[Sequence @@ eq, options];       timer = First@Timing[NDSolve`Iterate[state, tmax]];       {timer, state@"CurrentTime"["Forward"], state@"TimeStepsUsed"["Forward"], state@"SolutionVector"["Forward"]}     ]          (* ==> {0.048003, 1., 7032, {0.841471, 0.540302}} *)               Block[{state, options, ctime, ic, dt, count, timer},       options = {MaxSteps -> 1, Method -> method};       state = First@NDSolve`ProcessEquations[Sequence @@ eq, options];       count = 0;       ctime = state@"CurrentTime"["Forward"];       timer = First@Timing@While[ctime < tmax,           Quiet[NDSolve`Iterate[state, tmax*1.000001], NDSolve::mxst];           ctime = state@"CurrentTime"["Forward"];           ic = state@"SolutionVector"["Forward"];           dt = state@"TimeStep"["Forward"];           state = First@NDSolve`Reinitialize[state, {x[ctime] == ic[[1]], x'[ctime] == ic[[2]]}, StartingStepSize -> dt];           count++;          ];       {timer, state@"CurrentTime"["Forward"], count, state@"SolutionVector"["Forward"]}     ]          (* ==> {3.1722, 1., 2948, {0.841471, 0.540302}} *)`      Timing results are not optimistic. The situation is worse when one want use step size from the previous step (with `StartingStepSize -> dt` commented in Reinitialize). Is there a better (more efficient) way to to this?


title: How to plot a consecutive set of data?

text: I want to plot a series of data point:               q1 = {{0.0001, 0.762371}, {0.000621053, 0.768171}, {0.00114211,       0.773225}, {0.00166316, 0.777677}, {0.00218421,       0.781639}, {0.00270526, 0.785196}, {0.00322632,       0.788416}, {0.00374737, 0.791351}, {0.00426842,       0.794044}, {0.00478947, 0.79653}, {0.00531053,       0.798837}, {0.00583158, 0.800987}, {0.00635263, 0.803}, {0.00687368,      0.804891}, {0.00739474, 0.806675}, {0.00791579,       0.808362}, {0.00843684, 0.809962}, {0.00895789,       0.811485}, {0.00947895, 0.812936}, {0.01, 0.814322}}      q1 = ![enter image description here](http://i.stack.imgur.com/DuudC.jpg)               q2 = {{0.01, 0.814322}, {0.02, 0.833238}, {0.03, 0.844964}, {0.04,      0.853516}, {0.05, 0.860265}, {0.06, 0.865849}, {0.07,      0.870619}, {0.08, 0.874787}, {0.09, 0.87849}, {0.1,      0.881824}, {0.11, 0.884857}, {0.12, 0.887639}, {0.13,      0.890209}, {0.14, 0.892597}, {0.15, 0.894828}, {0.16,      0.896919}, {0.17, 0.898886}, {0.18, 0.900745}, {0.19,      0.902505}, {0.2, 0.904175}, {0.21, 0.905764}, {0.22,      0.907279}, {0.23, 0.908727}, {0.24, 0.910112}, {0.25,      0.91144}, {0.26, 0.912714}, {0.27, 0.913939}, {0.28,      0.915117}, {0.29, 0.916252}, {0.3, 0.917347}, {0.31,      0.918403}, {0.32, 0.919424}, {0.33, 0.920411}, {0.34,      0.921367}, {0.35, 0.922292}, {0.36, 0.923189}, {0.37,      0.924059}, {0.38, 0.924903}, {0.39, 0.925723}, {0.4,      0.92652}, {0.41, 0.927295}, {0.42, 0.928049}, {0.43,      0.928783}, {0.44, 0.929498}, {0.45, 0.930194}, {0.46,      0.930873}, {0.47, 0.931534}, {0.48, 0.93218}, {0.49,      0.932811}, {0.5, 0.933426}, {0.51, 0.934027}, {0.52,      0.934615}, {0.53, 0.935188}, {0.54, 0.93575}, {0.55, 0.9363}, {0.56,     0.936837}, {0.57, 0.937363}, {0.58, 0.937878}, {0.59,      0.938382}, {0.6, 0.938876}, {0.61, 0.93936}, {0.62,      0.939835}, {0.63, 0.9403}, {0.64, 0.940756}, {0.65,      0.941204}, {0.66, 0.941642}, {0.67, 0.942073}, {0.68,      0.942496}, {0.69, 0.94291}, {0.7, 0.943318}, {0.71,      0.943719}, {0.72, 0.944112}, {0.73, 0.944498}, {0.74,      0.944878}, {0.75, 0.945251}, {0.76, 0.945618}, {0.77,      0.945978}, {0.78, 0.946334}, {0.79, 0.946682}, {0.8,      0.947023}, {0.81, 0.947363}, {0.82, 0.947695}, {0.83,      0.948023}, {0.84, 0.948345}, {0.85, 0.948662}, {0.86,      0.948974}, {0.87, 0.949282}, {0.88, 0.949584}, {0.89,      0.949882}, {0.9, 0.950177}, {0.91, 0.950466}, {0.92,      0.950751}, {0.93, 0.951032}, {0.94, 0.95131}, {0.95,      0.951583}, {0.96, 0.951853}, {0.97, 0.952118}, {0.98,      0.95238}, {0.99, 0.952639}, {1., 0.952894}}      q2 = ![enter image description here](http://i.stack.imgur.com/titvq.jpg) When I tried to combine them the result was:               p1 = ListPlot[q1, PlotStyle -> Red];     p2 = ListPlot[q2, PlotStyle -> Blue];     Show[{p2, p1}]      ![enter image description here](http://i.stack.imgur.com/ryZ0l.jpg) As you can see the red part which is q1 is not noticeable. I also tried:               q3 = Join[q1, q2, 1];     ListPlot[q3]      ![enter image description here](http://i.stack.imgur.com/QLHYl.jpg) I want the graphs q1 and q2 as you can see above alongside each other as if they are one graph. q2 is the continuation of q1.


title: Series and that old ivar error

text: I am trying to compare plots of the function (1+x)^{1/3} and its power series. The code for the power series generates an error message referring to an invalid variable: 'General::ivar: -1.09993 is not a valid variable."' This message occurred with a minimum x of -1.1. Whatever value is given to the minimum x, the error message is always .00007 or .00008 greater. Yet it continues and plots the curve to maximum x. I would like to know the reason for the error message. A previous similar question by @fasttouch "Plot Series output?" was closed as off-topic. The apparent correct answers were to apply Normal[], which I have done, and Evaluate[], which here seems to have no effect, as the curves with and without it coincide. If there is a trivial syntax error, it would not surprise me, but I can't see it, nor does the answer appear to be easily found in the documentation. I have Mathematica 8. I am also wondering why I need to reference the series with an index in Plot, but not in Print.               x0 = 0; n = 30;          Print["Series up to 5th power: ",        Normal[Series[Power[1 + x, 1/3], {x, x0,  5}]]];          Plot[{       Evaluate[Normal[Series[Power[1 + x, 1/3], {x, x0,  n}][[1]]]],       Normal[Series[Power[1 + x, 1/3] + .01, {x, x0,  n}][[1]]]       }, {x, -1.1, 2.5}, Background -> White]      After submitting this, I find that all works well if I write it this way:               s[x_] := Normal[Series[Power[1 + x, 1/3], {x, x0,  n}]];          Plot[Evaluate@s[x], {x, -1, 1}]      My current guess is that there was some confusion of the x's in Series[] and Plot[].


title: Union::normal: Nonatomic expression expected when using Uncompress

text: I saved a expresion to a file like this               Export["file.dat",Compress@myExpression];      Then (i don't know why) when I import the file i get the compressed expresion embedded in a nested list like this:               test = Import["file.dat"] (* test -> {{ compressedString }} *)      So I use this to Uncompress the expresion:               myExp = Uncompress@First@Flatten@Import["file.dat"];      And I get my expresion back correctly, but i get these msg               Union::normal: Nonatomic expression expected at position 2 in <<1>>. >>     Union::normal: Nonatomic expression expected at position 2 in <<1>>. >>      Should I worry about those msg? Why am I getting those? You can check for yourselves: https://dl.dropboxusercontent.com/u/35192406/bad.dat


title: Transfer ColorFunction from ListContourPlot to ListLIC-Plot

text: I would like to transfer the colors of a ListContourPlot to a ListLIC-Plot. I tried to interpolate the data of the ListContourPlot and use it as ColorFunction for the second plot but I couldn't get it to work properly, is there a better way to do this?               data1 = Table[Sin[i + j^2], {i, 0, 3, 0.1}, {j, 0, 3, 0.1}];     data2 = Table[{Sin[i + j^2], Cos[i + j^2]}, {i, 0, 3, 0.1}, {j, 0, 3, 0.1}];     f = ListInterpolation[data1];     ListContourPlot[data1, ColorFunction -> "DarkRainbow"]     ListLineIntegralConvolutionPlot[data2, ColorFunction -> Function[{x, y, vx, vy, n},     ColorData["DarkRainbow"][f[x, y]]], RasterSize -> 100]      I get the following error:               InterpolatingFunction::dmval: Input value {0.,0.} lies outside the range of     data in the interpolating function. Extrapolation will be used. >>      ...      The result should look remotely like the following ![plot](http://i.imgur.com/Y3cO1Zc.jpg)


title: Assign values to variable names in lists

text: I hope somebody can help me in this (I guess) simple question: I have a list of variable names `ls={w0,w1,w2}` and another list of values `v={0.1,0.2,0.3}` What I'd like to do is to get the names of the variables from ls and assign to these variables the values in v, that is, to end up with variables w0,w1 and w2 that have the values `0.1`, `0.2` and `0.3`. I've tried things like `ToExpression[ls[[1]]] =ToExpression[v[[1]]]` but I keep getting messages of the form `Set::write: Tag ToExpression in ToExpression[\\[Omega]0] is Protected.` >> Can anybody tell me of a simple way to achieve what I'm looking for? Thanks...


title: strange timing behavior

text: The following code is from a book about Mathematica.               colMean[col_, str_String] := col /. str :> Mean[Cases[col, _?NumberQ]]          ReplaceString[matrix_, str_String] :=       Transpose[Map[colMean[#, str] &, Transpose[matrix]]]      Giving a matrix with numeric and string entries in a column it replaces the string entries by the mean average of the remaing numeric elements of the column. Here is a test of its efficiency.               With[{size = 1000}, mat = RandomReal[1, {size, size}];        rmat = ReplacePart[mat,          RandomInteger[{1, size}, {size, 2}] :> "non"]];     Timing[ReplaceString[rmat, "non"];]          {3.296875, Null}      Here is the respective time performance that appears in the book: **0.877081** So far everything sounds normal. The author may have a faster computer than mine. However, in order to check the efficiency of its code, the author compares it with the performance of some of the highly optimized built-in linear algebra functions.               mat = RandomReal[1, {1000, 1000}];     {Timing[Inverse[mat];], Timing[Det[mat];]}      The times are about, respectively, 0.4 and 0.14 sec. The strange thing, at least to me, is that my machine has the same time performance. In particular:                mat = RandomReal[1, {1000, 1000}];     {Timing[Inverse[mat];], Timing[Det[mat];]}           {{0.453125, Null}, {0.093750, Null}}      So, here comes my first question: How is it possible to be such a big difference in the performance of the user- defined code and almost identical timings in the performances of relevant built-in functions? What issues affect the performance of such codes? My second query now. In order to increase the efficiency of `ReplaceString` I tried to use parallel computing.               Clear[ReplaceString]     LaunchKernels[]     ReplaceString[matrix_, str_String] :=           Transpose[ParallelMap[colMean[#, str] &, Transpose[matrix]]]      Nevertheless, I did not get any change in the perfomance of the function `ReplaceString`.               In[6]:= $ProcessorCount     Out[6]= 4      The machine on which this computation was performed has two processors on which Mathematica can run kernels. (Actually, my machine has two physical processors and two virtual ones and so $ProcessorCount returns 4.) Why there is not an increase in the efficiency of the function? What am I missing here?


title: Insert all elements from one matrix into another

text: I have two matrices $A$ and $B$ which are the same size. Each element of $A$ is a list of numbers. Each element of $B$ is just a number. How do I insert each element of $B$ into the corresponding list of $A$? For example say I have:               A = {{{1,2},{3,4}},{{5,6},{7,8}},{{9,10},{11,12}}}      > $ = \begin{pmatrix} (1,2) & (3,4)\\ (5,6) & (7,8) \\ (9,10) & (11,12) > \end{pmatrix}$ and               B = {{0,0},{1,1},{2,2}}      > $=\begin{pmatrix} 0 & 0\\1&1\\2&2 \end{pmatrix}$ How do I form:               {{{1,2,0},{3,4,0}},{{5,6,1},{7,8,1}},{{9,10,2},{11,12,2}}}      > $ = \begin{pmatrix} (1,2,0) & (3,4,0)\\ (5,6,1) & (7,8,1) \\ (9,10,2) & > (11,12,2) \end{pmatrix}$ Thanks very much for any help


title: Manipulate AnimationRunning equivalent?

text: I have a `Manipulate` function with two variables. I would like one of them to begin autorunning immediately once the function is evaluated, but the other to remain static until moved. Does `Manipulate` have an equivalent to `Animate`'s `AnimationRunning->True`, which would enable me to allow one of the variables to start being animated without having to convert the entire function into an `Animate`, which would affect the way the panel is displayed, as well as making both variables begin playing at once?


title: Symmetric list with maximum in center

text: How to sort a list, e.g.               RandomInteger[{0, 100}, 50]      that the Maximum is in the center and all other elements are placed symetrically in descending order around the center?


title: String formatting

text: I have the following string:               "174,861.00 (      4,053.52)     206,850.48   118.29 (     31,989.48)"      Parentheses stand for negative numbers. I will like to get it converted/formatted to the following:               "174861.00,(4053.52),206850.48,118.29,(31989.48)"      Just having a problem collapsing the spaces between the `(` and the next valid digit.


title: Print all cells independently at once

text: Is there any way to print out to pdf file, in sequence, all cells independently? I have literally hundreds of cells that need to be printed in that way. Selecting each cell and "Print Selections" takes me ages before I finish.


title: Why is this code slow and how could I speed it up?

text: My goal is given an integer number to deduce if its digits increase (or remain the same) from left to right or not. Example: $1236, 123336$ are both considered numbers with increasing digits, but $1203$ is not. This is the code that I came up with during my first attempt:               incQ[n_] :=          And @@ (#[[1]] - #[[2]] <= 0 &) /@ Partition[IntegerDigits@n, 2, 1];      I'd like to know:   1. Whether an experienced user could, by looking at this construct, detect the bottleneck.   2. Whether it can be rewritten to speed things up, without completely altering its logic though.   3. If there's a way, besides Workbench, to measure how much time the parts of a compound expression consume (e.g., is the partitioning, the difference'ing or the AND'ing the offender here ?) **EDIT 1** : By slow, I mean that it takes ~2.6secs to check the first $10^5$ integers in Mac OSX 10.9.1, Mathematica 9.0.1, i5 @ 1.7 GHz. **EDIT 2** : As expected, I got lots of great answers (basically for Q2). Before accepting one, what would be the moral of this story? Perhaps, that built-in functions are more likely to be faster than their custom-made equivalent versions?


title: Given a list of context names, how can I access all the variables with the same name across all those contexts?

text: I'm looking to access variables in different contexts. The contexts are stored in a list labeled `contexttable`. Each context, of course, is a string. Is there any way, without using `NotebookWrite`, to access a variable of the same name, say `x`, in each context? I am looking for something like                contexttable = {"Context1`", "Context2`", ..., "ContextN`"};      Map[Print[# <> x]&, contexttable]      which would print the `x` variable in each context.


title: Package automated way of ReadProtecting all symbols

text: My template for building packages has, at the end, the following expression that automatically `ReadProtect`s all symbols defined in my `pack`:               ToExpression[Names["pack`*"], InputForm, SetAttributes[#, {ReadProtected(*,Locked*)}] &]      It works fine, with the exception of cases where I define a constant, like for example: `iso=3;` This produces the following message (when loading the package):               SetAttributes::sym: Argument 3 at position 1 is expected to be a symbol. >>      Can the automated expression that sets `ReadProtected` be changed to correct this behavior?


title: CreateCOMObject doesn't work on home edition

text: I can call an application named "PinPoint.Plate" with Visual Basic, Python and _Mathematica_ version 8 but not with version 9. I can still call Excel though. How can I fix this? This is what I did:               Needs["NETLink`"]     InstallNET[];     NETLink[];     p = CreateCOMObject["PinPoint.Plate"]      gives the error:                (* CreateCOMObject::netexcptn: A .NET exception occurred: System.Runtime.InteropServices.COMException (0x80040154): Retrieving the COM class factory for component with CLSID {9B7024E3-BD35-11D2-8EE4-0080C70A9C3D} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).        at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)        at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache)        at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)        at System.Activator.CreateInstance(Type type, Boolean nonPublic)        at Wolfram.NETLink.Internal.CallPacketHandler.createCOM(KernelLinkImpl ml). >> *)


title: Given f[1] ... f[k], k = 1, 2, 3... how do one find the general function f[n]?

text: If I have that               f[1] = 2 a b;     f[2] = 2 a b (1 + 6 a);     f[3] = 2 a b (1 + 9 a + 12 a^2);     f[4] = 2 a b (1 + 21 a + 72 a^2 + 60 a^3);     f[5] = 2 a b (1 + 45 a + 300 a^2 + 600 a^3 + 360 a^4);     f[6] = 2 a b (1 + 93 a + 1080 a^2 + 3900 a^3 + 5400 a^4 + 2520 a^5);     f[7] = 2 a b (1 + 189 a + 3612 a^2 + 21000 a^3 + 50400 a^4 + 52920 a^5 + 20160 a^6);      etc, how can I find a rule for $f(n)$ ?


title: Why doesn't Log[Gamma[]] simplify to LogGamma[] where it could?

text: I have been playing with various equations involving amount of permutations in relatively large sets. Easiest way to look at these is something like Log[10, bignumber!] . Often expressions, even indirect ones like Sum[Log[2,x], {x,1,2^32}] expand to forms involving Log[Gamma[...]] . This is problematic, since Gamma quickly grows past machine-representable numbers. OTOH, Mathematica knows this (for non-negative reals):               FullSimplify[Log[Gamma[x]] == LogGamma[x], x > 0]          (* True *)      It also knows that LogGamma can be split to Log[Gamma[...]]:               FullSimplify[LogGamma[x], x > 0,       ComplexityFunction -> (2 Count[#, _LogGamma, {0, Infinity}] +           LeafCount[#] &)]          (* Log[Gamma[x]] *)      ... but for what I really want, the reverse, it's not particularly forthcoming:               FullSimplify[Log[Gamma[x]], x > 0,       ComplexityFunction -> (1000 Count[#, _Gamma, {0, Infinity}] +           LeafCount[#] &)]          (* Log[Gamma[x]] *)      Yes, I know that I can do the transformation with rather trivial rule myself. Yet, I'm left to wonder a) why this transformation doesn't occur automatically even with above vigorous hint, b) is there an actual, good reason for the observed behaviour, and c) is there a non-manual way around it. I can only guess that similar condition applies to many other forms, too.


title: FindClusters for 3D Pancake/Platelet Shapes

text: I'm looking to properly cluster a dataset of roughly 3 million data points in 3-space. The shapes form closely spaced "clusters" that resemble pancakes. Here is a downsampled dataset:               data = Import["https://dl.dropbox.com/u/28603777/data.wdx"];      I have tried the standard distance methods (Canberra, Euclidean, Manhattan and BrayCurtis), yet each leaves some points from one cluster improperly sorted into another.               out = FindClusters[data, 6];      ![http://i.stack.imgur.com/O11qF.png](http://i.stack.imgur.com/5s7oO.png) The navy platelet "leaks" into the gold platelet due to the fact that the distance methods are isotropic. Also the gold platelet "leaks" into the red platelet. Is there a different way to cluster such that the distance method can be optimized in this way, or is there a fast way to cluster these platelets that does not rely on this function.


title: Can't edit MSPConfiguration.xml file and set Licence file in webMathematica

text: I have been working in Mathematica 9.0 for last 6 months. Now in our organization we got webMathematica. We don't know how to install webMathematica initially, with the help of this link http://support.wolfram.com/kb/3230 and other links we manage to install java(JDK 1.7) and tomcat (apache-tomcat-6.0.37).I had webMathematica in archive format. I have Unpacked the webMathematica web application archives into the webapps directory located in the Tomcat directory. The location where I copied webMathematica is **C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps** according to the guide from above given link. After that as per guide I tried to set the kernalExecutable and KernelLaunchFlags in MSPConfiguration.xml file which is found in **C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\webMathematica\WEB-INF** directory, But I faced two problems   1. Can't save the MSPConfiguration.xml after modify even though login as administrator.   2. I don't know how to save the licence of webMathematica whether in separate file or not. If it is separate file then which format it should be store. I tried like this to modify xml file                   <KernelPool>         <KernelPoolName>General</KernelPoolName>         <URLPattern>/*</URLPattern>          <KernelExecutable>C:\Program Files\Wolfram Research\Mathematica\9.0\MathKernel.exe</KernelExecutable>         <KernelLaunchFlags>-pwfile C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\webMathematica\WEB-INF</KernelLaunchFlags>         </KernelPool>      but when I tried to save MSPConfiguration.xml file with above said modification, I was not allow to save the xml file. I have checked the property of the file also, It says that administrator is have access of full control of read, write and all. I am login in as administrator as well. But I can't able to save the modification. Help to resolve this problem.


title: How to combine Plot and GeoGraphics?

text: I want to combine this map as "background" of this combined plot.   How can I do it?   The documentation doesn't show any similar demonstration.               GeoGraphics[ GeoRange -> "World", GeoBackground -> Automatic,                   GeoProjection -> {"Orthographic", "Centering" -> GeoPosition[{90, 0}]},                  AspectRatio -> 1/2]          Show[        ParametricPlot[{R Cos[t], r Sin[t]}, {t, 0, 2 Pi},                        PlotStyle -> Directive[RGBColor[0.75, 0.75, 0.75]]],        ListPlot[ Table[{{R Cos[t], r Sin[t]}}, {t, 0, 2 Pi, 2 Pi/24}],                  PlotStyle -> Directive[PointSize[Large], Orange]],        Axes -> False, Frame -> False, FrameTicks -> Automatic,        ImageSize -> Full, PlotRange -> All, AspectRatio -> 1/2]


title: Inputting two arrays for a module in Mathematica

text: I am relatively new to the _Mathematica_ enviroment and not sure where I am going wrong. I have evaluated the question and understand it, but dont know how to exactly create a module for it. The problem is:   * I need to calculate `PowerDensity` at a location $(x,y)$   * I am given the power $P$ at the source and its location $(x2,y2)$   * To calculate the `PowerDensity`, you use $P_d= \frac{P}{4\pi r^2}$   * The two $x$ and $y$ coordinates compute to give : $P_d = \frac{P}{(4*\pi*(y_2 - y_1)^2 - (x_2 - x_1)^2)}$ How do I write a `Module` like:               PowerDensity[antenna_, loc_] := Module[(* Enter your code here*)]      so the user would enter e.g. `PowerDensity[{1000,1000,12}, {0,0}]`? So far I have this:               PowerDensity[antenna_, loc_] := Module[{xone, yone, w} {xtwo, ytwo},         PD = w/(4*Pi*(ywo - yone)^2 - (xtwo - xone)^2),         print[PD]     ]      But it is not working. Any help?


title: Is it possible to run Mathematica on an HPC cluster with Torque?

text: I'm installing Wolfram gridMathematica in HPC cluster with TORQUE Resource Manager. There is a big problem because Mathematica suppost PBS pro. Can you help me or give some advice or coments?


title: Translating a "Point-to-Triangle" distance script from MATLAB to Mathematica

text: Update - Thanks everyone for your responses! After fixing a problem with vector normalization, the code below now works. * * * I'm a new user, and I was attempting to port some _Mathematica_ code from MATLAB for calculating the minimum distance between a point in 3-space and a triangle in 3-space. This is partly a result of me wanting to have this functionality in _Mathematica_ , and, I suppose, a good opportunity to practice learning the _Mathematica_ syntax. The original MATLAB code isn't mine (and can be found here), but appears to work well in MATLAB. Unfortunately, my translated version of the script in _Mathematica_ returns nonsense despite my almost verbatim copy of the script. I hope this question isn't inappropriate, but can anyone spot any naïve errors during the translation? Note that I had to change `D` to `Dnp` to avoid symbol protection issues.               P = {0.5, -0.3, 0.5};          P1 = {0, -1, 0};     P2 = {1, 0, 0};     P3 = {0, 0, 0};          vertices = {P1, P2, P3};          B = P1;     E0 = P2 - B;     E1 = P3 - B;          Dnp = B - P;     a = Dot[E0, E0];     b = Dot[E0, E1];     c = Dot[E1, E1];     d = Dot[E0, Dnp];     e = Dot[E1, Dnp];     f = Dot[Dnp, Dnp];          det = a*c - b*b;     s = b*e - c*d;     t = b*d - a*e;               If[(s + t) <= det,       If[s < 0,         If[t < 0,           If[(d < 0),             t = 0;             If[(-d >= a),              s = 1;              sqrDistance = a + 2*d + f;              ,              s = -d/a;              sqrDistance = d*s + f;              ];             ,             s = 0;             If[(e >= 0),              t = 0;              sqrDistance = f;              ,              If[(-e >= c),                t = 1;                sqrDistance = c + 2*e + f;                ,                t = -e/c;                sqrDistance = e*t + f;                ];              ];             ];           ,           s = 0;           If[e >= 0,            t = 0;            sqrDistance = f;            ,            If[-e >= c,              t = 1;              sqrDistance = c + 2*e + f;              ,              t = -e/c;              sqrDistance = e*t + f;              ];            ];           ];         ,         If[t < 0,           t = 0;           If[d >= 0,            s = 0;            sqrDistance = f;            ,            If[-d >= a,               s = 1;              sqrDistance = a + 2*d + f;              ,              s = -d/a;              sqrDistance = d*s + f;              ];            ];           ,           invDet = 1/det;           s = s*invDet;           t = t*invDet;           sqrDistance = s*(a*s + b*t + 2*d) + t*(b*s + c*t + 2*e) + f;           ];         ];       ,       If[s < 0,         tmp0 = b + d;         tmp1 = c + e;         If[tmp1 > tmp0,          numer = tmp1 - tmp0;          denom = a - 2*b + c;          If[numer >= denom,           s = 1;           t = 0;           sqrDistance = a + 2*d + f;           ,           s = numer/denom;           t = 1 - s;           sqrDistance = s*(a*s + b*t + 2*d) + t*(b*s + c*t + 2*e) + f;           ];          ,          s = 0;          If[tmp1 <= 0,           t = 1;           sqrDistance = c + 2*e + f;           ,           If[e >= 0,             t = 0;             sqrDistance = f;             ,             t = -e/c;             sqrDistance = e*t + f;             ];           ];          ];         ,         If[t < 0,           tmp0 = b + e;           tmp1 = a + d;           If[(tmp1 > tmp0),            numer = tmp1 - tmp0;            denom = a - 2*b + c;            If[(numer >= denom),             t = 1;             s = 0;             sqrDistance = c + 2*e + f;             ,             t = numer/denom;             s = 1 - t;             sqrDistance = s*(a*s + b*t + 2*d) + t*(b*s + c*t + 2*e) + f;             ];            ,            t = 0;            If[(tmp1 <= 0),             s = 1;             sqrDistance = a + 2*d + f;             ,             If[(d >= 0),               s = 0;               sqrDistance = f;               ,               s = -d/a;               sqrDistance = d*s + f;               ];             ];            ];           ];         ,         numer = c + e - b - d;         If[numer <= 0,          s = 0;          t = 1;          sqrDistance = c + 2*e + f;          ,          denom = a - 2*b + c;          If[numer >= denom,           s = 1;           t = 0;           sqrDistance = a + 2*d + f;           ,           s = numer/denom;           t = 1 - s;           sqrDistance = s*(a*s + b*t + 2*d) + t*(b*s + c*t + 2*e) + f;           ];          ];         ];       ];          If[(sqrDistance < 0), sqrDistance = 0;];          dist = Sqrt[(sqrDistance)]


title: Integration leading to logarithms and chosing branch

text: I m doing this interal with Mathematica               Integrate[(((1+b*t)^2)t)^(-1),t,Assumptions->b>0]      what I get back is               1/(1 + b t) + Log[-b t] - Log[1 + b t]      However there is a problem with the second term: imagine I set b to some positive number, as well as t, this would lead to an imaginary number instead a real one, as should be for a real integral. Indeed, just changing the sign works good, but I am puzzled about why Mathematica choses this solution. I guess must be related to choosing some branch for the logarithm or something similar, but still I don't figure out what Any suggestions?


title: What is the underlying algorithm for GroupElementToWord?

text: What algorithm is _Mathematica_ 9 using for `GroupElementToWord[group, g]`?


title: How to combine SparseArray and If

text: Because I am dealing with huge matrixes, my computer can not handle it, because of the memory. But, in my matrix, a very small percentage of the elements are non-zero. So I should use SparseArray as far as I am aware. The problem is that, I do not really know how to transform my old way of defining my matrix to the new "SparseArray way". I gonna give a very simple toy model of my old way:               n = 3;          H = ConstantArray[0, {n*n, n*n}];          Do[       i = ix + (iy - 1)*n;       j = jx + (jy - 1)*n;       x = ix;       y = iy;       If[i == n && j == i - 1, H[[i, j]] = t*Exp[I*x],        If[i == n && j == i + n, H[[i, j]] = t,         If[i == n && j == i - (n - 1), H[[i, j]] = t*Exp[-I*x],          If[i == n && j == i + n*(n - 1), H[[i, j]] = t, 0]]]],      {iy, 1, n,1}, {ix, 1, n, 1}, {jy, 1, n, 1}, {jx, 1, n, 1}];      So my matrixes are like this but with many-many If. Could somebody give me an idea of how to do it? Thanks a lot


title: Filling and Shading an Harmonic Curve

text: Suppose I have an equation plotted as shown:               Plot[(HarmonicNumber[K] - HarmonicNumber[K - r]) (HarmonicNumber[K] -       HarmonicNumber[-1 + r]) /. K -> 10, {r, 0, 11}, Filling -> 0.4]      ![image](http://i.stack.imgur.com/Eq2Cq.png) But what I really want is to have the two (triangular?) filling FLIPPED inside at $x \approx2$ and $x \approx9$. The direction of filling of the upper (semi- circular) part is not important. Preferably it can be Top/outside. Can anybody help with this flipping? Thanks


title: Has anyone seen (and been able to mend!) an error involving Symbol FE`DynamicModuleVariableList?

text: FE`ExecuteInDynamicModule::noval: Symbol FE`DynamicModuleVariableList$67 does not have a value. >>      I'm just posting the error for the moment as this is a problem that occurs in a largeish `Manipulate` that is being designed for a cdf document. It is wrapped in a `Dynamic` module which defines a number of symbols, including several functions. The context is this: I'm using `SaveDefinitions -> True` but it seems all definitions are not correctly saved once the kernel has gone. If I evaluate my `Manipulate` with the kernel running, the resulting interface runs correctly. If I copy it into a fresh document and save it as a separate cdf document, this document does not run properly in the CDF viewer. Now if I quit the kernel in the original document I see the same incorrect behaviour as in the cdf. The strategy I came up with was to move all the definitions outside the `Manipulate` into the initialization section or into the list of module variables so that I could stop using `SaveDefinitions -> True`. But as these sections get larger, I begin to get errors such as the above. If I can find a way of avoiding these, my strategy might work.


title: Access curated or locally stored data with curated data functions?

text: Say I have a toy package, something like:               BeginPackage["myPackage`"]     plotSomeData::usage = "plotFinancialData[symbol]... some usage language";     Begin["`Private`"]     plotSomeData[symbol_]:= DateListPlot[FinancialData[symbol, All]]     End[]     EndPackage[]      This should work fine, nothing particularly complicated here. So now, I'd like to extend the `FinancialData[]` function embedded in the package to enable it to seamlessly access _non-Wolfram curated data_ stored locally on my computer. I could rewrite the package and set up some conditional code that would replace `FinancialData[]` with `Import[]`, something like:               plotSomeData[symbol_] := DateListPlot[       Which[        symbol == "xyz", Import[pathAndFileName],        symbol != "xyz", FinancialData[symbol, All]        ]]      But, in my case, that would mean rewriting a bunch of perfectly good packges, so I'd like another solution. Some of the questions and answers such as: What is a paclet? UpValues TagSet and UpSet have me wondering if another more elegant way exists to do this. Could, for instance, one extend the paclet information for a set of curated data? I've used `TagSet` before to do things like define how to calculate the `CDF` of a custom distribution, but I don't see a clear way to use it to enable a curated data function to recognize the location of a data symbol it doesn't already know. `SetOptions` doesn't seem like the thing either. `UpVales` and `UpSet` might do it, but I don't see it yet. Ideally, I'd simply like to extend a curated data function to recognize the location of a data symbol it doesn't already know and thereby enable it to get the newly identified data. Best if I can do this outside of the packages I already have. Any ideas? (The tags I have on this question could use some improvement, if anyone has some better ideas.)


title: Sorting the element in a PDB text file

text: I am a new user of _Mathematica_ and currently using version 9. I want to rearrange the element of one PDB text file with respect to another PDB text file. Suppose I have a PDB file like this:               HETATM    1   C1 UNK     0      14.406  17.458  -0.592  1.00  0.00           C       HETATM    2   H1 UNK     0      15.490  17.698  -0.832  1.00  0.00           H       HETATM    3   C2 UNK     0      13.604  17.656  -1.892  1.00  0.00           C       HETATM    4   H2 UNK     0      14.009  16.956  -2.694  1.00  0.00           H       HETATM    5   H3 UNK     0      13.710  18.738  -2.241  1.00  0.00           H       HETATM    6   H4 UNK     0      12.506  17.420  -1.717  1.00  0.00           H       HETATM    7   C3 UNK     0      13.987  18.450   0.505  1.00  0.00           C       HETATM    8   O1 UNK     0      14.203  19.812  -0.103  1.00  0.00           O       HETATM    9   H5 UNK     0      12.905  18.324   0.828  1.00  0.00           H       HETATM   10   H6 UNK     0      14.669  18.317   1.409  1.00  0.00           H      Now I want to rearrange the above file with respect to the following file:               HETATM    1   H2 UNK     0      14.009  16.956  -2.694  1.00  0.00           H       HETATM    2   H1 UNK     0      15.490  17.698  -0.832  1.00  0.00           H       HETATM    3   C3 UNK     0      13.987  18.450   0.505  1.00  0.00           C       HETATM    4   H6 UNK     0      14.669  18.317   1.409  1.00  0.00           H       HETATM    5   H3 UNK     0      13.710  18.738  -2.241  1.00  0.00           H         HETATM    6   O1 UNK     0      14.203  19.812  -0.103  1.00  0.00           O            HETATM    7   C2 UNK     0      13.604  17.656  -1.892  1.00  0.00           C       HETATM    8   C1 UNK     0      14.406  17.458  -0.592  1.00  0.00           C         HETATM    9   H5 UNK     0      12.905  18.324   0.828  1.00  0.00           H       HETATM   10   H4 UNK     0      12.506  17.420  -1.717  1.00  0.00           H       How can I do it? Please help me. Thanks.


title: changing a symbol into a function variable

text: Struggled for a while on this problem and hopefully you can help... I have a mathematical expression that currently has a symbol where I used to have a function variable. How do I make the symbol back into a variable, so that my expression becomes a function again? My function became an expression when I saved it in a matrix, and so now I'm trying to make the different matrix elements back into functions after having constructed the matrix. Thanks in advance. > INCLUDING SOME CODE (my first time contributing on this website...) Imagine a For loop sum (I've removed a substantial amount of code that's irrelevant for now)               Pstatesalpha[λ_]=0;     RankMatrix={};     elecdipole (*some vector of numbers delem*)     SumPstatesalpha[λ_, Alpharank_]  (*a predefined function of λ, Alpharank*)          For[Alpharank = 1, Alpharank <= 3, Alpharank++,(        For[jsum = 1, jsum <=Length[elecdipole], jsum++,(     Pstatesalpha[λ_] = (delem*a0)^2*SumPstatesalpha[λ,Alpharank] + Pstatesalpha[λ];        )]     AppendTo[RankMatrix, {Alpharank,Pstatesalpha[λ]}]     )]      Note that I've saved Pstatesalpha[λ] as a function into `RankMatrix`. When I want to access (for instance)               RankMatrix[[1,2]]      Mathematica returns an expression that includes $\lambda$, but I can't use it as a function anymore.


title: How to expand a general expression in cross and dot product in Mathematica

text: I am looking for a way to simply the general expression in cross product and dot product with general vectors. I got a help in How do I simplify a vector expression? but soon I find that it doesn't work in the case               FullSimplify[Cross[vec[x], 2*vec[y]] + Cross[vec[y], 2*vec[x]] ]      it doesn't give zero. It seems that _Mathematica_ doesn't know how to expand the following expression               Cross[vec[x], 2*vec[y]] -> 2*Cross[vec[x], vec[y]]


title: GUI->Text code conversion

text: I have to solve about 30 symbolic equations simultaneously. _Mathematica_ is taking more than 24 hours to solve it on a 6 core system and now I have to run that on a cluster. In order to do so I need to convert GUI based code into text user interface code. Any suggestions how to proceed ?


title: Elegant high precision `log1p`?

text: Sometimes it is hard to understand how numerical expressions are evaluated. I remember reading claims by Wolfram on how smart the Kernel is to evaluate expressions trees numerically by recognizing patterns, yet I don't see how it applies in very simple examples. This question is about numerics, but to see if symbolics can help in an elegant way. It is known that when working with finite precision, the function $\log(1+x)$ should have a special implementation for small $x$. That is why functions like `log1p` exists in many libraries (on top of `log`). For example: http://gnu.ist.utl.pt/software/gsl/manual/html_node/Elementary- Functions.html#Elementary-Functions `/*C code*/ log(1. + 1.e-15) == 1.11022e-15` `/*C code*/ log1p(1.e-15) == 1.e-15` (The second version is more exact, the first is "wrong") In Mathematica: `Log[1. + 1.*^-15] == 1.11022*10^-15` (wrong answer) Mathematica doesn't have such `Log1P` function. One can say, well, that is because it doesn't need to, because of the symbolic power. In fact one can know the answer. `N[Log[1 + 1/10^15], 100] = 9.999999999999995000000000000003333333333333330833333333333335333333333333331666666666666668095238095*10^-16` But this is not general, if I want to evaluate `Log[1 + x]` and x has machine precision then I can't force to use something like `log1p`. Because `1+x` will evaluate to a machine precision number. These are my attempts:               x = 1.*^-15;     Log[1 + x]     Log[1. + x]     N[Log[1. + N[x, 20]], 20]     N[Log[1 + N[x, 20]], 20]      All evaluate to the wrong answer (`1.11022*10^-15`) Finally I find this expression,               N[Log[1 + Rationalize[x, 0]], 20]     9.999999999999995000*10^-16      But really? is it that hard to get `log(1+x)` for small x numerically? Do I have to roll my own `Log1p`?


title: Convolution of two dirac delta functions

text: Why mathematica doesnt produce any answer to the following integral?               Integrate[0.040608386793220284*DiracDelta[w]*DiracDelta[-w + x], {w, -2, 2}]      and how can I get a solution? Thank you very much.


title: Creating a Tooltip that knows what platform is currently being used

text: I have _Mathematica_ 8 on my PC. I also have a new Mac with CDF-player, but not _Mathematica_. I want a `Tooltip` that shows one thing if running on a PC, and something different if running on a Mac. Both of the following show `"MS- Windows"` in the `Tooltip` even when using my Mac.               Tooltip["A String",     If[StringMatchQ[$Version,__~~"Windows"~~__],"MS-Windows",(* else Mac *)"Probably OS X"]     ]          Tooltip["A String",     If[SystemInformation["FrontEnd","MachineType"]==="PC","MS-Windows",(* else Mac *)"Probably OS X"]     ]      It will be even better if it can hande a third case where the OS is neither Windows or OS X. Can you show me how to do it?


title: How to generate the truth table to prove logical equivalence?

text: How to generate the truth table to show that $p \implies (q \vee r)$ is equivalent to $(p \wedge \neg q ) \implies r$ ? Can I use `BooleanTable`?


title: Module that finds the sum of digits of any given positive integer

text: How can I make a module that finds the sum of digits of any given positive integer? I use this command               F[x_]:= Apply[ Plus, IntegerDigits[x] ]      Is there another module to do it ?


title: Elegantly pairing up mismatched lists

text: `HistogramList` returns a list of bin boundaries and a list of counts. There is one more boundary than counts, and I'd like to pair them up so I can feed it into `ListLinePlot` and get an alternative view of a histogram. Here's some code that will do this:               {bins, counts} = N[HistogramList[RandomVariate[NormalDistribution[5, 2], 100]]]          (* => {{0., 2., 4., 6., 8., 10.}, {13., 19., 37., 28., 3.}} *)          points = Transpose[{Riffle[bins, bins], Flatten[{0, Riffle[counts, counts], 0}]}]          (* => {{0., 0}, {0., 13.}, {2., 13.}, {2., 19.}, {4., 19.}, {4., 37.}, {6., 37.},             {6., 28.}, {8., 28.}, {8., 3.}, {10., 3.}, {10., 0}} *)      Note that it also adds in some zeros to bring the resulting curve down to the axis:               ListLinePlot[points]      ![Mathematica graphics](http://i.stack.imgur.com/cEF8v.png) Is there a simpler and/or more intuitive way of achieving this behavior?


title: Automatically detect largest interval over which NDSolve can find a solution

text: **Question** : Consider the following numerical resolution:               NDSolve[eqn, {x1[t], x2[t], y[t]}, {t, tmin, tmax}      where `eqn`, `tmin` and `tmax` are given. Suppose this gives an error (for example, a stiff system detection, or any numerical error). How would you do to adjust _automatically_ `tmin` and `tmax` to the largest (or a "large") interval where `NDSolve` doesn't give any error? I tried using `Check` but I don't manage to use it efficiently as I cannot catch the defective times. **Context** : In case you're wondering, I'm asking because I have a large number of odes `eqn` to solve, some of which work fine on $[t_\mathrm{min},t_\mathrm{max}]$, but some others don't. And of course I don't want to adjust the time interval by hand! **Example** : With               eqn = {x1'[t] == -x1[t]^2 - x2[t] + y[t]^3, x2'[t] == x1[t] - x2[t] + x1[t]^2 x2[t]^2,      y'[t] == x2[t]^2 + y[t] + x1[t]^2 y[t]^2 + 0.5` y[t]^3, x1[0] == 1, x2[0] == 1, y[0] == 1};      the following               {tmin, tmax} = {-1, 1};     NDSolve[eqn, {x1[t], x2[t], y[t]}, {t, tmin, tmax}];      yield an `NDSolve::ndsz` error while               {tmin, tmax} = {-0.5, 0.5};     NDSolve[eqn, {x1[t], x2[t], y[t]}, {t, tmin, tmax}];      works fine.


title: MatrixForm explanation as why row extract is displayed as a column?

text: I have a 5 x 5 matrix: cdsSpread5yrs = ![enter image description here](http://i.stack.imgur.com/0gX7b.png) But after doing a row extract, why is it displaying as a column?               rowSpread2 = cdsSpread5yrs[[2]];       rowSpread2 // MatrixForm      ![enter image description here](http://i.stack.imgur.com/SSIOn.png)


title: Working with Java hashmaps from Mathematica

text: I'm using J/Link to access data from an external Java program. The data are represented as a `ConcurrentHashMap` (see the official specification here). ` link = JavaNew["org.ddpclient.DDPTestClient"]; ` When I evaluate `data = link@mCollections` in my Mathematica notebook to access `mCollections` field where the data of interest are stored, I get a HashMap object: ` « JavaObject[java.util.HashMap]» ` Is there a way to convert this HashMap into a native Mathematica list (or nested list, to be more precise) so that I could work with it? I know that one can call a `toString[]` method on the HashMap object to convert it to a string. In my case, `data@toString[]` yields something like this: ` {G9fuqeYuiQpcmL8MW={playerId=zxcgf24ta, lastSeen=null, status=0.0, \ active=true}, aiej2mQppBAefhad7={playerId=lklu453da1, lastSeen=null, \ status=0.0, active=true}, Bbd8YqAx8yFcdcMcz={playerId=poo10alll235, \ lastSeen=null, status=0.0, active=true}, \ Gnt3KKrrgypgFEorp={playerId=hjffxz535cd, lastSeen=null, status=0.0, \ active=true}, ioydvWm7GacPg5DyM={playerId=asdfa123sa, lastSeen=null, \ status=1.0, active=false}, 8vZ6i73t6mbwTB63D={playerId=66df24hl, \ lastSeen=null, status=0.0, active=true}} ` It is probably possible to manually parse this, but I am afraid it would be really difficult to handle all the possible edge cases that could arise during the conversion. Is there a better way?


title: Unique CellID in-between notebooks

text: Documentation says that CellID is guaranteed to be unique for a given notebook. I've noticed that CellID are fairly high numbers and although probabilistically speaking the odds of coincidence are low, how can I modify its behaviour to have a guarantee of no repetitions in-between notebooks? For simplification let's assume that it should only hold for notebooks created on my machine and not ones downloaded from the internet etc.


title: Mathematica does not solve this integral

text: I want to compute the integral of a polynomial in t, which I know an analitical solution exist. But Mathematica give me as result the input, not the result of the integral: ![enter image description here](http://i.stack.imgur.com/lFTgK.jpg) I already know this since it is the input but I want to compute the value of this integral. Here is the code if you want to reproduce this (copy-pasted from mathematica, this is indeed ugly):               x[t_] := a0 + a1*t + a2*t^2 + a3*t^3 + a4*t^4 + a5*t^5;          a0 = x0;     a1 = v0;     a2 = acc0/2;     a3 = -((20 x0 - 20 xf + 12 v0 tf + 8 vf tf + 3 acc0 tf^2 - accf tf^2)/(2 tf^3));     a4 = -((-30 x0 + 30 xf - 16 v0 tf - 14 vf tf - 3 acc0 tf^2 + 2 accf tf^2)/(2 tf^4));     a5 = -((12 x0 - 12 xf + 6 v0 tf + 6 vf tf + acc0 tf^2 - accf tf^2)/(2 tf^5));          Jp = 1/2*Integrate[(x[t] - xf)^2, {t, 0, tf}];     Jv = 1/2*Integrate[(x'[t] - (vf + v0)/2)^2, {t, 0, tf}];     J3 = alpha*Jp + (1 - alpha)*Jv      Do you have an idea of what I am doing wrong? Thnk you in advance


title: How to pass arguments between functions

text: I have two Functions, `f[]` and `g[]`. `f` is passed some values ,say `{w,x,y,z}` and I want to send one of those to `g` say `x`. I don't want this operation to interfere with other operations.


title: Setting PropertyValue for VertexWeight is not persistent

text: g = CompleteGraph[8, VertexSize -> Medium];               PropertyValue[{g, VertexList[g][[1]]}, VertexWeight] = 10;         PropertyValue[g, VertexWeight]      > >     {10, 1, 1, 1, 1, 1, 1, 1} >                 PropertyValue[{g, VertexList[g][[2]]}, VertexWeight] = 10;         PropertyValue[g, VertexWeight]      > >     {1, 10, 1, 1, 1, 1, 1, 1} >                 PropertyValue[{g, VertexList[g][[3]]}, VertexWeight] = 10;     PropertyValue[g, VertexWeight]      > >     {1, 1, 10, 1, 1, 1, 1, 1} >   How come that I see only the last result from `PropertyValue`? It applies only to `VertexWeight` property. When I set `VertexStyle` (like in docs), everything is fine: I can change the vertex color one by one.


title: Options CellLabel not showing

text: I'm back with the labels and tags questions! Here is my code:               mb = CreateDocument[Null, ShowCellTags -> True];      In the new document, I create a new cell, add some random code, and select the bracket of the cell. When I then process               SetOptions[NotebookSelection[mb], CellTags -> "tag test",       CellLabel -> "label test"]      I indeed see in the mb notebook the label and the label appear. Good. Now, I process the code (with the same selection: the cell bracket in the notebook mb)               Options[NotebookSelection[mb], {CellLabel, CellTags}]      and I get as output > >      {CellLabel -> None, CellTags -> "tag test"}. >   Why isn't the CellLabel showing up? I can't get my head around this one... Thanks for all help, as always!


title: Weighted mean of complex exponential function using NIntegrate

text: I have defined the following functions:               γ[r_, v_, rDet_] :=        Which[        Abs[r - v tDet] >= rDet, 0,         r + v tDet <= rDet, π,         True, ArcCos[((v tDet)^2 + r^2 - rDet^2)/(2 v tDet r)]];     ρ[r_, v_, v0_] := Exp[-(1/2) (r/rCloud)^2] r Exp[-(1/2) (v/v0)^2]  v;     ΔΦ[v_] := (2 π )/λ c (4 (v*t)^2)/(rBeam)^2;      I want to weight `ΔΦ` by `ρ` and `γ`. I do so by defining a function `Awfc` that numerically integrates the product of the three functions over `v` and `r` and divides by the numerical integral over the two weighting functions:               Awfc[rDet_?NumericQ, v0_?NumericQ] :=        NIntegrate[ γ[r,v,rDet]*ρ[r,v,v0]* Exp[I ΔΦ[v]], {r,0,∞}, {v,0,∞ }}]/        NIntegrate[ γ[r,v,rDet]*ρ[r,v,v0], {r,0,∞}, {v,0,∞}}];      I calculate `Awfc` for some parameters `rDet` and `v0`               AwfcTable =        ParallelTable[         {rDet, Awfc[rDet, 0.5 v0], Awfc[rDet, v0], Awfc[rDet,2 v0], Awfc[rDet,3.7 v0]},          {rDet,0.0005,0.010,0.0005}];      using these values for the other parameters:               tDet = 0.7;     t = 0.230;     rCloud = 0.0025;     λ =  780 10 ^-9;     c = λ/20;     v0 = 0.00588;     rDet = 0.008/2;              rBeam = 0.015;      All kernels throw warnings: > NIntegrate::slwcon: Numerical integration converging too slowly; suspect one > of the following: singularity, value of the integration is 0, highly > oscillatory integrand, or WorkingPrecision too small. I think that `ΔΦ` is a hightly osciallating function so I don't see a way to fix this problem. I use `TableForm[Abs[AwfcTable]]` to get the amplitude of the complex numbers in `AwfcTable`. The problem with the output is, that this amplitude is significantly larger than 1, especially for larger `v0` and small `rDet`. The function `ΔΦ` I am calculating the weighted mean of, has a maximum amplitude of 1 so I think the weighted mean should also have a maximum of 1. (The complex phase is consistent with what I expect from a different approach to the problem I did using MATLAB) Is there something wrong with my reasoning (meaning that the result _Mathematica_ gives is actually correct), or is does the fault lie with my implementation of the problem?


title: How to add images where each represents a different color channel?

text: So I have three matrices that represent say the R, G, and B channels of an image:               mR = RandomInteger[{0, 255}, {2, 2}];     mG = RandomInteger[{0, 255}, {2, 2}];     mB = RandomInteger[{0, 255}, {2, 2}];      I would like to add these to get an overall image made of these three channels, but I can't seem to be able to do that. Trying to understand the documentation under "Image", I tried               Image[{mR, mG, mB}, "Byte"]      but this gives me an image that's 3x2: ![RGB](http://i.stack.imgur.com/0srHu.png) Also when I try               Image[{mR, ConstantArray[0, {2, 2}], ConstantArray[0, {2, 2}]}, "Byte"]      I don't get the red channel. I just get the first row of the image above with zeros everywhere else: ![R](http://i.stack.imgur.com/vCR48.png) I can't understand the documentation here, and any help would be greatly appreciated!


title: Problem with NDSolve in Mathematica 9 / 10

text: I'm having trouble by solving the following differential equation in _Mathematica_ 9 and 10, where the code works fine in version 7:               τp = 200*10^(-15);      e = 1.60217653*10^(-19);      me = 9.1093826*10^(-31);      c = 2.99792458*10^(8);      ϵ = 8.854187817*10^(-12);      h = 6.626*10^(-34);      hbar = h/(2 Pi);       λ = 786*10^(-9);     n0 = 1.45;      mred = 0.635*me ;     Eg = 7.5*e;     τr = 220*10^(-15);     ω = (2 Pi c)/λ;     k0 = (n0 ω/c);     rhocrit = (ϵ*mred*ω^2/(e^2));     H = 2*10^(4);     I0 = H*(2 Sqrt[Log[2]])/(τp Sqrt[Pi]);     Int1[t_] := I0*Exp[-4 Log[2] (t^2/τp^2)];     γ[Int_] := (ω/e)*Sqrt[(mred c n0 ϵ Eg)/(2 Int)];     Γ[Int_] := γ[Int]^2/(1 + γ[Int]^2);     ζ[Int_] := 1/(1 + γ[Int]^2);     β[Int_] := Pi^2/(2 EllipticK[ζ[Int]]*EllipticE[ζ[Int]]);     x[Int_] := (2 Eg)/(Pi hbar ω Sqrt[Γ[Int]])*EllipticE[ζ[Int]];     μ[Int_] := IntegerPart[x[Int] + 1] - x[Int];     Q[Int_] :=        Sqrt[(Pi)/(2 EllipticK[ζ[Int]])]          Sum[           Exp[-s Pi ((EllipticK[Γ[Int]] - EllipticE[Γ[Int]]) /              (EllipticE[ζ[Int]]))] DawsonF[Sqrt[β[Int] (s + 2 μ[Int])]],            {s, 0, 5}];     WPI[Int_] :=        If[10^(3) > Int,           0,           (2 ω)/(9 Pi) *((ω mred )/(hbar Sqrt[Γ[Int]]))^(3/2)*Q[Int]*            Exp[-Pi ((EllipticK[Γ[Int]] - EllipticE[Γ[Int]])/              (EllipticE[ζ[Int]]))*IntegerPart[x[Int] + 1]]];     Ekrit[t_] := Eg (1 + 1/(4 γ[Int1[t]]^2));     Ekin[t_] := Ekrit[t]/10;          s1 =        NDSolve[{sol1'[t] == WPI[Int1[t]] +          (((k0 ω ((16 Pi ϵ^2 Sqrt[mred Ekin[t]^3]) /                    (Sqrt[2]*e^4*sol1[t])))/              (n0^2 rhocrit                 (1 + ω^2*(((16 Pi ϵ^2 Sqrt[mred Ekin[t]^3]) /                    (Sqrt[2]*e^4*sol1[t]))^2)))) sol1[t] Int1[t])/           (Eg) - sol1[t]/τr, sol1[-3 τp] == 1},          sol1, {t, -3.1 τp, 4 τp}];      In version 7 there are no error messages and with:               LogPlot[Evaluate[sol1[t] /. s1], {t, -2 τp, 2τp}]      I get the expected result: ![enter image description here](http://i.stack.imgur.com/S2kEZ.png) But when I use one of the newer versions, the kernel shuts down without giving an output. Anyone got an idea how to solve this problem?


title: Column and CellLabel

text: Is it possible to add a CellLabel over multiple lines? When trying the code               SetOptions[ NotebookSelect[mb], CellLabel-> Column@{"line 1", "line 2"} ]      with a Cell selected in the mb Notebook, nothing shows up. What's the solution for this? Thanks all!


title: Constraining two points, a specified distance apart, to a line

text: Suppose that I have two points in the _xy_ plane: `pt1` and `pt2init`. `pt1` is fixed in space, while `pt2init` is supplied by the user (but its returned value will in general be different). I wish to write a function that will return the coordinates of a point `pt2result` that is located a user-specified distance `d` from `pt1` **along the line connecting`pt1` and `pt2init`** and that is _closest_ to `pt2init`. I wrote the following function `f` (and its supporting function `dist2D`, which finds the distance between two points with x- and y-coordinates):               dist2D[pt1_, pt2_] :=       Sqrt[(pt2[[1]] - pt1[[1]])^2 + (pt2[[2]] - pt1[[1]])^2]          f[pt1_, pt2_, d_] := Module[{line, x2result, y2result, pt2result},       line = Normal[LinearModelFit[{pt1, pt2}, xvar, xvar]];       Solve[{dist2D[{pt1[[1]], pt1[[2]]}, {x2result, y2result}] == d,         y2result == (line /. xvar -> x2result)},        {x2result, y2result}];       pt2result = {x2result, y2result}       ]      But when I run it:               f[{0.77825, 0.551441676}, {0.7075, 0.67398427}]      it does not return anything. Is it possible to do constrained optimization like this?


title: Can't solve equation having complex coefficients

text: Why can't _Mathematica_ solve $\quad\quad\frac{1-i}{\sqrt{2}}=e^{i \alpha } \tan \left(\frac{\beta }{2}\right)$ with the restrictions $\alpha \in [0, 2 \, \pi)$ and $\beta \in [0,\pi]$:               Solve[(1 - I)/Sqrt[2] == E^(I alpha) *Tan[beta/2] &&  0 <= beta <= π && 0 <= alpha < 2 π]      > Solve::nsmet: This system cannot be solved with the methods available to > Solve. The solution is $\beta=\frac{\pi}{2}$ and $\alpha=\frac{7 \cdot \pi}{4}$. If I give _Mathematica_ the value for $\beta$,               Solve[((1 - I)/Sqrt[2] == E^(I alpha) *Tan[beta/2] /.        beta -> π/2) && 0 <= beta <= π && 0 <= alpha < 2 π]      I get the solution               (*{{alpha ->  ConditionalExpression[(7 \[Pi])/4, 0 < beta < \[Pi]]}}*)      What is the problem here? I also tried the other functions like `FindRoot`, `Reduce`, etc.


title: Accessing list elements by name

text: First, a bit of a long introduction to my problem: I only have a few weeks of Mathematica experience. I am creating a mathematica application that calculates some material properties of steel based on metallurgical functions that include multiple chemical elements. I currently have the chemistry stored in a vector, and the list of elements stored in a second vector of the same length. Here's an example:               elements={"C","Mn","S","P","Si","Cu","Ni","Cr","V","Cb","Mo","Sn","Al","Ca","B","Ti","N","O","Ce","Pb","Bi","W","As","Zn","Sb"};     chemistry={0.032`,1.2`,0.0259`,0.006`,0.04`,0.15`,0.06`,0.04`,0.001`,0.051`,0.167`,0.007`,0.035`,0.0001`,0.`,0.001`,0.0087`,0.0176`,0.0002`,0.0001`,0.`,0.`,0.004`,0.036`,0.`};      I created a function called _elem_ to look up the element name in _elements_ , and find the corresponding entry in _chemistry_ (or any other chemistry list of proper format):               elem[chem_,element_] := chem[[Flatten[Position[elements,element]]]][[1]];      For example, if I want to look up Nickel ("Ni") from the _chemistry_ list, I use the following to get 0.06:               elem[chemistry, "Ni"]      The neat thing about this is when you write a formula using the elem function, the list _elements_ can be used to print the formula in a more user-friendly way for verification. For example, the Titanium to Nitrogen ratio is one of the simpler formulas of interest:               TiByN[chem_] := elem[chem, "Ti"]/elem[chem,"N"]      When called with _chemistry_ , it returns a number (0.114943), but when you call _TiByN_ with _elements_ , it returns the formula **Ti/N**. This way, I can print a list of formulas in a format that the metallurgists can read when they audit my application. **My question is one of performance.** I need to do an optimization involving these formulas, and I think this method of indexing the chemistry is one of my big bottlenecks. Is there any way to precompile a function like _elem_ for the list _elements_ so that the position doesn't have to be looked up for every element in every formula on every iteration of the optimization? Thanks


title: Efficiently exporting many images as a video

text: I have many .gif images and I would like to export them as a single video file (I prefer .mov, but any video format is fine). But what if I have several tens of megabytes of .gif images? Is it possible to export them efficiently, without running out of memory? For example, suppose I have many .gif files in the current directory. One way to compile them into a .mov video is to import _all_ the images at once, in a single table, and then call `Export`:               files = FileNames["*.gif"];     images = Map[Import, files];     Export["video.mov", images]      But, for several tens of megabytes of .gif images, pre-importing all the images in a list (i.e., `images`) may be impossible because of insufficient memory. Is there any way to work around this?


title: Inconsistent initial and boundary conditions

text: I have a 4th order nonlinear PDE with the following BCs and IC:               (* Boundary conditions *)        (h^(1,0,0))[0,y,t]==0.0,     (h^(1,0,0))[L,y,t]==0.0,     (h^(0,1,0))[x,0,t]==0.0,     (h^(0,1,0))[x,L,t]==0.0,          (h^(3,0,0))[0,y,t]==0,     (h^(3,0,0))[L,y,t]==0,     (h^(0,3,0))[x,0,t]==0,     (h^(0,3,0))[x,L,t]==0,          (* Initial condition *)     h[x, y, 0] == 1 + (-0.05 Cos[2 π x/L] - 0.05 Sin[2 π x/L]) Cos[2 π y/L]      I realized that the first derivative and third derivative of my initial condition, `h[x,y,t=0]` wrt to `x` evaluated at `x=0` and `x=L` are not `0` and hence pose an inconsistency (I get the `ibcinc` error). I can't change my boundary conditions as the example problem here does because my boundary conditions represent static contact angles and they are either a zero or a number. And I don't want to change the ICs because this is the initial condition I have been using all throughout and I'd like consistency in comparison of my results. What should I do about this? The entire code follows:               $HistoryLength = 0;     Needs["VectorAnalysis`"]     Needs["DifferentialEquations`InterpolatingFunctionAnatomy`"];     Clear[Eq0, EvapThickFilm, h, Bo, ε, K1, δ, Bi, m, r]     Eq0[h_, {Bo_, ε_, K1_, δ_, Bi_, m_, r_}] := D[h, t] + Div[-h^3 Bo Grad[h] +          h^3 Grad[Laplacian[h]] + (δ h^3)/(Bi h + K1)^3 Grad[h] +          m (h/(K1 + Bi h))^2 Grad[h]] + ε/(Bi h + K1) +          (r) D[D[(h^2/(K1 + Bi h)), x] h^3, x] == 0;     SetCoordinates[Cartesian[x, y, z]];     EvapThickFilm[Bo_, ε_, K1_, δ_, Bi_, m_, r_] := Eq0[h[x, y, t], {Bo, ε, K1, δ, Bi, m, r}];     TraditionalForm[EvapThickFilm[Bo, ε, K1, δ, Bi, m, r]];          L=2*92.389;TMax=2491.29*100;          Clear[Kvar];     Kvar[t_]:=Piecewise[{{1,t<=1},{2,t>1}}]     (*Ktemp=Array[0.001+0.001#^2&,13]*)     hSol=h/.NDSolve[{     (*S,G,E,K,D,VR,M*)     EvapThickFilm[0.003,0,1,0,1,0.025,0],     (*h[0,y,t]==h[L,y,t],     h[x,0,t]==h[x,L,t],*)          (* Boundary conditions *)        Derivative[1,0,0][h][0,y,t]==0.0,     Derivative[1,0,0][h][L,y,t]==0.0,     Derivative[0,1,0][h][x,0,t]==0.0,     Derivative[0,1,0][h][x,L,t]==0.0,          Derivative[3,0,0][h][0,y,t]==0,     Derivative[3,0,0][h][L,y,t]==0,     Derivative[0,3,0][h][x,0,t]==0,     Derivative[0,3,0][h][x,L,t]==0,          (* Initial conditions *)     (*h[x,y,0] == 1.1+Cos[km x] Sin[2 km y] *)     h[x,y,0]==1+(-0.05 Cos[2 π x/L]-0.05 Sin[2 π x/L]) Cos[2 π y/L]     },     h,     {x, 0, L},     {y,0, L},     {t, 0, TMax},     Method->{"BDF","MaxDifferenceOrder"->1},MaxStepFraction->1/50     (*StepMonitor:> Print["time= ",t] *)     ][[1]]      What I have tried so far:   1. I tried using `Piecewise` but my Piecewise function needed more than 2 arguments so I failed.   2. I tried changing the solution method to  Method -> {"MethodOfLines", "SpatialDiscretization" -> {"TensorProductGrid", "MinPoints" -> 100}} This didn't yield anything either.   3. I also tried setting `"DifferentiateBoundaryConditions"->False`, I still get the same error. Is there a fix to this "inconsistent ic/bc" issue? ## Update 5/31/2012 I changed the boundary conditions to reflect the initial condition (I changed the BCs to the first and third derivatives of the initial condition so as to make them consistent) but still, I get the same error.


title: How to solve a symbolic equation with symbols in powers

text: I am trying to solve $\dfrac{\rho\ ((1-b)\ \lambda _f\ \lambda _s\ P _A)^{\rho }}{b-1}+\dfrac{\rho \left(\dfrac{b\ \text{ps}\ x}{1-\text{ps}}\right)^{\rho }}{b}=0$ in terms of $b$, I entered                  Solve[((((b ps x)/(1 - ps))^ρ ρ)/          b + ((-(-1 + b) PA λf λs)^ρ ρ)/(-1 + b)) == 0, b] // Simplify      but `Solve` function results to this message > `!Solve::nsmet: This system cannot be solved with the methods available to > Solve. >>{1]` How can I solve this equation?


title: Minimize loop optimization

text: I'm new in _Mathematica_ 10. So far, I have a two variable-function and I've use Minimize to find the optimal solution. Nevertheless, I'd like to make a sensibility analysis and study how this optimal solution behaves, doing a "For" cycle changing some coefficient of this function and keeping all the optimal solution in a table or matrix. Is that possible to do? I've tried using a For cycle but I don't know how to save the optimal value in an auxiliary variable. For instance :               Table[NMinimize[{a x + b y, 0.2 x + 0.1 y >= 14, 0.25 x + 0.6 y >= 30,          0.1 x + 0.15 y >= 10, x >= 0, y >= 0}, {x, y}][[2]], {a, 0, 3, 1}, {b, 0, 3, 1}]      Does anyone one how to save all of the X and Y Values in only 2 columns? I'd like to associate those columns to de corresponding value of a and b


title: How to create a list of variable names to some function of that variable

text: For example, for a single variable I can write               Print[Unevaluated[a], "=", f[a]]      But if I try the next thing I'd think of doing, assuming I want a list, it doesn't work (as intended):               Print[Unevaluated[#], "=", f[#]] & /@ {a, b, c}      This will print the actual value of `a`, instead of "a" itself (i.e. the variable name.) Any thoughts how I can achieve this? -- Edit: To be perfectly clear, I want something like:               {{"a", f[a]}, {"b", f[b]}, ...}      as the output. It tentatively seems to me that this just simply isn't possible (without putting a Hold or similar on every single thing in the list ...), but I hope I'm wrong. -- Another edit: Thanks for the comments; I've almost been able to do what I need. Here's the essential code:               { SymbolName@Unevaluated[#] & /@ Unevaluated /@ Unevaluated@#1,       Distribute[f[#1, #2], List]} & @@        Unevaluated /@ Unevaluated@{{x, b, c}, {x, y}}      with output               {{x,b,c},{f(2,2),f(2,y),f(b,2),f(b,y),f(c,2),f(c,y)}}      Note that I'm only able to print "{x, b, c}" here. I actually would like a tree; i.e.,               {{x,{x,y}},{b,{x,y},{c,{x,y}}, {f(...), ...}      or something that is equivalent in letting my match the input to the output ..., any thoughts? I'm trying this myself but I keep getting stuck with how Unevaluated treats parameters ... (i.e. it's not listable; and Distribute seems to require that, in order to work in the expected way...) (I should note, the only reason I want that tree form is because getting the exact form I asked for initially within the confines of the Distribute and so on seems harder (I couldn't work it out ...).) I don't actually care how it comes out, as long as I can Partition or whatever to get the appropriate structure. -- Final edit: Just incase anyone is interested, here is what I finally went with; it may not be amazingly elegant, but it's sufficient for what I needed. Note that it's actually neccessary to duplicate the expressions into the `Unevaluated` calls (afaik).               fMap = Flatten[Outer[f[#1, #2], A, B, 1]];     n1 = SymbolName@Unevaluated[#] & /@         Unevaluated /@ Unevaluated[{x, b, c, d}];     n2 = SymbolName@Unevaluated[#] & /@         Unevaluated /@ Unevaluated[{x, y, z}];      I can then create the listing I wanted via               Grid[{         grid1 =           Flatten@Insert[n1, ConstantArray["", Length@n2 - 1],             Table[{i + 1}, {i, Range[Length@n1]}]],         grid2 = Flatten@ConstantArray[n2, Length@n1],         fMap         }\[Transpose], Frame -> All];


title: How to extract and replace submatrix of a doubly-periodic matrix?

text: How can I effectively extract and replace a rectangular subpart of a toroidal matrix, i.e. one where boundaries are connected at opposite ends? Since the submatrix can overhang the edges, a simple `Take` won't work, as the submatrix cannot be extracted if it is not continuous. At present, I construct a table of positions that are extracted/replaced via `ReplacePart`, but I feel there must be more elegant and faster solutions. Such answers could add to the usefulness of Elegant operations on matrix rows and columns. Consider the following example:               n = 8; (* matrix edge length *)     m = 4; (* submatrix edge length *)          matrix = Table[0, {n}, {n}];     sub = RandomReal[{.2, 1}, {m, m}]; (* random submatrix *)     pos = {6, 7}; (* position of sub assuming bottom left corner as origo *)          subPos = Table[{i, j}, {i, m}, {j, m}];     repPos = Map[Mod[# + pos - 1, n, 1] &, subPos, {2}]; (* list of positions to extract *)          new = ReplacePart[ReplacePart[matrix, Flatten@MapThread[Rule, {repPos, sub}, 2]], pos -> 2];       (* Replace the explicit list of positions with the elements of sub *)          ArrayPlot[Reverse@Transpose@new,       ColorRules -> {2 -> Pink, 0 -> White}, Mesh -> All, ImageSize -> 300]      ![Mathematica graphics](http://i.stack.imgur.com/Zy3NN.png) Pink cell indicates the origin of the submatrix. **Question** : Can the extraction/replacement done faster, assuming that `matrix` and `sub` could be huge (e.g. 10 000x10 000 and 50x50, respectively)?


title: How can I superimpose points or disks on an image at specified coordinates?

text: I have a TIFF image of 640 x 640 pixels, over which I would like to plot a list of points or disks of small radius. I have been testing different alternatives and I found ImageCompose command.               ImageCompose[image, {Graphics[{PointSize[.009], Black, Point[{0, 0}]}], .6}, {600, 600}]      This places a point at location `{600, 600}` relative to the origin at the left-bottom of the image, but if I set a point close to the right edge of the image, say `{635, 600}`, the point is in the frame but there is no image behind it, because the image is not showing all its pixels. It appears that the first 20-25 pixels of the image and the last 20-25 pixels of the image are invisible. When I tick the image it shows the image at the center of the frame and two blank vertical spaces at right and left of the image. Two questions:   * Does there exist any option or command I could use to show the full image, i.e., the entire 640 x 640 pixels?   * How can I superimpose a list of points (e.g., 40 points) at specified pixel coordinates within the same image.


title: Inserting button in image

text: Can I insert a button in an image at specified location? I have tried but it shows Button is not a graphic function.


title: About extension fibonacci

text: I have been trying to solve this problem, it worked slow. I know there is a efficiently way. How do I get it? The following is my code:               f[{a_, b_, nth_}] := Nest[#~Join~IntegerDigits@Tr[#[[-2 ;;]]] &, {a, b}, nth - 2][[nth]];          f /@ {{1, 1, 2}, {1, 1, 8}, {1, 4, 8}, {1, 5, 10^5 - 1}, {1, 7, 10^5}}      # additional   1. Integer a,b in range 0 to 9,combine them to a string ab   2. Make the last and penultimate number plus then appendto ab repeat 2.,the string can any infinitely expanding. Now we need know what is the nth number. For example: 1,1 ==> 11235813471123... 1,2 ==> 12358134711235... 1,5 ==> 156112358134711... f(1,1,2)=1 f(1,1,8)=3 f(1,4,8)=9 **update** I have got a way, but I feel it's not neat.               f[{a_, b_, n_}] :=       Module[{li, pos, left, repeat},        li = NestWhile[#~Join~IntegerDigits@Tr[#[[-2 ;;]]] &, {a, b},           FreeQ[Partition[#[[;; -2]], 2, 1], #[[-2 ;;]]] &];             pos = Position[Partition[li, 2, 1], li[[-2 ;;]], 1, 1][[1, 1]];        {left, repeat} = {#[[;; pos - 1]], #[[pos ;; -3]]} &@li;        If[n <= Length[left], left[[n]],          repeat[[Mod[n - Length[left], Length[repeat], 1]]]]        ];          f /@ {{1, 1, 2}, {1, 1, 8}, {1, 4, 8}, {1, 5, 10^8 - 1}, {1, 7, 10^8}}


title: A problem about generating `[]` automatically

text: I have using the Wolfram Mathematica for two years.And I know the Mathematica has the operation `Alt + ]` that can generate `[]`. However,when I use this shortcut,it cannot generate a `[]`. So my question is: 1.How to generate the `[]` rightly? 2.In other IDE like `InteljIDEA`,when I key the symbol `[`,it will generate the ` []` automatically. Is it possible to do that in `MMA front-end`? ![enter image description here](http://i.stack.imgur.com/pyyc4.png) ## Edit As @xzczd said,the `Alt +)` will generate ![enter image description here](http://i.stack.imgur.com/XCBXA.png) In adition,it is not convenient to use the `Alt )` and `Alt +}` because I must key three keyboard `Shift + Alt +]`


title: Avoid writing explicit form of operator

text: I would like to evaluate the following (simplified) expression with Mathematica : $\frac{\delta}{\delta J} \exp[(J(x)+K(x)) \Delta (J(x)+K(x))]$ where $\Delta$ is a differential operator independent of $J$, depending on $x$. The thing is, I don't want to write an explicit expression for $\Delta$ since it is not necessary. Is there a way to do that ? I apologise if the question is very basic, but I'm quite new to Mathematica and I have a hard time understanding how it works. Thanks in advance. Edit : here are a few additional details. The operator $\Delta$ is a differential operator of the form $\Box - mˆ{2}$, typical KG but not in a flat metric (if that is helpful for the question). I need to actually compute : $$\exp \left(- \frac{i}{4} J_4 \left(i \frac{\delta}{\delta J} \right)ˆ4 \right) \exp[(J(x)+K(x)) \Delta (J(x)+K(x))] $$ so I thought about expanding the exponential in a sum and apply the sum on the exponential on the right to see if a pattern could be found, in order to get an analytical expression for that. Doing the differentiation by hand is quite long and tedious, so I wanted to see whether Mathematica could help me or not.


title: How can I create a glass distortion effect in an image?

text: I'd like to overlay a glass jar onto an image with realistic light bending. Can anyone think of a way to automate this effect (perhaps this can be done with the raytracing package rayica)? ![enter image description here](http://i.stack.imgur.com/LH11n.png) ![enter image description here](http://i.stack.imgur.com/2KISh.jpg)


title: How do I remove the top bar and bottom bar from the Mathematica window?

text: Any idea how to remove the top bar saying "Wolfram Mathematica .... Demonstrations MathWorld Studenforum Help" from the Mathematica main window (see screenshot). It has no use to me and it steals real estate from my laptop sreen. Also: How do I remove the bottom bar with the zoom button? Appreciate any help! N3rd Edit: Uploaded Screenshot Edit: Added bottom bar question as well... ![frontend](http://i.stack.imgur.com/LePp2.png)


title: Upon opening my notebook, I must evaluate cell for code to work properly

text: I am new to Mathematica. Once I evaluate the cell containing the code, my Manipulate works as desired; however, if I open the file and do not evaluate the cell, the Manipulate goes haywire. Can anyone help please? The code below is all in the same cell.               Sequence1[n_] := { 1 / n, (-1)^n / n, 1 / Sqrt[n] };     Function1[x_] := { ( x - 2 )^2, 2 - x^2, 2^x };          Manipulate[           Grid[ { { "Function" , "Sequence of Outputs" },              { data =           List[Transpose[{Table[ Sequence1[n][[sss]], {n, 1, t}],              Table[ Function1[Sequence1[n][[sss]]][[hhh]], {n, 1, t}]}]];          ListPlot[data, PlotRange -> {{-1, 1}, {0, 5}},           AspectRatio -> 1/1, ImageSize -> Full],               ListPlot[Table[Function1[Sequence1[n][[sss]]][[hhh]], {n, 1, t}],           PlotRange -> Automatic, ImageSize -> Full]},             { "Close-Up" , "Tabular Values" },              { data =           List[Transpose[{Table[ Sequence1[n][[sss]], {n, 1, t}],              Table[ Function1[Sequence1[n][[sss]]][[hhh]], {n, 1, t}]}]];          ListPlot[data, PlotRange -> {{-.1, .1}, {0, 5}},           AspectRatio -> 1/1, ImageSize -> Full]  ,          If[ t < 11,           TableForm[            Transpose[ {Range[1, t],              Table[ Sequence1[n][[sss]], {n, 1, t} ],              Table[Function1[Sequence1[n][[sss]]][[hhh]], {n, 1, t}]}]],           TableForm[           Transpose[ {Range[t - 10, t],              Table[Sequence1[n][[sss]], {n, t - 10, t} ],              Table[Function1[Sequence1[n][[sss]]][[hhh]], {n, t - 10,                t}]}]]]}},            ItemSize -> {{Scaled[.4], Scaled[.4]}}, Frame -> All,        Spacings -> {2, 2}],           {{sss, 3, "sequence"}, {1 -> " 1 / n ", 2 -> " (-1)^n / n ",         3 -> "1 / Sqrt[n] "},        SetterBar}, {{hhh, 3, "f(x)="}, {1 -> "(x-2)^2", 2 -> "2-x^2",         3 -> "2^x"}, SetterBar}, {t, 1, 100, 1}]


title: RootSum result manipulation/simplification

text: Consider the sum               sum1 = Sum[ k/( k^7 - 2 k + 3), {k, Infinity}]      > >     -RootSum[ 2 + 5 #1 + 21 #1^2 + 35 #1^3 + 35 #1^4 + 21 #1^5 + 7 #1^6 + > #1^7 &, >               ( PolyGamma[0, -#1] + PolyGamma[0, -#1] #1)/( 5 + 42 #1 + 105 > #1^2 + 140 #1^3 >                  + 105 #1^4 + 42 #1^5 + 7 #1^6)& ] >   Back in the day of `Mathematica 3.0` this same sum gave               sum2 = RootSum[( 3 - 2 #1 + #1^7) & , -(( PolyGamma[0, -#1] #1)/(-2 + 7 #1^6))& ]      > >     -RootSum[ 3 - 2 #1 + #1^7 &, ( PolyGamma[0, -#1] #1)/(-2 + 7 #1^6)& ] >   They are numerically equal               (sum1 - sum2) // N // Chop      > >     0 >     * Are the two RootSum expressions equivalent? and If so:   * How do I manipulate/simplify sum1 result to the simpler form of sum2?   * Why is the current result more complicated?


title: Build tabular like Wolfram Tutorial Collections

text: In **Wolfram Tutorial Collections** ,I see many tabular shown as below: ![enter image description here](http://i.stack.imgur.com/eGyJ4.png) ## My Trial **Firstly,I copy the tabular template from the WRI** ![enter image description here](http://i.stack.imgur.com/64Ht9.png) http://www.mathematica- journal.com/data/uploads/2010/09/TMJ_AuthorTemplate_v10.nb **Secondly, I can achieve the result :** ![enter image description here](http://i.stack.imgur.com/7BOuV.png) However,I cannot achieve the effect that shown. **So my question is :** **how to achieve same tabular like`Wolfram Tutorial Collections`?** ## Feeling @eldo I think use the code to generate is inconvenient.


title: Why has my syntax coloring changed?

text: Local variables in `Module` are no longer specially colored for me, but other syntax coloring remains, for example iterators in a `Table`: ![enter image description here](http://i.stack.imgur.com/efW6M.png) What causes this? How can I restore the original syntax coloring behavior? The altered behavior has persisted across hundreds of rebootings and new notebooks. And the preference for "local variables of Module and With" is correctly set, but shows the incorrect behavior in the example: ![enter image description here](http://i.stack.imgur.com/cMz1v.png) Resetting to defaults does not restore order. Changing the color to something different also has no effect. Restarting after clearing the `init.m` file using:               RenameFile["~/Library/Mathematica/FrontEnd/init.m", "~/Library/Mathematica/FrontEnd/init.m_Backup"]      also does not change the behavior.


title: Nminimize fails claiming not a number value, even with _?NumericQ

text: I have the following function to minimize for `a > 0`               f[a_?NumericQ] := Log[ Exp[ (a^2) * 6.47368e-07 + 0] +                             Exp[ (a^2) * 7.44746e-06 + 0] +                            Exp[ (a^2) * 8.59531e-07 + 0]] /a      `NMinimize` gives me:               NMinimize[{f[a], a > 0}, a]      > >     Minimize::nnum: -7 + 0.0541561 e    -6 + 0.0623024 e >     The function value 10.9333 Log[E + E -7 + 0.0719048 e ] is not a number >     at {a} = {0.0914636}. >   The error happens even without `?NumericQ`, but I found that specifying it could have helped, but not in this case. Given that I'm a complete beginner with _Mathematica_ , I'd love some hints about what I'm doing wrong and how to fix it.


title: Coordinates for multiple countries

text: I am trying to plot polygons for multiple countries, say `"UnitedStates"` and `"Canada"`. US data is generated thus:               coordsUS = CountryData["UnitedStates", "Coordinates"]      and Canadian data thus:               coordsCanada = CountryData["Canada", "Coordinates"]      I want to pass the combination of these two lists into the routines on this page. I cannot figure out how to combine these two lists into a single list of the same structure. The structure is:               {{{a,b},{c,d},{e,f}}}      I know how to combine lists of the following form:               {{a,b},{c,d},{e,f}}       but the extra depth is confounding me. I try putting the latter into a list thus:               l = {{a,b},{c,d},{e,f}}      z = {l}      but that does not work. `AppendTo` does not work either. Help is appreciated. Thanks! -Tony


title: Is it possible to use infix notation ~ for functions with one argument or more than 2 arguments?

text: According to a Mathematica textbook, we can write `N[x,n]` by using infix notation as `x ~ N ~ n`. How about other functions with one argument or more than 2 arguments, is it possible?


title: How can I add a background to a stylesheet?

text: In version 9 we can set the background to an image, however I'd like to save this into a stylesheet that can be installed.


title: How to turn a random graph into a matrix

text: I have constructed a random graph with Mathematica using the `RandomGraph` command. Now I would like to convert this graph to a matrix, but I don't know how. The command `//MatrixForm` just shows the same with "//MatrixForm" so that doesn't help to much either.


title: Texture mapping and resizing a sphere primitive in Mathematica

text: **Background Info** In Mathematica, it's only possible to texture map a sphere through the use of `SphericalPlot3D` or `ParametricPlot3D`.               image = Import["MyTexture.jpg"]; (* Pretend this is something you'd use *)          sphere = SphericalPlot3D[1, {theta, 0, Pi}, {phi, 0, 2 Pi},       Mesh -> None, TextureCoordinateFunction -> ({#5, 1 - #4} &),      PlotStyle -> Directive[Texture[image]],      Lighting -> "Neutral", Axes -> False, Boxed -> False];      Now that's all nice and everything. But what if we want multiple spheres on the same exact image, each with an arbitrary size? To position a single sphere is simple:               s1 = Graphics3D[      Translate[First@sphere, {3, 2, 1}],      Lighting -> "Neutral"]      Then you just position each sphere and `Show` them together:               Show[{s1, s2}, PlotRange->{{-5, +5}, {-5, +5}, {-5, +5}}]      * * * **The Issue** That's great and all, but **what if you need each sphere to be a distinct size**? Positioning and sizing regular `Sphere[]` primitives is easy and built directly into their definition. But if I want the same for a _textured_ sphere, I have to jump through all these hoops. Furthermore, it's not obvious how I can achieve this. Any ideas on how I can achieve arbitrary placement and sizing of _textured_ spheres?


title: Optimizing a simple calculus using a list of matrices - Repeated dot product between a vector and a list of matrices

text: I want to make the following operation : $$ \begin{bmatrix} \dot q_1\\\dot q_2 \end{bmatrix} + \begin{bmatrix} \begin{bmatrix} q_1 & q_2 \end{bmatrix} \mathbf A_1 \begin{bmatrix} q_1\\ q_2 \end{bmatrix} \\ \begin{bmatrix} q_1 & q_2 \end{bmatrix} \mathbf A_2 \begin{bmatrix} q_1\\ q_2 \end{bmatrix} \end{bmatrix} = \begin{bmatrix} \dot q_1\\\dot q_2 \end{bmatrix} + \begin{bmatrix} \begin{bmatrix} q_1 & q_2 \end{bmatrix} \begin{bmatrix} 0&1\\ 1&1 \end{bmatrix} \begin{bmatrix} q_1\\ q_2 \end{bmatrix} \\ \begin{bmatrix} q_1 & q_2 \end{bmatrix} \begin{bmatrix} -1&0\\ 0&0 \end{bmatrix} \begin{bmatrix} q_1\\ q_2 \end{bmatrix} \end{bmatrix} = \begin{bmatrix} \dot q_1\\\dot q_2 \end{bmatrix} + \begin{bmatrix} {q_1}^2 + q_2(q_1+q_2)\\ -{q_1}^2 \end{bmatrix}$$ I also want to put the two $\mathbf A_1$ and $\mathbf A_2$ matrices inside a list of matrices `A` in mathematica. So I started creating my list of matrices `A` and did the following :               A={{{0, 1}, {1, 1}},{{-1, 0}, {0, 0}}};     res={{q1, q2}.A[[1]].{q1, q2},{q1, q2}.A[[2]].{q1, q2}};     final={q1p,q2p}+res;      Now, my question : is there a way to optimize the calculation of `res`? The goal is to avoid calling `A[[1]]` and `A[[2]]` independently each time. The perspective is to extend the `A` list to a list of dimension $n \gt 2$ (something like this) : $$ \begin{bmatrix} \dot q_1\\\dot q_2 \\ \vdots \\ \dot q_n \end{bmatrix} + \begin{bmatrix} \begin{bmatrix} q_1 & q_2 & \cdots & q_n\end{bmatrix} \mathbf A_1 \begin{bmatrix} q_1\\ q_2 \\ \vdots \\ \dot q_n \end{bmatrix} \\ \begin{bmatrix} q_1 & q_2 & \cdots & q_n \end{bmatrix} \mathbf A_2 \begin{bmatrix} q_1\\ q_2 \\ \vdots \\ \dot q_n \end{bmatrix} \\ \vdots \\ \begin{bmatrix} q_1 & q_2 & \cdots & q_n \end{bmatrix} \mathbf A_n \begin{bmatrix} q_1\\ q_2 \\ \vdots \\ q_n \end{bmatrix} \end{bmatrix}$$


title: Using mouse back/forward buttons in Mathematica's help system

text: I have a generic mouse with back/forward buttons. Those buttons are recognized by the system - I can use `xev` to see that they generate events for buttons number 8 and 9. I am so used to using them for web browsing, that I sometimes end up pressing them when I'm browsing through Mathematica's help system. Is there some way to bind those buttons to the back/forward functions in the help system? I looked around in the settings but haven't found anything. I'm using Mathematica 8.0 in Linux, if this is relevant. Any ideas?


title: ToDiscreteTimeModel fails following video

text: Following the systems-modeling video here at about 15 min, 20 seconds in, the presenter (Bob Sanhedrick, I think) shows a model for an "Asteroids-game"-like 2D spacecraft. The model is trivial:               dynamics = {m x''[t] == u1[t], m y''[t] == u2[t]}      or, in state-space form:               spacecraft = StateSpaceModel[       dynamics,        {x[t], y[t]},       {u1[t], u2[t]},       {x[t], y[t]},       t]      > >     {{{0, 1, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 1}, {0, 0, 0, 0}}, >      {{0, 0}, {1/m, 0}, {0, 0}, {0, 1/m}}, >      {{1, 0, 0, 0}, {0, 0, 1, 0}}, >      {{0, 0}, {0, 0}}} >   The next step is converting it to a discrete-time model (15:52 in the video):               spacecraftD = ToDiscreteTimeModel[spacecraft, 1, Method -> "ZeroOrderHold"]      This fails (even in the downloaded copy of the video's notebook -- it's not my typo): > >     During evaluation of In[3]:= General::ivar: 0 is not a valid variable. > >> >     During evaluation of In[3]:= General::ivar: 0 is not a valid variable. > >> >     StateSpaceModel[{ >       {{1, 1, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 1}, {0, 0, 0, 1}}, >       {{1/(2 m), 0}, {1/m, 0}, {0, 1/(2 m)}, {0, 1/m}}, >       {{1, 0, 0, 0}, {0, 0, 1, 0}}, {{0, 0}, {0, 0}}, >       Automatic}, >       $Failed, >       {\[FormalK]}, >       SamplingPeriod -> 1] >   Fortunately, I can copy out the failed model explicitly, leaving out the `Automatic`, and reproduce the rest of the demonstration verbatim: ![enter image description here](http://i.stack.imgur.com/mDtz4.png) The question is "why did this fail, and what can I do to fix it." I read the documentation for `TransferFunctionModel` and tried a number of hacks, to no avail. I'd like to know this so that as I go to more advanced models I don't get stuck with something that doesn't have so obvious a workaround.


title: How to draw a plane parallel to one of the coordinate planes?

text: Sorry for the fact that I ask actually the same question on three different stackexchange sites (stackoverflow, mathematics and now here), but I need to find an answer to my problem as quickly as possible. The question is how to draw a 3D plot of functions: $$ y + 5 = 0 \\ x + 2y = 0 $$ The first one is a plane parallel to the $oxz$ plane. If anyone has an answer to this, please provide some explanation, not just `Plot3d[y + 5, {x, -20, 20}, ...]`. Thank you.


title: LF line break instead of CR+LF when exporting text files on Windows

text: I want my program to always save a text file with unix-style `LF` line breaks (even when _Mathematica_ runs on Windows). But the way the built-in `Export` command works depends on the operating system. For example the following code:               testFile = "newlinetest.txt";     testStringList = {"abc", "abc"};     Export[testFile, testStringList, "List"];     BinaryReadList[testFile]      Linux or Mac OS gives exactly what I want: > {97, 98, 99, 10, 97, 98, 99} Windows adds an extra `CR` symbol: > {97, 98, 99, **13** , 10, 97, 98, 99} Is there a normal way to save text files with unix-style newline on Windows?


title: ListPlot with high precision

text: I have a list of numbers, e.g. `{{1.,0``27.698970004336022},{2.,0``27.698970004336015}}` but usually much longer, suitable for `ListPlot`. `ListPlot` however does not display anything, even if I reduce `PlotRange` manually. Obviously the numbers are too small for `ListPlot`. The numbers do indeed represent only noise, the relative deviation of two numerical computations at different precision. I do this because I want a visual ipression of the numerical error of a computation depending on one parameter. Can I give an argument to `ListPlot` or similar in order to force it to display the small numbers and, if not, how can I compactly multiply the second elements in the list by a suitable number to scale the plot range to `0...1`?


title: Composition of functions using slots

text: Apolgies if this has been asked and answered, but I'm not even sure what to search for. I have two functions defined as follows:               F[n_]:=Max[Select[Divisors[n],#<=Sqrt[n]&]];     P[n_] := Select[Range[1, 1000], F[#] == n &];      I have two questions:   1. I have read the _Mathematica_ help page on the `#` symbol, and I think I understand most of that. I do not, however, understand what `#` and `&` do in this specific context.   2. How can I write `P[n_ ]` using a single line of code? It doesn't work if I simply copy and paste the definition for F into the definition of P:              P[n_] := Select[ Range[1, 1000], Max[Select[Divisors[n],#<=Sqrt[n]&]] == n &]


title: Mathematica 10 crashes on copy/paste

text: Mathematica 10 crashes in the following (simple) situation:               FormulaLookup["gas"]      This command will produce a long list of possible formulas. Then I type the following command below the list (and not run it)               FormulaData[]      When I copy one of the formulas produced by the FormulaLookup command and paste it in the square brackets of the FormulaData command Mathematica crasches. It happens only if the formula list is very long (as in looking for "gas") and not always but almost always. Can someone check if that's a Mathematica bug or some specific problem with my machine? (I'm on windows 8.1).