title: How to keep PlotLegend expressions on top of each others even when placed at Bottom?

text: Version 9. When writing               Plot[{Sin[x], Cos[x]}, {x, -2 Pi, 2 Pi},       PlotLegends -> Placed[TraditionalForm /@ {Sin[x], Cos[x]}, Right]]      The result is ![enter image description here](http://i.stack.imgur.com/WBBuW.png) Now I'd like to put the legend below the plot, but at the same time keep them looking the same way. i.e. `sin(x)` on top and `cos(x)` below. I do not want them to flatten. But when I do               Plot[{Sin[x], Cos[x]}, {x, -2 Pi, 2 Pi},       PlotLegends -> Placed[TraditionalForm /@ {Sin[x], Cos[x]}, Bottom]]      The result is ![enter image description here](http://i.stack.imgur.com/Wd2Jb.png) I can't use Grid or such to format these myself in the way I like them, since if I do, then `PlotLegend` will not see them any more. i.e. I can't just write something like               Plot[{Sin[x], Cos[x]}, {x, -2 Pi, 2 Pi},       PlotLegends -> Placed[ Column[{Sin[x], Cos[x]}], Bottom]]      ![enter image description here](http://i.stack.imgur.com/ilC2T.png) Any one knows of a trick to do this? I looked at options for PlotLegend but do not see anything right away.


title: What is the most elegant way to specifiy a start case for recursion?

text: When writing recursive code that computes the least value at which a condition is true and various other scenarios it is often necessary to specify a base case. What I have done to supply this is create a function parameter that must always have the specified base case passed into it: `least2nbigger[x_, n_] := If[2^n >= x, 2^n, least2nbigger[x, 1 + n]]` This is used with a structure like `least2nbigger[4097, 1]` Where the 1 is the start value for the recursion. x is the only parameter of interest to someone using the function; n is always to be passed as 1. In SML I would do something like this:               fun least2nbigger x = least2nbigger (x, 1)     |   least2nbigger (x, n) =     let         p = pow (2, n)     in         if p > x then p          else least2nbigger (x, n+1)         end;      (My SML is a bit rusty, that might not be entirely valid but the idea is clear). There is an alternative definition provided for the recursive case; the function can be called without the tuple. The only way I see to do this in Mathematica would be to make two functions, the recursive case and a dummy function that calls the recursive case with is base parameter. Is there a better way to accomplish this?


title: ParametricNDSolve: Parameter inside UnitStep leads to longer integration times

text: I have found one of the most annoying issues in ParametricNDSolve. When a parameters occurs inside UnitStep (and Piecewise and If) the integration takes much longer time. I illustrate this by an easy example First, create two identical systems with an infusion running for 100 time units. In the first system we set the value of the infusion time and in the second system this parameter value will be set later on to the same value.               sys1 = {x'[t] == RATE*UnitStep[100 - t], x[0] == 0};     sys2 = {x'[t] == RATE*UnitStep[tInf - t], x[0] == 0};     vars = {x};      Create two ParametricNDSolve objects:               p1 = First@     ParametricNDSolve[sys1, vars, {t, 0, 200}, {RATE},      Method -> {"ParametricSensitivity" -> None,        "ParametricCaching" -> None}];     p2 = First@     ParametricNDSolve[sys2, vars, {t, 0, 200}, {RATE, tInf},      Method -> {"ParametricSensitivity" -> None,        "ParametricCaching" -> None}];      Now we crete a large set of of random parameter values for the parameter RATE.               runs = 10000;     rvs = RandomReal[{0, 1}, runs];      Solve the first system (with only one parameter) a large number of times and take the time.               AbsoluteTiming[Do[x[rvs[[i]]] /. p1, {i, runs}]]          {1.546088, Null}      Solve the second system, with parameters RATE and tInf where tInf=100, a large number of times and take the time.               AbsoluteTiming[Do[x[rvs[[i]], 100] /. p2, {i, runs}]]          {9.052518, Null}       The second systems take approximately 6x longer to solve. What is going on here? There might be a large issue here with the ParametricNDSolve environment.


title: NotebookWrite undo

text: Is there way to make `NotebookWrite`s undooable? For example let's say I open a new notebook and then run.               NotebookWrite[EvaluationNotebook[], Cell["New content", "Subsection"]]      Is there way to make the text above then dissapear when I hit `Ctrl`+`z`.


title: neighbor swapping distance between two strings

text: **Updated Problem Description** I have a collection of strings $S$ that only contain two (or $m$ in general) kinds of elements: in this case C and D. For all $s\in S$, the length is the same, the number of C is the same (and so does the number of D). For instance consider the following two strings: CCDCDCDCDCDCDCDCDCDCDCDCDCDCDCDD and CDCDCCDCDCDCDDCDCDCDCDCDCDCDCDCD. They have the same number of characters, the same number of C and D. Could anyone suggest how can I count the minimum number of neighbor swappings needed to transform from the 1st string to the 2nd string in Mathematica? **Information that is irrelevant to the problem itself** : I am doing this to compare how close the best candidate solution obtained by a problem-specific genetic algorithm to the real optimal solution. You are welcome to suggest other measures of "closeness". **Update 1** : There is not periodic boundary condition in my problem. I do not treat the string as necklace. **Update 2** : In the comments, @Stephen mentioned Kendall tau distance, but I'm not sure whether it applies to my problem considering that there is no order relation between C and D and so many characters in the string are the same one, i.e. there are so many C in one string.


title: Generating an "average curve" from a dense set of "semicontinuous curves" which clear trends

text: This question is related to a previous one of mine: Partitioning a superset of coordinates into subsets that generate continuous curves, where the challenge was to partition a data set into two clusters representing distinct "semicontinuous curves" (we mean this in the loose sense that a ListPlot generated two curves that by eye appeared to be continuous). The user rm -rf illustrated and demonstrated that FindClusters could very nice solve the problem using a Euclidean distance metric (a hat tip also to g3kk0 who elaborated on this approach). My question here is how one would approach a much more pathological case, where we have multiple closely spaced curves, displaced some amount vertically, and we would like to generate an "average" curve that represents a sort of average for the shape of all the semicontinuous curves. Take a look at the following plots (data uploaded to: https://www.dropbox.com/sh/751invayqe3ip9b/r6raIrdvLF): Plot A: ![enter image description here](http://i.stack.imgur.com/RvgFN.png) Plot B: ![enter image description here](http://i.stack.imgur.com/9zilo.png) In both cases, we can more or less clearly make out by eye what the shape of each semicontinuous curve looks like. For example, take the following "hand drawn" traces of two semicontinuous curves in Plot B: ![enter image description here](http://i.stack.imgur.com/Heggt.png) While it may not be possible to separate the data sets for Plot A and Plot B into clusters that represent each of these semicontinuous curves (I'd love to be corrected on this point), how can we automatically generate a sort of "average curve" that follows the trend for each of the semicontinuous curves? Update: In reponse to rm -rf's comment, if we take a similar data set to Plot B and bin along the X-axis and then compute a mean for each bin (computing the median generates a similar result), the resulting plot looks like this: ![enter image description here](http://i.stack.imgur.com/btBP5.png) My explanation for this is that we cannot "see" (i.e. we do not have access to) all of the semicontinuous curves in the plot. A peak in the set of curves may cause additional curves to appear near the bottom of the plot (see the $X \approx 5000$ to $8000$ region in Plot B), and vice versa. * * * Update 2: If we connect all points within some small cutoff distance $T$ (perhaps $T = 1$ here), generating a random geometric graph, perhaps we could look at the angle of the edges connecting the points / vertices? This shouldn't be affected very much by the presence of peaks or troughs of curves at the bottom and top of the plot, respectively. * * * Update 3: Provided that the data here is generally periodic along the $y$-axis, it might be reasonable to treat the surface as if it it curves around on itself like a tube (where the x-axis is the long-axis of the tube, and the curvature occurs along the y-axis).


title: HornerForm of polynomials in terms of E^(i x)

text: I want to know how to get the `HornerForm` of the following expression in terms of `E^(I x)`:                E^(I x) + 2 E^(2 I x) + 3 E^(3 I x) + 4 E^(4 I x) + 5 E^(5 I x) +           6 E^(6 I x) + 7 E^(7 I x) + 8 E^(8 I x) + 9 E^(9 I x) + 10 E^(10 I x)      `HornerForm[ expr, E^(I x)]` doesn't work as well as something like `Collect[ expr, E^(I x]]`.   How can I get the desired form?


title: InverseFunction oddity

text: InverseFunction[ConditionalExpression[#, 0 <= # <= 1] &]     InverseFunction[ConditionalExpression[#, -1 <= # <= 1] &]      The first line produces what I would expect:               ConditionalExpression[#1, 0 <= #1 <= 1] &      But when I make the lower limit in `ConditionalExpression` negative, the inequalities become strict:               ConditionalExpression[#1, -1 < #1 < 1] &      Why is this happening?


title: Torus triangulation

text: I'd like to plot something similar to this but with a triangle instead of a pentagon. Also, I'd like to triangulate the faces, that is, to insert the diagonals for each face of the 3 prisms used. In fact, I'd like to plot the minimal simplicial complex for the torus. I tried to compute the vertices to use some polygon plot3d function but no progress. Sorry. ![enter image description here](http://i.stack.imgur.com/87swL.gif) **Edit:** Here is the code I have. I'm trying to see the 3 cycles to determine the faces. The problem is that they are not equilateral triangle.               pic3 = Graphics3D[{Green,         Polygon[{{0, -1, Sqrt[3] - 1}, {1, -1 - Sqrt[3],            Sqrt[3] - 2}, {-1, -1 - Sqrt[3], Sqrt[3] - 2}}]}];      pic2 = Graphics3D[{Pink,         Polygon[{{0, 0, 1}, {1, 0, Sqrt[3]}, {-1, 0, Sqrt[3]}}]}];     pic1 = Graphics3D[{Blue,          Polygon[{{0, 1, Sqrt[3] - 1}, {1, 1 + Sqrt[3], Sqrt[3] - 2},                   {-1, 1 + Sqrt[3], Sqrt[3] - 2}}]}];      ![enter image description here](http://i.stack.imgur.com/GDKeU.gif) **Edit 2:** Using some rotation transformation, I defined some points and rotated them to produce another triangles. The code below produces a better result. Now I'd like to make it fancier, maybe with transparent or glass style.               triang1 = {{0, 0, 1}, {1, 0, 1 + Sqrt[3]}, {-1, 0, 1 + Sqrt[3]}};     triang2 = RotationTransform[2 Pi/3, {1, 0, 0}, {0, 0, 0}][triang1];     triang3 = RotationTransform[4 Pi/3, {1, 0, 0}, {0, 0, 0}][triang1];          pic1 = Graphics3D[{Blue, Polygon[triang1]}];     pic2 = Graphics3D[{Red, Polygon[triang2]}];     pic3 = Graphics3D[{Green, Polygon[triang3]}];          trapez1 = {triang1[[1]], triang2[[1]], triang2[[2]], triang1[[2]]};     Gtrapez1 = Graphics3D[{Yellow, Polygon[trapez1]}];     trapez2 = {triang1[[1]], triang3[[1]], triang3[[2]], triang1[[2]]};     Gtrapez2 = Graphics3D[{Yellow, Polygon[trapez2]}];     trapez3 = {triang3[[1]], triang2[[1]], triang2[[2]], triang3[[2]]};     Gtrapez3 = Graphics3D[{Yellow, Polygon[trapez3]}];     trapez4 = {triang1[[1]], triang2[[1]], triang2[[3]], triang1[[3]]};     Gtrapez4 = Graphics3D[{Yellow, Polygon[trapez4]}];     trapez5 = {triang1[[1]], triang3[[1]], triang3[[3]], triang1[[3]]};     Gtrapez5 = Graphics3D[{Yellow, Polygon[trapez5]}];     trapez6 = {triang3[[1]], triang2[[1]], triang2[[3]], triang3[[3]]};     Gtrapez6 = Graphics3D[{Yellow, Polygon[trapez6]}];          Show[Gtrapez6, Gtrapez5, Gtrapez4, Gtrapez3, Gtrapez2, Gtrapez1,          pic1, pic2, pic3, Boxed -> False, AspectRatio -> Automatic]      ![enter image description here](http://i.stack.imgur.com/LAN3s.gif)


title: To inscribe a circle in a given triangle

text: I am trying to to inscribe a circle in a given triangle but it isn't working. I've used GeoGebra with this construction and worked but as I'm new to Mathematica I am missing something. It can't be so complex to do. Here is my code:               pA = {0, 0}; pB = {1.1, 1}; pC = {1.5, 0};          midAB = (pA + pB)/2; midBC = (pB + pC)/2; midAC = (pA + pC)/2;          myT = Triangle[{pA, pB, pC}];          centerC = (midAB + midBC + midAC)/3          raioC = Last[centerC]          Graphics[{EdgeForm[Directive[Thick, Blue]], White,        myT, {PointSize[Large], Red, Point[midBC]}, {PointSize[Large], Red,         Point[pA]},       {Orange, Line[{pA, midBC}]},       {Orange, Line[{pB, midAC}]},       {Orange, Line[{pC, midAB}]},       {Red, Circle[centerC, Last[centerC]]},       }, AspectRatio -> Automatic, PlotRange -> All]           I understand that I'm not doing right the radius of the circle but I've tried more than one way to do that. Here is the original (book) construction: To construct: The circle inscribed in ^ABC Construction: Construct the bisectors of two of the angles of ^ABC. Their intersection is the center of the required circle, and the distance (perpendicular) to any side is the radius. (Any point on the bisector of an angle is equidistant from the sides of the angle.) As I said, it worked in GeoGebra and it is almost working with my code. Thank you for any help.


title: How to create a large sparse block matrix

text: I need to generate a very large sparse block matrix, with blocks consisting only of ones along the diagonal. I have tried several ways of doing this, but I seem to always run out of memory. The fastest way of doing this that I've come up with so far is as follows: (typically, I will need `n` to be at least 2500 and m of the order 50).               tmp= SparseArray[{}, {n,n}, 1];          SparseArray@      ArrayFlatten@       Table[If[i == j, tmp, 0], {i, m}, {j, m}]      Example when n=2, m=4: ![Matrix](http://i.stack.imgur.com/PIpvo.png) The problem with this construction is that `ArrayFlatten` for some reason converts the result to a normal matrix, and I run out of memory. That is, when it works, this code computes the end result very quickly and the result does not take up much memory. At some specific number however, it suddenly crashes as the intermediate `ArrayFlatten` step clogs up the memory. Any help will be greatly appreciated!


title: How to obtain a complete list of WordData's "Properties"?

text: Command `WordData["Word", "Properties"]` seems have an endless list of properties, such as : `"Definitions"`, `"PartsOfSpeech"`, `"Definitions"`, `"Examples"`, `"Synonyms"`, `"Antonyms"`, `"BroaderTerms"`, `"NarrowerTerms"`, `"ConceptWeight"`, `"BritishSpelling"`, `"AmericanSpelling"`... Is it possible obtain a complete list of it?


title: How can estimate the PSF function to deblur an image of plate licence of a car

text: I want to deblur a blurred image of a plate licence of a car. I need to deblured it. I have used the ImageDeconvolve[] function and Sharpen but the problem is still difficult because I need to estimate the kernel or the PSF function. A lot of techniques have been used to estimate the PSF. I wondered How the Fourier transform of the blurred image can gives us an idea about the PSF function. Any help?               psfMotion[dim_?NumberQ, theta_?NumberQ] :=       Module[{PSF},         PSF = ConstantArray[0.0, {dim, dim}];         PSF[[Ceiling[dim / 2.0], All]] = 1.0 / dim;         Return[ImageRotate[Image[PSF], theta  Degree]];        ];     psf = psfMotion[14, 0];     Table[ImageDeconvolve[licence, psfMotion[2, \[Theta]],        Method -> "RichardsonLucy", MaxIterations -> 15], {\[Theta], 0,        180}]      Image: ![enter image description here](http://i.stack.imgur.com/2HYeW.png) licence ![enter image description here](http://i.stack.imgur.com/qkXP2.png)


title: Stochastic Simulation using the Gillespie algorithm

text: I'm trying to reproduce the simulation with demographic stochasticity in Figure 1 from the paper entitled "Dynamical Resonance Can Account For Seasonality of Influenza Epidemics" (http://www.pnas.org/content/101/48/16915.full). My code works just fine when $t$ is small $(0<t<0.02)$, but when I increase the value of $t$ (as below), the simulation doesn't finish compiling. Thus, I'm wondering if there's an issue with my code. Ideally, I would like my code to function when $(10<t<20)$ so I can compare my results to the paper. Any input would be greatly appreciated.               Clear[S, Infe, R, No, b0, b1, b, t, Ro, d, L, event, fun, main, list1, list2, data]      No = 500000;      b0 = 500;      b1 = 0.04;      d = 0.02;      L = 4;      list1 = {};      list2 = {};      b[t_] := b0 *(1 + b1* Cos[2 Pi t]);      main[] := Module[{S = 499999, Infe = 1, R = 0, t = 0},      While[t < .03 && Infe > 0, {S, Infe, R, t} = fun[S, Infe, R, t];     AppendTo[list1, Infe]; AppendTo[list2, t] ]];          fun[S0_, Infe0_, R0_, t0_] :=      Module[ {S = S0, Infe = Infe0, R = R0, t = t0},      TransRate = (b[t]*S*Infe)/No;      RecoveryRate = Infe/d;      ImmunityLoss = (No - S - Infe)/L;      TotalRate = TransRate + RecoveryRate + ImmunityLoss;           t = t + RandomReal[ExponentialDistribution[TotalRate]];      event = RandomReal[UniformDistribution[]];           If[event < TransRate/TotalRate,      S = S - 1 ; Infe = Infe + 1,      If[event < (TransRate + RecoveryRate)/TotalRate,      Infe = Infe - 1 ; R = R + 1, R = R - 1 ; S = S + 1]];      {S, Infe, R, t}         ]          main[]      data = Transpose@{list2, list1};     ListPlot[data]


title: Plotting partial sums of Fourier sine series

text: How do I plot this on Mathematica version 5.2? $\frac{4}{\pi} \sin{x} + \frac{4}{3 \pi} \sin{3 x} + \cdots + \frac{4}{(2 N+1) \pi} \sin{(2 N+1) x}$ over $x \in [-\pi,\pi]$ for $N= 3, 6, 12, 24$. I tried and got this error: ![enter image description here](http://i.stack.imgur.com/ju3UT.jpg)


title: Check if a scalar falls within the range given by sub-arrays of a matrix

text: I have a rank 3 matrix:               r = {{{1, 10}, {19, 71}, {111, 159}}, {{1, 5}, {25, 63}, {118, 132}, {164, 185}}, {{1, 19}, {28, 49}, {157, 203}}};      and each of the sub-arrays above represents a range. No two sub-arrays in a given row has any overlap. I want to check if given `i` of `r[[i]]` and a scalar `x`, I want to check if any of the sub-arrays have `x` within their range. e.g. if `i =2` and `x=175` is TRUE because `{164,185}` has it, but `x=75` is FALSE since none of the `{1, 5}, {25, 63}, {118, 132}, {164, 185}` has it. I do not want to use `MapThread` and use compilable functions, `UnitStep` if possible.


title: Avoid trigonometric simplifications?

text: When evaluating the expression               Sinh[x]^2 + Cosh[x]^2 // FullSimplify      I get               Cosh[2 x]      That is indeed a simplification, but there are cases when I would not want that to happen. What if I have a much more complicated expression that I want to simplify generally, but still wish to stay in `Sinh[x]^2` and `Cosh[x]^2`. So under no circumstances do I wish to change to `Cosh[2 x]` or similar expressions. Is there a way to explicitly tell Mathematica **not** to use trigonometric relations? Or to use the trivial `Cosh[x]^2 - Sinh[x]^2 = 1` but none of the composed ones? Preferably, maybe there is a switch that disables the sensitivity of _Mathematica_ to trigonometric relations in an entire notebook?


title: Third syntax version of LogitModelFit: unexpected result of "BestFit"

text: The third listed syntax version of `LogitModelFit` allows one to specify input in a simple way: Only a design matrix (with a row of values of the explanatory input variables for each of the output values) and a response vector are needed. The following example is straight from the `LogitModelFit` help page:               dm = {{1, 1}, {1, 2}, {1, 3}, {1, 4}};     resp = {0, 1, 0, 1};     model = LogitModelFit[{dm, resp}]      ![Mathematica graphics](http://i.stack.imgur.com/ygo8s.png) As usual in these types of fits, Mathematica returns an object that can be interrogated with various methods. In this case, I just want to have the best fit:               model["BestFit"]      ![Mathematica graphics](http://i.stack.imgur.com/JXCUt.png) I noted something here that I feel is strange. Although this looks like a pure function (which is what I expected, given no formal variable names are specified in this syntax), it really isn't, since the required `&` at the end is missing. Hence, a construction like `model["BestFit"][1,2]` doesn't work. Is this a bug, or is this useful in some way and am I missing something? I note that neither the `"Function"` method of `LogitModelFit` nor something like `model//Normal` yields anything useful. The former generates an error which suggests to me that there is indeed a bug in this syntax variant. The latter returns the same as `"BestFit"`. My workaround for now is to use:               mod = model["BestFit"] // Evaluate // Function;      (`Evaluate` because of the `HoldAll` attribute of function)               mod[1, 2]      > 0.3883882668


title: Exp is slower for some number ranges

text: I get a hit on performance with the `Exp` function depending on the range of my inputs. for example, with:               w1 = RandomComplex[-20000 I, {10000000}];     Exp[w1]; // Timing          w2 = RandomComplex[-20 I, {10000000}];     Exp[w2]; // Timing      Results in 2.4 and 0.4 sec respectively. What mystifies me is that the involved numbers are not in a numerically "interesting" range. The transition to slower times starts gradually at about `-500 I` and asymptotically stabilizes by about `-10000 I`. Past these ranges the timings are stable:               w = RandomComplex[-I, {1000000}];     t = Table[{10^n, Timing[Exp[10^n w]][[1]]}, {n, 1.5, 5, .01}];     ListLogLinearPlot[t, AxesLabel -> {"Scaling", "Time"}]      ![](http://i.stack.imgur.com/fYrA4.png) Any ideas what might be happening here? Any simple fixes to get faster performance with high scaling factors?


title: Using NETLink.MathKernel.Compute() for graphics results fails with GraphPlot[]

text: I'm using MMA 8.0 to provide backend on a .NET application I'm writing. I am trying to use the high-level `Wolfram.NETLink.MathKernel` interface to export an image created with GraphPlot[]. Although the Result comes back as '-Graphics-', I find that Graphics[] is empty. Changing the Compute() to another graphic generating command returns an image in the Graphic[] as expected. Here's my example code:               Wolfram.NETLink.IKernelLink _iKernelLink;          string cmdLine = "-linkmode launch -linkname \"C:/Program Files/Wolfram Research/Mathematica/8.0/MathKernel.exe\"";     _iKernelLink = Wolfram.NETLink.MathLinkFactory.CreateKernelLink(cmdLine);     _iKernelLink.WaitAndDiscardAnswer();          var k = new Wolfram.NETLink.MathKernel(_iKernelLink); // new MathKernel          k.AutoCloseLink = true; // close link when object is disposed     k.CaptureGraphics = true; // capture graphics output     k.CapturePrint = true; // capture print output     k.CaptureMessages = true; // capture messages     k.HandleEvents = true; // lets Compute thread handle application events     k.UseFrontEnd = false; // don't use Mathematica Notebook front-end          // this produces empty Graphic[] result     string command = @"GraphPlot[{1 -> 2, 2 -> 1, 3 -> 1, 3 -> 2, 4 -> 1, 4 -> 2, 4 -> 4}]";          // this command produces the expected Graphic[] result     //string command = @"BarChart@Range[5]";          k.Compute(command);          if (k.Graphics.Length > 0) // <-- should be an image for both commands         return k.Graphics[0];     else         return null;


title: Why modules with no variables?

text: I was reading some code, in particular, recipe 4.13 on unification pattern- matching in Sal Mangano's Mathematica Cookbook, and there were many instances of Modules with no variables in them, such as               Lookup[x_] := Module[{}, x /. $bindings]      i didn't understand the point. Why not just write               Lookup[x_] := x /. $bindings      ? Sal uses such modules frequently, so I'm supposing there is some deep reason I'm missing, hence the question here.


title: Detecting and correcting gradational brightness variations in a grayscale image

text: I am trying to quantify the proportions of various components in a greyscale image (backscattered electron image of a polished rock sample). Here is the original image:               bse = Import@"http://i.stack.imgur.com/eQece.png";      ![enter image description here](http://i.stack.imgur.com/eQece.png) The image is comprised of components (minerals) that should have the same intensity response. For example, the abundant 'mid-grey' component (plagioclase) should have a fixed grey-level across the entire image. It doesn't. By masking the other components of the image and adjusting the contrast, the gradations in brightness become more obvious:               bsek = ImageSubtract[bse, ColorNegate@Binarize[bse, {0.16, 0.24}]];     ImageAdjust[bsek, {3, 1.1}]      ![enter image description here](http://i.stack.imgur.com/Xo6C5.png) There seems to be two effects: a first order decrease in brightness towards the bottom corners and a second-order periodic vertical striping (comprised of short wavelength gradients). _Why bother? - Correcting for variations in brightness is an important step prior to segmentation analysis of the image_ By approximating the variation in grey-values for the plagioclase, the difference in birghtness between the top and bottom of the image can be modelled (albeit crudely).               ksim[im_] := Module[{kdf, kdl},       kdf = SmoothKernelDistribution[First@im];       kdl = SmoothKernelDistribution[Last@im];       Plot[{PDF[kdf, x], PDF[kdl, x]}, {x, 0, 0.3}, Filling -> Axis,         Exclusions -> None]]     ksim[ImageData[bsek]]      ![enter image description here](http://i.stack.imgur.com/i8hOp.png) The following creates a gradational filter that causes the grey-level peaks to overlap (by adjusting the value of `shift`).               bsedim = ImageDimensions[bse]     shift = 0.2;     grad = 1 +         Transpose@         Array[Table[x, {x, -shift, 0., shift/bsedim[[1]]}] &, bsedim[[1]]];     gradi = Image[grad];          bsekm = ImageMultiply[bsek, gradi];     ksim[ImageData[bsekm]]      ![enter image description here](http://i.stack.imgur.com/paB4h.png) This filter can then be applied to the original image:               bsem = ImageMultiply[bse, gradi]      ![enter image description here](http://i.stack.imgur.com/CWRuh.png) This clumsy method does an _OK_ job of levelling the first-order brightness defect. However, this effect looks to have a spherical gradient (dimmer in the bottom corners than the middle) which is not accounted for. As yet, I have not found a way to correct the second order periodic effect. Can anyone suggest a more straightforward way to detect and correct these kinds of brightness variation defects? Extra bonus gratitude to anyone who can help to correct the second-order periodic aberration. * * * **Update** Here is a contrast stretched image showing the vertical aberrations:                ImageAdjust[bse, {4.5, 3.85}]      ![enter image description here](http://i.stack.imgur.com/orqOk.png)


title: What are the algorithm details of FindRoot?

text: The Help page of `FindRoot` says: "by default, `FindRoot` uses Newton's method (Newton-Raphson) to solve a nonlinear system".   But I still have the following puzzles:   1. How will the Jacobian be calculated in each iteration : symbolically or using finite difference approximation only?   2. Is there any dumping method of the step being used when the Jacobian at any step is invertible?


title: Inequality of reciprocal functions

text: Simplify[1/(1/a + 1/b)]      { (a b)/(a + b) } That doesn't look right. The given function has an infinite term for `a = 0` and one for `b = 0`, while the result has one for `(a + b) = 0`. So that's probably the reason why:               a b/(a + b) === 1/(1/a + 1/b)      { False } though only a minute ago it Simplified it that way! Also               Simplify[1/(1/x)]        { x } seems to disregard the `1/0` case. Can anybody get me out of my confusion?


title: Code Golf: Least Common Multiple

text: "CodeGolf" challenge: write the shortest practical Least Common Multiple function that:   1. Does not use built in `GCD`, `LCM` or any related fuctions   2. Accepts multiple arguments in any order, e.g. `LCM[3, 20, 6]`   3. In the spirit of the original, obfuscated is better


title: Copy a variable to a specific kernel in Mathematica

text: I would like to copy some parameter from the main Kernel of Mathematica to the parallel kernels available. So I'm running now a command like:               LaunchKernels[]     ParallelEvaluate[var = 10, #] & /@ Kernels[]      Now running this is not a problem. But say I have another variable `var2` and I want to copy its content to all other kernels or a specific kernel. How can I do this?


title: Creating partly filled disks based on percentage

text: I'm trying to create a function that returns a partly filled `Disk`, based on a percentage. So inputting `1` would give a fully filled disk, while inputting `0.5` would return a `Disk` with half of if it filled (from 12 'o clock to 6 'o clock). Etc. So far I've written this:               Graphics[{{EdgeForm[Thick], White, Disk[{0, 0}, 1]},                {Blue, Disk[{0, 0}, 1, {4 Pi/3, Pi/2}]}}]      ![enter image description here](http://i.stack.imgur.com/uCZI7.png) The function part is not difficult but I can't get the coordinates to work properly. How do I transform a percentage like 0.1 to the correct segment of the `Disk`? (The `{4 Pi/3, Pi/2}` of the function).


title: Specifying the ports used by LinkCreate or LinkLaunch

text: Whenever a `Link` is created using `LinkCreate` or `LinkLaunch` with `LinkProtocol -> "TCPIP"`, Mathematica opens up two ports for communicating with the attached process. Can these be specified by the user of these functions? I ask because it would allow me to route all communication over ssh via port- forwarding.


title: How to remap a fisheye image?

text: I want to flatten a series of fisheye images by remapping them to a rectinlinear projection. To achieve this, I need to be able to remap the pixels of the image using fisheye correction formulas for the x-, and y-coordinates. How can I achieve this? I have found this question and this question but I wonder how to use this for fisheye correction. So far I've tried to use ImageTransformation for this, but I can't get the function to work properly.                 f[pt_] := With[{s = {.5, .5}},       Module[{rd, polarcoor, ru, newcoor},        rd = Norm[pt - s]^2/Norm[s];        polarcoor =          CoordinateTransform[{"Cartesian" -> "Polar", 2}, (pt - s)];        ru = 1*Tan[2*ArcSin[((polarcoor[[1]])/(2*1))]];        CoordinateTransform["Polar" -> "Cartesian", {ru, polarcoor[[2]]}]        ]       ]     ImageTransformation[image,f]      This should first translate the image coordinates to polar coordinates, then calculate the new r (ru=r undistorted), and than translate these back to cartesian coordinates. The `ru = 1*Tan[2*ArcSin[((polarcoor[[1]])/(2*1))]]` is based on the above links, with a random value chosen as f. It fi I get an error message, saying the function doesn't map. Anyone have an idea how to fix this and any further suggestions on how to improve the code? ![Example fisheye image](http://i.stack.imgur.com/JDX9f.jpg) **Update 2 22-10-2013** Changed the code to:               image = Import["http://i.stack.imgur.com/JDX9f.jpg"];     r[pt_] := Module[{rd, ru, polarcoor, a},       rd = Norm[pt];       ru = *Transformation formula*        a = ArcTan @@ (pt);       ru {Cos[a], Sin[a]}       ]      Using `ru = Sqrt[rd];` `ImageTransformation[image, r, DataRange -> {{-1, 1}, {-1, 1}}]` gives ![enter image description here](http://i.stack.imgur.com/cdvgw.jpg) Using `ru = ArcTan[rd];` `ImageTransformation[image, r, DataRange -> {{-2, 2}, {-2, 2}}]` gives ![enter image description here](http://i.stack.imgur.com/9JQVP.jpg) Both look like a step in the right direction, with straightened lines, but I got them by trial-and-error so I don't know the correctness.


title: Does Share have any side effect?

text: According to the documentation, > `Share[expr]` changes the way `expr` is stored internally, to try and > minimize the amount of memory used. How should I then interpret the fact that `x1 != x2 + x3` after running the following code?               e = Table[j (x + i), {i, 5}, {j, i}];     x1 = ByteCount@e     x2 = Share[e]     x3 = ByteCount@e


title: Simplifying expressions using rules that span nonconsecutive terms

text: Suppose there is some function with the property               f[x,y] f[y,x^2] / f[x^3,y] == f[2x,y]      How can I simplify an arbitrary expression that contains the lhs of the above equation in a somewhat obscured way? Say as in               a f[x^3,y] b / (c f[y,x^2] d f[x,y] e)      I tried Simplify with TransformationFunctions but I only seem to be able to replace the three f when they're literally next to each other in the syntax tree. Any ideas on how to proceed?


title: Mathematica Workbench - when to expect an update?

text: I'm considering getting Mathematica Workbench 2. Looking at the videos on Workbench 2 and on "Profiling Mathematica code" @ 01:09 I see the current version nr 2 dates back to at least oktober 3 2007 i.e soon to be 7 years old. This seems a bit outdated to be software. I don't seem to find any revision history. Are there any alternatives on the market, that have similar capabilities and are more up to date ?


title: Declaration of variables in large Linear Programming model with NMaximize

text: I want to solve a large LP problem using `NMaximize`. This is a small instance of my bigger problem: $$max \sum^{4}_{t=1}(\sum^{4}_{c=1} V_{c}*f_{c,t})\\\ s.t\quad \sum^{5}_{t=1} f_{c,t} \leq 100,\forall t$$ where $ f_{c,t} \geq 0$ and $c=1...5$ and $t=1...5$ I wrote the following:               NMaximize[{Sum[f[c, t]*V, {c, 1, 4}, {t, 1, 4}],        Sum[f[c, t], {c, 1, 5}] <= 100}, {f[c, t]}]      How can I declare `f[c,t]` as a variable?


title: Collect and simplify both the coefficents and the matched patterns

text: (This is a far tighter version of a previous question I asked) The problem with Collect is that while `Collect[exp, pattern, Simplify]` will simplify the coefficients, it does nothing to the matched patterns themselves. If one then calls `FullSimplify` on the result of the collection, it frequently undos the collect. This is especially important when collecting and matching with complicated non-integer exponents or exponentials. To solve this, what do you think of the following solution? Is there any way I could lose parts of the expression tree with this transformation?               CollectFullSimplifyImpl[exp_, pat_]:= If[MatchQ[#,pat], FullSimplify@#, #]& //@ Collect[exp, pat, FullSimplify];     CollectFullSimplify[exp_, pat_]:= FixedPoint[CollectFullSimplifyImpl[#, pat]&, exp]      I think I want to do a depth first MapAll so simplify the expressions from the bottom up if they are recursive and ensure that I don't undo the previous collections as I go through (i.e. calling FullSimplify on a higher level node could mean lower nodes no longer match the pattern). Why have a Fixed point? Want to allow the recollection//further simplification if the exponents have themselves simplified and could be combined, but having trouble finding a minimal example. Might be unncessary... *) To see the results, try the following tests:               exp = ((b - a)/a - b/a )x^(((b - a)/a) - (b/a)  )+(1 + a)x + (b - 1)x;     exp2 = ((b - a)/a - b/a )x^(((b - a)/a) - (b/a)  )+ x^x^((b - a)/a - b/a-1/x+x^((b - a)/a - b/a)); (* Test out the recursion *)     Print["Collect, then Collect with simplification, then CollectFullSimplify"]     Collect[exp, x^_]     Collect[exp, x^_, FullSimplify]     CollectFullSimplify[exp, x^_]          Print["Collect, then Collect with simplification, then CollectFullSimplify"]     Collect[exp2, x^_]     Collect[exp2, x^_, FullSimplify]     CollectFullSimplify[exp, x^_]      The following is the output               "Collect, then Collect with simplification, then CollectFullSimplify"          (*     ==> (1 + a) x + (-1 + b) x + (-(b/a) + (-a + b)/a) x^(-(b/         a) + (-a + b)/a)     *)          (* ==> (a + b) x - x^(-(b/a) + (-a + b)/a) *)          (*     ==> -(1/x) + (a + b) x          During evaluation of     *)          "Collect, then Collect with simplification, then CollectFullSimplify"          (*     ==> -x^(-(b/a) + (-a + b)/a) + x^x^(-(b/a) + (-a + b)/a - 1/x +        x^(-(b/a) + (-a + b)/a))     *)          (*     ==> -x^(-(b/a) + (-a + b)/a) + x^x^(-(b/a) + (-a + b)/a - 1/x +        x^(-(b/a) + (-a + b)/a))     *)          (* ==> -(1/x) + (a + b) x *)      One problem I have found is the following: `CollectFullSimplifyImpl[v[l][z_] , z^_]` becomes `v[l][Pattern[(If[MatchQ[#, z^Blank[]], FullSimplify[#], #]& )[z], Blank[]]]` This is ugly since I commonly want to call CollectFullSimplify on rules of the form `{v[l][z_] -> COMPLICATED STUFF`, and this wrecks it.


title: ReadList or any other command to read in blocks of very large numbers

text: I have a data file, data.txt, having following data:               3                                                         -0.2352894126386808187350075012389752796853e-1 0.2637308884075999426372690567963259521074e-30     0.1162118209477691344763370597452108929431e-2 -0.5392062060774676319404139679768941598284e-32          0.1993639851597459864147785133041034189591e0 -0.6630323032648363841595581393885521890515e-30     -0.3297790594809971083794788173889365177346e0 0.9104893688834152505592072881087608656528e-31          0.2855754609815511932435778845835014061846e2 -0.4206735153962858572318973522081457438191e-28     0.3384007339539669275065289685447274745546e2 0.4527037649170679926834370576825317093893e-28      i.e., the top integer digit which is the no. of blocks, then three blocks each of two rows. Each row has two numbers corresponding to real and imaginary parts. I am trying to read these data in Mathematica using               var = Table[x[i], {i, 1, 2}]          readoutputfile[fname_, var_] :=       Module[{stream, noofvariables, nooftotalsol},       stream = OpenRead[fname];       noofvariables = Length[var];       nooftotalsol = Read[stream, Number];       Print["Total no of real solutions is ", nooftotalsol];       Do[soltmp[l] = {};        Do[soltmp[l] =           Append[soltmp[l], Read[stream, {Number, Number}]], {i, 1,           noofvariables}],        {l, 1, nooftotalsol}];            Close[stream];            sol = Table[soltmp[i], {i, nooftotalsol}];       sol = Table[         Table[sol[[j, i]] /. {t_, y_} -> t + I y, {i, noofvariables}], {j,           nooftotalsol}];       ]      and then running               readoutputfile["data.txt", var]      But it is giving me error as > General::digit: "Digit at position 1 in > !(\"-0.2352894126386808187350075012389752796853\") is too large to be used > in base 10. ImportList etc. isn't helping me so far. Any better way of doing this? Thanks, John


title: FindRoot kills kernel

text: **Bug introduced in 7.0.1 or earlier. Persists through at least 10.0.0.** * * * I'm having problems with FindRoot killing the kernel. In my real application, I want to FindRoot on a black-box function containing an NDSolve that takes a list of unequal length lists as input and output. The goal is to find limit cycles of a forced system of differential equation. Sometimes it works, but other times it kills the kernel when I run it (beep, then dead kernel, no messages). The real example is horrible, but here's a minimal example:               f[xs_?(VectorQ[Flatten[#], NumericQ] &)] := {{Sin[xs[[1, 1]]]}};     Do[FindRoot[f[{{x}}] == {{x}}, {x, 0.3}], {1000}]      where the Do loop almost assures failure (Mathematica 10.0.0 on a Mac). Any idea why or how to fix it? For whatever reason, using a single level list seems OK, so maybe that's the solution.


title: Homotopy Visualization

text: I noticed that both the lower cased 'i' and the Apple logo  are topologically equivalent to the disjoint union of two closed discs. ![enter image description here](http://i.stack.imgur.com/B7Fka.png) I'd like to animate a homeomorphism from the left to the right, can this be done in Mathematica 10 with built in functions?


title: Mathematica as a normal programming language

text: I'm interested in Mathematica's core language for both practical development and as an object of computer science study. Actually, the former is more of a means to the latter. I would like to create complete applications, but mainly to get experience and ideas for creating my own language. I have many ideas for it already, and one of them is to explore Mathematica's unique M-expression syntax, rule-based programming, and other interesting semantics. To this end, I have two questions:   1. Is the language specification available anywhere? And are there any particularly significant resources on Mathematica _as a language_?   2. Are there any legal restrictions on applications created and/or compiled with Mathematica, and if so, do they differ between offerings?


title: Auto-completion doesn't work as my expectation in version 9.0

text: When I input the following line in version 8, and press `Ctrl`+`K` after `Re`, I can get a drop-down auto-completion list including `Rectangle`: ![enter image description here](http://i.stack.imgur.com/YFPJb.jpg) But the same input in version 9 gives me only one candidate: ![enter image description here](http://i.stack.imgur.com/xfXvY.jpg) and the short-cut key `Ctrl`+`K` seems not working. **Questions:** Is there any thing I missed? How can I get a drop-down auto-completion menu with a full candidates list? My operation system is Windows 7 64-bit.


title: How do I evaluate a symbolic integral involving Hermite polynomials?

text: I want to test a difficult integral : Integral on all reals of some complicated function involving the Hermitian polynomials, exponentials, squares, factorials, and being general considering any Hermitian polynomials. I know the answer (it's ridiculously short compared with the statement) and just wanted to check. But why _Mathematica_ doesn't calculate my integral ? (I'm quite new on the system and don't understand what causes the trouble) :               Integrate[(HermiteH[n, x/a]*Exp[-x^2/(2 a^2)]/((n!)^(1/2) (Pi a^2)^(1/4)))^2*x^2,               {x, -Infinity, Infinity},                Assumptions :> {Element[n, Integers], Element[a, Reals], a > 0}]      And getting as a result: > >       Integrate[(x^2 exp[-(x^2/(2 a^2))]^2 HermiteH[n, x/a]^2)/(Sqrt[a^2] > Sqrt[Pi] n!), >                 {x, -∞, ∞}, >                 Assumptions :> {n ∈ Integers, a ∈ Reals, a > 0}] >   What do I have to change to get an answer?


title: What do the elements of the Parallel Kernel Status screen mean?

text: I just managed to get my multiple kernels up and humming on a new multi-core machine, which I am quite happy about. I am slightly at a loss, though, about the meaning of the different parts of the Parallel Kernel Status monitoring screen, as the official documentation on it is quite sparse. ![enter image description here](http://i.stack.imgur.com/bxaDO.png) This screen is accessible from the Evaluation menu. Clicking on `Select Columns...` goes some way into clarifying some of the more mysterious elements: ![enter image description here](http://i.stack.imgur.com/WrFHN.png) In particular   * **CPU** gives the CPU time used so far by that kernel, and    * **RAM** gives the RAM it's currently using.   * The dots change color from green to red when a kernel starts calculation and back to green when it finishes. However, I have a few specific questions:   * What does the **Time** column measure?   * What does the **Elapsed** dialog measure?   * What exactly is the **speedup**? What is it comparing with?   * What are the green bars? Upon mouseover they grow tooltips with percentages with no indication of what they are. For the ones above I imagine the kernels are not really being used to their full potential; is that the case? (And, if so, is there a good resource for ideas on fixing that?)


title: How to use adaptive precision in matrix computations?

text: I wish to compute the pseudo inverse of rectangular (or square) matrices by the cubically method of Chebyshev given by $X_{k+1}=X_k(3I-AX_k(3I-AX_k))$ where $X_0=\frac{1}{\|A\|_F^2}A^*$. The procedure is simple as I wrote in the following sample example:               Clear["Global`*"]     SeedRandom[1234];     m = 400; n = 500;     Id = SparseArray[{{i_, i_} -> 1.}, {m, m}, 0.];     A = RandomReal[{-100, 100}, {m, n}];     X[0] = 1/Norm[A, "Frobenius"]^2 ConjugateTranspose[A];     max = 50; k = 1; stop = 1;     While[k <= max && stop > 10^-2, {         AX = A.X[k - 1];         X[k] = X[k - 1].(3 Id - AX.(3 Id - AX));         stop = Norm[X[k] - X[k - 1], "Frobenius"]/Norm[X[k], "Frobenius"];         }; k++]; // AbsoluteTiming          {(k - 1), Norm[Chop[X[k - 1] - PseudoInverse[A]], 1]}      Running the above piece of code, will produce the pseudo inverse in 12 number of iterationsin 1.8 seconds (in my computer). The only problem of the Chebyshev method is that it is **slow** at the beginning of the process. I mean the third order of convergence can only be seen in the last four iterations. On the other hand, my aim and question is to reduce the computational time/effort of implementing this method in MMA. Since the method is asymptotically stable, I think one way for reducing the computational time is to use **adaptive precision**. So, is there any way to apply adaptive precision in the implementation of the above piece of code? I mean, it would be too nice if we could run the method in Single Precision at the beginning of the process and then when the stopping termination ("stop") reaches a pre-tolerance, then we back to the machine precision (double precision)? Note that I used $SetAccuracy[exp,digits]$, but I think it is so costly for matrix-matrix multiplications and is not useful. Any idea that could be helpful is fully appreciated.


title: BipartiteMatching hangs with floating-point weights in Mathematica 7 (package Combinatorica)

text: I am trying to use Combinatorica's BipartiteMatching algorithm on a weighted graph. I need to use real numbers as weights. If I try the following               graph = CompleteGraph[1, 1]     graph = SetEdgeWeights[graph, {1}]     BipartiteMatching[graph]      it correctly gives the perfect matching {{1,2}}. But if instead I try this               graph = CompleteGraph[1, 1]     graph = SetEdgeWeights[graph, {1.}]     BipartiteMatching[graph]      (the only difference being the decimal point), it hangs, apparently forever. Am I missing something obvious? Any help would be much appreciated!


title: In a CDF can I suppress or avoid "This file contains potentially unsafe dynamic content..."

text: I created a CDF to distribute to a single trusted user who both knows and trusts me and everything I make for them. I downloaded the CDF player and the CDF to one of their computers. The CDF works great, **except** every time it runs the document displays the message: > This file contains potentially unsafe dynamic content..." ![Unsafe content message](http://i.stack.imgur.com/TpySj.png) I've found some discussion about this at the old site: Why do I get security warning message..., but I don't see anything specific or useful in the link for CDF distribution. The warning makes the user VERY NERVOUS and frankly appears slapdash and unprofessional. The blank gray field below it does nothing to inspire confidence. This makes for a very bad user experience. When one launches an app or an application (created with anything else), presumably one has already vetted its provenance. Launch an application and one should see the application, not a disturbing warning. Lots of applications use "dynamic content". An application should just work. Sorry to get on a soap box here (well maybe not that sorry). It just seems that if Wolfram wants Mathematica to have the functionality to make real stand alone applications, then what we build should actually look like real applications. _Question 1: Can one suppress this unfortunate message programmatically from within the CDF document or its Manipulate[]?_ When using Mathematica, one can place a notebook and probably a CDF in a trusted directory (see the above link), which avoids the display of this message. It just seems to defeat the purpose of a CDF and its great potential as a distribution platform to expect a user who does not have Mathematica to go to the trouble to figure out how to do that or even to have to do it. _Question 2: Can one even specify a trusted directory in the CDF Player?_ _Question 3: Does a CDF really need an installation program that would create a trusted directory and how could I do that?_ Premiere support had no solution to this. I still have a little bit of hope that someone here might.


title: Rearranging a simple algebraic equation

text: Suppose I have a simple algebraic equation like:               ChebyshevT[4, p] == 0      > >     1 - 8 p^2 + 8 p^4 == 0 >   and I want to solve for the term `p^4` by simple rearrangement:               p^4 == -(1 - 8 p^2)/8      How do I do that in _Mathematica_ ? And how can I then assign the solution to replace.


title: How to increase font-size of Text in ShowLegend

text: The default font-size of `Legend` text generated using `ShowLegend[]` is too small. How does one increase this? The code I am working with is:               Needs["PlotLegends`"]     LstTest = Flatten[Table[{i, j, (i + j)/200}, {i, 1, 100}, {j, 1, 100}], 1];     plTest = ListContourPlot[LstTest, Contours -> 9, ColorFunction -> "Rainbow"];     LMax = Max[LstTest[[All, 3]]]; LMin = Min[LstTest[[All, 3]]];          ShowLegend[plTest,                 {ColorData["Rainbow"][1 - #1] &,                  10,                  ToString[Round[LMax, 0.01]],                  ToString[Round[LMin, 0.01]],                  LegendPosition -> {0.6, 0}                }               ]      The `0.01` and `1.0` appear too small, and I would like to increase the font- size of these. Thanks for any help!


title: Camera Troubles in Mathematica

text: I'm trying to animate a torus being cut by a plane, so that as the plane enters the torus the part in front of the plane disappears (the idea is to show the cross section). That much I can do, but I can't seem to get the camera to behave. I'd like everything to stay the same size and position, but despite setting `ViewVector`, `ViewAngle`, and `ViewVertical` the scene becomes smaller as the animation progresses. Note that I chose the settings pretty arbitrarily. I am baffled as to why the camera view changes with these three options fixed. Here is the code (I produce the frames in a table, and then export them for the animation).               Table[Show[       ContourPlot3D[(1 - Sqrt[x^2 + (y + 1/2)^2])^2 + z^2 - 1/4 ==          0, {x, -2, 2}, {y, -2, 2 - 2 t}, {z, -2, 2}, Mesh -> False], (*The torus*)       ContourPlot3D[y == 2 - 2 t, {x, -2, 2}, {y, -2, 2}, {z, -2, 2},         Mesh -> False, ContourStyle -> {White, Opacity[.5]}],         (*The plane*)       Axes -> False, Boxed -> True, PlotRange -> All,       ViewVector -> {{5 Sqrt[6], 10 Sqrt[6], 5 Sqrt[6]}, {0, 0, 0}},        ViewAngle -> 3 Pi/50, ViewVertical -> {0, 0, 1}], {t, 0, 1, .5}]      And here is the result. ![Torus cross sections](http://i.stack.imgur.com/dAmjH.png) As you can see, the camera zooms out and seems to rotate slightly. Any idea how to fix this? (Edited to add `PlotRange -> All`)


title: Algorithm for parts integration

text: Sorry if this is a duplicate, I've searched how to do this to no avail. What I'd like to do is a function that integrates by parts $n$ times, i.e $$ \int u(x) v(x) dx = u \left(\textstyle{\int}v\right) - \displaystyle{\int} u' \left(\textstyle{\int}v\right)dx $$ where $\textstyle{\int}v$ is the primitive of $v$. I've done a very rustic function that does this,               parts[u_,v_]:=(#1 Integrate[#2,x] - Integrate[D[#1,x] Integrate[#2,x],x]&[u,v];      which performs well but, as you all can see has -at least- the mayor limitation that `u` and `v` should be given as functions of `x`. At least it works, for example               In[1]=  parts[Exp[-x],1/x^2]     Out[1]= -Exp[-x]/x - ExpIntegralEi[-x]      The thing is, I'd like to tell `parts` to operate $n$ times, for example \begin{align} \mbox{parts}\big(u,v,2\big) &= u v - \mbox{parts}\left(u',\textstyle{\int}v,1\right) \\\ \\\ \mbox{parts}\big(u(x),v(x),3\big) &= u(x)v(x) - u'\left(\textstyle{\int}v\right) + \mbox{parts}\big(u''(x),\textstyle{\iint}v,1\big) \end{align} and so on. I hope my question is clear.


title: Where did I go wrong with my implementation of finding a plane tangent to a surface?

text: I am working on finding the plane tangent to a paraboloid at a given point. ![author's solution:](http://i.stack.imgur.com/XAHoy.png) My code:               z[x_, y_] := 10 - x^2 - 2 y^2;     Subscript[z, x][x_, y_] := D[z, x];     Subscript[z, y][x_, y_] := D[z, y];     z[1, 2] + Subscript[z, x][1, 2] (x - 1) +      Subscript[z, x][1, 2] (y - 2)(*The plane tangent equation*)      However, it doesn't work. My question is: where did I go wrong?


title: Half kth term if n is even and k=n/2?

text: I am trying to write a function which will perform the equation in the attached image. So far, I have:               x[n_] :=      x[n] =       2^(1 - n) Sum[Binomial[n, k] T[n - 2 k], {k, 0, n/2}]          x[6]      which outputs: $ \frac{1}{32} (20 T(0)+15 T(2)+6 T(4)+T(6)) $ How can I write an `If[]` (or similar) statement to half the `kth` term when `n` is even and `k=n/2`? Thanks in advance! ![Equation 2.14](http://i.stack.imgur.com/NKC7G.png)


title: Open data file from CDFPlayer?

text: Using a CDF program running in CDF Player, is it possible to use a system dialog box, or even just an Import statement such as Import["*.CSV"], to import data from a text or comma separated file on a personal computer? I have browsed the forums and Wolfram documentation and it appears that it is not possible, but all the questions were a little bit different in one way or another. My own attempts have failed to produce a dialog box.


title: Plot rate of change in $x$ axis of list of points

text: I have a list of points, that may have clusters in some of the $x$ axis values, and my goal is to get a function that shows that graphically. Something like this, but the red function is "hand drawn", it's just for reference. ![frequency plot](http://i.stack.imgur.com/YKYL4.png) The high points of the red plot shows where the clusters are and the low points where are the points that are most isolated.


title: Integral of Lorentzian yields different results depending on when parameter assigments are made

text: I'm evaluating the integral of a Lorentzian, which I know equals one. First I define the function and evaluate the integral in two slightly different ways. Surprisingly, I do not get the right answer when I do symbolic integration first.               g[x_] := (a/(2*\[Pi]))/((x - x0)^2 + (a/2)^2);          Integrate[g[x], {x, -Infinity, Infinity}] /. {x0 -> 10} /. {a -> 4}      > Undefined               Integrate[g[x] /. {x0 -> 10} /. {a -> 4}, {x, -Infinity, Infinity}]      > 1 What is the issue here?


title: Strange Integrate behavior (a bug!)

text: The following two calculations should give the same result. After all, integration is a linear operation. ![enter image description here](http://i.stack.imgur.com/HoIYA.png) * * * I have pasted the code below in case you want to play with it.               Integrate[Integrate[v[x], x] -           Integrate[Integrate[v[x], x] * u'[x], x]/u[x], x]          Integrate[Integrate[v[x], x], x] -         Integrate[Integrate[Integrate[v[x], x] * u'[x], x]/u[x], x]


title: Histogram with variable bin size

text: Suppose I have some dataset,e.g.,               Histogram[RandomVariate[PoissonDistribution[2], 10000], 10]      which gives, $\hspace{2cm}$![enter image description here](http://i.stack.imgur.com/yb46O.jpg) How can I change the histogram such that it has variable bin size such, e.g., the first six bins have size 1 while the last two have size 2?


title: How to increase the size of the dot produced by OverDot[]

text: As the title says, I want to find a way to increase the size of the dot produced by `OverDot[]`. Here is a simple code               f = (x^2*px^2 - px^2*(px^2 - 1)) + (x^2 + px^2)/2 - 2*x^4;     cnt = {0.002, 0.015, 0.0312, 0.05, 0.15, 0.3, 0.45, 0.5612, 0.64, 0.73, 0.778};     xmin = 1.5;     C0 = ContourPlot[f, {x, -xmin, xmin}, {px, -xmin, xmin},      Contours -> cnt, ContourStyle -> {Black}, ContourShading -> False,      FrameLabel -> {"x", OverDot["x"]}, RotateLabel -> False,      Axes -> False, FrameStyle -> Directive[FontSize -> 22, FontFamily -> "Helvetica"],      PlotRange -> xmin, ImageSize -> 550]      which gives this output ![plot](http://i.stack.imgur.com/dePLk.png) We see, that even if I used a relative large fonts size (22), the dot above $x$ (`OverDot["x"]`) at the vertical axes is tiny and hardly visible if I print out this plot. So, my question: is there a way to increase the size of that dot? Many thanks in advance. **EDIT** Following @Hector suggestions I used `Overscript["x", Style["\[FilledSmallCircle]", FontSize -> 12]]` which gives ![plot2](http://i.stack.imgur.com/4rFKt.png)


title: Whitespace after number subscript

text: When I write something like this:               (Subscript[x, 0], f(Subscript[x, 0]))       I get some undesirable whitespace after each of the `Subscript[x, 0]`. The whitespace disappears or is at least significantly reduced, if I write e.g. `Subscript[x, i]` instead. This is a screen shot of the problem: ![Screen shot](http://i.stack.imgur.com/BGGbU.png) I have looked around the object inspector for a solution, but I haven't found one. It appears to be a font specific problem: If I use `Times` \- the problem goes away, but for most other fonts - it is there (I use `Georgia`). The raw cell looks like this:               Cell[TextData[Cell[BoxData[      FormBox[       RowBox[{"(",         RowBox[{         SubscriptBox["x", "0"], ",",          RowBox[{"f", "(",           SubscriptBox["x", "0"], ")"}]}], ")"}], TraditionalForm]],      FormatType->"TraditionalForm"]], "Text",      CellChangeTimes->{{3.590903299361623*^9, 3.590903306745799*^9}}]


title: Organise a graph's vertices into levels

text: I would like to organise a graph's vertices in levels. Consider               g = {       0 -> 1, 1 -> 2, 2 -> 3, 0 -> 4, 0 -> 5, 2 -> 6, 2 -> 7, 8 -> 3, 4 -> 9, 5 -> 9,        6 -> 9, 6 -> 10, 7 -> 10, 8 -> 10, 9 -> 11, 9 -> 12, 10 -> 11, 10 -> 12 };     Graph[g]      Using nested list of vertices such as `{{0, 1, 2, 3}, {4, 5, 6, 7, 8}, {9, 10}, {11, 12}}`, I would like to see graph with 4 levels wherein vertices 0, 1, 2, 3 placed in line on the top level, vertices 4, 5, 6, 7, 8 in line on the level below and so on. ![enter image description here](http://i.stack.imgur.com/ZoubU.png)


title: KolmogorovSmirnovTest[] On Frequency Data

text: I have two observed frequency data, let say               f1 = {100, 200, 150, 100, 50};     f2 = {110, 195, 160, 105, 40};      and i want to know whether these random samples belong to the same distribution using `KolmogorovSmirnovTest[]`. Since `KolmogorovSmirnovTest[]` takes raw data, i simulate them based on `f1` and `f2`.               data1 = {};     data2 = {};     k = 1;     Do[data1 = Join[data1, Table[k n, {f1[[n]]}]], {n, 1, Length[f1]}]     Do[data2 = Join[data2, Table[k n, {f2[[n]]}]], {n, 1, Length[f2]}]      The test gives the result               KolmogorovSmirnovTest[data1, data2]     0.99998      Is this correct procedure to perform KS on frequency data? I have changed `k` with any other number and got the same result. Thank you.


title: Getting Internal Self-Test Error

text: I have two questions related to this simple code:               CDFDeploy[SystemDialogInput["FileSave"],        Panel[Row[{Button[Text[Style["sav", FontSize -> Scaled[.2]]],ImageSize -> Scaled[.2]],            Button[Text[Style["save", FontSize -> Scaled[.2]]],ImageSize -> Scaled[.2]]}],           ImageSize -> Scaled[2]], WindowSize -> Scaled[2]]                    1. Sometimes, I am getting `Internal Self-Test Error`. Why?   2. I am able to scale `Button` size, `Fontsize` and `Panel`size in the Horizontal direction but not in the vertical direction. How to do this?


title: How to suppress Tooltip in built-in templates?

text: ...or maybe switch the message. But I will be happy with no `Tooltip` at all. ![enter image description here](http://i.stack.imgur.com/Th4We.png) I've naively tried with               Block[{$PerformanceGoal="Speed"}, ...]      because it works in case of `Charts`` tooltips, but with no effect :)


title: Confused with HoldForm in Postfix notation

text: Why does the following code produce different result? In my mental model, they should be the same.               Table[With[{x = i^k}, HoldForm[x]], {k, 1, 5}]     With[{x = i^k}, HoldForm[x]] // Table[#, {k, 1, 5}] &      Output:               {i,i^2,i^3,i^4,i^5}     {i^k,i^k,i^k,i^k,i^k}


title: How to find the maximum value of an integer that satisfies some inequality

text: Consider the following Mathematica expression:               Reduce[2^j/(j + 1) <= 10, j, Integers]      which outputs:               j == 0 || j == 1 || j == 2 || j == 3 || j == 4 ||      j == 5 || j == 6 || (j \[Element] Integers && j <= -2)      Therefore, the maximum integer $j$ satisfying $\frac{2^j}{j + 1}$ is 6. I tried to using the `FindMaximum`, as follows:               FindMaximum[{j, 2^j/(j + 1) <= 10 && j \[Element] Integers}, j]      but it gives the following error:               FindMaximum::eqineq: "Constraints in {j\[Element]Integers,2^j/(1+j)<=10} are      not all equality or inequality constraints.      With the exception of integer domain constraints for linear programming,      domain constraints or constraints with Unequal (!=) are not supported."      My general question is: > How to solve inequalities like $\frac{2^j}{j + 1} \le c$ (for some constant > $c$) in Mathematica, over Integers?


title: GraphHighlightStyle with multiple datasets

text: I am trying to highlight several subgraphs of a graph using the following command:                HighlightGraph[        GridGraph[{10, 10}], {{1 \[UndirectedEdge] 2,          2 \[UndirectedEdge] 12}, {4 \[UndirectedEdge] 5,           5 \[UndirectedEdge] 15}}, GraphHighlightStyle -> "Thick"]      It turns out that there is no action of `GraphHighlightStyle` on how my subgraphs look like. Compare with, e.g.,                   HighlightGraph[ GridGraph[{10, 10}],               {{1 \[UndirectedEdge] 2,2 \[UndirectedEdge] 12}},                  GraphHighlightStyle -> "Thick"]      So what has to be changed so that `GraphHighlightStyle` actually worked on multiple datasets in `HighlightGraph`?


title: How to cancel floating point factors?

text: I am currently having problems with some floating points. I have a function, which gives as an intermediate result (for example)               -(10000. - 10000. a) E^(-16.4157 kp^2 x^0.277)/((-1. + a) a x^0.252525 xj^4.47047)      It gets passed through into another function, which will fill in the value `a = 1`. Then Mathematica reacts with a `1/Sqrt[0]` error. However, as you can see, the factor `(10000. - 10000. a)` should cancel with the factor `(-1.+ a)` in the denominator to give 10000, the result is thus well-defined. Do you have any idea how to let Mathematica cancel these factors out? I have tried `Simplify` and `FullSimplify` with `Assumptions -> a!=1` but it doesn't work. I cannot change much to the function itself, as it is an intermediate result (and it is just an example for this post; other intermediate results also occur, sometimes with the same problem, sometimes they work fine).


title: I need to remove a line from a ParametricPlot

text: What happens is that when I make this ParametricPlot:               ClearAll [f, g]           f2 [t_]:= t + 1 / t      g2 [t_]:= t - 1 / t      ParametricPlot [{f2 [t], g2 [t]}, {t, 0.00001, 20},       PlotRange -> {{0, 5}, {-4, 1}}, ImageSize -> 200]      ParametricPlot [{f2 [t], g2 [t]}, {t, -80, 80},       PlotRange -> {{-4, 4}, {-2, 4}}, ImageSize -> 200]       The graph of the parametric function appears and additionally appears a straight line through the origin. How I can remove it?


title: Finding the position of similar elements in a matrix

text: I want to find the position of the elements which are equal in a matrix. For example in the case of the following matrix: $m =\left( \begin{array}{cc} a & x \\\ x & a \\\ \end{array} \right)$               m = {{a, x}, {x, a}};      I want to get these two sets: > >     {{{1, 2}, {2, 1}}, {{1, 1}, {2, 2}}} >   How can I do that? Is there a built in function?


title: Creating sculptural forms using graphics primitives

text: This is a question based on this answer by halirutan. Some amazing images can be created with this code, and I was wondering whether it was possible to extend the principle to different shapes. I would like to create images based on the sculptures of Naum Gabo & Barbara Hepworth as shown below: ![](http://i.stack.imgur.com/7nesm.jpg) ![](http://i.stack.imgur.com/WM2sp.jpg) Below is an image made with halirutan's code, included to clarify the similarity: ![](http://i.stack.imgur.com/l3Auh.gif)               x = 50; drawMe@Table[Mod[i, x], {i, E x}]      My question is threefold really. Is it possible to : * extend this principle to other shapes? * extend this to 3D? * distort the shapes with a mesh distort or similar (see image below)? ![](http://i.stack.imgur.com/J4eUz.png)


title: Solving a system of difference equations in an exponential steady-state growth setting

text: I have a system of difference equations in an exponential steady-state balanced growth setting; all variables grow at the same steady-state rate, say, $g$. I use the notations as follows: Variable $X$ at time $t$ is denoted by $X(t)$. As any variable grows at the rate of $g$, $X(t)$ can be expressed as $X(t)=X(0)e^{tg}$, where $X(0)$ is the initial value of $X$. Now, my equations system is this:               X(t)=Y(t-a)     Z(t)=X(t-b)     Y(t)=pZ(t-c)      Variables with time notation are endogenous variables: $X$, $Y$, $Z$. Variables without time notation are exogenous: $a$, $b$, $c$, $p$ and also the initial values of the endogenous variables, $X(0)$, $Y(0)$, $Z(0)$ are exogenous. You can interpret these equations as saying that, as for the first equation, $X$ at any time is equal to $Y$ of $a$ periods ago. I would like to do two things using Mathematica: First, find a solution of the three endogenous variables $X(t)$, $Y(t)$, and $Z(t)$ expressed with exogenous parameters given in the model and with the growth rate $g$. Second, plugging successively one equation into another yields what can be called 'characteristic equation' of the system. I would like to generate the simplest expression of this characteristic equation. I know it will be consisted of $g$ and the other exogenous parameters. You can verify this by manually solving the model. (In this sense, in this model, $g$ is endogenously determined by the exogenous parameters.) Any help will be greatly appreciated!


title: install mathematica 9 on linux encounter "Glibc_2.4" not found

text: I tried install mathematica 9 on linux. The whole process is fine. After the installation. I type "mathematica", and came up following lines: > > /usr/local/Wolfram/Mathematica/9.0/SystemFiles/FrontEnd/Binaries/Linux-x86-64/Mathematica: > /lib64/tls/libc.so.6: version `GLIBC_2.4' not found (required by > /usr/local/Wolfram/Mathematica/9.0/SystemFiles/Libraries/Linux-x86-64/libML64i3.so) > > > /usr/local/Wolfram/Mathematica/9.0/SystemFiles/FrontEnd/Binaries/Linux-x86-64/Mathematica: > /lib64/tls/libc.so.6: version `GLIBC_2.4' not found (required by > /usr/local/Wolfram/Mathematica/9.0/SystemFiles/Libraries/Linux-x86-64/libQtCore.so.4) It seems that I need to update my Glibc. But I received warnings that update Gilbc is highly risky. What should I do? How to update Glibc safely?? Or should I return to low edition mathematica? my Glibc version is glibc-2.3.4-2.39. Which edition of mathematica can I install?


title: Extracting a single weakly connected component from a network of many weakly connected components?

text: Hello Mathematica friends! I've got a network with thousands of edges and vertices, but not all in one connected component. I'm trying to extract specific connected components from the network, and assign them as new variables.               g = Graph[{1 \[UndirectedEdge] 2, 2 \[UndirectedEdge] 3, 1 \[UndirectedEdge] 3, 4 \[UndirectedEdge] 5, 7 \[UndirectedEdge] 6, 8 \[UndirectedEdge] 6, 5 \[UndirectedEdge] 7, 7 \[UndirectedEdge] 8}]      I know it's a disconnected component because of:               WeaklyConnectedGraphQ[g]     False      I know there are two components:               Length[WeaklyConnectedComponents[g]]     2      I know how many vertices are in each component:               Length /@ WeaklyConnectedComponents[g]     {5, 3}      And I know what vertices are in each component:               WeaklyConnectedComponents[g]     {{7, 6, 5, 8, 4}, {3, 2, 1}}      What I don't know is how to a assign on of these components to a new variable to then proceed with analysis on just a single connected component?


title: How to evaluate Floor[1/2 + Arg[z]/(2π)] with Re[z] > 0

text: I want to do a series expansion of an expression containing `Gamma` functions with specific arguments. An example is the following:               Series[Gamma[I p/x + z /x], {x, 0, 0}, Assumptions -> {x > 0, p > 0, z > 0}]          (* (2^-Floor[1/2 + Arg[(I p)/x + z/x]/(2 π)]) ... *)      The result then depends on expressions containing Floor functions:                Floor[1/2 + Arg[(I p)/x + z/x]/(2 π)]      However, because I am assuming all variables to be positive (and nonzero) the Arg[] will not return any values outside the open interval (-π/2, π/2). Therefore, the `Floor` expresisons should simplify to just 0. Now I would like to know how I can get _Mathematica_ to do this simplification automatically. Maybe this is something that can be done by adding rules to `FullSimplify` with the option `TransformationFunctions`?


title: fourier issue arising from input miscommunication

text: xdomain = Table[i , {i, -10, 10, .1}];     ListPlot[InverseFourier[       Fourier[E^-#^2 & /@ xdomain]*E^#^2 & /@ xdomain]]      So I want to numerically fourier transform a function, multiply that fourier'd function by a second function, and then inverse fourier transform it. The code above doesn't work. I get a blank graph, I think, because it doesn't properly multiply the two vectors that I commanded to multiply. I'm not sure why I can't get {a,b,c}*{1,2,3} to multiply inside my fourier function, but I have tried putting evaluate functions in different spots inside to see if that would fix it.


title: Creating hyperlinks from a list of file names

text: Suppose I use `FileNames` to get a list of file names. I know that it's possible to make a hyperlink using this kind of pattern....               Cell[TextData[ButtonBox["Link Label", BaseStyle->"Hyperlink",                    ButtonData->{FrontEnd`FileName[{"Folder names"}, "FileName.nb",                                   CharacterEncoding -> "UTF-8"], None}]],         "Text"]      I would appreciate help with taking a list of file names and writing them as working hyperlinks in a specified notebook. To be clear, I'd like the hyperlink to open the file referred to by the hyperlink. I tried taking a file path, splitting it to get the parts, using that for the folder structure and the file name, but couldn't get it to work.


title: Heat Transfer equation by numerical methods

text: I want to solve the following heat conduction equation using numerical methods: D[u[x, t], t] -alpha*D[u[x, t], {x, 2}] == 0 u[x, 0] == 1/(1 + x^2)^0.25, u[-10, t] == u[10, t] == 0,               x0 = -10;     xn = 10;     dx = 0.1;     n = 200;     t0 = 0;     tn = 10;     dt = 0.01;     steps = tn/dt;     alpha = 0.2;      I define:               points = Table[-10 + i*dx, {i, 0, n}];          u[0] = Module[{i, l= {0}},  For[i = 1, i <= n - 1, i = i + 1;      AppendTo[l, 1/(1 + points[[i]]^2)^0.25]]; AppendTo[l, 0];l];              previous[dt_, dx_, u0_, alpha_] := Module[{i, ans},      ans = u0[[2]] + alpha*(dt/dx^2)*(u0[[3]] - 2 u0[[2]] + u0[[1]]); ans];      I aproximate the values of the following steps:               u[k_] := Module[{l,ans= {u[0]}}, For[j = 1, j <= k, j = j + 1, l = {0};      For[i = 2, i <= n, i = i + 1, AppendTo[l, previous[dt, dx, {ans[[j]][[i - 1]],      ans[[j]][[i]], ans[[j]][[i + 1]]}, alpha]]]; AppendTo[l, 0];      AppendTo[ans,l]]; ans[[k + 1]]]      However, it takes a lot of time to compute u[steps]=u[1000].And when want to plot the answer it gets stuck...               GraphicsGrid[Table[{Graphics[Table[{RGBColor[u[k][[i]], 0, 1 - u[k][[i]]],      Rectangle[{points[[i]] - dx/2, 0}, {points[[i]] + dx/2, 1}]}, {i, 1, n}]]},      {k, 0, steps, IntegerPart[1/dt]}]]      What is the problem? Is there a better way to define u[k]? Thank you for your help.


title: How to solve three equations with four unknowns iteratively?

text: I have three equations of the form $\quad \eta = f(N1L, N2L)$ $\quad N1L = g(\eta, R)$ $\quad N2L = h(\eta, R)$ I want to eliminate $\eta$, so that I can get $N1L$ and $N2L$ for a range of $R$. I copied my short program bellow (which can't be solved by the methods I know.) I really appreciate any help.               Clear["Global`*"]     T = 25 + 273.15;                          k = 1.3806488*10^-23;           theta = Degree 10;                   gama = 0.07199;                 Psat1 = 3.168*10^3;              PL = 101.325*10^3;                            vLinf = (1/997.0479)*18.015/1000;        L = 0.45;                   Vcontainer = L^3;           N1total = 3.049*10^27;     N1 = N1total/Vcontainer;                                        N2total = 3.67*10^22;                N2 = N2total/Vcontainer;                                       qc = 1.22*10^8;     w = 50*10^-6;      alfa = Degree 45;     KH = 1639.34*10^5/(10^3*6.02*10^23);             Vv[R_] := (Pi*R^3/3)*(2 -           3*Sin[theta - alfa] + (Sin[             theta - alfa])^3 + (Cos[theta - alfa])^3/Tan[alfa]);     Asv[R_] := Pi*R^2*(Cos[theta - alfa])^2/Tan[alfa];     Alv[R_] := 2*Pi*R^2*(1 - Sin[theta - alfa]);     H[R_] := R*(1 - Sin[theta - alfa] + Cos[theta - alfa]/Tan[alfa]);          (******************This is where my qyestion is:*******************************)          N1L[R_] := N1 - qc*(etha[R]*Psat1*Vv[R]/(k*T));          N2L[R_] := N2/(1 + qc*PL*Vv[R]/((N1L[R]*PL/KH)*k*T));          etha[R_] := Exp[vLinf*(PL - Psat1)/(k*T) - N2L[R]/N1L[R]];          Rc[R_] := 2*gama/(etha*Psat1 + PL*(N2L[R]/(N1L[R]*PL/KH)) - PL);         B[R_] := qc*(-2*gama * Vv[R]/Rc[R] +            gama*(Asv[R]* Cos [Degree (theta)] + Alv[R])) +         N1total*k*T*(N2/N1 - N2L[R]/N1L[R]) +         N2total*k*T*         Log[N1*k*T/(N1*k*T - qc*etha*Psat1*Vv[R] + qc*Vv[R]*KH)];          t1 = Table[{ R*10^6, Rc[R]*10^6}, {R, 10^-6, 10^-5, 10^-7}];     ListPlot[t1, Joined -> True, PlotStyle -> {Thick},       AxesLabel -> {Style["R(micrometer)", "Graphics", FontSize -> 13],         Style["Rc (micrometer)", "Graphics", FontSize -> 13]},       AxesOrigin -> {0, 0}, TicksStyle -> Directive[12]]


title: Transforming a huge rectangular table to Sparse Array

text: I am interested in the most efficient way to transform a huge rectangular array to a sparse array structure. Consider a numeric rectangular table that is rather sparse, with zero positions being set to Null rather than 0, which saves time and memory during the fill. The problem is that SparseArray function can not be directly applied to that kind of table. First, every Null should be replaced by 0, as can be seen in the following example:               Q = 100;(*the matrix dimension is QxQ.*)     f[p1_,p2_]:=If[PrimeQ[p1+p2],1,Null];(*the specific form of the matrix elements chosen for illustrative purposes only*)     mat=ParallelTable[f[p1,p2],{p1,Q},{p2,Q}];(*the matrix to be later compressed to SparseArray*)     mat0=mat/.(Null)->0;(*Here we replace Nulls with zeroes*)     sparse=SparseArray[mat0];(*Now the SparseArray may be applied*)      However, during such replacement procedure, the ByteCount[mat0] is dramatically increased, and at sufficiently large Q one runs out of memory. Besides, it does not seem logical to artificially inflate the matrix in order to be able to compress it afterwards. So, how can I transform a huge rectangular array full of Nulls to a sparse array structure, without replacing Nulls with zeroes? Thank you! P.S. Other ways to form a sparse array that I am aware of are getting too speed- and memory inefficient as Q is taken large (say, Q > 50000), e.g. this way               SparseArray @ Flatten[ParallelTable[{p1, p2} -> f[p1, p2], {p1,Q}, {p2,Q}] /. (_ -> Null) -> Sequence[]];      takes 100Gb of memory to form a sparse array of 10 Gb. P.P.S. One could ask, what's the need to compress a matrix that is already quite sparse? The SparseArray version takes less memory, anyway: ByteCount[sparse] is less than ByteCount[mat]. P.P.P.S. Above was the toy problem. The more realistic code is as follows:               << CompiledFunctionTools`     Compiler`$CCompilerOptions = {"SystemCompileOptions" ->      "-fPIC -Ofast -march=native"};     On[ Compile::noinfo]     n = 4;(*the number of electrons*)     Upp = 6;(*Upp is the upper occupied      quantum state*)     a = Subsets[Range[Upp], {n}];(*a is the set of all many-particle states*)     Q = Binomial[Upp, n];(*The number of many-particle states in a*)     (*Fast compiled function that compares two vectors and returns the positions of different elements.*)     VectorCompare =      Compile[{{v1, _Integer, 1}, {v2, _Integer, 1}}, Block[{i1 = 1, i2 = 1, d1 = Internal`Bag@Most[{0}],       d2 = Internal`Bag@Most[{0}]},     (*Run along the lists,recording differences as we go*)      While[i1 <= Length[v1] && i2 <= Length[v2],       Which[v1[[i1]] < v2[[i2]], Internal`StuffBag[d1, i1]; i1++,        v1[[i1]] > v2[[i2]], Internal`StuffBag[d2, i2]; i2++, True, i1++;        i2++]];     (*Fix up in case we ran off the end of one of the lists*)     While[i1 <= Length[v1], Internal`StuffBag[d1, i1]; i1++];     While[i2 <= Length[v2], Internal`StuffBag[d2, i2]; i2++];     {Internal`BagPart[d1, All], Internal`BagPart[d2, All]}],      "CompilationTarget" -> "C",      CompilationOptions -> {"ExpressionOptimization" -> True,       "InlineExternalDefinitions" -> True}, RuntimeOptions -> "Speed",      RuntimeAttributes -> {Listable}, Parallelization -> True];          CompareMatrix = SparseArray@     Developer`ToPackedArray[     ParallelTable[       If[p1 < p2, vc = VectorCompare[a[[p1]], a[[p2]]];         diff = Length@Flatten@vc;         Which[diff == 2, {vc[[1, 1]], vc[[2, 1]], 0, 0},          diff == 4, {vc[[1, 1]], vc[[2, 1]], vc[[1, 2]],           vc[[2, 2]]}]], {p1, Q}, {p2, Q}] /. (Null) -> {0, 0, 0, 0}];      The array I need could be built without any unnecessary zeros by running the following code:               CMB2 = Internal`Bag@Most[{0}];     CMB4 = Internal`Bag@Most[{0}];     Do[vc = VectorCompare[a[[p1]], a[[p2]]]; l = Length@Flatten@vc;      Which[l == 2,Internal`StuffBag[CMB2, {p1, p2, vc[[1, 1]], vc[[2, 1]]}],     l == 4,Internal`StuffBag[CMB4, {p1, p2, vc[[1, 1]], vc[[2, 1]], vc[[1, 2]], vc[[2, 2]]}]], {p1, 1, Q - 1}, {p2, p1 + 1, Q}];      If only it were parallelizable... Edit: The fastest and memory-efficient solution is as follows:               CM=Join @@ ParallelMap[Developer`ToPackedArray,     Table[vc=VectorCompare[a[[p1]],a[[p2]]];diff = Length@Flatten@vc;     Which[diff > 4, empty,      diff == 4, {p1,p2,vc[[1,1]],vc[[1,2]],vc[[2,1]],vc[[2,2]]},     True, {p1,p2,vc[[1,1]],vc[[2,1]],0,0}],     {p1,1,Q-1},{p2,p1+1,Q}]];      In essence, this closes the question.


title: Doing local FFT on huge 3D vector data cell mesh and visualizing it spatially?

text: **Simulation type:** I'm running a simulation with the OOMMF micromagnetics package http://math.nist.gov/oommf/ where are magnet is represented by a **mesh of 3 million cells** , it gets excited by a magnetic pulse, the single cells oscillate and data output for every cell is $x, y, z$ direction and absolute magnetic field value of every component over time, so a mini-magnet. Now I want to do a FFT on $m_z(t)$ **for every cell** and later visualize this magnet over time while cells with $m_z(t)$ showing common oscillation modes/eigenfrequencies get same color. **Data output format:** It is "data binary 4" and as said $x, y, z$ and absolute field value for every component is given for all time steps (below 300-500 time steps). Download an example of a time-step data file from the middle of the simulation: The manual says: > **The binary representations are IEEE floating point in network byte order > (MSB)**. To insure that the byte order is correct, and to provide a partial > check that the le hasn't been sent through a non 8-bit clean channel, the > first datum is a predened value: 1234567.0 (Hex: 49 96 B4 38) for 4-byte > mode, and 123456789012345.0 (Hex: 42 DC 12 21 83 77 DE 40) for 8-byte mode. > The data immediately follow the check value. The structure of the data > depends on whether the \meshtype" declared in the header is \irregular" or > \rectangular". **For irregular meshes, each data element is a 6-tuple** , > consisting of the x, y and z components of the node position, followed by > the x, y and z components of the field at that position. Ordering among the > nodes is not relevant. The number of nodes is specied in the \pointcount" > line in the segment header. For **rectangular meshes, data input is field > values only, in x, y, z component triples.** These are ordered with the x > index incremented first, then the y index, and the z index last. This is > nominally **Fortran order** , and is adopted here because commonly x will be > the longest dimension, and z the shortest, so this order is **more memory- > access ecient than the normal C array indexing of z, y, x.** The size of > each dimension is specied in the \xnodes, ynodes, znodes" lines in the > segment header. I use a rectangluar mesh here **Question:** The FFT can be done using something like MATHEMATICA or MATLAB for a single cell and ($m_z$/ number, time/number) data list .dat file, but a data binary 4 file for a single time step for 3 million cells is up to 20 MB big, workstation with 30 GB RAM and 12 Cores available. The manual above mentions FORTRAN (to my knowledge not so easy to learn language although very fast). What is the way to achieve the results I'm looking for and described above? From my point of view I face the problem to do the FFT in reasonable time with a script process for around 3 million cells and then transforming that data into a spectrogram (to see what different eigenfrequencies and higher harmonics exist, also this can be done by using the average $m_z$ (summed over all single cells) and simply FFT it) but also have a output format of that data binary 4 format after FFT that can be used to feed a visualization software that can read such mesh data and color code it, show single 2D slices of the 3D object. I read that MATHEMATICA can deal with binary 4 and offers high performance, but as this is completely new land to me, I first want to ask given above constraints and wishes, what is the best way and software/programming language to achieve this in **reasonable time (few weeks)**?


title: Fit an image within a Rectangle [] in Graphics

text: Based on the following Code (yet the white text in the image is added with PPT), I would like to have an image fit within one of the rectangle. For Example the image from there : http://dailytechgadgets.files.wordpress.com/2011/02/old-ferrari.jpg 2 main problem : Although I know about Texture[], I have not been able to use it in my rectangle, nor drawing the correct polygon, or the correct vertex coordinates. The image might not be of the same ratio, so I would like to crop it accordingly. I have not been able to yet without deforming the image. My Ideal OutPut below : ![enter image description here](http://i.stack.imgur.com/ZxLCi.png)               c0 = {RGBColor[23/85, 29/255, 142/255], RGBColor[244/255, 1, 59/255],            RGBColor[1, 0, 32/85], RGBColor[18/85, 72/85, 197/255]}          Graphics[{EdgeForm[Thickness[.005]], White,       Rectangle[{0, 0}, {160, 90}], Black, Opacity[.7],       Rectangle[{0, 0}, {80, 63}], White, Opacity[1],       Rectangle[{80, 0}, {160, 63}], Opacity[1],       Flatten@({Flatten@(Table[            RandomChoice[{GrayLevel[.15], c0[[#]]}], {3}] & /@           Range[2, 4, 1]),        MapThread[        Function[{Xs, Ys},          Rectangle[{Xs, Ys}, {Xs + 16, Ys + 9}]], {Flatten@          Table[Range[0, 32, 16], {3}],          Flatten@(Table[#, {3}] & /@             Range[63, 81, 9])}]}\[Transpose])},       Method -> {"ShrinkWrap" -> True}, ImageSize -> 500]


title: Can't use CUDA shared memory

text: CUDALink is properly installed and up to date, all built-in functions work fine, and all little functions I did worked fine... Until I tried using shared memory. The only example I found on the help doesn't work for more than one reason. It declares the memory without a type and my compiler complains. So that's a bad start. Anyway, I'm trying the most basic function I can, and I can't make it work. I would appreciate if anyone could tell me what's wrong, or if it works (or doesn't) for you, or give me an example that does work... Sample code I'm trying                   testf = CUDAFunctionLoad["__global__ void test(int* out)        {         extern __shared__ int smem[];            if(threadIdx.x==0)         {             smem[threadIdx.x]=7;             out[threadIdx.x]=3;         }else             out[threadIdx.x]=33;           }", "test", {{_Integer, "Output"}}, 16];      When I run it I get a _CUDAFunction::internal:`CUDALink` experienced an internal error. >>_ and then I need to restart the kernel to make `CUDALink` work again               testf[Range[16], 16]      Just commenting out the line with the `smem[threadIdx.x]=7` assignment makes it work. The compiler issues no warnings


title: How to automatically restart Mathematica kernel after out-of-memory error

text: I want to run a Mathematica code repeatedly, even after the kernel shuts down when it is out of memory, because I have designed my program to continue appending the data to a file. Currently, I have to restart the kernel manually every 10 minutes. Does anyone have an idea how one can automate this process? Thanks.


title: Apply 2 Styles within Text[]

text: Please consider :               aboveBox[info_, colors_] :=       Graphics[{colors, EdgeForm[Thick], Rectangle[{0, 0}, {26, 3}],         Text[Style[info, 18, Bold, Black, TextAlignment -> Center],              {26, 3}/2]}, ImageSize -> 300]      ![aboveBox\[\] output](http://i.stack.imgur.com/Hsj0u.png) Now I would like to have a second bit of text aside, with a different style. I know I could use 2 `Text[]`s, but I then struggle with the alignment. Is there a way to have two bits of text with different Style within the same `Text[]` Example of desired output : ![aboveBox\[\] with text in different styles](http://i.stack.imgur.com/611aJ.png)


title: How to plot vector function r(t) = i + j + t*k

text: How can I plot the vector function $r(t) = i + j + t\;k$, where _i, j, k_ are unit vectors, and _t_ is the parameter of the function r.


title: Running a Mathematica Notebook from command line and saving the output

text: I am working on a project that requires some calculations to be done in Mathematica. I don't know Wolfram language and I don't have the time to learn it (I am using a 30-day trial) so I have a python program that is generating a lot of .nb files. What I would like to do would be to be able to run this .nb files from command line and then save their outuput to a .txt, .png, .jpg, any format I can work with without having to open Mathematica, run the notebook and grab the data. The output of the notebook file is given by some calls to Print and also the following command               Show[Graphics[...], Graphics[...],            Graphics[...], Graphics[...], Axes -> False]      The ... were added for this question. I am hoping for a command like: mathematica-command -options file.nb > output_file I have Windows 8 and the latest Mathematica. Thanks in advance.


title: Error messages from compiling the Piecewise function

text: The following works               Compile[{{x, _Real}}, Piecewise[{{{0., 0.}, x > 5.}}, {1., 1.}]]      but if I enter the `Piecewise[...]` in the bracket style, I get two error messages > Compile::cif: The types of the two results in If[True,{1.,1.},0] are > incompatible because their ranks are different. Evaluation will use the > uncompiled function. >> > > Compile::cif: The types of the two results in > If[x>5.,{0.,0.},If[True,{1.,1.},0]] are incompatible because their ranks are > different. Evaluation will use the uncompiled function. >> It seems the bracket style input form of the `Piecewise` function is transformed into               If[x>5.,{0.,0.},If[True,{1.,1.},0]]      and `0` has a different type than `{1.,1.}`. Here is the screenshot: ![enter image description here](http://i.stack.imgur.com/UUQLa.png) `In[2]` works as expected, but when I type the bracket style of `Piecewise` in `In[3]`, it doesn't work. However, if I copy the output bracket style of `Piecewise` in `Out[2]` and put it in `In[4]`, it works again. Why this happens and how to fix it? Am I making stupid mistakes or what?


title: What's inside InterpolatingFunction[{{1., 4.}}, <>]?

text: I'm curious what's inside the `InterpolationFunction` object? For example:               InputForm[Interpolation[{1., 2., 3., 4.}]]     (*       InterpolatingFunction[         {{1., 4.}},          {4, 7, 0, {4}, {4}, 0, 0, 0, 0, Automatic},          {{1., 2., 3., 4.}},{Developer`PackedArrayForm, {0, 1, 2, 3, 4}, {1., 2., 3., 4.}},          {Automatic}]     *)      What do those arguments mean?


title: Cleaning the hyperlinked string from its hyperlink property

text: I need to rename a number of files. These are graphic jpg files, and I have an Excel table in which the initial names of these files are collected. For example, this is the name of one of these files taken from the table: 121026_DeviceData\63486504438_Osc.jpg My problem is that the above name in my Excel file is a hyperlink, rather than a string. By directly addressing this hyperliknk from Mathematica a notebook with a mess inside opens, instead of the desired image. My question is: How could I clean the text of this file name off from its hyperlink property, such that after the cleaning I get a pure string "121026_DeviceData\63486504438_Osc.jpg" instead of the hyperlink? Added later: I have found such an approach:               (hyperlinkText/.Hyperlink->String)[[1]]      that returns me a string: "121026_DeviceData\63486252521_Osc.jpg" With this the question is answered, though somebody might propose a better solution.


title: Text in columns

text: So far I've only seen the front end work in a one-cell-below-the-other manner, so I am probably not expecting much of this question, but here it goes. Is there any way to create a document with text arranged in columns? Perhaps a way to create a cell with two (or more) inline cells with fixed locations that grow as you type? Any ideas?


title: Parallelize evaluation of function with memoization

text: I have a complicated function that I need multiple times, so I want to memoize it and have the first evaluation done in parallel. Unlike in my example below it's not a continuous function, so interpolation is not an option. (In fact, it's values are also functions.) The naive approach clearly does not work, because the memoized value is then only known on the kernel it was evaluated on:               LaunchKernels[2];     f[x_] := f[x] = (Pause[3]; N[Sin[x]]); (*Expensive calculation*)     ParallelDo[f[x], {x, 3}];          ParallelEvaluate[AbsoluteTiming[f[1]]]          (* ==> {{3.000632, 0.841471}, {0.000024, 0.841471}} *)      I believe I found a workaround by doing something like this:               f[x_] := (Pause[3]; N[Sin[x]]); (*Expensive calculation - NO memoization*)     t = ParallelTable[f[x], {x, 3}];     Do[f[x] = t[[x]], {x,3}];      Using `SetSharedFunction[f]` before `ParallelDo` also yields a non-optimal result:               {{0.012051, 0.841471}, {0.012202, 0.841471}}      0.01 s is still a long time to look up a value (see above, it should be < 1 ms). Is there something more elegant or do I have to keep it like this? Edit: Just to be clear, the workaround above without Shared Functions works, it runs in parallel and the main kernel knows the values afterwards, but it strikes me as an ugly hack. I was wondering if there was an "official" solution.


title: Add contour lines to Graphics3D

text: I am writing the following code:               points = {{6, 2.12, .4738}, {8, 2.05, .5254}, {10, 1.99, .5520}, {12,          1.73, .5595}};     faces = {{1, 2, 4}, {2, 3, 4}};     colors = {32.4, 24.3, 19.2, 16.5};     color1 = (colors[[1]] - Min[colors])/(Max[colors] - Min[colors]);     color2 = (colors[[2]] - Min[colors])/(Max[colors] - Min[colors]);     color3 = (colors[[3]] - Min[colors])/(Max[colors] - Min[colors]);     color4 = (colors[[4]] - Min[colors])/(Max[colors] - Min[colors]);     pts = Map[toPoint, points];     Graphics3D[{GraphicsComplex[ points, Polygon[faces],         VertexColors -> {RGBColor[color1, 0, 1], RGBColor[color2, 0, 1],           RGBColor[color3, 0, 1], RGBColor[color4, 0, 1]}]},       BoxRatios -> {1, 1, 1/2}, Axes -> True, Lighting -> Automatic]      The result is successful, but lacks contour lines for a 3D effect. How can I add that feature? ![My image:](http://i.stack.imgur.com/kJj3n.jpg) Edit: pts is leftover code from something else. It does nothing. I am trying to get continuous mesh over the surface of both triangles to make them look more 3-dimensional. The two surfaces in the attached image are in different planes, but they share a common edge. I need contour lines or mesh to emphasize that these two surfaces are not in the same 2-dimensional plane.


title: What format can Image3D be exported to?

text: ![3ds not working](http://i.stack.imgur.com/MPpmn.png) ![enter image description here](http://i.stack.imgur.com/tiacJ.png) I made a 3D image by stacking 2D images (Image3D command). When I tried to export it, 3DS and X3D are not working. What format can I export?


title: Combining two notebooks

text: I have a notebook which contain all the variables and defined functions. I want to do two tasks. As an example, I want to find the density and energy which have equations in terms of above mentioned variables and functions. If I write one code for these two tasks, it is a very large notebook. So, if I have separate notebooks for "variables and functions",density and energy, how can I connect each notebook so that they can run properly and give the result? Could anyone please help me to do this?


title: Why are some option values symbols, other strings?

text: Is there a rationale, beyond historical accident, why some _Mathematica_ option values are strings, while others are symbols? It seems natural that some value spaces, e.g. named color schemes, are so numerous and only applicable to `ColorData`, e.g. `ColorData["HTML"]` and so should be strings. On the other hand wouldn't it make more sense if `"XAxis"` in `PairedHistogram[..., BarOrigin -> "XAxis"]` were a built in symbol to be shared as an option value across composite graphics functions?


title: From ReadList[package,String] back to a Package

text: I read in a package as a list of strings Using ReadList ReadList["package1`", String] StringReplace can then be used on (e.g. mapped over) this list of strings. Is there anyway to save/export the result as a revised package (overwriting "package1`")


title: How do I create a histogram out of this datastructure: x[i] = value_i?

text: Here is my SSCCE:               a[1] = 2; a[2] = 3; a[3] = 6; Histogram[a]      This throws and error though. Here are my questions:   1. What kind of data type is a? Is it an Array? a List? So far as I can tell it's neither.    2. How do I get the above to work?


title: How to programmatically comment out multiple source files?

text: How to programmatically comment out the entire content of multiple `.m` source files assuming they start with correct Mathematica syntax? I need it to be robust so the content of the file can be anything as long as it's valid `.m` source file.


title: Is it possible to modify the tick marks in BarChart plot?

text: I need to specify the length of the tick marks on the x axis in a `BarChart` plot:               BarChart[      {{1, -2}, {2, -3}, {3, -4}},      BarSpacing -> {0, 1},      Axes -> True,      Ticks -> None,      TicksStyle -> Red]       ![enter image description here](http://i.stack.imgur.com/91rdN.png) I can modify the style settings for the tick marks on the x axis. However, I found no possibility to remove (see code above with the option `Ticks -> None` ) nor to give the specified positions of the tick marks. In particular, I want to specify the lengths in the positive and negative directions, like described in the `Ticks` description in the documentation center.