title: Using Map with If

text: I have an If statement I need to carry out where the result should be a single number for each time the if is executed. What I have at the moment returns a list for each time the If is executed. I specifically do not want to use a Do loop so is there a way to use Map to do this?               x = {0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`};     y = {0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`};     z = {0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};          TimeModelSelection[41]     {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}      The first few lines of the result are               Map[If[# == 0, x*y, z] &, TimeModelSelection[41], {1}]     {{0.8053429162, 0.8053429162, 0.8053429162, 0.8053429162,        0.8053429162, 0.8053429162, 0.8053429162, 0.8053429162,        0.8053429162, 0.8053429162, 0.8053429162, 0.8053429162,        0.8053429162, 0.8053429162, 0.8053429162, 0.8053429162,        0.8053429162, 0.8053429162, 0.8053429162,        0.8053429162}, {0.8053429162, 0.8053429162, 0.8053429162,        0.8053429162, 0.8053429162, 0.8053429162, 0.8053429162,        0.8053429162, 0.8053429162, 0.8053429162, 0.8053429162,        0.8053429162, 0.8053429162, 0.8053429162, 0.8053429162,        0.8053429162, 0.8053429162, 0.8053429162, 0.8053429162,        0.8053429162},...      I have also tried thefollowing without luck               Map[If[# == 0, x[[#]]*y[[#]], z[[#]]] &, TimeModelSelection[41], {1}]


title: Bug when using Plot3D over an ImplicitRegion?

text: Evaluating this expression seems to cause Mathematica to beep and quit the kernel:               Plot3D[Exp[Sqrt[x^2]] - Exp[-Sqrt[x^2]], {x, y} \[Element] ImplicitRegion[-5 <= x <= 5 && -5 <= y <= 5 , {x, y}]]      I am running Mathematica 10.0.0 on MacOS 10.9.4. Is this a known issue? Interestingly, plotting only one of the exponentials rather than their difference does not produce any problems.


title: Forget past outputs to free memory

text: While tinkering with a notebook that loads a large chunk of data in memory, I noticed that if I run it multiple times, the past chunks reside in memory. I understand that the reason (or one of) for which this happens is that the past output mechanism (`%`) keeps a reference to them, so they cannot be garbage collected. Is there a way to explicitly make _Mathematica_ forget some data?


title: Sparse convolution of sparse arrays

text: The documentation for `ListConvolve` mentions that "ListConvolve works with sparse arrays", which is true. The result, however is never sparse, eg:               a = SparseArray[50 -> x, 1000];     b = SparseArray[40 -> 2, 50];     ListConvolve[b, a]      Is there a way to do "sparse convolution"? (The background is multiplication of high-degree many variables polynomials.)


title: Any ideas on how GeneralMiniMaxApproximation is implemented?

text: `GeneralMiniMaxApproximation` is used to construct minimax approximations of parametrically defined functions. I am curious about how `GeneralMiniMaxApproximation` is implemented (just a general overview). Any ideas? Or is this a _Mathematica_ trade secret?! The document states that `MiniMaxApproximation` uses Remez's second algorithm, but does this algorithm extend to parametrically defined functions? I can't seem to locate any references.


title: How to correctly call a Module within another Module?

text: How to embed and call the correct embedded modules inside another `Module`? Say:               importNames:=Module[{},           CWC=FinancialData["CWC.L","Jan. 1, 2007"];           KON=FinancialData["AH.MI","Jan. 1, 2007"];           IFX=FinancialData["IFX.DE","Jan. 1, 2007"];           ISYS=FinancialData["ISYS.L","Jan. 1, 2007"];           LAD=FinancialData["LAD.L","Jan. 1, 2007"];       ]            checkLength:=Module[{},           LCWC=Length[CWC];           LKON=Length[KON];           LIFX=Length[IFX];           LISYS=Length[ISYS];           LLAD=Length[LAD];       ]            plotNames:=Module[{},           plotCWC=DateListPlot[CWC];           plotKON=DateListPlot[KON];           plotIFX=DateListPlot[IFX];           plotISYS=DateListPlot[ISYS];           plotLAD=DateListPlot[LAD];       ]          Remove[corrMat];       Remove[importNames];       Remove[checkLength];       Remove[plotNames];             corrMat:=Module[{},             importNames;           checkLength;           plotNames;       ]            corrMat       plotNames       plotKON        When doing `plotKON`, how do I know it is calling from within the base definition of `plotNames`, or it is called from `corrMat.plotName.plotKON` (using java syntax)?


title: Creating a cross referencing shortcut

text: I believe I have gather all the pieces of information I need to create what I want but yet I cannot make the connection. Let me start with the goal. # Simple Cross referencing Let us start by creating a new notebook. Here we create a `"DisplayFormulaNumbered"` cell. Enter whatever contents you want here. Then press `command`+`J` or `control`+`J` in windows and enter the tag that you want to give your equation. Here is a screenshot of what I have so far: ![enter image description here](http://i.stack.imgur.com/P1INB.png) To be able to see the tag go to `Cell > Cell Tags > Show Cell Tags`. What we want now is to refer to eq1. Here is a text cell: ![enter image description here](http://i.stack.imgur.com/CdpRs.png) Notice here that I'm using the exact $\LaTeX$ notation. What I want to do now, is to be able to select the text cell, press some button in a palette and obtain this: ![enter image description here](http://i.stack.imgur.com/yWq6F.png) # Tools gathered so far jVincent showed me here how to create the a button that executes a function to replace a selected part of the text. Notice here that I do not want to be selecting parts of text manually, I want to apply the function to the whole cell and replace the part containing ref with `CounterBox["DisplayFormulaNumbered", "eq1"]`. In other words, the ref parts will tell it to put "DisplayFormulaNumbered" and the text in between the brackets next to ref is the tag. To find the cases where I have ref we can use something like this:               StringCases["Reference \\ref{tag1} goes here. Reference \\ref{tag2} \here.", "\\ref{" ~~ __ ~~ "}"]          {"\\ref{tag1} goes here. Reference \\ref{tag2}"}      Unfortunately, I'm not quite making a good use of it. But the idea is to maybe use something like this to obtain the tag. Next we have to check if this is a valid tag in the notebook (given that we were able to locate the tag in the whole string):               MemberQ[NotebookTools`NotebookCellTags[EvaluationNotebook[]], "tagName"]      This is thanks to Rojo's answer. I feel a little ashamed that I cannot combine the tools that you guys have provided me yet but I'd rather get this out of the way so that I can be more efficient when doing cross referencing. What do you guys think? Is this worth the trouble of creating a palette button that does this? # EDIT: The idea I was suggesting for making the shortcut is by no means what I wanted to see. I guess I should have clarified that really all I wanted to see was an easy and fast method of dealing with cross referencing. Albert Retey has shown two methods in his answer and makes a good point that if you were to keep typing large chunks of text and evaluate everything in one go then my suggestion would be justified. In any case, I'm satisfied with Retey's method but other neat ideas are still welcomed.


title: IntegerDigits has Listable attributes, but not fast

text: See this example, a function has `Listable` attributes often more efficient than `Map`,but why is this one is an exception?               With[{n = 6},        IntegerDigits[Range[10^(n - 1), 10^n - 1]]        ] // Hash // AbsoluteTiming     (*{1.573090, 756716557}*)          With[{n = 6},        IntegerDigits /@ Range[10^(n - 1), 10^n - 1]        ] // Hash // AbsoluteTiming     (*{0.202012, 756716557}*)


title: Implementing Central Symmetry

text: I'm interested in implementing symmetry groups. So it would be useful to have central symmetry (isometry transformation). There are built-in functions: `RotationTransform`, `TranslationTransform` and `ReflectionTransform`, but I was not able to find something like central symmetry. The goal is to translate one object of any kind (image or built-in graphical primitives) into the symmetric analog to it. If anyone has any thoughts, please write!


title: How to compute values only if input fields are filled?

text: In the following code how can I keep the DynamicModule from computing values if the input values are not all filled? If I don't specify default values it will show the code used to compute the values instead of blank values. Thanks.               backingAgreementValue[w_, \[Sigma]_,        a_] := \[Sigma] /Sqrt[2 \[Pi]] Exp[ -(w - a)^2/(2 \[Sigma]^2)] +        w CDF[NormalDistribution[0, 1], (w - a)/\[Sigma]]          DynamicModule[{w = 40, \[Sigma] = 600, a = 0, n = 100, horseCut = 0.5,        backingValue, expectation, backerValue, horseValue,        horseExpectationPercentage, values},       Deploy[Style[        Panel[Grid[          Transpose[{{Style["Mean", Blue],              Style["Standard Deviation", Blue], Style["Threshold", Blue],              Style["N", Blue], Style["Player Cut", Blue],              Style["Backing Agreement Value", Orange],              Style["Expectation", Orange], Style["Player Value", Orange],              Style["Player Expectation Percentage", Orange],              Style["Backer Value", Darker[Magenta]]}, {InputField[              Dynamic[w], Number], InputField[Dynamic[\[Sigma]], Number],              InputField[Dynamic[a], Number],              InputField[Dynamic[n], Number],              InputField[Dynamic[horseCut], Number],             Dynamic[              Style[backingValue =                 backingAgreementValue[expectation, \[Sigma] Sqrt[n], a] //                  N, If[backingValue >= 0, Darker[Green], Red]]],             Dynamic[              Style[expectation = w n // N,                If[expectation >= 0, Darker[Green], Red]]],             Dynamic[              Style[horseValue = horseCut  backingValue // N,                If[horseValue >= 0, Darker[Green], Red]]],             Dynamic[              Style[horseExpectationPercentage =                 horseCut backingValue/expectation // N,                If[horseExpectationPercentage >= 0.5, Darker[Green], Red]]],             Dynamic[              Style[backerValue = (expectation -                     backingValue + (1 - horseCut) backingValue) // N,                If[backerValue >= 0, Darker[Green], Red]]]}}],           Alignment -> Left], ImageMargins -> 10],         DefaultOptions -> {InputField -> {ContinuousAction -> True,             FieldSize -> {{5, 30}, {1, Infinity}}}}]],       SaveDefinitions -> True]


title: SplineDegree->1 does not work with BezierFunction?

text: This works (`SplineDegree -> 2`)               ParametricPlot[BezierFunction[{{0, 0}, {1, 0.5}, {2, 2}}, SplineDegree -> 2][u], {u, 0, 1}]      ![BezierFunction SplineDegree 2](http://i.stack.imgur.com/8fZhz.png) but this does not (`SplineDegree -> 1`)               ParametricPlot[BezierFunction[{{0, 0}, {1, 0.5}, {2, 2}}, SplineDegree -> 1][u], {u, 0, 1}]      > BezierFunction::invdeg: Value of option SplineDegree -> 1 should be a > positive integer, or a list of positive integers I found no reference to a possible issue in the documentation for `BezierFunction`. `SplineDegree -> 1` works fine with `BSplineFunction` and `BezierCurve`; shouldn't it also work with `BezierFunction`? (Mma 8.0.4 Mac OSX)


title: Is there a way to use functions like Prime[n] within Solve[]?

text: I'm trying to see if a number can be written as the sum of two prime numbers. Ideally, I would like to use               Solve[ Prime[n] + Prime[m] == 100, {n, m}]      But that simply doesn't work in _Mathematica_. So is there another way to implement this?


title: How and when to use Evaluate?

text: A month ago, I used Mathematica to solve my experiment of the Test Technology of Mechanics Engineering. The exeriment is mainly about the Fourier Transform and verify the validity of the theory of Fourier. My code is below:                originwave[t_] :=        If[-5 <= t <= 5, t, If[t > 0, originwave[t - 10], originwave[t + 10]]];     (*the definition of SawtoothWave function*)      **four periodic originwave**               Column[           {Plot[originwave[t], {t, -20, 20}, PlotRange -> {-5, 5},                 AspectRatio -> 1, ImageSize -> 300, AxesStyle -> Arrowheads[0.03],                 AxesLabel -> {"t", "four periodic originwave"}           ]},           Center]      ![four periodic originwave](http://i.stack.imgur.com/ty9AL.png) **The seven order Fourier series expansion**               Column[           {Plot[Evaluate[FourierTrigSeries[originwave[t], t, 7]], {t, -20, 20},                PlotRange -> {-5, 5}, AspectRatio -> 1, ImageSize -> 300,                 AxesStyle -> Arrowheads[0.03],                 AxesLabel -> {"t", "The seven order Fourier series expansion"}]},           Center]      ![The seven order Fourier series expansion](http://i.stack.imgur.com/TAmCy.png) Furthermore,I encounter a problem about Taylor Series that we can use the approximate value of Maclaurin Series to replace a function. I can see the degree of closeness between them by changing the variable n. That's my trial:               Manipulate[               Show[                   Plot[E^x, {x, 0, 5}, PlotStyle -> Pink],                   Plot[Evaluate@Normal@Series[E^x, {x, 0, n}], {x, 0, 5},                         PlotRange -> {0, 150}]],              {{n, 6}, 0, 10, 1, Appearance -> "Labeled"}]      ![enter image description here](http://i.stack.imgur.com/nfGeM.png) Lastly ,the problem of plotting 2-D graph of `|x|+|2x+y|=1`, below is the solution:               Plot[y /. Solve[Abs@x + Abs@(x + y) == 1, y, Reals] //           Evaluate, {x, -2, 2}, AspectRatio -> Automatic]      ![enter image description here](http://i.stack.imgur.com/Yc75g.png) **Summary and my confusion:** In three tasks, I am alway using the `Evaluate` command. Firstly,I know this command and I will remember it when the MMA cannot give the result that I want. However, it is confusing to me that I don't know when to use it or not use it. Can someone help me?


title: Finding a Concave Hull

text: I have a 3d clustered data: Is there any other way to get concavehull of 3D data points?


title: Exporting extremely large images; arrays generated via TensorProduct use 5 times as much RAM as expected?

text: I am generating plots of the roots of certain classes of polynomials, in the spirit of the multicolored visuals on the Wiki page on algebraic numbers. I've thus far been able to make some extremely spectacular plots, such as this 3600 x 3600 image of the roots of the monic quadratics and cubics (very low-res preview below) ![enter image description here](http://i.stack.imgur.com/KZYZa.jpg) and this 4600 x 4600 image of the roots of the cubics with lead coefficient 5 (low-res preview below) ![enter image description here](http://i.stack.imgur.com/G37MC.jpg) and this 4600 x 4600 image of the roots of the cubics with lead coefficient 1 or 5 (low-res preview below). ![enter image description here](http://i.stack.imgur.com/yBjIW.jpg) I have been running into a RAM usage bottleneck during the `Export` step as I try to make more detailed visuals. To make the images, I essentially execute               Export["Imagename.PNG",Image[A]]      where $A$ is roughly a $4600\times 4600\times 3$ rank-3 array specifying the RGB color channels. I was having issues with the MathKernel swallowing many gigabytes of RAM and initially thought it was from the Image `Export` step, but it turns out it's due to the `TensorProduct` I used to generate $A$. I've begun to observe that arrays generated via `TensorProduct` occupy 5 times as much RAM as I would naively expect. For example,               $HistoryLength = 0;     L = 2000;     a = RandomReal[{-10^6, 10^6}, {L, L}];     b = RandomReal[{-10^6, 10^6}, 3];     c = TensorProduct[a, b];     d = RandomReal[{-10^6, 10^6}, {L, L, 3}];     ByteCount[a]     ByteCount[b]     ByteCount[c]     ByteCount[d]     Quit[]      indicates that $c$ occupies 480 MB RAM, while $d$ occupies 96MB RAM. Choosing $L=4600$ shows that $c$ occupies 2.6 GB RAM, while $d$ occupies 500 MB RAM. Changing the ranges of `RandomReal` from $10^6$ to other numbers does not significantly alter the result. This is a bit unexpected, since both $c$ and $d$ are of the same dimension and same MachinePrecision entry type, and yet the manner of array generation seems to strongly impact the space it occupies in RAM. Question: _Does anyone know why using`TensorProduct` to generate an array creates an array object which occupies 5 times the normal RAM amount as comparable arrays generated via other means?_ EDIT: After applying the packed array fixes, things work well. Here are links to the two notebooks that can be used to generate the images I used. _Root Generator_ is used to compute and export the polynomial roots of one's choice to sparse matrix formats, and _Root Visualizer_ imports the sparse matrices and exports the images. I use packed arrays in the RAM-intensive parts, and `Compile` the convolution kernel used to blur the image. If anyone sees any obvious improvements that could be made, I'd love to hear it.


title: Permutation count for sets with multiplicities

text: I am able to do a permutation counr for the set `{a, a, b}` which gives me 3 groups. I am happy with that result. However, if the set is `{a, a, b, c, c, d}`, _Mathematica_ gives me all the possible groups, but it is difficult to count the number of groups. Can _Mathematica_ find the total number of groups? If so, which function to do I use?


title: Pattern evaluation in nested function call

text: I'll put the question right here, but will add some context below in case someone wonders why the heck I'm trying to do this. Why is it that I have to do two passes to get the value of the arguments in the call to f1 below?               In[24]:= s = { 10 Cos[-Pi t], -4 Sin[0.23 t]};          In[25]:= f2[a1_, a2_, a3_] := Module[                {a = a1, phi = a3},                Function[                   a a2[phi #1]                ] (* #1 is the time *)               ]                   f1 := Function[                      f2[#1, #2, #3]              ]          In[27]:= l = Cases[s, amp_ trig_ [afreq_ t] -> f1[amp, trig, afreq]]              %[[1]][.33]          Out[27]= {a$1667 Cos[phi$1667 #1] &, a$1667 Sin[phi$1667 #1] &}              (* I expected amp and afreq to have been replaced by                 their matched values, and a numerical value here *)     Out[28]= amp Cos[0.33 afreq]                   (* It works as I (naïvely) expected when I introduce this temporary symbol, func *)     In[29]:= l = Cases[s, amp_ trig_ [afreq_ t] -> func[amp, trig, afreq]]              % /. func -> f1              %[[1]][.33]          Out[29]= {func[10, Cos, \[Pi]], func[-4, Sin, 0.23]}          Out[30]= {a$1668 Cos[phi$1668 #1] &, a$1669 Sin[phi$1669 #1] &}          Out[31]= 5.09041      **Context:** I'm a total noob to Mathematica, but I do ok with plenty of other progamming languages. This issue came up in a structural dynamics course I'm teaching, using Mathematica as a support tool. Not that it should matter here, but I'm using it to compute the dynamic response of a SDOF system to a periodic excitation. I compute the Fourier series expansion of the forcing function, then apply a function that I've written to all terms of the expansion and then sum it all up. I have removed all of the details of this to concentrate on the essence of the problem, but I'd be more than happy to post the entire functions in case it helps. I come from a hpc background, where we tend to overcomplicate things in search of "efficiency", bear that in mind :) The general ideal is that the response is a function of many physical parameters, and the time, but for a single term of the expansion, only the time varies and the physical parameters are fixed. I wrote a function that takes all the physical constants and forcing terms, computes some constants _as local variables inside a module_ , and returns a function of time using these constants. For all terms of the expansion, however, the physical parameters are the same, just the forcing terms are different, so I wrote another function that takes the physical constants, and returns a function that takes only the forcing terms, combines them with the physical parameters and calls the function above, returning a function that depends only on time, and has all that is constant precomputed. It's worth noticing that the variable that is not local to the module always gets substituted. Even though the original question has been answered, I'm adding the original functions here as a justification for my roundaboutery...               fresp[F0_, w_, m_, c_, k_, trig_] :=       Module[{phi = ArcTan[k - m w^2, c w], A = F0/Sqrt[(k - m w^2)^2 + (c w)^2]},       Function[ t, A trig[w t - phi]]]     ]          tresp[ m_, c_, k_] := Function[        fresp[#1 (*F0*), #2(*w*), m, c, k, #3(*trig*)]     ]          mck1 = tresp[2., 2., 3.]     mck2 = tresp[1., 1., 2.]      The idea being that each mck function would represent the response of a different physical system. I apologize if my mind has been poisoned by object orientation :)


title: How can I make a ContourPlot3D with inequality constraints?

text: I need to plot a function in implicit form as below:               ContourPlot3D[{73.04 z*y^2 - 293.04 z*x^2 ==         2605.68 y^2 - 2605.68 x^2}, {x, 0, 3}, {y, 0, 6}, {z, 0, 15}]      but with the constraint `x > y`. How can I do this with _Mathematica_?


title: Set of integers not divisible by smaller set of primes

text: Let $p_n$ be the sequence of prime numbers, and $s(x,n)=$ the set of integers less or equal than $x$ that are _not_ divisible by $p_1,\dots,p_n.$ I can define it as follows:               s[x_,n_]:=DeleteCases[Map[If[Total[Table[Map[If[CoprimeQ[Prime[Range[n]],a][[#]]==True,1,0]&,Range[n]],{a,1,x}],{2}][[#]]==n,Range[x][[#]],0]&,Range[x]],0]      But it is inefficient. I am sure there is a more efficient way of doing this.


title: How to make this particular replacement involving exp

text: I apologize if similar questions have already been asked, but I have some difficulties with replacements in Mathematica and I would like to make a substitution like               Exp[I m phiA] --> f[m,phiA]     Exp[I m phiB] --> f[m,phiB]      where m is a number and `phiA`,`phiB` are variables, in expressions that contain sums in the exponent, e.g.               2 + Exp[-2 I (phiA + phiB)] + Exp[2 I phiA + 2 I phiB]      which should give               1/4 + f[-2,phiA] f[-2,phiB] + f[2,phiA] f[2,phiB]      Is this possible? How can it be done?


title: A Box for the integral or partial derivative d

text: I am looking for the name of the box in the Box Language of Mma making integrals, such as those shown in the image below ![enter image description here](http://i.stack.imgur.com/5t7Nx.jpg) as well as of the sign of the partial derivative. I understand that I can get it through MakeBoxes trick, but it would be nicer to have special operator for such a purpose. The code with such an operator will be more concise.


title: Can ReplacePart be sped up?

text: Test case:               data = RandomReal[1, {1000, 1000}];     pos = RandomInteger[{1, 1000}, {5*10^5, 2}];     r1 = ReplacePart[data, pos -> 0]; // AbsoluteTiming     (data[[##]] = 0) & @@@ pos; // AbsoluteTiming     data == r1          (*     {3.433196, Null}     {1.892108, Null}     True     *)      The similar matlab code only takes about 0.16 second:               tic;     A=rand(1000,1000);     pos= randperm(5e5);     A(pos)=0;     toc;     (*Elapsed time is 0.166717 seconds.*)      I am looking for a more efficient way.


title: How can I get $(r^{1/x})^x$ to simplify to $r$?

text: `Simplify` and `FullSimplify` do not simplify this kind of expression: $(r^\frac{1}{x})^x$. Consider               FullSimplify[r^2+(r^(2/x))^x+(r^(2/(x+y)))^(x+y)]      _Mathematica_ 's output is the same as my input, instead of `3 r^2`. Is there a way to simplify $(r^\frac{1}{x})^x$ to $r$?


title: Domain restrictions for NMaximize

text: I am trying to solve a maximization problem, where my variable can only take a limited number of values. (Probably) the easiest example would be               dom = {0, 1/2}; NMaximize[{x^2, Element[x, dom]}, {x}]      While the `Element[x,dom]` syntax works just fine for `dom = Integers`, I keep getting error messages for any other domain. (edit: this seems to be because my chosen domain is invalid to use with ∈) edit: I also tried the `MemberQ` syntax as stated below:               dom = {0, 1/2}; NMaximize[{x^2, MemberQ[dom, x]}, {x}]      This seems to be an acceptable constraint, but for some reason _Mathematica_ seems unable to find a value that meets the constraint, as I get the following message: > NMaximize::nsol: There are no points that satisfy the constraints {False}. Any other ideas? edit: just to clarify. I need to restrict the variable(s) to a finite set of real numbers, hence I cannot use ">=/<=" constraints to get the job done. The above is just the simplest application I could think of.


title: Log is not being evaluated inside Grid

text: My command is:               Grid[{{N, logN!, N log N - N}, {10, Log[10!], 10 Log[10] - 10}}, Frame -> All]      In the second row of the grid, the function `Log[]` is not being evaluated. Please let me know what is going wrong.


title: How to render a 3D ellipsoid with Graphics3D?

text: With `Graphics3D[Sphere[{0,0,0},1]]` I can render a uniform 3D sphere, but how can I render an ellipsoid? I would need to specify the rotation of the ellipsoid and the length of the main axes. And the method should be reasonable fast to display around 100 at once.


title: Help on evaluation control?

text: I want to plot series of slopes: x, 2x, 3x, 4x, 5x, 6x... I'm trying to do this:               a = Range[10]; c = 0; Clear[b]     f := ToExpression[ToString[b] <> ToString[a[[c = c + 1]]]]      So everytime I input `f`, it gives me:               b1     b2     b3     b4     ...      Now I want to assign every bn to one of the plots:               b1=Plot[x,{x,1,10}]     b2=Plot[2x,{x,1,10}]     b3=Plot[3x,{x,1,10}]     b4=Plot[4x,{x,1,10}]     ...      I've tried to do this:               f=Plot[x,{x,1,10}]      But It will only switch the variable from the first fuction to the Plot function. How can I do to the `f`become `b1` first and then the `b1` be assigned to the Plot function? I guess it has something to do with evaluation control, something like that. NOTE:. The ? in the title means that I'm not very sure If it's about evaluation control.


title: How to get the quantity of Physical constants?

text: I need to get the quantity of gravitational constant: `QuantityMagnitude[GravitationalConstant]` why this is not work? Already load the `PhysicalConstants` package.


title: Interpreting a certain result of Minimize

text: I am given a certain function $f(k_1)$ that I would like to minimize. Asking Mathematica to do it (and supplying the given bounds of other parameters in the expression) I get the following result:               f[k1,k2] = (k2 * r + k1)/(r + (k2*r + k1 -1)*d) + (k1 * r + k2)/(r + (k1*r + k2 -1)*d)     k2 = 2*n/(r+1)-k1       Minimize[f, {k1 >= 0, r >= 2, n >= 2,k1 <= 2*n/(1+r),  d >= 2, d <= r}, {k1}]      > >      {Piecewise[{{f, d >= 2 && r >= d && n >= 2}}, Infinity], >          {k1 -> Piecewise[{{n/(r+1), d >= 2 && r >= d && n >= 2}}, > Indeterminate]}} >   My question now is: What is this result supposed to mean? Somehow I am not able to understand what the output tells me about the minimum of the function I am trying to minimize.


title: How to get the distance of Jupiter from the sun?

text: I am aware of the command `AstronomicalData["Jupiter", "Distance"]` from which I can get the distance between the earth and Jupiter. Is there any way to use `AstronomicalData` to get the distance between the sun and Jupiter?


title: Solve Laplace equation using NDSolve

text: I am new to Mathematica, a friend recommended this software and started using it, in fact download the trial version to know. I recently did a program in C to calculate numerically the solution to the Laplace equation in two dimensions for a set of points as in the figure. ![enter image description here](http://i.stack.imgur.com/ustcO.png) The result was very good, finding the image below. ![enter image description here](http://i.stack.imgur.com/6OKmy.png) This program took me about 100 lines in C, my friend told me that Mathematica could do it in a couple of lines, which seemed quite interesting. I studied a bit and found that Mathematica can solve the Laplace and Poisson equations using NDSolve command. However, this command requires to be given to the specific boundary conditions. The boundary condition in which $\phi = 0$, it is quite easy to introduce. But on the inside border, where $\phi = 100$, I failed to get the condition. My idea is to make this problem as follows:                           uval = NDSolveValue[{D[u[x, y], x, x] + D[u[x, y], y, y] ==                  0,                  u[x, 0] == u[x, 100] == u[0, y] == u[100, y] == 0,                  u[40, y] == u[60, y] == u[x, 40] == u[x, 60] == 100},                  u, {x, 0, 100}, {y, 0, 100}]      But this does not work, and I could not give the boundary conditions on the inner square. Any help would be the most grateful.


title: Find the point that holds a given property

text: I have a normal distribution with mean 106, and a standard deviation of 8. I'm being asked to find the point that has the property that 25% of these values have this value or lower. What I've concluded on my own (I'm just learning _Mathematica_ ) is that the value I'm looking for would be `y` in the following:               NProbability[x <= y, x \[Distributed] NormalDistribution[106,8]] = 0.25      Since I'm not very well versed in the language, I'm hoping someone can lead me in the right direction here.


title: Find file names in directory

text: I am trying to find the list of any file in any directory of a given name (by in the directory, I mean directly in the directory, so in a directory which is in the directory would not count). For the sake of example. Let's suppose I want to find all files in each folder called "Preferences", and let's restrict our search to the folder ~/.Mathematica. If I wanted to do this from the terminal, I could just do `find ~/.Mathematica -regex ~/.Mathematica.*Preferences/[^/]*`. This works and I see there is a single file matching my criteon, `~/.Mathematica/ApplicationData/Parallel/Preferences/Preferences.m` But I want to try to do it conveniently in mathematica. I am thinking the `Filenames` function should do it. I will first run `SetDirectory["~/.Mathematica"]` Then I would run               fileAndDirectoryNames =       FileNames["*",RegularExpression[".*Preferences"], 1]      followed by               fileNames = Select[fileAndDirectoryNames, ! DirectoryQ[#] &]      However, this gives incorrect results for me: `fileAndDirectoryNames` is an empty list. If I instead run               fileAndDirectoryNames =       FileNames["*", RegularExpression[".*/.*/Preferences"], 1]      and recompute `fileNames` as before, then I get correct output. I am confused because it seems to me that the regular expression in my second attempt is stronger (allows for fewer matches) than the one in my first attempt. The fileNames function should have a monotonicity property in the second argument that if you weaken the pattern, then the new output ought to be a superset of the original output. Yet this doesn't seem to happen. Why is this? I am not sure if I am having a problem with mathematica or my understanding of regular expressions.


title: Visualization of iteration procedure in NMinimize

text: I have this optimization code:               vars1 = Array[Subscript[x, #] &, {4}];     ka = {35, 10, 20, 25};     objectiveFunction = Total[ka.vars1^5];     NMinimize[{objectiveFunction/100,      Apply[And, Thread[GreaterEqual[vars1, 0]]] && Total[vars1] == 100 &&     Element[vars1, Integers]}, Flatten[vars1], MaxIterations -> 200]      How is it possible in MMA to capture the values of variables and also objective function in each iteration and plot them versus iteration number??(Separate plots or all in one plot?)


title: Strange behaviour of Internal`InheritedBlock

text: I was going to post an answer for fast way to replace all zeros in the matrix. I was even quite happy because timings were the same order of magnitude as others. The idea was to overwrite `Identity`:               Internal`InheritedBlock[{Identity}, Unprotect[Identity]; Identity[0] = 1;              Map[Identity, {{2, 0}, {Pi, 9}}, {2}]]      > >     {{2, 1}, {Pi, 9}} >   But I've checked that for bigger matrices the result is not even close to the expected one:               Internal`InheritedBlock[{Identity}, Unprotect[Identity]; Identity[0] = 1;              m = RandomInteger[1, {100, 2}];         Map[Identity, m, {2}] ~ Shallow ~ {5, 2}]      > >     {{0, 1}, {1, 0}, <<98>>} >   * * * It seem it breaks at **size** of the array of about $90$ positions:                test = Internal`InheritedBlock[{Identity}, Unprotect[Identity]; Identity[0] = 1;                   Apply[               Boole[Map[Identity, RandomInteger[1, {##}], {2}] == ConstantArray[1, {##}]                    ]&,                                    Array[List, {35, 35}],               {2}]];          Show[MatrixPlot[test, DataReversed -> True, Mesh -> All],          ContourPlot[x y == 90, {x, 1, 35}, {y, 1, 35}]          , BaseStyle -> {Thickness@.01, 18}]      ![enter image description here](http://i.stack.imgur.com/XLFUA.png) * * * I hope I haven't missed anything obvious. Any ideas?


title: how to take some parts of String with certain pattern

text: I have the large number of files in which the file's names follow certain pattern. for example here are names of two files               name1="event_No. 2_20140311_910_914.jpg"     name2="event_No. 403_20140311_230727_230731.jpg"      I need to extract the last two numbers of the names to get something like this (String or Expression, it does not matter):               {"910","914"}     {"230727","230731"}      I tried StringTake but it is not supporting Rules and patterns. can any one suggest some way to do this? Thanks


title: How to determine BLAS/LAPACK implementation used internally for numerical matrix operations?

text: Is there a command which reveals which implementation of BLAS and LAPACK are used in Mathematica's matrix operations such as `Eigensystem`? I asked a related question on StackOverflow and one user mentioned that in Julia, the BLAS/LAPACK implementation can be found by executing `versioninfo()`. Several users who tried my code there had varying results, with some observing Mathematica to execute faster, and others observing Julia executing faster. In my case, my Julia installation appears to make use of the OpenBLAS implementation, and it runs between 3 to 6 times slower than Mathematica's `Eigensystem` for randomly-generated arrays of size $1000\times1000$ to $2000\times2000$. In the Mathematica documentation's tutorial/SomeNotesOnInternalImplementation, it mentions "For dense arrays, LAPACK algorithms extended for arbitrary precision are used when appropriate" and "BLAS technology is used to optimize for particular machine architectures", but nothing more. EDIT: So in response to Kuba's comment, apparently one of the Julia devs noted that there is anomalous behavior in Julia with regards to eigenvector computation speed as a function of BLAS thread number. In short, using more threads in Julia's use of OpenBLAS appears to slow things down considerably. For reference, in Mathematica:               SetSystemOptions["MKLThreads" -> 1];     First@Timing@Eigensystem[RandomReal[{-500, 500}, {1000, 1000}]]     SetSystemOptions["MKLThreads" -> 2];     First@Timing@Eigensystem[RandomReal[{-500, 500}, {1000, 1000}]]     SetSystemOptions["MKLThreads" -> 3];     First@Timing@Eigensystem[RandomReal[{-500, 500}, {1000, 1000}]]     SetSystemOptions["MKLThreads" -> 4];     First@Timing@Eigensystem[RandomReal[{-500, 500}, {1000, 1000}]]     (*Out:*)     1.747211     1.466409     1.341609     1.357209      So I guess there's nothing wrong with Mathematica's implementation.


title: MathLink linking error after OS X 10.9 (Mavericks) upgrade

text: After macosx 10.9 mavericks upgrade i have a compilation problem, you can see below. Even the examples given in /Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/MacOSX-x86-64/MathLinkExamples are not compiling anymore. It throws an error about the architecture. I also followed the solution given by MathLink compile errors, reinstalling the Xcode and command line tools. It didnt work. I also checked the _libMLi3.a_ for architecture and seems like it is ok *libMLi3.a: Mach-O universal binary with 2 architectures libMLi3.a (for architecture i386): current ar archive random library libMLi3.a (for architecture x86_64): current ar archive random library* and clang/gcc as well > Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn) Target: > x86_64-apple-darwin13.0.0 Thread model: posix > > gcc -v Configured with: > \--prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include- > dir=/usr/include/c++/4.2.1 Apple LLVM version 5.0 (clang-500.2.79) (based on > LLVM 3.3svn) Target: x86_64-apple-darwin13.0.0 Thread model: posix which are the latest. **I wonder if anyone manages to compile the MathLink examples after the 10.9 upgrade?** Here is the error message:               /Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/MacOSX-x86-64/MathLinkExamples]:>      g++  -I/Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/MacOSX-x86-64/MathLinkExamples/../CompilerAdditions \     addtwotm.o addtwo.o -L/Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/MacOSX-x86-64/MathLinkExamples/../CompilerAdditions \     -lMLi3 -lstdc++ -framework Foundation -o addtwo     Undefined symbols for architecture x86_64:       "std::string::find_last_of(char const*, unsigned long, unsigned long) const", referenced from:           MLThreads::DestroyName(std::string&) in libMLi3.a(mlplatformthreads.cpp.o)       "std::string::find_first_of(char const*, unsigned long, unsigned long) const", referenced from:           MLThreads::NameValidQ(std::string&) in libMLi3.a(mlplatformthreads.cpp.o)           MLThreads::DestroyName(std::string&) in libMLi3.a(mlplatformthreads.cpp.o)       "std::string::find(char const*, unsigned long, unsigned long) const", referenced from:           _mlipinterfacecontainer_get_domain_names in libMLi3.a(mlipinterface.c.o)           MLNetwork::MLIPAddress::LoadDomainName(bool) in libMLi3.a(mlipaddress.cpp.o)           MLNetwork::MLIPAddress::IPV4NameQ(std::string) in libMLi3.a(mlipaddress.cpp.o)           MLNetwork::MLIPAddress::IPV6NameQ(std::string) in libMLi3.a(mlipaddress.cpp.o)           MLNetwork::MLIPAddress::AutoconfiguredQ() const in libMLi3.a(mlipaddress.cpp.o)           _pipe_make in libMLi3.a(_pipe.c.o)           MLDevices::MLTCPIPDevice::OldConnectServer() in libMLi3.a(mltcpip.cpp.o)        .        .        .        .        .        .           ...       NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.     ld: symbol(s) not found for architecture x86_64     clang: error: linker command failed with exit code 1 (use -v to see invocation)


title: How do I save/export a list so that it can later be easily imported as a list again?

text: I have a couple of big lists (each of them contains elements that are themselves lists of two elements, i.e. an element of each list that I have is of the form {x, y}) that I want to save/export. Their generation namely takes hours, and I don't want to do this every single day. I looked at the Mathematica help section on this (http://reference.wolfram.com/mathematica/tutorial/ImportingAndExportingData.html), but found that if I follow the example, I can't just import the data back into a list as it was before. It just ends up being something really messy. So given such a list, say, list = {{1,2}, {1,3}, ... , {500, 500}}, what do I do, so that the next day I can just write list = Import[...]?


title: How to create an adjustable Bézier curve?

text: I tried to create an adjustable `Bézier curve` with the following simple code. However the curve didn't show up. What is the problem? Please help.               pts = {{0, 0}, {1, 2}, {2, 0}, {3, 3}};     bez = BezierFunction[pts ];          Manipulate[      Show[Graphics[{Red, Point[lo], Green, Line[lo]}, Axes -> True],        ParametricPlot[bez[lo ], {t, 0, 1}], ImageSize -> { 200, 200 }],      {{lo, pts}, Locator}      ]      ![enter image description here](http://i.stack.imgur.com/YOKLG.gif)


title: Compute coefficient of Generating function

text: Given a generating function $F(z)$, is there any way to compute the coefficient $a_k$ of $z^k$ by Mathematica? One method is to calculate by the equation $\frac{F^{(k)}(0)}{k!}$. However, this approach is not feasible for $k$ large.


title: displaying Laurent polynomials nicely

text: I have some 2-variable Laurent polynomials in $q$ and $t$, and I'd like to collect powers of $q$ and display them without using fractions, and to sort the terms by the power of $q$. For example, I'd like to display $(t-t^{-1})q^{-1} + (t^{-1})q$, instead of $(t-\frac 1 t)\frac 1 q + \frac q t$ which is what Mathematica wants to output. Is there a nice way to do this? Right now I'm applying the function > StandardForm[# /. Power[expr_, r_?Negative] :> Superscript[expr, r]] & to the polynomials I'd like to display, which makes negative powers display as exponents. But the problem is that Mathematica then doesn't sort the terms correctly, since it doesn't recognize the "Superscript" as a power.


title: How to convert an output to a graphic that can be selected like a plot?

text: EDIT: István Zachar informed me of the **Rasterize[]** command, which does exactly what I need. Danke! I have a self-built function that uses Grid[] to create a table that is more presentation-friendly than TableForm. Example output is: ![Example output of dougTable](http://i.stack.imgur.com/tbBLt.png) What I usually do to copy this into a presentation is take a screenshot with the Snipping Tool. For plots, I can just select the plot in Mathematica and then select Edit -> Copy As -> Bitmap. I want to be able to do the same with this table. Right now, if I try selecting the table, I get a cursor and can start typing in the figure. I was hoping there was a Mathematica function that just puts a selectable bounding box around the entire output of a function, but I've been unable to find one yet. Does anyone have any ideas on how to make this entire table selectable? Source code for my function can be found below, although you shouldn't need to use it to find a solution to the problem: any function with a non-graphic default output should work fine.               Clear[dougTable]     dougTable[data_List, cols_List: {}, rows_List: {}] :=      Module[       {genOpts, none, colHead, rowHead, both, font},       genOpts = {Frame -> All, Background -> RGBColor[1, .9, 0],          FrameStyle -> Thickness[1]};       font = {FontFamily -> "Arial", FontSize -> 12, FontWeight -> "Bold"};       none = {genOpts,          Dividers -> {{1 -> Thickness[2], -1 -> Thickness[2]}, {1 ->              Thickness[2], -1 -> Thickness[2]}}};       both = {genOpts,          Dividers -> {{1 -> Thickness[2], -1 -> Thickness[2],             2 -> Thickness[2]}, {1 -> Thickness[2], -1 -> Thickness[2],             2 -> Thickness[2]}},          ItemStyle -> {{Directive[font], Automatic}, {Directive[font],             Automatic}}};       colHead = {genOpts,          Dividers -> {{1 -> Thickness[2], -1 -> Thickness[2]}, {1 ->              Thickness[2], -1 -> Thickness[2], 2 -> Thickness[2]}},          ItemStyle -> {Automatic, {Directive[font], Automatic}}};       rowHead = {genOpts,          Dividers -> {{1 -> Thickness[2], -1 -> Thickness[2],             2 -> Thickness[2]}, {1 -> Thickness[2], -1 -> Thickness[2]}},          ItemStyle -> {{Directive[font], Automatic}, Automatic}};            Which[Length[cols] == 0 && Length[rows] == 0, Grid[data, none],        Length[cols] != 0 && Length[rows] == 0,         Grid[Prepend[data, cols], colHead],        Length[cols] == 0 && Length[rows] != 0,         Grid[MapThread[Prepend[#1, #2] &, {data, rows}], rowHead],        Length[cols] != 0 && Length[rows] != 0,         Grid[Prepend[MapThread[Prepend[#1, #2] &, {data, rows}], cols],          both]]       ]


title: Plotting in the "Manipulate" function - simple coding

text: Hello Mathematica community, my name is Preston! I have a real quick question that should be easy to answer. Alright, so for a research project that I'm involved it at my university, I need to illustrate the outline of a Cassini Oval using something I've been calling "concentric circles" - but that doesn't really matter. I've decided to use Mathematica in my research. I used the "Manipulate" function in order to illustrate what these "concentric circles" would do as their radii varied over a specific interval. Here's the code for that:                   Manipulate[         Graphics[{Circle[{-1, 0}, H], Circle[{1, 0}, 1.2/H]},          Axes -> True], {H, Sqrt[1.2 + 1] - 1, Sqrt[1.2 + 1] + 1}]        That is all fine and good, and it does exactly what I want. However, I really need to somehow plot the curve of the following function in the Manipulate:                   [(x+1)^2+y^2]*[(x-1)^2+y^2]=(1.2)^2      So, basically, as the manipulator runs, I want the "concentric circles" to do what they do, but I want the function I just listed to just sit still. The idea is that as the "concentric circles" change over the interval defined for $H$, their intersection will outline a Cassini Oval (the equation above). I would greatly appreciate any help. Thanks! Also, what I'm trying to do may be illustrated in the following code:                    x = Table[{(-1 + H^4)/(4 H^2), Sqrt[1 - H^2 + (2 H^2 (-1 + H^4))/(4 H^2) -               H^2 ((-1 + H^4)/(4 H^2))^2]/H}, {H, 1, 1 + Sqrt[2], 0.01}];              x1 = Table[{(-1 + H^4)/(4 H^2), -(Sqrt[1 - H^2 + (2 H^2 (-1 + H^4))/(4 H^2) -               H^2((-1 + H^4)/(4 H^2))^2]/H)}, {H, 1, 1 + Sqrt[2], 0.01}];              x2 = Table[{-((-1 + H^4)/(4 H^2)), Sqrt[1 - H^2 + (2 H^2 (-1 + H^4))/(4 H^2) -               H^2 ((-1 + H^4)/(4 H^2))^2]/H}, {H, 1, 1 + Sqrt[2], 0.01}];              x3 = Table[{-((-1 + H^4)/(4 H^2)), -(Sqrt[1 - H^2 + (2 H^2 (-1 + H^4))/(4 H^2) -               H^2 ((-1 + H^4)/(4 H^2))^2]/H)}, {H, 1, 1 + Sqrt[2], 0.01}];               m =              Manipulate[                  Graphics[{Green, Circle[{1, 0}, 1/H], Blue, Circle[{-1, 0}, H],                   Black, {BezierCurve[x]}, {BezierCurve[x1]},                   {BezierCurve[x2]}, {BezierCurve[x3]}}, Axes -> True], {H, 1/(Sqrt[2] + 1),                   Sqrt[2] + 1}]      This is something I did for a trivial Cassini Oval with constant product equal to 1. It sort of does what I want, but it's way to complicated and glitchy. I want to know if a more evolved code is possible.


title: ParametricPlot with plot markers

text: I have a parametric plot, and would like to fit a line to it with "■" `PlotMarkers` on it, but am unable to do so.               ParametricPlot[{f(x), g(x)}, {x, 0, 1}, AxesLabel -> {"x", "y"}, PlotMarkers->{"■", 10.9}]


title: Numerically Solving two dependent Transcendental Equations

text: I need to solve a system similar to the following (Except it is quite large. Solving this ought to do the job): $$ \tan[2f(t)] = 1+ t^2\ $$ and $ f(t) $ is $ k $, such that$$ \tan[2kt]-(1+k^2) = 0\ $$ I have used `RootSearch` for both equations as I also know the range in which $k$ and $T$ lie. The sample of my code is below.               f[T_] := k /. Extract[Flatten[Quiet[RootSearch[Tan[2*k*T] - (1 + k^2) == 0, {k, 0, 1}],              $MinPrecision::precset]], -1];          Extract[Flatten[Quiet[RootSearch[Tan[2*f[T]] - (1 + T^2) == 0, {T, 0, 1}],             $MinPrecision::precset]], -1]      and I end up getting the following error               ReplaceAll::reps: {k,0,1} is neither a list of replacement rules nor a valid dispatch table,     and so cannot be used for replacing. >>      Please suggest a solution. It would be preferable to use something as powerful as `RootSearch` because my other equations seem to be unsolvable via `FindRoot` or `NSolve`.


title: Fill circle layers with colors according to read values from a plotted curve

text: I want to read (temperature) values from plotted (cooling) curves and visualize them in layered circles. I have an example made manually for clarification: 3 plotted curves, at certain time steps the value of all plotted curves are read out -> I made a scale assigning (temperature) values to colors. These colors are used further to color the inner circle ( _value from curve "center"_ ), the mid-layer ( _value from curve "half radius"_ ) and the outer layer ( _value from curve "radius"_ ). Data can be found here (csv-file) Thank you for helping me! ![enter image description here](http://i.stack.imgur.com/Pb4IH.jpg)


title: False Color SEM image with Mathematica

text: I have a question regarding colouring and binary image filtering, but unfortunately, the system doesn't permit the inclusion of images for first- timers. If anyone would like to see the images described below, please email me directly. I have an image of gold electrodes on a flat substrate obtained with a scanning electron microscope. I would like to colour in all the gold electrodes and particles that appear in the centre of the image, leaving the colour of the background as it is for now. I perform straightforward routines by implementing the following code: Firstly, I rename the image q: `q=Image`; Then I apply the PeronaMalik Filter to enhance the edges and diffuse the background:               pq = PeronaMalikFilter[q, 20, 0.02, 2]      The background in the image thus obtained looks more diffused and uniform, while the edges of the gold electrodes and particles appear sharp, in contrast to the background. Then I give the following command to colour in the gold               goldq = ImageApply[# {1., 0.843104, 0.} &, q,        Masking -> SelectComponents[Binarize[pq, 0.36], "Area", # > -300 &]]      The result is an image in which the gold electrodes are almost entirely coloured in gold, but there are also large regions that are coloured by gold, which shouldn't be; for instance, the left side of the image, and the top right and bottom right. It seems that these areas receive colour due to the fact that they have the same binary level as the actual gold electrodes, which is an artefact of the scanning, and should definitely have the same zero level as the rest of the background. Is there any way to correct this gaffe digitally using Mathematica's built-in functions? Is it possible, additionally, to give the background a different colour? * * * As suggested, here are all three images: Original image: ![original image](http://i.stack.imgur.com/Lns0F.jpg) After filter: ![After filter](http://i.stack.imgur.com/kcHJ6.jpg) After gold: ![After gold](http://i.stack.imgur.com/qqcBa.jpg)


title: Prevent interdependence of controls

text: My question is probably best illustrated with this small sample code:               Manipulate[      Plot[{eqn1, eqn2, eqn1-eqn2}, {x,-5,5}],      {{eqn1,r-x,"y1="}},{{eqn2,E^-x,"y2="}},      {r,-2,2}     ]      I would like to be able to have the user input two equations which including a variable `r`, and then use the slider to manipulate this variable. The issue is that `Manipulate` changes `r` within the input field, and then doesn't update the graphs. Is there a way of allowing the user to input an equation which contains one of `Manipulate`'s variables without having it change that variable within the input field?


title: Convolution with interpolated function

text: I have some problems to calculate in reasonable speed the convolution of an interpolated function with a Gauss function. I have here (ExampleData.txt, alternate Pastebin link) data which I interpolate linearly:               data = Import["ExampleData.txt", "Table"];     interPolFunc = Interpolation[data, InterpolationOrder -> 1]      First, I tried to work with following function (I have to add a Dirac delta function to my interpolated function):               firstTry[y_] := Integrate[        PDF[NormalDistribution[0, 0.008],x-y]*(interPolFunc[x] + 4 DiracDelta[1-x]), {x, 0, 1.1}];      If I calculate some values with               firstTryTable = ParallelTable[{u, firstTry[u]}, {u, 0, 1.1, 0.005}];      I only get back the contribution of the Dirac delta function. If I use this function                secondTry[y_] :=           Integrate[PDF[NormalDistribution[0, 0.008], x - y]*4*DiracDelta[1 - x],{x, 0, 1.1}]  +           Integrate[PDF[NormalDistribution[0, 0.008], x - y]*interPolFunc[x],{x, 0, 1.1}];      and calculate values with                secondTryTable = ParallelTable[{u, N[secondTry[u]]}, {u, 0, 1.1, 0.005}];      then the result seems to be reasonable. So, my first question (not so important) is:   Why do I get back two different results? The second is:   Is there any way to decrease the calculation time? It is really slow. I would be happy about some help.


title: How can a big table be treated as a database?

text: I often work with big tables that I want to treat kind of like a database. Here's an example table.               theTable = {      {"id","color","size","flavor"},      {1,"blue",5,"cherry"},      {2,"green",5,"piquant"},      {3,"blue",20,"peppermint"}     }      In a database I would ask               SELECT * FROM `theTable` WHERE `color` = 'blue' AND `size` > 10      and get effectively               {{3, "blue", 20, "peppermint"}}      in response. In _Mathematica_ , I need to determine the "column number" for `color` and `size`, then use `Cases` with `And` to do the same thing.               Cases[theTable[[2 ;;]], a_ /; And[a[[2]] == "blue", a[[3]] > 10]]      This is operationally much clumsier than the database way. Unfortunately setting up a database for every such table is too much extra work, particularly since I want the data to end up in mma anyway. How can this approach be improved? Specifically, how can I more easily use the column names directly, instead of their part numbers? And how can I avoid the ugly `a_/;f[a]` pattern?


title: Defining extra boundary conditions for NDSolve?

text: I have a second order reaction / diffusion type ODE of the form $\frac{D_{o}}{r^2} \frac{d}{dr}\left(r^2 \frac{dC}{dr} \right) - \frac{aC}{C+k} = 0$ where $a, k$ and $D_{o}$ are constants and $C$ is a function of $r$. I know the following; $C(r_{o}) = \omega$ , $C(r_{n}) = 0$ and $C'(r_{n}) = 0$ , where $r_{o}$ and $r_{n}$ are positions and $\omega$ is a known constant. To model this behaviour, I am using `NDSolve`, which takes two conditions for these types of ODEs. For example, this gives a potential curve between the boundaries $r_{n}$ and $r_{o}$ ;               eqn = ((Do2/(r^2))*D[(r^2*(O2'[r])), r] - (a)*((O2[r])/(O2[r] + k)));               s = NDSolve[{eqn == 0, O2[rn] == 0, O2[ro] == omega}, O2, {r, rn, ro}]      This gives me one curve which I can readily plot; however is I instead tell `NDSolve` to use different conditions like this -               s = NDSolve[{eqn == 0, O2'[rn] == 0, O2[ro] == omega}, O2, {r, rn, ro}]      I get a different curve. However, I suspect I should be getting the same curve regardless. If the problem is narrowing it down to a unique solution from an array of possible solutions, is there a way to make Mathematica take all three BCs? I'm also open to the possibility that there is a more fundamental mathematical error or perhaps a bad assumption on my part, so please by all means point it out to me if I've missed it . Thanks in advance - grateful for any advice on this!


title: Join all square root expressions?

text: Sometimes I observe _Mathematica_ produce expressions exactly like the following after a simplification step: $$\frac{a+\sqrt{-(1-b)}\sqrt{\frac{1}{b-1}}}{\sqrt{c}\sqrt{\frac{1}{c}}}$$ Now, any further generic `Simplify` or `FullSimplify` would not do any good any more. One is tempted to use `PowerExpand`, but this would just introduce an annoying `i` term in the numerator, instead of simplifying correctly. Therefore, what I have been doing is typing in simplifications like:               /.Sqrt[x_]Sqrt[y_]/(Sqrt[z_]Sqrt[m_])->Sqrt[x y]/Sqrt[z m]//Simplify      by hand. This is very annoying. Maybe there is a _Mathematica_ function which joins all the square roots in all possible places of an expression together? **EDIT** Example code to be simplified:               Sqrt[-(1 - b)] Sqrt[1/(b - 1)]      Generally, any simplification involving explicitly specifying properties of terms involved does not help really, since the amount of actions is the same as manually correcting the expression. What I am looking for is a function which merges all possible square roots together, regardless of content. **EDIT2** Please note the following triviality: a search for a function performing the merging of all square roots in an expression only makes sense if an appropriate branch for the square root functions is chosen so that $\sqrt{x}\sqrt{y}=\sqrt{x y}$ is actually true for the expressions in question. Thank you.


title: Wrapping grid with dynamic

text: I'm trying to build a sortable grid:               sortBy[data_, idx_] :=        If[idx == 0, data, Sort[data, #1[[idx]] < #2[[idx]] &]];     sortableTable[data_, header_] := DynamicModule[       {h, sort = 0},       h = MapIndexed[Button[#1, sort = #2] &, header];       Dynamic[Grid[Prepend[sortBy[data, sort], h]]]];     sortableTable[       Table[         RandomInteger[100], {i, 3}, {j, 4}],          {"First", "Second", "Third", "Fourth"}]      For some reason it is not behaving like I expected: header disappears and sorting doesn't occur. I've tried all sorts of stuff but can't make it work like intended. Any help is much appreciated.


title: How to scale vectors in VectorPlot?

text: I generated some pics from 2 datum，one in $x$ direction and the other in $y$，so I used the commands:               exfield = Range[200];     polarplane = Range[200];     Get["C:\\Users\\dc\\Desktop\\polarplane.dat"];     Get["C:\\Users\\dc\\Desktop\\exfield.dat"];     xx = Table[     Transpose[{exfield[[25, i]], polarplane[[25, i]]}], {i, 71}];     ListVectorPlot[xx]      to get the vector field. But one problem here is, all the pics generated by the commands share the same maximum length of the vector. I can only see the orientation change but no magnitude change. I need a cartain standard (for instance, 1 cm vector length for the maximum data value $a_{max}$) to generate all the pics, so I can see the relative magnitude change. But I couldn't find the options. Have anyone encountered this same problem? Thank you. And the sample datum are like:                exfield[[001]] = {                   {        a11,        ……，        a1i，     },     {        a21,        ……，        a2i，      },        ……      {        ai1,        ……，        aii，       },      }      and the sample data: data


title: Nested If statements

text: When I do this:               Apply[(If[#2 == what, "yay", If[#2 == whoops, "nay"]]) &, {-5, what}]      I get:               yay      But when I do this:               Apply[(If[#2 == what, "yay", If[#2 == whoops, "nay"]]) &, {-5, whoops}]      I get:               If[whoops == what, "yay", If[whoops == whoops, "nay"]]      This setup does work for numbers:               Apply[(If[#2 == 2, "yay", If[#2 == 3, "nay"]]) &, {-5, 3}]     nay      What I was trying to do was when I got stuck here was define a `VertexRenderingFunction` in a `GraphPlot`               VertexRenderingFunction -> ({White, EdgeForm[Black], Disk[#, {2, 1}],      Black, Text[      If[#2 == alpha1, "Alpha",        If[#2 == beta, "Beta",         If[#2 == alpha2, "Alpha",          If[#2 == gamma, "(70,55)",           If[#2 == delta, "(90,50)"]]]]], #1]} &)      What am I doing wrong? Any help will be greatly appreciated. Thanks.


title: Solve equations real and imaginary part separately

text: For my system of equations, the procedure described in Solving complex equations of using `Reduce` works no more. How can I separate the real and imaginary part of the equations? Because then I could use `Solve[equations, vars, Reals]`. Nevertheless I hope for a simpler way to overcome this issue. **Example**               Vector = {v1, v2, v3, v4};     Matrix = {{c11, c12, c13, c14},                {c21, c22, c23, c24},                {c31, c32, c33, c34},                {c41, c42, c43, c44}};     Reduce[Table[0 == Sum[Matrix[[r, k]] Vector[[k]], {k, 4}], {r, 4}] &&       Element[{v1Real, v1Complex, v2Real, v2Complex, v3Real, v3Complex, v4Real, v4Complex}, Reals],      {v1Real, v1Complex, v2Real, v2Complex, v3Real, v3Complex, v4Real, v4Complex}] /.       {v1 -> v1Real + I v1Complex, v2 -> v2Real + I v2Complex, v3 -> v3Real + I v3Complex, v4 -> v4Real + I v4Complex}


title: Least Square Fitting

text: stuck on a mathematica assignment and could really use some help. A) Fit a function with the shape log(Y) = a0 + a1log(U) to the datapoints (log(Ui), log(Yi) with an least square fitting. Show this in a plot ... B) Use your answer in A) to find a function Y = kU^n that fit to the datapoints (Ui, Yi) The U datapoints is: (600000, 200000, 60000, 10000, 2500) The Y datapoints is: (250, 60, 25, 12, 5) I've done this:               data2 = {{Log[2500], Log[5]}, {Log[10000], Log[12]}, {Log[60000],         Log[25]}, {Log[200000], Log[60]}, {Log[600000], Log[250]}}          fitExample = Fit[data2, {1, x}, x]      Am I right to be using the Fit function this way? How can I use this answer in the B question?


title: How to close the front end so I can clear all Global variables?

text: I first thought that doing Quit[] in a cell, or Evaluation->Quit kernel, is supposed to remove all Global variables, but I have a case where this is not happening, then I read that there is a command Quit from the menu to also shut down the front end, so I wanted to try that to see if that will clear those variables, which I suppose are saved by the front end. (I know I can ofcourse just type Remove["Globals`*"], but was looking looking at what seems like a symbols leakage problem with Manipulate. **Any one knows how to close the front end please?** I can't find this Quit command from the menu, which is supposed to be different from the Quit[] for the kernel? I only see Quit kernel in the menu. But when I try that, these variables are not cleared! ![enter image description here](http://i.stack.imgur.com/2Udnz.png) Again, the reason I wanted to do the above is because not all variables are cleared when I restart the kernel (either by Quit[] or by stopping the kernel from the menu: ![enter image description here](http://i.stack.imgur.com/EkBjW.png) Btw, according to this answer here Quit[] the kernel is supposed to clear all variables ! but this is not the case with me here. ps. I never even knew before there was a `Quit` command for the front end. ps. I will be happy to post the code that generates this if needed. thanks edit(1) According to help message above, it said there is **Quit** menu item to close the from end, but on windows, V 8.04, I only see Quit kernel, which is the same as Quit[] typed in the notebook. ![enter image description here](http://i.stack.imgur.com/OCO24.png)


title: Export a Row or Column as an image

text: How could I export the following as a single image and set its dimensions ?               Column[{Row[{Graphics@Disk[], Graphics@Rectangle[]}],             Row[{Graphics@Rectangle[], Graphics@Disk[]}]}]      ![enter image description here](http://i.stack.imgur.com/3diB3.png)


title: Practical uses of DynamicWrapper

text: I am looking for practical uses of the function `DynamicWrapper` . I read documentation and know whatever it says. I would appreciate a clear example of a useful dynamic interface (an app) that would be hard to implement without `DynamicWrapper`.


title: Solving NLODE with substitution

text: I am trying to get a solution to a non-linear ODE, below is the code that works for my problem.               s = NDSolve[{y'''[x] + y[x]^2 y''[x] - y'[x] == 0, y[0] == 0, y'[0] == 0, y''[1] == 1}, y, {x, 0, 1}];     Plot[Evaluate[{y[x], y'[x], y''[x]} /. s], {x, 0, 1}]      1 Question how do you get the equations of the lines that are being plotted? So say on x from 0 to 1 what is the equation of the line. 2 How do solve the same problem but using a substitution of u=dy/dx?               u''[x] + y[x]^2 u'[x] - u[x] == 0, u[0] == 0, u'[1] == 1      and we need to integrate to get the y value, not sure how to set that as a BC as well. Thank you


title: Managing formatted usage messages in Wolfram Workbench

text: We have numerous packages (defined in `.m` files) that we maintain and develop in WolframWorkbench (2.0), and in those packages, we use the traditional method of determining which symbols are public by assiging `::usage` messages to them. It's also nice to have at least that much documentation for every public symbol. I've been spending some time reviewing and improving the documentation for these public symbols, and one thing I'd like to be able to do is emulate the formatting that Wolfram uses for its own usage messages, for example: > ![Binomial::usage](http://i.stack.imgur.com/K3KAM.png) It's not particularly difficult to make that sort of formatted text in the notebook interface. However, getting that formatted text into a package file in Workbench requires copying the formatted text, pasting it into an input cell, and then copying the resulting string into Workbench:               "\!\(\*RowBox[{\"Binomial\", \"[\", RowBox[{StyleBox[\"n\", \"TI\"], \     \",\", StyleBox[\"m\", \"TI\"]}], \"]\"}]\) gives the binomial \     coefficient \!\(\*RowBox[{\"(\", GridBox[{{StyleBox[\"n\", \"TI\"]}, \     {StyleBox[\"m\", \"TI\"]}}], \")\"}]\). "          The additional copy/paste step is requiried to keep some of the quotes escaped; it goes wrong if you paste directly to Workbench. Suffice it to say, this is a pain, and editing the resulting string directly is pretty unpleasant. So far the best I've been able to figure out for editing the strings is to do something like this in a notebook file:               CellPrint[Cell[DisplayForm@Binomial::usage, Editable -> True]]      Is there a better way to do this? Just having the arguments in usage strings appear in _italics_ is a big win from a readability standpoint. **UPDATE** in respose to @István Zachar's comment: I knew about the "Show Cell Expression" menu item mentioned in the answers to your question, but I didn't realize that you could edit the displayed cell expression. That's less awkward than the `CellPrint` approach, at least. **UPDATE** the second: The main reason we don't just use autogenerated packages is that we have a setup where "build" an application from packages for deployment on remote machines, and all the packages are in Subversion. Using autogenerated packages with this workflow is very awkward.


title: Possible to Solve a LocationEquivalenceTest?

text: I have 5 groups, each containing around 20 elements. These elements are all dependent on x. For example: `Set1 = {1.5x + 1, 2x + 0.5, 1 x + 1, ...}` etc. Now, I want to compare these 5 groups and see if there is a significant difference between one or more of these groups (for `0 < x < 1`). As my data does not follow normal distribution, I use the Kruskal-Wallis test. To try and visualise this, I plugged this into _Mathematica_               Plot[LocationEquivalenceTest[{Set1, Set2, Set3, Set4, Set5}], {x, 0, 1}]      which, unexpectedly, gives a nice plot of the p-value set out over x. Now, I want to determine for what values of x the p-value is <0.05, so I thought that, since the Plot worked out nicely, I might be able to achieve that by using               Solve[LocationEquivalenceTest[{Set1, Set2, Set3, Set4 ,Set5}] == 0.05, x]      Unfortunately, that just gives me a bunch of errors saying that > The argument _list of the elements of set1_ at position 1 should be a list > containing two or more vectors of real numbers with length greater than 2. Is there a function in _Mathematica_ that does allow me to determine for which values of x the p-value would be 0.05?


title: Take off {} using Position []

text: Please consider :                subIDs = {"AK6", "CF11", "CL4", "FC21", "MK5"};           subColors = {LightOrange, LightBlue, LightYellow, LightGreen, LightRed}           Graphics[{subColors[[Flatten@Position[subIDs, #, 3]]],Rectangle[]}]&/@subIDs      ![enter image description here](http://i.stack.imgur.com/aOKVa.png) How could i avoid the output of position to be 1 for example instead of {1} which seems to be my problem.


title: Copying an image from the clipboard, modifying it and returning it to the clipboard

text: I have a Mathematica script to help me copy images from PDFs and then make the (presumably white or nearly white) background transparent. Typically, I am looking at the PDF in Adobe Acrobat and I use the snapshot tool to copy the image to Microsoft Window's clipboard. Then I paste the image into mathematica and assign it the name q. Where I typed `{IMAGE}` below is where I paste the image into the code:               q = {IMAGE};     p = ColorNegate[Binarize[ImageApply[Min, q], 0.99]];     s = SetAlphaChannel[q, p];     Export["img.png", s];      I run the code and I get a PNG with a transparent background and then I can insert the png with the transparent background into OneNote. The point of doing this is images with a transparent background are easier to arrange since the don't obscure the other texts. This makes it a snap to place graphs and equations in my notes. I would like to make this even easier by enhancing my script. This is why I am asking for help. My goals are:   1. Is there some Mathematica command I can use to copy the image from the clipboard automatically without having to manually paste it.   2. Is there a way to get Mathematica to place the image back into the clipboard with a transparent background, thus cutting out the step of using a file. What I have found is if I use a command like `CopyToClipboard[s]`, it doesn't work.   1. Are there any other enhancements that would make the whole process more automated? (A side note: it's been a while since I wrote this code, but if I remember correctly, I convert the image to black and white, figure out the background then use the pixels that were designated as background to figure out which pixels to set as transparent in the original image.)


title: Split a string at specific positions

text: Given a string of alphanumerical characters, how to split it simply and quickly at the **center** of continuous letter-substrings? Is there an elegant and fast solutions out there in the "computational universe"? The splitter should create "syllables" with one digit as a nucleus for each syllable, that is, at the end there should be **only one digit per sublist**. When there are more letter characters between digits, letters should be shared by the bordering digits (here I simulated a half share, distributing towards the right bordering digit in case of an odd number of letters), and starting and ending letter-sequences should be just attached to the closest digit.               "xxx00xxx000x0xx0xxxx000xx0xx" (* original string *)          "xxx0 | 0x | xx0 | 0 | 0 | x0x | x0xx | xx0 | 0 | 0x | x0xx" (* intermediate *)          {"xxx0", "0x", "xx0", "0", "0", "x0x", "x0xx", "xx0", "0", "0x", "x0xx"} (* end *)      Note that the string never contains spaces by default.


title: How to capitalize the first letter of each word in a string

text: The following examples only work for the first character of the whole string, but not of words.               s = "words are lowercase";     StringJoin[MapAt[ToUpperCase, Characters[s], 1]]   (* ==> "Words are lowercase" *)     StringReplacePart[#, ToUpperCase[StringTake[#, 1]], 1]&@s  (* ==> "Words are lowercase" *)      Is there any method along these lines to produce correct **title case** strings of the form:               "Words Are Lowercase"


title: Summation over 3 lists

text: I have three lists. As an example,               a = {10, 5, 6, 8, 7};     b = {4, 8, 9, 7, 9};     c = {7, 5, 12, 4, 1};      I want to get $$x(i)=\sum _{i=0}^i\frac{1}{2}\left(a_ib_i+a_{i+1}b_{i+1}\right)\left(c_{i+1}-c_i\right)$$ i goes from 1 to 4. i.e. I want to get: x(1),x(2),x(3) and x(4) So, I used following code               x=Sum[1/2*(a[[i]]*b[[i]] + a[[i + 1]]*b[[i + 1]])*(c[[i + 1]] -      c[[i]]), {i, 1, 4}]     For[i = 0, i < 4, x, Print[x]]      But, I didn't get expected output. Could anyone please tell me how to do this?


title: Reducing quality of Graphics3D scene to improve performance?

text: `ProteinData["SERPINA1", "MoleculePlot"]` gives the detailed `Graphics3D` plot below. I'd like to make many small copies of this object and place them in a single `Graphics3D` scene, but I'm running into performance problems because the molecule graphics-object is a pretty complicated mesh. Are there general methods of reducing the quality/detail of graphics objects like the one below that would allow me to place many of these in a single scene? ![enter image description here](http://i.stack.imgur.com/XlvG4.png)


title: How to lookup by a string key after GroupBy? Inconsistent data type handling

text: **This is relates to a bug was introduced in 10.0.0 and shall be fixed in 10.0.1**   **It also relates to an issue that has yet to be corrected.** * * * After applying `GroupBy` to a key all of whose `"values"` are `String`, is it possile to force the internal type representation to subsequently lookup by `"value"` rather than `Key@"value"`? `GroupBy` modifies internal type representation:               titanic = ExampleData[{"Dataset", "Titanic"}];          (* ... Vector[Struct[List["class", "age", "sex", "survived"],        List[Atom[Enumeration["1st", "2nd", "3rd"]], Atom[Integer],         Atom[Enumeration["female", "male"]], Atom[Boolean]]], AnyLength] ... *)      (so does Normal'izing following by casting back to Dataset though `AnyLength` is replaced by a numerical value, eg 1309.) Even though the keys (formerly values) are String:               titanic[GroupBy[Key@"sex"]][Keys, # -> Head[#] &]          (* {"female" -> String, "male" -> String} *)      This lookup fails:               titanic[GroupBy[Key@"sex"]]["female"]          (* ... Part female is not applicable to <|(Alternatives[Enumeration[female, \     male]] -> _List)..|> ... *)      Note: lookup query `Key@"female"` works. Strangely, works also without `Key` when `KeyDrop` is applied before `GroupBy`: `titanic[All, KeyDrop["survived"]][GroupBy[Key@"sex"]]["female"]`               (* ... {<|"class" -> "1st", "age" -> 29, "sex" -> "female"|>, ... *)      Conversely, if `Span` substitutes `KeyDrop`, the data are the same               titanic[All, 1 ;; 3][GroupBy[Key@"sex"]][Keys, # -> Head[#] &]          (* {"female" -> String, "male" -> String} *)      but lookup also fails even using `Key`:               titanic[All, 1 ;; 3][GroupBy[Key@"sex"]][Key@"female"]          (* ... Key Key["female"] is not one of {}. ... *)      I'm not sure how to interpret that message: b/c the internal the representation is `AnyType`:               Assoc[Atom[AnyType],       Vector[Assoc[Atom[String], Atom[AnyType], 3], AnyLength], AnyLength]      How to handle these various cases uniformly?


title: Help with Integrals (and conditional expectations) of the Beta distribution: Integrate[e^(az) z^a (1-z)^b, {z, 0, 1}]

text: I have a Beta distribution, and am interested in calculating expectations and conditional expectations. The domain on the distribution is $z \in [0,1]$ Ignoring constants of proportionality, the expectation of an exponential function is:               $Assumptions = z >= 0 && z <= 1 && a > 0 && b > 0 && c > 0 && d > 0 && d < 1;          Print["*******Different parameters, {a,b}"];     Integrate[Exp[c z]  z^(a - 1) (1 - z)^(b - 1), {z, 0, 1}]          Print["********Symmetric parameter, a"];     Integrate[Exp[c z]  z^(a - 1) (1 - z)^(b - 1) /. {b -> a}, {z, 0, 1}]      The output from this is:               Gamma[a] Gamma[b] Hypergeometric1F1Regularized[a, a + b, c]     (-c)^(1/2 - a) E^(c/2) Sqrt[\[Pi]]  BesselI[-(1/2) + a, -(c/2)] Gamma[a]      These are solid. The problem I am having is when calculating conditional expectations, which is effectively integration over a subset of the domain. Again ignoring constants of proportionality,               Print["********Truncated Integral on [d, 1], symmetric for simplicity"];     Integrate[Exp[c z]  z^(a - 1) (1 - z)^(b - 1) /. {b -> a}, {z, d, 1}]      This is unable to solve it. Any idea on this? Are there any tricks in mathematica, in math that I am missing?


title: Use Mathematica to calculate the area enclosed between two curves

text: use mathematica Hence, calculate the exact area enclosed by these curves using _Mathematica_. $f(x)=x^3$ and $g(x)=x^5 - 2 x^3 - 3 x$ i have got the graph...now I'm stuck with finding the area


title: Sorting a matrix alphanumerically

text: Somewhat related to Sort matrix by columns and rows without changing them, but more general. I'd like to sort a square matrix (a 3 by 3 in my case, but surely the general solution will treat any), say, `M = {{i, b, c}, {d, e, f}, {g, h, a}}`, into lexicographic form without changing `Abs[Det[M]]`, so all row, column and diagonal swaps are allowed. In the example the wanted result would be `{{a, c, f}, {h, b, e}, {g, i, d}}`. Obviously I can't split the sorting into row, column and diagonal sorts separately. (The latter CAN be split off but this would still require in my own dumb algorithm: write down the 36 permuted orderings explicitly and pick the first.) Surely you have a more intelligent (and completely unintelligible, for a n00b like me :-) sorting algorithm? (Like, sorting the list on all levels simultaneously? Only I don't know how yet. Guess it needs a lot of ampersands and octothorpes :-) BTW, I need it to sort a (formal) 9j symbol list and eliminate equivalent duplicates.


title: Tangent to a circle

text: I am trying to show vector of fixed length which is the tangent to a circle which rotates. Any suggestions on how to simplify this ? My question is not about using Manipulate etc but more is there an easier way to compute and draw the tangent ?               x[t_] := Cos[t];     y[t_] := Sin[t];     d[x_, y_] := If[y == 0, 0, -x/y];     tangent[1, 0] = Arrow[{{1, 0}, {1, 1}}];     tangent[-1, 0] = Arrow[{{-1, 0}, {-1, -1}}];     tangent[0, -1] = Arrow[{{0, -1}, {1, -1}}];     tangent[0, 1] = Arrow[{{0, 1}, {1, 1}}];     tangent[x_, y_] =        If[y > 0,         Arrow[{{x, y}, {x - Cos[ArcTan[d[x, y]]],            y - Sin[ArcTan[ d[x, y]]]}}],        Arrow[{{x, y}, {x + Cos[ArcTan[d[x, y]]],            y + Sin[ArcTan[ d[x, y]]]}}]];     Manipulate[      p = ParametricPlot[{x[t], y[t]}, {t, 0, 2 \[Pi]},         PlotRange -> {-2, 2}];      g = Graphics[{{Blue, Line[{{0, 0}, {x[a], y[a]}}]}, {Red,           tangent[x[a], y[a]]}}];      Show[{p, g}],      {a, 0, 2 \[Pi]}]      ![Moving tangent](http://i.stack.imgur.com/oYVSH.jpg) I extended my example above to include a 3D solution using suggested solutions -               Module[{x,y,z,tangent},     x[t_]:=Cos[t];     y[t_]:=Sin[t];     z[t_]:=0;     r ={{-2,2},{-2,2},{-2,2}};     p=ParametricPlot3D[{x[t],y[t],z[t]},{t,0,2\[Pi]},PlotRange->r,BoxRatios->1];     tangent[x_,y_,z_]:={Red,Arrow[{{x,y,z},{x-y,x+y,z}}]};     Manipulate[     g :=Graphics3D[{Sphere[{x[t],y[t],z[t]},0.2],     {Green,Arrow[{{x[t],y[t],z[t]},{x[t],y[t],1}}]},     {Blue,Arrow[{{0,0,0},{x[t],y[t],z[t]}}]},     tangent[x[t],y[t],0]     },PlotRange->r,BoxRatios->1];     Show[p,g],     {t,0,4\[Pi]}     ]     ]      ![3D](http://i.stack.imgur.com/DQYE2.jpg)


How to make a defined symbol stay in symbol form?               w = 3; g = 4;          {w, g}[[2]]      > `3` I want the output to be **`g`** and not `3`. For example if I I want to save different definitions by `DumpSave` in different files like below: Example: `Table[DumpSave["/Users/simonlausen/Desktop/Input/ex"<>ToString[i]<>".mx",{w,g}[[i]]],{i,1,2}]` Any Suggestions?


title: Creating a trigger to update a previous ListPlot output with new data

text: Imagine I'm running a loop that's manipulating and changing elements in an array. Is it possible for me to create a `ListPlot` output in my notebook that updates on command? I'm imagining taking something like this:               testArray = Array[{0, 0} &, 10^3];     For[i = 1, i <= 10^3, i++,            testArray[[i]] = {i, i};            If[Mod[i, 10] == 0,        Print[ListPlot[testArray, PlotRange -> All]];       ];          ];      And transforming it into something like this (with the imaginary command `fTriggerUpdateForPreviouslyExistingListPlot`):               testArray = Array[{0, 0} &, 10^3];     For[i = 1, i <= 10^3, i++,            testArray[[i]] = {i, i};            If[Mod[i, 10] == 0,        fTriggerUpdateForPreviouslyExistingListPlot[{testArray}];       ];          ];      Here, `fTriggerUpdateForPreviouslyExistingListPlot` is some kind of switch that takes a listplot, say, in another notebook (within the context of the same kernel) or the current one, and plots the new data. Is this possible? * * * The function `Monitor` comes close to what I'm looking for:               testArray = Array[{0, 0} &, 10^3];          Monitor[        For[i = 1, i <= 10^3, i++,          Pause[0.1];          testArray[[i]] = {i, i};        ];     ,     ListPlot[testArray, PlotRange -> All]];          ListPlot[testArray, PlotRange -> All]      However, this updates whenever `testArray` changes, and not on a trigger. I could create a separate `testArrayForMonitor` and move data from `testArray` to `testArrayForMonitor` to trigger an update, but this seems a bit of an odd thing to do, and incurs a significant overhead.


title: How to set the return type of a compiled function? (Compile::noinfo warning)

text: I have simple function I would like to compile, but I get a warning and a call to MainEvaluate. I would like to avoid both.               ClearAll[MakeInPeriodicCell]     On["CompilerWarnings"]     MakeInPeriodicCell =        Compile[{x, cellwidth},         First@Sort[{x, x - cellwidth, x + cellwidth}, Abs[#1] < Abs[#2] &]];     CompiledFunctionTools`CompilePrint[MakeInPeriodicCell]            (*Compile::noinfo: No information is available for compilation of      Sort[{x,x cellwidth,x+cellwidth},Abs[#1]<Abs[#2]&].      The compiler will use an external evaluation and make assumptions about the return type.*)          (*     ...     5   T(R1)2 = MainEvaluate[ Function[{x, cellwidth}, Sort[{x, x - \     cellwidth, x + cellwidth}, Abs[#1] < Abs[#2] & ]][ R0, R1]]     ...     *)      **EDIT** (I got the correct syntax for the subexpression from an answer that got deleted?) I tried setting the type of a subexpression like this:               MakeInPeriodicCell =       Compile[{x, cellwidth},        First@Sort[{x, x - cellwidth, x + cellwidth},          Abs[#1] < Abs[#2] &], {{Sort[_,_], _Real,1}}]      This gets rid of the warning, but the call to MainEvaluate remains. Can this snippet be compiled without a call to MainEvaluate? * * * **EDIT 1** Since compile is always about speed, here is some benchmark info. (the code is here, as it clutters the question a bit)               data = RandomReal[{-100, 100}, 100000];     (*Original implementation*)     m0 = MakeInPeriodicCellOrig[data, 30]; // AbsoluteTiming (*0.8370473*)     (*my revritten*)     m1 = MakeInPeriodicCellImp[data, 30]; // AbsoluteTiming  (*0.0360021*)     (*F'x answer*)     m2 = MakeInPeriodicCellFx[data, 30]; // AbsoluteTiming   (*0.0140008*)          m0 == m1 == m2 (*True*)      So getting read of MainEvaluate gives you about 20x speed-up and changing to a better algorithm another 3x. I usually have a million to ten million points, so the speed-up is very welcome.


title: How to remove border points from InputForm?

text: I have this code, and it generates the below `ListStreamPlot`. The second graph is the `ListStreamPlot` overlaid with the points comprising the `ListStreamPlot` (extracted after looking at `// InputForm`); unfortunately, the extracted points also include the border points. These "border points" are not of predictable coordinates, so there doesn't seem to be an easy way to remove them from the set. (I want this code to be as case-inspecific as possible, since I am analyzing many additional data sets.) Is there a simple way -- perhaps in the original `ListStreamPlot` code -- to remove the "border points" from the points list?               v3 = ListStreamPlot[vectorsT, StreamStyle -> "Line", StreamPoints ->        {{xcorT[[midpoint + 4]], ycorT[[midpoint + 4]]}}]          points = v3[[1, 2, 1]];          xPoints = Transpose[points][[1]];      yPoints = Transpose[points][[2]];          pointsOnly = ListPlot[Transpose[Join[{xPoints}, {yPoints}]]] ;      graph 1: ![](http://i.stack.imgur.com/M3Gps.png) graph 2: ![](http://i.stack.imgur.com/9AZJm.png) **Entire source code**               (* Set directory to that of this notebook *)     SetDirectory[NotebookDirectory[]];          (* Import CSV'd data *)     dat = Import["test_data2b.txt", "CSV"];          (* Divide data *)     datAll = Flatten[Partition[dat[[1]], 7]];     datAllCpy = datAll;          (* Divide data into components *)     (* ID *)          ID = Flatten[Partition[datAll, 1, 7]];     datAll = RotateLeft[datAll];          (* Longitude *)     LONG = Flatten[Partition[datAll, 1, 7]];     datAll = RotateLeft[datAll];          (* Latitude *)     LAT = Flatten[Partition[datAll, 1, 7]];     datAll = RotateLeft[datAll];          (* SFC_SPD *)     SPD1 = Flatten[Partition[datAll, 1, 7]];     datAll = RotateLeft[datAll];          (* SPF_SPD _KT *)     SPD2 = Flatten[Partition[datAll, 1, 7]];     datAll = RotateLeft[datAll];          (* SFC_SPD _MP *)     SPD3 = Flatten[Partition[datAll, 1, 7]];     datAll = RotateLeft[datAll];          (* SFC_DIR *)     DIR = Flatten[Partition[datAll, 1, 7]];          (* Restore original list *)     datAll = datAllCpy;          (* Make longtitudes negative *)     LONG = Abs[LONG];     LONG = 0 - LONG;          (* Convert from degrees to radians *)     DIR = DIR *(2 Pi/360);          (* Graph data as vectors *)     xcor = LONG;     ycor = LAT;     xvc = SPD1*Cos[DIR];      yvc = SPD1*Sin[DIR];     vectors = Table[{{xcor[[i]], ycor[[i]]}, {-yvc[[i]], -xvc[[i]]}}, {i, 1, Length[xcor]}];          (* Calculate midpoint of data *)     midpoint = Flatten[Position[SPD1, 0.]][[1]];          (* Transpose all points to be around origin *)     LONGT = LONG - (LONG[[midpoint]]);     LATT = LAT - LAT[[midpoint]];           (* Graph data as vectors *)     xcorT = LONGT;     ycorT = LATT;     xvcT = SPD1*Cos[DIR];      yvcT = SPD1*Sin[DIR];     vectorsT = Table[{{xcorT[[i]], ycorT[[i]]}, {-yvcT[[i]], -xvcT[[i]]}}, {i, 1, Length[xcor]}];          v3 = ListStreamPlot[vectorsT, StreamStyle -> "Line", StreamPoints -> {{xcorT[[midpoint + 4]], ycorT[[midpoint + 4]]}}]          points = v3[[1, 2, 1]];           xPoints = Transpose[points][[1]];      yPoints = Transpose[points][[2]];          pointsOnly = ListPlot[Transpose[Join[{xPoints}, {yPoints}]]] ;          Show[v3, pointsOnly]


title: 3D plots with parallel projection

text: It is easy to make 3D Plots with _Mathematica_ , e.g. use:                Plot3D[Sin[x+y^2],{x,-3,3},{y,-2,2}]      But I want to have nice plots in my thesis, so I decided to use pgfplots for $\LaTeX$ together with _Mathematica_. There you can use a picture (of _Mathematica_ ) and draw with $\LaTeX$ well readable axes etc. around the picture (see e.g. p.44 et seq. here). But to use both programs together, I need plots which are in a parallel and not perspective projection. As you can see from the pic, ![Picture with perspective projection](http://i.stack.imgur.com/BNGmv.png) _Mathematica_ gives me a perspective projection. Is there a way to get a parallel projection?


title: Using singular value decomposition for graph clustering

text: I have a fairly large graph (50-60 vertices) with directed, weighted edges, and I am attempting to cluster the vertices. Prior to this, I have only worked with undirected graphs having symmetric adjacency matrices, and I am struggling to figure out an effective means of clustering for the asymmetric case. It seems like the "SingularValueDecomposition" command may be helpful, but I have no experience with this process, and I'm struggling to find an adequate tutorial online. If anyone knows of such a tutorial (or has suggestions for another means of clustering), I would appreciate the help.


title: Consecutive Print to target same output Cell

text: Is it possible to conveniently direct the output of consecutive **Print** statements to the same output **without actually accumulating the output in a temporary string/variable**. This would be useful in cases where there are a lot of small outputs say like in the example below:               For[i=1,i<=1000,i++,     Print[i," "];     ]      By default each of the Print statement produces a new output cell, which is not desirable. I would prefer a C-style dump-to-terminal output, where one just prints i with a space


title: Rotate doesn't work with BarChart and BoxWhiskerChart

text: Rotate@BarChart[RandomReal[1, {4, 5}], ChartLayout -> "Percentile"]       Even though the FullForm generated by BarChart is Graphics expression, Rotate has no effect on BarChart and many other packaged plot functions. However, it's frequently necessary to rotate, scale and align such plots to other graphics in composite data visualizations (eg, imagine a heatmap augmented with row and column descriptive statistics visualized with two corresponding BoxWhiskerChart) How can rotatable, translatable, etc. graphics be extracted from functions like BarChart and BoxWhiskerChart?


title: How to solve this logarithmic equation?

text: The equation $$x^2\cdot\log_2\dfrac{3+x}{10}-x^2\cdot\log_{\frac{1}{2}}(2 + 3x)=x^2 - 4+2\cdot\log_{\sqrt{2}}\dfrac{3x^2+11x+6}{10}$$ has two solutions for x, namely 1 and 2. I tried               Reduce[x^2*Log[2, (3 + x)/10] - x^2*Log[1/2, 2 + 3*x] ==        x^2 - 4 + 2*Log[Sqrt[2], (3*x^2 + 11*x + 6)/10], x]      and               Solve[x^2*Log[2, (3 + x)/10] - x^2*Log[1/2, 2 + 3*x] ==        x^2 - 4 + 2*Log[Sqrt[2], (3*x^2 + 11*x + 6)/10], x]      but I could not get these two solutions. How do I tell _Mathematica_ to do that?


title: Fixing quirky typesetting in plot labels

text: Consider this example plot.               Plot[      1-Exp[-x],      {x,0,3},      AxesLabel->{"thickness (μm)","power density (W/m^2)"}     ]      ![Example plot with quirky plot labels](http://i.stack.imgur.com/qLjlE.png) Let us hold the typographical quality of the labels to the standard set by LaTeX. There are four distracting quirks:   1. The "m" in "m^2" is italicized   2. The "2" in "m^2" is set high enough to be _above_ the "m"   3. The parentheses in "(W/m^2)" are comically small   4. The "µ" in "µm" is italicized  Am I entering the labels in the wrong form? How can they be fixed?


title: Choosing range when plotting data from array

text: I have loaded data from a CSV file which i want to plot in a `BarChart` but i only wish to plot `0:100` instead of the entire dataset. Is there a way to set a range for the `data`? So far i am just plotting everything:               data = Import["/Users/matek/NetworkTest/without_use_in_and_out.csv", "Table"]          Show[         BarChart[data, ChartLegends -> {"TX", "RX"}],         ImageSize -> 600     ]      `data`:               {{1,2},{3,4},{5,6},...}


title: Where do Mathematica's probability functions draw a line in the sand for predicates?

text: Thinking about a recent question mis-posted here (belonged on _math_ ), I noted the following. A contrived example - probability that _a_ or _b_ are 1:               Probability[ a == 1 || b == 1, {a \[Distributed] DiscreteUniformDistribution[{0, 1}],       b \[Distributed] DiscreteUniformDistribution[{0, 1}]}]      outputs as expected 3/4. Now if one had a more complicated predicate, say ten variates involved, it would be a messy predicate to do manually. Of course, one could use various facilities to build it auto-magically, or just use something like (keeping it simple as above, but one can see how this makes extension to many variates simple):               Probability[Total[Unitize[{a, b}]] > 0, {a \[Distributed] DiscreteUniformDistribution[{0, 1}],       b \[Distributed] DiscreteUniformDistribution[{0, 1}]}]      which returns the expected result. However, something that intuitively seems it _should_ work, like:               Probability[      Count[{a, b}, 0] != 2, {a \[Distributed] DiscreteUniformDistribution[{0, 1}],       b \[Distributed] DiscreteUniformDistribution[{0, 1}]}]      does not, and somewhat worryingly returns a result (invalid) of 1 rather than an error or warning for an unusable predicate. The same results occur with `NProbability`. (1) Is there any rhyme or reason around what works and what doesn't? (2) Is there any method to get _Mathematica_ to use such a construct directly, or at least spit back a "no can do"?


title: Suppress warnings in ParallelTable

text: I'm using `ParallelTable` to evaluate a function that involves `NIntegrate`. There are a lot of `NIntegrate::slwcon` warning messages. In fact, every kernel prints the same messages. I am aware that Mathematica is printing these warnings and now want to suppress them. I tried `Quiet[]` and `Off[NIntegrate::slwcon`. But they seem to have no effect whatsoever when using `ParallelTable`. How can I turn off (any) warning message when using `ParallelTable`?