title: Passing an internal static class in JLink?

text: I am trying to get started with the Stanford NER tools tools in Mathematica, and am having difficulty translating the demo they provide into JLink. The relevant code in the demo is:               /* Usage: java -cp "stanford-ner.jar:." NERDemo */          import edu.stanford.nlp.ling.CoreLabel;     import edu.stanford.nlp.ling.CoreAnnotations;          ...           for (CoreLabel word : sentence) {       ... w.word() ... word.get(CoreAnnotations.AnswerAnnotation.class) ...      So I tried:               InstallJava[ClassPath -> ".../stanford-ner.jar"];          answerAnnotation = LoadJavaClass["edu.stanford.nlp.ling.CoreAnnotations$AnswerAnnotation"]      > JavaClass[edu.stanford.nlp.ling.CoreAnnotations$AnswerAnnotation,<>]               (...things that appear to be working correctly...)          w      > « JavaObject[edu.stanford.nlp.ling.CoreLabel]»               w@word[] (* works *)     w@get[answerAnnotation] (* $Failed *)      > Java::argx1: Method named get defined in class > edu.stanford.nlp.ling.CoreLabel was called with an incorrect number or type > of arguments. The argument was > JavaClass[edu.stanford.nlp.ling.CoreAnnotations$AnswerAnnotation,<>]. The (inherited) method signature of `get` is               get(java.lang.Class<? extends TypesafeMap.Key<VALUE>> key)      http://nlp.stanford.edu/nlp/javadoc/javanlp/edu/stanford/nlp/util/ArrayCoreMap.html#get(java.lang.Class)


title: Multiple Simulations of a Markov Chain

text: I am trying to create a simple series of Bernoulli bits whose probabilities follow a two-state Markov chain.               ProbInitial = 1 (*Initial State of Markov Chain*)     (*Define Two-state Markov Transition Matrix*)     p11 = 0.4;(*Probability of a Success given a Prior Success*)     p01 = 0.8;(*Probability of a Success given a Prior Failure*)      I want to create a Table containing NEvents for each of NSimulations. I am able to create a single Table containing NEvents that behaves properly, i.e., the estimates of p01 and p11 are correct. However, when I try to scale the following code to NSimulations, I get strange values of p011 and p11 back for all the NSimulations on some runs. Sometimes I get the same sequence of bits for all the NSimulations. I realized that the Mathematica was remembering function values and decided to use the Module function as follows:               ProbSuccess[ii_Integer] := If[ii == 0, p01, p11]          ClearAll[SimDataUnit];     SimDataUnit[k_] := Module[       {Sucess},        Success[1] := RandomVariate[BernoulliDistribution[ProbInitial]];        Success[ii_Integer] := Success[ii] =           RandomVariate[BernoulliDistribution[ProbSuccess[Success[ii - 1]]]];        Table[Success[jj], {jj, 1, NEvents}]          ]      I call SimDataUnit[k] to to get different random realizations for each of the Nsimulations.               SimDataMany = Table[SimDataUnit[ii], {ii, 1, NSimulations}]      I was hoping that that making the {Success} variable local to the Module would make a difference but it did not. Any and all suggestions are welcome.


title: How to obtain all the partitions in a set $A$ such that the union of these partitions equals $A$?

text: I'm trying to make a visual proof on the irrationality of $\sqrt{2}$. At the moment, I've created a figure to show that $b^2$ elements always constitute a square: ![enter image description here](http://i.stack.imgur.com/1A373.png) And I want to show that it's not possible to make a square with $2b^2$ elements but showing all possible trials of mounting a square with these number of elements. My guess is that I'll need something that allows me to contruct arbitrary partitions:               {a,b,c} → {{a},{b,c}}, {{a,b},{c}}, ...      Such that their union is always equals to `{a,b,c}` but I have no idea on how to do it. I've tried a few times with `Subsets` and `Partition` but I got no success until now.


How to obtain the form of sin(nx) and cos(nx) from the result of FourierSeries[]. For Example, $$\text{FourierSeries}[x,x,5]=i e^{-i x}-i e^{i x}-\frac{1}{2} i e^{-2 i x}+\frac{1}{2} i e^{2 i x}+\frac{1}{3} i e^{-3 i x}-\frac{1}{3} i e^{3 i x}-\frac{1}{4} i e^{-4 i x}+\frac{1}{4} i e^{4 i x}+\frac{1}{5} i e^{-5 i x}-\frac{1}{5} i e^{5 i x}$$ How do I obtain the form $$a_1 \cos (x)+a_2 \cos (2 x)+a_3 \cos (3 x)+a_4 \cos (4 x)+a_5 \cos (5 x)+a_0+b_1 \sin (x)+b_2 \sin (2 x)+b_3 \sin (3 x)+b_4 \sin (4 x)+b_5 \sin (5 x)$$ from the result of                 FourierSeries[x,x,5]      Thanks!


title: Generating a list of specific intermediate numbers associated with continued fractions

text: First of all, I don't know how `ContinuedFraction[]` or `Convergents[]` are implemeneted, and I think it is immaterial to my question. for some number $x$ there's an associated continued fraction representation $[a_1,...,a_i,...]$ (finite or not), and, for this matter, two other sequences $[x_1,...,x_i,...]$ and $[d_1,...,d_i,...]$ defined like this: As we follow the implementation of some $a_i$ into the fraction, further action is due on some number $x_{i+1}=n_{i+1}+d_{i+1}$. It consists of setting $a_{i+2}=n_{i+1}$, and repeating the action on $x_{i+2}=1/d_{i+1}=n_{i+2}+d_{i+2}$. I am interested in an (possibly) efficient way of extracting the $[d_1,...,d_i,...]$ for some number $x$, preferably using functional programming in Mathematica. Any clue\lead would be very much appreciated! **I know I didn't give any base code to work with which is annoying, and I don't really expect anyone to come forth and solve someone else's problem from start to end. Having said that, hopefully, comments regarding this annoyance will be spared..**


title: Circle detection using invariance kernels

text: I'm not sure, if this belongs more to the signal processing forum or if I can post it in here, but I want to solve it via mathematica and it's some kind of image-processing I guess. I have a noisy picture with a circle in it: ![enter image description here](http://i.stack.imgur.com/POS2E.jpg) Now I want to detect the circle, by using so called invariance Kernels like a Fourier-Mellin transform. In short, I want to replicate what the authors of this paper (see Section 4) did in mathematica. So what they did, was using Fourier-Mellin transform to detect a noisy image with a circle in it. I have some troubles grasping the mathematics behind it and I hope someone could help me out in understanding and implementing it in a mathematica code.


title: How to operate with function body without evaluation

text: I have several functions (let `a[x]` and `b[x]`), defined as expressions with integrals and differentiations. I want to perform some manipulations with these expressions - for example, ask _Mathematica_ to simplify `a[x] + b[x]` without evaluations of integrals. `Hold` doesn't works (as I tried) as I used to expand functions `a[x]` and `b[x]` first. I think, that I could replace `Integrate` and `D` with some meaningless heads `integrate` and `d`, and then expand functions with another meaningless symbol `x`, but I can't achieve this, because _Mathematica_ tries first to perform integrations and fails. Example:               a[t_] := Integrate[t, {x, -∞, ∞}]     b[t_] := Integrate[t^2, {x, -∞, ∞}]     a[t]+b[t]  (* this doesn't works, as it "evaluates" integrals;                    I want to see simple sum *)      _ADDED:_ I want to see something like `myIntegrate[t, {x, -∞, ∞}]+myIntegrate[t^2, {x, -∞, ∞}]`. Really, _a_ and _b_ are more complicated, and they contain more than one integrals. I want Mathematica to perform expression simplification keeping integrals unevaluated. I could manually modify definition for _a_ and _b_ , but they are rather complicated, and don't want to keep two copies (one with Integrate, and one with some myIntegrate).


title: Pattern definition for replacing plus and subtract

text: Suppose I have two functions $h_1(x)$ and $h_2(x)$, for which we know their sum and their difference: $$ h_1(x)+h_2(x) = d(x) \qquad h_1(x)-h_2(x) = i f(x) $$ I have a complicated expression, in which I'd like to replace these sums and subtractions. In principle, I could just define               h1[x_]:= 1/2 (d[x] + I f[x])     h2[x_]:= 1/2 (d[x] - I f[x])      and use `Simplify`. However, this is not an option as I'd like to keep the $h_i(x)$ when they appear alone (i.e. not as a sum/subtraction). So I defined a function `simp` as follows:               ClearAll[h1,h2,simp]     simp[a_. (b_. h1[x_] + b_. h2[x_]) + e_.] := simp[2 a b d[x] + e]     simp[a_. (b_. h1[x_] - b_. h2[x_]) + e_.] := simp[2 a b I f[x] + e]      This works for the addition, but not for the subtraction, as can be seen with the test expressions:               simp[1/2 a h1[x] + 1/2 a h2[x]]     simp[1/2 a h1[x] - 1/2 a h2[x]]      Why is this? Any idea how I can solve it?


title: Treat strings as variables?

text: I have a list of strings,               {"x1", "x2", "x3", "x4"}      And a list of linear equations:               {"x1" + "x3" - "x4" == 0, "x1" + "x2" + "x3" == 0}      How can I use `Eliminate` to eliminate `"x1"` from these equations? It complains that `"x1"` is not a valid variable. Is there a workaround?


title: Another difference between Set and Setdelayed. Evaluation shortcut?

text: A little while ago I wondered why               f[x_] = f[x]      gives an infinite iteration. I ended up discovering the following difference in evaluation between `Set` and `SetDelayed` with `Evaluate`.               count = 0;     ClearAll@a     a /; (count++ < 20) = {a}     a // OwnValues     count = 0;     a      Output               {{{{{{{{{{{{{{{{{{{{{a}}}}}}}}}}}}}}}}}}}}}     {HoldPattern[a /; count++ < 20] :> {a}}     {a}      and               count = 0;     ClearAll@b     b /; (count++ < 20) := Evaluate@{b}     b // OwnValues     count = 0;     b      Output               {HoldPattern[b /; count++ < 20] :> {b}}     {{{{{{{{{{{{{{{{{{{{b}}}}}}}}}}}}}}}}}}}}      Can somebody explain the difference? Can we say that there is an evaluation shortcut at work here? **Related** This is a follow up question: Strange results of definitions using OwnValues Why x = x doesn't cause an infinite loop, but f[x_] := f[x] does? Does Set vs. SetDelayed have any effect after the definition was done?


title: Symbolic matrix simplification and solving

text: I am trying to expand or solve an equation that contains matrices for a certain matrix, but it is not working:               $Assumptions =        {Element[X, Vectors[n]], Element[Zu, Vectors[n]],         Element[Fu, DiagonalMatrix[n]], Element[Y, Matrices[{n, n}, Reals]]};          Solve[Y.Fu.(Zu + X.Y) + (Zu + X.Y).Fu.Y + 2 λ X == 0, X]          ExpandAll[Y.Fu.(Zu + X.Y) + (Zu + X.Y).Fu.Y + 2 λ X]          Simplify[Y.Fu.(Zu + X.Y) + (Zu + X.Y).Fu.Y + 2 λ X]      None of the above inputs works. Am I doing something wrong or is it that _Mathematica_ cannot solve for matrix equation symbolically?


title: Unexpected result {".a", "co", ".m"} from Sort[{".m", ".a", "co"}]

text: I came across the following situation: Evaluating               Sort[{".m", ".a", "co"}]      Results in               {".a", "co", ".m"}      I wondering: What was the criterion that _Mathematica_ use to output this? According to the documentation: > ...Sort orders strings as in a dictionary, with uppercase... After reading this, I expect a dictionary sort like this:               {".a", ".m", "co"}      Or               {"co", ".a", ".m"}      Can anyone explain me what was the criterion used by _Mathematica_ to perform this sort? Thanks in advance.


title: Strange results of definitions using OwnValues

text: I am asking this question simultatenously with this one, which is strongly related. I was trying to see if I could create the behaviour as in that question without using `Condition` by setting `OwnValues`. I ran into the following strange behaviour. The following gives an infinite recursion               Clear[c]     OwnValues[c] = {HoldPattern[c] -> {c}}      So does this               Clear[d]     OwnValues[d] := {HoldPattern[d] -> {d}}      But this does not               Clear[e]     OwnValues[e] := {HoldPattern[e] -> Unevaluated@{e}}      Actually this last piece evaluates to something other than `Null`, which is not what we expect from `SetDelayed`. Simpler expressions of similar form will also return something. This is what the aside here is about. Question: Can somebody explain what is going on here? Why do these definitions cause infinite recursions? ## Aside _Maybe I will write a separate question about this ;)_ **Tool** I have made the following tool that can show us when a particular function is being called, and with what arguments. It uses `Print` to display this information. Note that it is quite buggy. For now let's only use it on `SetDelayed`. Making both `SetDelayed` and `Set` print this way crashes the kernel I think. This is the tool.               SetAttributes[letPrint, HoldAll];     letPrint[symb_] :=      (       ClearAttributes[symb, Protected];       DownValues[symb] = {};       With[        {uq = Unique[]},        uq = False;        expr : symb[___] /; (uq = ! uq) := (Print[           Column[{uq, ToString[Unevaluated[symb]],              HoldForm@InputForm[expr]}]]; expr)        ]       )      Now we can do               (*warning, overloads and Unprotects SetDelayed*)     letPrint@SetDelayed      We then have that               Clear[aaa, bbb]     aaa := bbb      Prints               True (*not really meaningful*)     SetDelayed     aaa:=bbb      but               Clear[a]     OwnValues[a] = {HoldPattern[a] :> 1};      does not print anything. My suspicion is that there is some internal code associated with `OwnValues` that prevents the expression with head `SetDelayed` from being evaluated like normal. To restore `SetDelayed`, I think you can do               Clear@SetDelayed; Protect@SetDelayed


title: Forming product of function of prime factors

text: Given a list of numbers each containing 2 prime factors, I wish to make a list of the products of the logs of each factor. For example, given L = {4,6,9}, I would like to form P = {Log[2]*Log[2],Log[2]*Log[3],Log[3]*Log[3]}. FactorInteger seems like a questionable route since it would require some work to distinguish squares from numbers with two distinct prime factors. Any suggestions? Thank you.


title: How to label axes in 3D plot adequately?

text: The following code produces plot with axes labels, which are jumping constantly.               object = Cuboid[{-100, -100, 300}, {100, 100, 500}];          screenWidth = 640;     screenHeight = 480;     screen = Polygon[{{-screenWidth/2, -screenHeight/2,           0}, {-screenWidth/2, screenHeight/2, 0}, {screenWidth/2,           screenHeight/2, 0}, {screenWidth/2, -screenWidth/2, 0}}];          spaceWidth = 2000;     spaceHeight = 2000;     spaceDepth = 2000;     Graphics3D[{Opacity[0.5], object}, Axes -> True,       AxesOrigin -> {0, 0, 0},       PlotRange -> {{-spaceWidth/2, spaceWidth/2}, {-spaceHeight/2,          spaceHeight/2}, {-spaceDepth/2, spaceDepth/2}},       AxesLabel -> {"X", "Y", "Z"}, BoxRatios -> {1, 1, 1}]      **Sample 1** ![enter image description here](http://i.stack.imgur.com/06Y59.jpg) Cube is near Y label, although it is on Z axes. **Sample 2** ![enter image description here](http://i.stack.imgur.com/aaR6E.jpg) Cube is now near X label, after rotated infinitesimally.


title: ListPolarPlot: 0 Degree at vertical axis

text: Is it possible to have ListPolarPlot start plotting at the vertical axis? By Default ListPolarPlot gives this result:               ListPolarPlot[Reverse[Range[20]], PolarAxes -> True,       PolarTicks -> {"Degrees", Automatic}]      ![enter image description here](http://i.stack.imgur.com/hWJu6.png) But I want it to look like this (rotated with `Rotate[%,1/2pi]`: ![enter image description here](http://i.stack.imgur.com/q0I0n.png) Just rotating the graphic probably is the easiest way, but adding ticks and legends is a crime... I am hoping for a way to simply set the starting angle. Specifying angles at each data point and adding 1/2pi does not solve my problem because the angles in the PolarAxes would be off.


title: How to export this PDF figure with a small size

text: I want to export a PDF figure with the following codes, but the size of the PDF is too big, about 1.5M. I hope the size can be around 100k. I have tried for a long time but can not find a good solution. Any help or suggestion will be highly appreciated!               \[Rho]2plus = {{0.2011205485336045077` +       1.`*^-6 I, -0.017422322154311026` -       0.508770348467936524` I, -0.01627481119236278` -       0.009599125271231317` I,      0.00012377921551508936` -       0.0001037303194895626` I}, {-0.317422322154311026` +       0.008770348467936524` I, 0.5253584399150775` + 1.`*^-6 I,      0.1810835129135062` - 0.050379441418388037` I,      0.012122030783398718` -       0.00011053335415397864` I}, {-0.01627481119236278` +       0.009599125271231317` I,      0.4810835129135062` + 0.050379441418388037` I,      0.07251617971431137` + 1.`*^-6 I,      0.011027619410833644` +       0.00549701145732366` I}, {0.20012377921551508936` +       0.0001037303194895626` I,      0.012122030783398718` + 0.00011053335415397864` I,      0.011027619410833644` - 0.00549701145732366` I,      0.001004831837006529` + 1.`*^-6 I}};          \[Rho]2minus = {{0.005277185010322719` + 1.`*^-6 I,      0.0010040157957586214` +       0.04371079428674348` I, -0.09005650743684472643` -       0.046221573555130006` I, -0.003643884304307673` -       0.001085378855037156` I}, {0.2010040157957586214` -       0.24371079428674348` I,      0.0131515781501287` + 1.`*^-6 I, -0.1857896769310657` +       0.01114973388880884` I,      0.008915832323651186` +       0.03176372686431984` I}, {0.5005650743684472643` +       0.046221573555130006` I, -0.0857896769310657` -       0.01114973388880884` I,      0.07651833701845997` + 1.`*^-6 I, -0.0025963451307736015` -       0.034899274546212444` I}, {-0.003643884304307673` +       0.001085378855037156` I,      0.208915832323651186` -       0.23176372686431984` I, -0.0025963451307736015` +       0.034899274546212444` I, 0.005052899821088675` + 1.`*^-6 I}};                    figplus=GraphicsRow[     DiscretePlot3D[#@\[Rho]2plus[[i, j]], {i, 1, 4}, {j, 1, 4},        BoxRatios -> {1., 1., .8}, ExtentSize -> 0.5,        PlotRange -> {{.5, 4.5}, {.5, 4.5}, {-.5, .526}},        ColorFunction -> (Blend[{Hue[2/3], Hue[0]}, #] &),        ExtentElementFunction -> "ProfileCube",        Ticks -> {{{1, "A"}, {2, "B"}, {3, "C"}, {4, "D"}}, {{1,            "E"}, {2, "F"}, {3, "G"}, {4, "H"}}, Automatic},        AxesEdge -> {{-1, -1}, {1, -1}, {1, 1}},        FillingStyle -> Opacity[1],        LabelStyle ->         Directive[FontSize -> 12, FontFamily -> "Helvetica"],        Boxed -> True] & /@ {Re, Im} , ImageSize -> 500 ];                    figminus =GraphicsRow[DiscretePlot3D[#@\[Rho]2minus[[i, j]], {i, 1, 4}, {j, 1, 4},        BoxRatios -> {1., 1., .8}, ExtentSize -> 0.5,        PlotRange -> {{.5, 4.5}, {.5, 4.5}, {-.5, .523}},        ColorFunction -> (Blend[{Hue[2/3], Hue[0]}, #] &),        ExtentElementFunction -> "ProfileCube",        Ticks -> {{{1, "A"}, {2, "B"}, {3, "C"}, {4, "D"}}, {{1,            "E"}, {2, "F"}, {3, "G"}, {4, "H"}}, Automatic},        AxesEdge -> {{-1, -1}, {1, -1}, {1, 1}},        FillingStyle -> Opacity[1],        LabelStyle ->         Directive[FontSize -> 12, FontFamily -> "Helvetica"],        Boxed -> True] & /@ {Re, Im} , ImageSize -> 500 ];     gg = Grid[{{figminus}, {figplus}}, Spacings -> {0, 0}]     Export["Fig8.pdf", gg, ImageResolution -> 600]      ![enter image description here](http://i.stack.imgur.com/wmYxp.jpg)


title: CDF embedded in web page and Windows desktop magnification

text: I am running Windows 8.1 on a ThinkPad T540P with a 3K screen, which is equivalent to Apple Retina screens. I have configured Windows to increase the magnification of the desktop to make fonts legible. When I open a CDF using CDF Player 9.0 the resulting image appears magnified, although it does not display fonts using ClearType. When the CDF is embedded in a browser window, the height and width of the tag are magnified appropriately but the CDF itself is not, appearing smaller than the embedding area. Does anyone know of a way to force the CDF plugin to use the actual rendered size of the magnified embedding area? Thanks.


title: Making simultaneous equation solving more efficient

text: I am trying to solve a system of several simultaneous equations that have been generated by a series of modules and functions, using this module:               SolvePhiEqs[number_] :=     Module[{eqs, simeqs, diffsimeqs, Xvalues},          eqs = GeneratePhiEqs[number];          Xvalues = XValues[Range[1, 2*number]];          k = 1;     r = 1;          simeqs =         Table[Eq[j] -> Phi[j] == Phi[j + 1] /. eqs /. x -> x[j] /.         Xvalues , {j, 2*number}];     diffsimeqs =         Table[Eq[j + 2*number] -> xDiffPhi[j] == xDiffPhi[j + 1] /. eqs /.         x -> x[j] /. Xvalues, {j, 2*number}];          EquatedEqs = Flatten@{simeqs, diffsimeqs};          Coefficients =         Flatten@{Table[R[j], {j, 0, number - 1}], Table[T[j], {j, number}],        Table[A[j], {j, number}], Table[B[j], {j, number}]};          FinalCoefficient =         Solve[Simplify[Reduce[Array[Eq, 4*number] /. EquatedEqs]],         Coefficients]          ]      However after having to solve more than 4 simultaneous equations (what is generated by using a 'number_' argument of 1), my computer starts churning away and does not come back with an answer for at least 10 mins (the longest I've tried so far). As this is supposed to be a general solution to a problem, I am looking at generating solutions up to at least 'number = 20' or so, so this is not particularly encouraging. However, I am fairly sure the code is functional, if not particularly efficient. Whilst I appreciate that it is not easy to make a specific comment based on incomplete code, if anyone has any more general suggestions as to how to make simultaneous equation solving more efficient, they would be much appreciated!


title: Save all input History in a log file

text: I would like to write some code in my init.m to save all inputs `{In[1],In[2],...In[lastone]}` right before I close the kernel (or exit Mathematica). Such a script probably should be kernel-specific but I can settle with one log file. In this way I will be able to review each day's work and assess my productivity. Also I can trace some tweaks I am implementing without the need to remember in which file I did this and that ... I hope others in SE also would like such an option.


title: How to do Fast Fourier transform (FFT) for singular functions?

text: I want to do a 3-dimensional FFT on this function $\frac{\cos (x) \cos (y) \cos (z)-\sin (x) \sin (y) \sin (z)}{\left((1.0001+\sin (y)+\cos (z))^2+(0.0001+\cos (x)+\sin (z))^2+(0.0001+\sin (x)+\cos (y))^2\right)^{3/2}}$ for it looks intractable via analytical Fourier expansion. Let's denote the number of numerical sampling points in each dimension as $N$. FourierParameters -> {a, b}. $a=-1$ for $1/N^3$ normalization in conformity with commonly used coefficients in FourierSeries. $b=-1$ for forward, not backward transform.               nn = 10; step = (2 \[Pi])/nn; mx0 = 1.0001; my0 = 0.0001; mz0 = 0.0001;      data = Table[ ( Cos[x] Cos[y] Cos[z] - Sin[x] Sin[y] Sin[z])/((mz0 + Cos[y] + Sin[x])^2 + (mx0 + Cos[z] + Sin[y])^2 + (my0 + Cos[x] + Sin[z])^2)^(3/2), {x, 0, 2 \[Pi] - step, step}, {y, 0, 2 \[Pi] - step, step}, {z, 0, 2 \[Pi] - step, step}];     s = Fourier[data, FourierParameters -> {-1, -1}]; s[[1, 1, 1]]      As far as I've tried, using **Fourier[ ]** in _Mathematica_ , the transformation result doesn't converge even when $N=500$, oscillating drastically with respect to $N$ in fact. Besides, I also tried some FFT routine from MKL library by C++, which showed similar behavior. I checked the programs with many other non-singular functions, they turned out to be good. So I guess the problem may be caused by the special form of the singular function (denominator can be zero at some points). I tried $\frac{1}{0.9-\sin{(x+y+z)}}$. It doesn't oscillate so much, but still considerably. Can anyone shed some light on this problem? Thanks in advance!


title: How to use NIntegrate when there are symbolic constant coefficients

text: I would like to numerically integrate an equation such as the one below in which there are symbolic constant coefficients. I used a very simple code but it doesn't work in general, that tried to deal with constant coefficients with patterns. Is there any general approach to NIntegrate where symbolic constant coefficients exist?               11.94` a[1, 1]^2 Cos[x]^2 Cos[θ]^2 +         21.31` c[1, 1]^2 Cos[x]^2 Cos[θ]^2 +         0.14702` a[1, 1] b[1, 1] Cos[x] Cos[θ]^2 Sin[x] - (        1.395` b[1, 1]^2 Cos[x] Cos[θ]^2 Sin[x])/(1 + x/2)^3 +         0.4669` b[1, 1]^2 Cos[θ]^2 Sin[x]^2 + (        1.395` b[1, 1]^2 Cos[θ]^2 Sin[x]^2)/(1 + x/          2)^4 /.      {b[a1_, a2_] b[a3_, a4_] g_ :> b[a1, a2] b[a3, a4] NIntegrate[g, {θ, 0, 2}, {x, 0, 1}],       a[a1_, a2_] a[a1_, a2_] g_ :> a[a1, a2] a[a1, a2] NIntegrate[g, {θ, 0, 2}, {x, 0, 1},                                     Method -> {Automatic, "SymbolicProcessing" -> 0}],      a[a1_, a2_] a[a3_, a4_] g_ :> a[a1, a2] a[a3, a4] NIntegrate[g, {θ, 0, 2}, {x, 0, 1},                                     Method -> {Automatic, "SymbolicProcessing" -> 0}],      b[a1_, a2_] b[a1_, a2_] g_ :> b[a1, a2] b[a1, a2] NIntegrate[g, {θ, 0, 2}, {x, 0, 1},                                     Method -> {Automatic, "SymbolicProcessing" -> 0}],      c[a1_, a2_] c[a1_, a2_] g_ :> c[a1, a2] c[a1, a2] NIntegrate[g, {θ, 0, 2}, {x, 0, 1},                                     Method -> {Automatic, "SymbolicProcessing" -> 0}],      a[a1_, a2_] b[a3_, a4_] g_ :> a[a1, a2] b[a3, a4] NIntegrate[g, {θ, 0, 2}, {x, 0, 1},                                     Method -> {Automatic, "SymbolicProcessing" -> 0}],      a[a1_, a2_] c[a3_, a4_] g_ :> a[a1, a2] c[a3, a4] NIntegrate[g, {θ, 0, 2}, {x, 0, 1},                                     Method -> {Automatic, "SymbolicProcessing" -> 0}],      b[a1_, a2_] c[a3_, a4_] g_ :> a[a1, a2] a[a3, a4] NIntegrate[g, {θ, 0, 2}, {x, 0, 1},                                     Method -> {Automatic, "SymbolicProcessing" -> 0}],      c[a1_, a2_] c[a3_, a4_] g_ :> c[a1, a2] c[a3, a4] NIntegrate[g, {θ, 0, 2}, {x, 0, 1},                                     Method -> {Automatic, "SymbolicProcessing" -> 0}]        } // Timing


title: Obtain approximate Hessian using FindMinimum

text: According to the documentation, when `FindMinimum` is told to use the method `"QuasiNewton"` on a unconstrained problem, it uses the BFGS approximation to the Hessian matrix of the function being optimized. How can I recover the Hessian matrix computed by Mathematica using `StepMonitor`, `EvaluationMonitor` or any other devious trick?


title: How to make a function like Set, but with a Block construct for the pattern names

text: How can we define a function that works like `f[x_]=ComputeSomething[x]` and treats `x` as a variable that does not have a value? We could call this function `LocalSet` and the computation should be done when the assignment is made as in the following example.               var=3;     LocalSet[f[var_],Normal[Series[Exp[var],{var,0,3}]]];     DownValues[f]          (*     ---> {HoldPattern[f[var_]]:>1+var+var^2/2+var^3/6}     *)          var     (*     ---> 3     *)       Notice I don't want to be limited to a pattern variable (`x_`). The function called `LocalSet` should figure out what symbols are used for patterns and evalute the right side with those variables in a `Block` construct.


title: How do I access the name of a list in a function?

text: Background:                 bar := {1, 1, 1};       foo[var_] := {Hold[var], 2 var}       SetAttributes[foo, HoldAll]       foo[bar]      Result, as expected:                 {Hold[bar], {2, 2, 2}}      What I then do ( which is clearly not correct, but I don't know another way ) is that I `ToString` the first element of the list, i.e. `Hold[bar]` and then extract the substring "bar" out of it. What I want is just this:                 f[data_?VectorQ] := f[data, name_of_data]       f[data_?VectorQ, name_?StringQ] := "Save data as name" ...      So for example:                  ape = {1,2,3};        bear= {2,3,4};        f[ape] translates to f[{1,2,3"}, "ape"]        f[bear, "bird"] translates to f[{2,3,4}, "bird"]        f[ape+bear] translates to Null or False.      **Question: How do I access the name of a list in a function ?**


title: Wolfram Workbench - Mathematica Development Alternatives

text: Are there any alternatives (IDE or other workflow) to Wolfram Workbench for development and debugging? Elaboration: An open source alternative.


title: How can I extract the data from an image and process it pixel by pixel?

text: For example, to change the color of each pixel to the mean color of the three channels, I tried               i = ExampleData[{"TestImage", "Lena"}];     Mean[i]      but it just remains unevaluated: ![enter image description here](http://i.stack.imgur.com/K1RRR.png) How can I read the colors of an image into a list or matrix and change the color codes and save it back to an image?


title: Can I check if an expression is positive using assumptions?

text: I have the following notebook:               $Assumptions -> { {c1, c2, λ, μ} > 0, Element[{c1, c2, λ, μ}, Reals], μ > λ}          (* True -> {{c1, c2, λ, μ} > 0, (c1 | c2 | λ | μ) ∈ Reals, μ > λ} *)          f1 := c1 * (λ/(μ - λ)) + μ * c2          df1 = D[f1, μ]          (* c2 - (c1 λ)/(-λ + μ)^2 *)          Solve[df1 == 0, μ]          (* {{μ -> (-Sqrt[c1] Sqrt[λ] + Sqrt[c2] λ)/Sqrt[        c2]}, {μ -> (Sqrt[c1] Sqrt[λ] + Sqrt[c2] λ)/Sqrt[c2]}}*)           D[df1 , μ]           (* (2 c1 λ)/(-λ + μ)^3 *)      The last line is getting the second order condition. Since all terms in the numerator are positive, the numerator is positive. Since $\mu > \lambda$ by assumption, then $(-\lambda + mu)^3$ is also positive for any $\mu$, $\lambda$ combination. Is it possible for _Mathematica_ to use the stated assumptions to tell me that the second order condition is positive, given the set of assumptions?


title: Creating Plots for a Family of Solutions

text: I am wondering how do you set the parameters appropriately for $a_n,\,\alpha,\,\text{and }b_n$ to plot the family of solution of: > $u_n(r,t) = [a_n\cos(k_n\alpha t)+b_n\sin(k_n\alpha t)]J_0(k_nr)$ where the Bessel function of the first kind of zero order represents $J_0.$ $0<k_1<k_2<\ldots<k_n<\ldots$ are all positve zeros of $J_0$. The original equation is: $u_{tt}=\alpha(u_{rr}+\tfrac{1}{r}u_r), \quad 0<r<1,~ t>0,$ $u(1,t)=0, \qquad t>0,$ $u(r,t)$ remain finite as $r\rightarrow 0^+,$ $u(r,0)=f(r), \qquad 0<r<1,$ $u_t(r,0)=g(r), \qquad 0<r<1,~~$ where $f,g$ are initial displacement and velocities. I tried something of the type: > >     0<r<1; >     t>0; >     Plot3D[Cos[8.654 t] + Sin[8.654 t] BesselJ[0, 8.654 r], {r, 0, 1}, {t,0, > 10}] >   Choosing other parameters in the solution to have the value of 1. The output would resemble the following: ![vm](http://i.stack.imgur.com/ANTSt.png) First graphic is for $J_0(2.4r)$, Second graphic is for $J_0(5.5r)$, and Third graphic is for $J_0(8.7r)$.


title: Mathematica: Label specific vertices in GraphPlot

text: How can I label particular vertices in GraphPlot? And have the arrows space out accordingly, for the width of the label? I have Mathematica 7, but I think this question applies to all versions. ![Mathematica Graph Plot](http://i.stack.imgur.com/YEq9j.png) Edit: I posted the above graph so you can see label overlap might kill whatever information the graph is displaying. For simplicity, lets do a mock graph: Generate the Data:               data = #[[1]] -> #[[2]] & /@ Partition[RandomInteger[10, 100], 2]      Plot the Graph:               GraphPlot[data, EdgeRenderingFunction -> ({Red, {Arrowheads[Small], Arrow[#1, .07]}} &)]      Gives something like: ![Random GraphPlot](http://i.stack.imgur.com/kIHgg.png) If I wanted to explicitly label "1" and "5", this is where I'm completely lost: I'm happy with the ugly yellow boxes for now:               GraphPlot[data,EdgeRenderingFunction->({Red,{Arrowheads[Small],Arrow[#1,.07]}}&), VertexLabeling->True]      ![yellow box, on all labeling](http://i.stack.imgur.com/ItSw3.png) But you can see it can be problematic if I labeled every point in the first graph. I wish the `VertexLabelingFunction` help pages was a bit more thorough, all it seem it do is some sort of rule based, rather than explicit labels. I'm thinking it'll be some `VertexLabelingFunction -> (If[#1 == "1" || #1 == "5", Text[#1]])&` But that always gives me an error.


title: When must I use the Return function?

text: In a comment to my answer to this question, QuantumDot asks, "Where can I find more information on when I must use the 'Return' function?". I found this too deep a question to be answered by leaving a comment in reply. I think it deserves to be asked as an question in own right. I am posting my answer below, but I hope there will be others. I doubt I have the definitive view of this matter.


title: Subtle difference in conditional rules placement

text: I had gotten used to thinking of the placement of a condition in a rule definition as logically immaterial. In my specific example, namely               ClearAll[f,g,h];     SetAttributes[f,HoldAllComplete];     f[x_ /; Head@Unevaluated@x === Symbol] := x;          SetAttributes[g,HoldAllComplete];     g[x_] := x /; Head@Unevaluated@x === Symbol;          SetAttributes[h,HoldAllComplete];     h[x_] /; Head@Unevaluated@x === Symbol := x;      all three produce the same results when applied to the same symbol               In[13]:= f[foo] === g[foo] === h[foo] === foo          (* Out[13]= True *)      But now I try to get fancy and write the following               ClearAll[f, g, h, foo];     SetAttributes[f,HoldAllComplete];     f[x_ /; Head@Unevaluated@x === Symbol] := Unevaluated@x;          SetAttributes[g,HoldAllComplete]     g[x_] := Unevaluated@x /; Head@Unevaluated@x === Symbol;          SetAttributes[h,HoldAllComplete]     h[x_] /; Head@Unevaluated@x === Symbol := Unevaluated@x;          In[20]:= {f[foo], g[foo], h[foo]}      and the results are very different               (* Out[20]= {foo, Unevaluated[foo], foo} *)      I try to figure it out with traceView2; I can see the differences ![traceView2 differences](http://i.stack.imgur.com/RApTe.png) but I get quickly lost in the documents trying to understand what, why, and how. Seems even this example is not so simple and probes dark (at least to me) corners of the evaluator. I'd be grateful for advice, explanations, ideas.


title: Quality of random numbers

text: Mathematica has several ways of generating random numbers: Congruential, ExtendedCA, Legacy, MersenneTwister, MKL, ParallelGenerator, ParallelMersenneTwister, Rule30CA. For `Method -> "Congruential"` the page notes that this generates low-quality randomness. What is known about the others? I came across a paper today (available here and here) showing that `Method -> "Rule30CA"` has an extremely small effective size, suggesting that it is probably unsuitable for simulation work. I was a little concerned on reading this, since there was nothing in the help that suggested it should not be used. Which of the others are known to be good? In particular, is the default `Method -> "ExtendedCA"` known to pass such tests as BigCrush or Dieharder? I know of results for the Mersenne Twister, of course (does well on all but the linear complexity tests). ## Summary of Results So Far   * Congruential: Low quality (per documentation)   * ExtendedCA: Apparently high-quality; Lichtblau reports (in an answer below) that it passes BigCrush.   * Legacy: Presumably low quality, else would not have been obsoleted   * MersenneTwister: Fairly high quality, though fails some BigCrush tests   * MKL: Similar to MersenneTwister?   * ParallelGenerator: What is this?   * ParallelMersenneTwister: Same as MersenneTwister?   * Rule30CA: Low quality (Meier & Staffelbach 1991, Sipper & Tomassini 1996) _This question touches on math and computer science, but this se seemed the best fit._


title: Paging RAM in case of memory shortage issue

text: Is there some way in Mathematica where I can issue execution of some command with letting Mathematica use my hard disk in case it is short of RAM. It will drastically reduce the speed but I am fine with it as long as I get appropriate results.


title: Rebuild a polygon so it doesn't self intersect

text: If you consider the following `Polygon`:               coor = {{6, 0}, {6, 1}, {4, 0}, {5, 2}};     (* and coor = {{7, 2}, {7, 1}, {5, 2}, {6, 1}} *)     pol = Polygon@coor;     Graphics@pol      ![Mathematica graphics](http://i.stack.imgur.com/BQWUW.png) I would like to know if there is any way to rebuild it _automatically_ in order to remove the self intersection. Self intersection can be check thanks to J.M.'s comment by:               interPolQ = Not@Graphics`Mesh`SimplePolygonQ[#]&;     interPolQ@pol      > True Knowing that `Graphics`Mesh`SimplePolygonQ[]` is undocumented I'm wondering if there is a hidden built-in function for that purpose as well. * * * The output should look like the following and have for coordinates `desiredcoor`:               coor = {{6, 0}, {6, 1}, {4, 0}, {5, 2}};     desiredcoor = {{4, 0}, {6, 0}, {6, 1}, {5, 2}};     Graphics[{EdgeForm[Dashed], FaceForm@Opacity@.2, Polygon@{coor, desiredcoor}}]      ![Mathematica graphics](http://i.stack.imgur.com/TWkJd.png)


title: show fit information on plot

text: After performing a fit in Mathematica, I would like to show the fitted parameters in a box on the plot showing the fitted function. How would I go about achieving that? Here is a MWE:               func[a_, b_, x_] := a*x + b;     nlm = NonlinearModelFit[{{1, 1}, {5, 5}, {2, 3}}, func[         a,         b,         x],        {{a, 1}, {b, 0}}, x];                    Plot[Normal[nlm[t]], {t, 0, 1.0}, PlotRange -> Full]     nlm["ParameterTable"]


title: How to fit one parametric array to another numerical array?

text: I have two arrays of length `n`. One of them is obtained by experiment, so every element of the array is a number. The other array is parametric, each element is a combination of a parameter and numbers. There are 8 parameters. In theory, arrays one and two must be the same. I want to find the best possible set of 8 parameters which fit the parametric array to the experimental one. How can I do that in Mathematica? `FindFit` needs an array and a function. I do not know how to fit the two arrays. * * * I tried to subtract the two arrays and use `NMinimize` to minimum the new array with respect to the parameters. It didn't work. It returns:               NMinimize::bcons: The following constraints are not valid: {0.004 -4 (E^(-          (0.002/Subscript[<<2>>])) Subscript[a, 1]+E^(-(0.002/Subscript[<<2>>])) Subscript[a,           2]+E^(-(0.002/Subscript[<<2>>])) Subscript[a, 3]+E^(-(0.002/Subscript[<<2>>]))           Subscript[a, 4]),4-4 (E^(-(0.002/Subscript[<<2>>])) Subscript[a, 1]+E^(-          (0.002/Subscript[<<2>>])) Subscript[a, 2]+E^(-(0.002/Subscript[<<2>>])) Subscript[a,           3]+E^(-(0.002/Subscript[<<2>>])) Subscript[a, 4]),<<48>>,<<1588>>}. Constraints should           be equalities, inequalities, or domain specifications involving the variables. >>      Mathematica thinks that the first argument of `NMinimize` contains some constraints, which is not the case. It thinks so perhaps because the first argument cannot be an array.


title: How to display output as symbols?

text: I have this piece of code which populates a matrix following different rules depending on row and column number:               MQp := Array[Qp, {Length[a], Length[a]}];     Do[Qp[i, 1] = a[[i]], {i, 1, Length[a]}];     Do[Qp[1, j] = a[[j]]/2, {j, 2, Length[a]}];     Do[If[(i == j),         If[((2 j - 1) <= Length[a]), Qp[i, j] = a[[2 i - 1]]/2 + a[[1]],          Qp[i, j] = a[[1]]],         If[(i != 1 && j != 1),          If[(i + j - 1) <= Length[a],           Qp[i, j] = a[[i + j - 1]]/2 + a[[Abs[i - j] + 1]]/2,           Qp[i, j] = a[[Abs[i - j] + 1]]/2]]], {i, 1, Length[a]}, {j, 1,         Length[a]}];     Qp[1, 1] = a[[1]];     MatrixForm[MQp]      Currently "a" is a table of numerical values. I would like to generate a table of symbolic a's, and then be able to substitute the numerical values into the matrix. This way I can easily check that the values in the matrix correctly match what should be generated. I've tried several methods, but so far I get errors or nothing is output at all? Can someone help me out? Thanks in advance. PS: How do I display code blocks correctly? I did a line and eight spaces but it looks like it didn't work.


title: Why do Tooltips slow down Dynamic so much? Is there a faster alternative?

text: I'm working on a Dynamic ListPlot with a few thousand plots, and it seems that wrapping the points with Tooltip slows the Dynamic responsiveness substantially. With the simple example below, dragging the Slider is sluggish. If you change the Show line from "plot1" to "plot2", the Slider response is smooth. Notice that the ListPlot and Tooltips are not being modified by the Control. Maybe Show is muddling things when it combines the graphics, but still, the slowdown doesn't make sense to me, since Tooltip isn't active during the drag, and isn't changing in any way.               x = Table[RandomVariate[NormalDistribution[0, .5], 2], {i, 5000}];     boxPts[x_] := {{x, x}, {-x, x}, {-x, -x}, {x, -x}};     plot1 = ListPlot[MapIndexed[Tooltip[#1, First[#2]] &, x]];     plot2 = ListPlot[x];     Control[{{z, .5}, 0, 1.5}]     overlay = Graphics[{Opacity[.2],         FilledCurve[{{Line[boxPts[1.5]]}, {Dynamic[Line[boxPts[z]]]}}]}];     Show[overlay, plot1, PlotRange -> 1.5, AspectRatio -> 1]      ![Output of above code](http://i.stack.imgur.com/5F7EJ.png) I'd prefer to be able to use Tooltip, if it's fixable, or at least understand why it's so slow. I'd also be interested in any alternative methods for doing mouseover-style feedback, which could show up inside or outside the plot area. Thank you! (This is in Mma 9.0.1 on OSX 10.8.5, on a 2012 MBP.) Update: I noticed that if I execute the Control line _after_ the Show line with plot1, the Slider works smoothly. I then noticed that merely moving the cursor away to a new point can make the Control work normally. This only makes a difference with the plot that has Tooltips, since the other is always smooth.


title: Solve for variable in integral limit when using NIntegrate

text: I am trying to solve for a variable which appears in the limits of an integral, rather like in the following;               Clear[f, a, x]     f[a_] := Integrate[x^2 + a x, {x, 0, a }]     f[Power[6, (3)^-1]]     NSolve[5 == f[a], a, Reals]      This works absolutely fine. But the integral I really care about is a mess, and so has, of course, no nice closed form. So I try the following;               Clear[f, a, x]     f[a_] := NIntegrate[x^2 + a x, {x, 0, a }]     f[Power[6, (3)^-1]]     NSolve[5 == f[a], a, Reals]      and this does not work. Instead I get `NIntegrate::nlim: x = a is not a valid limit of integration.` In both of these examples, the third line evaluates the function `f[a]` fine. I also tried               f[a_?NumericQ] := NIntegrate[x^2 + a x, {x, 0, a }]      which fails with `NSolve::nsmet: This system cannot be solved with the methods available to NSolve.` I rather hoped the link below would answer my problem, but of course it refers to `Integrate`, not `NIntegrate`. http://math.stackexchange.com/questions/38012/compute-unknown-limit-from- known-integral-in-mathematica I'd be very grateful for any suggestions.


title: What are the upper bound and stability conditions for the following simple linear system

text: Consider the following linear system $$\dot{x}=\sum\limits_{i=1}^{m}{{{\alpha }_{i}}}\left( t \right)\cdot {{A}_{i}}\cdot x \quad (1) $$   where, $x\in {{\mathbb{R}}^{n}}$ represents the state vector, $\sum\limits_{i=1}^{m}{{{\alpha }_{i}}}\left( t \right)=1$, ${{\alpha }_{i}}\left( t \right)$are functions and ${{\alpha }_{i}}\left( t \right)>0$, ${{A}_{i}}\in {{\mathbb{R}}^{n\times n}}$ are constant matrices, $i=1,\cdots ,m$. Once system (1) is stable , then the Euclidean norm of vector $x$ is bounded. Now, the questions are as the following: 1) what’s the upper bound for $\left\| x \right\|$ when system (1) is stable; 2) what’s the stability condition for system (1)? (Lyapunov function may be an appropriate and conventional method to derive the conditions for the stability of system (1).)


title: Sample code for generating mosaic images doesn't work

text: I'm reading the blog on mosaics by Theodore Gray. I tried the first example:               dir = "d:\\mosaic\\pool\\*.jpg";       master = "d:\\mosaic\\master.jpg";       imagePool = Map[With[{i = Import[#]}, {i, Mean[Flatten[N[i[[1, 1]]], 1]]}] &,        FileNames[dir]];     closeMatch[c_] := RandomChoice[Take[SortBy[imagePool, Norm[c - #[[2]]] &], 20]][[1]];     Grid[Reverse[Map[closeMatch, Import[master][[1, 1]], {2}]], Spacings -> {0, 0}]      but it gives me errors: > Part::partd: Part specification (<an image>)[1,1] is longer than depth of > object. I'm using Mathematica version 9. A comment on the blog says the code has to be modified for version 8, so I guess the changes are also required for version 9. How can I make this code work?


title: Mathematica loop code not behaving as expected

text: getAvgs[A_, M_] := Module[{i, j, rArr, gArr, bArr},        rArr = {};        gArr = {};        bArr = {};        For[i = 1, i <= Length[A], i += 1,         For[j = 1, j <= Length[A[[1]]], j += 1,           If[M[[i, j]] == 255,             Append[rArr, A[[i, j, 1]]];             Append[gArr, A[[i, j, 2]]];             Append[bArr, A[[i, j, 3]]];             ];           ];         ];        Return[{rArr, gArr, bArr}];        ];      This code returned an array containing three blank arrays {{},{},{}}, meaning none of the Append functions worked. A_ and M_ are two images, A is 24-bit 3-channel colour, while M is black and white. They have the same dimensions, the idea is to use M as a mask to find the average colour of all pixels that are shown by the mask. However, none of the Append functions worked. Append[{}, ImageData[,Byte][[30, 30, 3]]] correctly returned the value, so the syntax should be fine. When I made the for loop increment a counter, the counter correctly returned the number of masked pixels, so the for loop is working correctly too. From what I know, Module basically declares the variables locally, preventing variable collisions. Is this correct as well?


title: Export of 3D Plot

text: I finally got my 3D Graph :) Unfortunately, when I export I get a bad image quality. ![Exported PNG](http://i.stack.imgur.com/f8hCp.png) How can I export the image without the white stripes? Here is the code for reproducing the error               scaleR = 1.2;     ni = 1;     no = 2;     IP = {3, 4, 4};          IncidentIn = {0, 1.5, 1.5};     IncidentOut = IP;     scale = Norm[IncidentOut - IncidentIn];     i = Normalize[IncidentOut - IncidentIn];     RadiusIn = IP;     n = Normalize[{0, 1, 1}];     t = Normalize[     ni/no i - n (ni/no (n.i) - Sqrt[1 - (ni/no)^2 (1 - (n.i)^2)])];     r = Normalize[i - 2 (n.i) n];     axial = {1, 0, 0};     cylinder = ContourPlot3D[     y^2 + z^2 == 32, {x, IncidentIn[[1]], (IP + scale r)[[1]]}, {y, -6,     6}, {z, -8, 8}, Mesh -> 1,      ContourStyle -> FaceForm[{White, Red}, Opacity[0.0]],      AxesLabel -> {"x", "y", "z"}];     cylinder2 =      ContourPlot3D[y^2 + z^2 == 32, {x, IncidentIn[[1]], -(IP + scale r)[[1]]}, {y, -6, 6},      {z, -8, 8},      Mesh -> None, ContourStyle -> Directive[Red, Opacity[1]],      AxesLabel -> {"x", "y", "z"}];     areaR = ContourPlot3D[     axial.({x, y, z} - IncidentIn) == 0, {x,      IncidentIn[[1]], (IP + scale r)[[1]]}, {y, -6, 8}, {z, -6, 8},      Mesh -> False];     planeOI = ContourPlot3D[Cross[r, t].({x, y, z} - IncidentIn) == 0, {x,      IncidentIn[[1]], (IP + scale r)[[1]]}, {y, 0, Sqrt[64]}, {z, 0,      Sqrt[64]}, ContourStyle -> {White, Opacity[1]}, Mesh -> False];     axial = Graphics3D[{Arrowheads[0.03], Black, Dashed,      Arrow[{{0, 0, 0}, {(IP + scale r)[[1]] + 2, 0, 0}}],      AxesLabel -> {"x", "y", "z"}}];      radius = Graphics3D[{Arrowheads[0.03], Black, Dashed,      Arrow[{{3, 0, 0}, 1 + IP + scale n}],      AxesLabel -> {"x", "y", "z"}}];     inv = Graphics3D[{Thick, Arrowheads[0.03], Darker[Red],      Arrow[{IncidentIn, IP}], AxesLabel -> {"x", "y", "z"}}];     outv = Graphics3D[{Thick, Arrowheads[0.03], Darker[Blue],      Arrow[{IP, IP + scale t}], AxesLabel -> {"x", "y", "z"}}];     reflv = Graphics3D[{Thick, Arrowheads[0.03], Darker[Green],      Arrow[{IP, IP + scale r}], AxesLabel -> {"x", "y", "z"}}];     points = Graphics3D[{PointSize[0.008], Opacity[1],      Point[{IncidentIn, IP, IncidentIn*{1, 0, 0} + IP*{0, 1, 1},      IP + scale t, IP + scale r }]}];     directCosinv =      Graphics3D[{Darker[Red], Dashed,      Line[{IncidentIn, (IncidentIn*{1, 1, 0} +      IP*{0, 0, 1}), (IncidentIn*{1, 0, 0} + IP*{0, 1, 1}), IP}],      AxesLabel -> {"x", "y", "z"}}];     directCosoutv =      Graphics3D[{Darker[Blue], Dashed,      Line[{IP, (IP*{1, 1, 0} + (IP + scale t)*{0, 0, 1}), (IP*{1, 0,            0} + (IP + scale t)*{0, 1, 1}), IP + scale t}],      AxesLabel -> {"x", "y", "z"}}];     directCosreflv =      Graphics3D[{Darker[Green], Dashed,      Line[{IP, (IP*{0, 1, 1} + (IP + scale r)*{1, 0, 0}), (IP*{0, 0,      1} + (IP + scale r)*{1, 1, 0}), IP + scale r}],      AxesLabel -> {"x", "y", "z"}}];     plt = Show[points, planeOI, directCosreflv, directCosinv,      directCosoutv, outv, areaR, reflv, inv, axial, radius, cylinder,      cylinder2, Axes -> False, AxesLabel -> {"x", "y", "z"},      Boxed -> False, ImageSize -> Large,      ViewPoint -> {1.388, -2.089, 2.27},      ViewVertical -> {-0.13, 0.09, 1}, Lighting -> "Neutral"]     Export["FresnelInVectors.png", plt, "PNG", ImageResolution -> 600]


title: Convert probability example to a distribution

text: Consider a box which contains 30 balls. 10 red, 10 white and 10 blue balls. There will be picked 4 balls randomly, without putting the balls back to the experiment. My question is: How do I create a distribution of this senario, so I can find the probability that none of the 4 balls are red, and to calculate the mean and variance? I am aware the math is: $$\frac{20}{30} \times \frac{19}{29} \times \frac{18}{28} \times \frac{17}{27}=0.1768$$ But I need to convert it into a distribution and use the Probability function.


title: Detecting double click events

text: Is there a way to detect double click events? I did not find anything on the doc page of `EventHandler`. Use case: I want to re-implement the `Crop Image...` functionality available form the context menu when clicking images. The cropping GUI appears much too slowly with even moderately large images, such as screenshots of the full screen. Although I could use a button to crop, I'd prefer using double click, just like in the original implementation.


title: Projection of Density Plot

text: Say I have a density plot such as               DensityPlot[Sin[x]*Sin[y],{x,-2,2},{y,-2,2}]      Is there a way to see a projection of this plot. For example is there a way to see a plot of the maximum values from x=-2 to x=2? Or perhaps the values from x=-2 to x=2 along the line y=0? Maybe a way to get the numerical values and plot it? Thanks! P.S. I am looking to do this from the plot, not setting y=0 and solving mathematically.


title: What's the most intelligent way to store the information of a selfmade graph?

text: I have a very long list of element, say $a1,a2, a3$,..., and they are all connected in that each is the child of many parents. E.g. $a74$ is associated with $a2,a55,a71$, and also contains information, like 'the name of $a74$ is bob. It's an upwards tree if you want, with the $a$'s as vertices. Now I wonder what the most efficient way to store this information in Mathematica is, given that I might have to run exhaustive computation along that graph. I'll mainly call the list of $a$-symbols to use them to climb further and I want to compute statistics about the graph itself. Sometimes I'll need the names of the vertices or other information. * * * My naive ideas are to make all symbols a list               a74={{a2,a55,a71},"bob"};      and then $a74[[1]]$ is the partent list and so on. Or maybe I could define fictions $n\rightarrow \text{list}$ and store the information in them, like               parent[a5]={a1,a4};          parent[a74]={a2,a55,a71};      and               name[a5]="mila";          name[a74]="bob";      Or a mix, depending on what I call more often? Or are there structures, which simplify or automatize these kind of things? * * * I don't know yet how computationally difficult it's going to be, so the practical point might also be considered. In any case, I'd like to hear what seems to be not the way to do it. > What is the right way to do this and/or are there other options? At the moment I'd just generate the lists as in the first example. In actuality, I will write the list in a text-file and only later read in the information to a Mathematica file.


title: FindRoot constrained to maximum

text: I am using `FindRoot` to find the local maximum op some function, by examining where its derivative is zero. However, keeping the starting value the same, sometimes `FindRoot` returns the local minimum of my function, as the derivative is, obviously, also zero there. How do I require `FindRoot` to look whether the derivative is positive (local minimum) or negative (local maximum), before accepting a particular root? For example:               Plot[{x^3 - 4 x, 3 x^2 - 4}, {x, -3, 3}]     FindRoot[3 x^2 - 4, {x, 1}]     FindRoot[3 x^2 - 4, {x, -1}]      The real problem:               Plot[{(-9-90 s-160 s^3+s^2 (-16+Sqrt[-(((9+16 s^2) (-9-180 s+320 s^3-16 s^2 (1+200 Log[5])+1600 s^2 Log[2 \[Pi] (1/4+9/(64 s^2))]))/s^4)]))/(320 s^2)},{s,0,3}]     FindRoot[(-9-90 s-160 s^3+s^2 (-16+Sqrt[-(((9+16 s^2) (-9-180 s+320 s^3-16 s^2 (1+200 Log[5])+1600 s^2 Log[2 \[Pi] (1/4+9/(64 s^2))]))/s^4)]))/(320 s^2),{s,1}]     FindRoot[(-9-90 s-160 s^3+s^2 (-16+Sqrt[-(((9+16 s^2) (-9-180 s+320 s^3-16 s^2 (1+200 Log[5])+1600 s^2 Log[2 \[Pi] (1/4+9/(64 s^2))]))/s^4)]))/(320 s^2),{s,1/10}]


title: How to plot 2D plot against two functions

text: I need to `Plot` two functions one is on x-axis and second on y-axis, both function have common variable $x$. The two functions are               myfunction1[{al_, be_, ga_}] := (al*be)/2 Cos[x]     (Sec[x/2])^2 (Tan[x/2])^-(be + 1) (1 + ga (Tan[x/2])^-be)^(-(al/ga) - 1)     myfunction2[{al_, be_, ga_}] := (al*be)/2 Sin[x] (Sec[x/2])^2 (Tan[x/2])^-(be + 1) (1 +      ga (Tan[x/2])^-be)^(-(al/ga) - 1)      where $0<x<\pi$, and al, be and ga are equal in both functions. I have no idea how to use `Plot` function or there is any other function in `Mathematica` to plot this?


title: Matrix Multiplication in context of row and column vectors

text: I've been looking at some matrices in Mathematica and I've noticed something very weird: They're extremely temperamental when it comes to dot products! For example, if I have the following,               i={{1},{2},{3}}     j={1,2,3}     k=i.j      the as far as I remember I should get a $3x3$ matrix since we have `(3x1).(1x3)` and the 1s "cancel" to produce 3x3. But I get this error: > >     Dot::dotsh: "Tensors {{1},{2},{3}} and {1,2,3} have incompatible shapes. > " >   But then if I do `j.i` I get `{14}` which is correct. Also, I've noticed sometimes with more complex matrices `i` and `j`, that if I set `k=i.j`, no calculation will be done, and the output will just show the two matrices in juxtaposition. But if I just do `i.j` (without the `"k="` part), a calculated output is shown. Does anyone know what the heck I'm doing wrong? This is driving me crazy!


title: How to open/close all collapsed/open cells?

text: Is there a way to open/close all collapsed/open cells? The reason is for a long notebook, it is convenient to see all the section and subsection headings at once.


title: how to filter out numbers of specific type in a table

text: I am working with a way to generate a table of some numbers, but the one functions could return the complex numbers which I don't want. I am going to filter out the complex numbers. The only way I can think of is to use a loop to copy the desired numbers from one list to another               fun1[{a_, b_, c_}] := {a, a*b + c, c};     fun2[a_, b_] := Sqrt[a - a/b];     pval = Table[{2, fun2[3, i], i}, {i, -0.5, 1.5, 0.15}];          pval2 = {};     For[k = 1, k <= Length[pval], k++,        If[SameQ[Head[pval[[k, 2]]], Complex] == False,           pval2 = Insert[pval2, pval[[k]], Length[pval2] + 1]]]     pval = fun1 /@ pval2      In this code, fun2 might return real or complex number. pval is a table with each elements a list of 3 numbers, the second number of each table element is returned by fun2. I don't want to keep any elements contains complex numbers. Above code is just an example. In the practical case, the functional form of fun1 and fun2 will be more complicated.


title: Extract table from image

text: I have the image of a matrix (download it to see it bigger): ![a matrix](http://i.stack.imgur.com/NQr6I.png) Is there a way to convert this into a Mathematica numerical matrix, using Mathematica?


title: How to transform an expression using algebraical instead of pattern rules

text: I would like to transform rules algebraically. A very simple example would be: -               k^2 - 2 k x + x^2 /. {2*k -> 1}      This transforms to: - $$k^2-2 k x+x^2$$ However, I would like it to return something more like: - $$\frac{1}{4}- x+x^2$$ In fact, I am more interested in solving quadratic, cubic and quartic polynomials. For example, I am able to set the discriminant of a quadratic to zero as a rule since the solution of a quadratic is already in an expanded form: -               quadratic = a*x^2 + b*x + c     Solve[quadratic == 0, x]  /. { Discriminant[quadratic, x] -> 0 }      This yields the correct results: - $$\left\{\left\{x\to -\frac{b}{2 a}\right\},\left\{x\to -\frac{b}{2 a}\right\}\right\}$$ To achieve something similar for the cubic one must expand the solution while also transforming the discriminant.               cubic := a*x^3 + b*x^2 + c*x + d;     ExpandAll[Solve[cubic == 0 , x]] /. { Expand[-27*a^2*Discriminant[cubic, x]] -> 0 }      This process requires some forward thinking and doesn't easily apply to a quartic. I am hoping Mathematica has some built in transformation rules for substituting expressions algebraically (obviously assuming certain criteria, i.e field/ring etc..) Does anyone have any suggestions?


title: Replacing composite variables by a single variable

text: To replace a single variable by another variable, one can simply use the the replace all (`/.`) operator (e.g., `x/(y*z) /. x -> w` returns $\displaystyle \frac{w}{yz}$). How does one replace an expression consisting of multiple variables? Trying to replace the denominator in the previous expression by a single variable fails with the following syntax:               x/(y*z) /. y*z -> w     x/(y*z) /. y*z :> w     x/(y*z) /. (y*z) -> w     x/(y*z) /. (y*z) :> w     x/(y*z) /. Times[y, z] -> w     x/(y*z) /. Times[y, z] :> w      **Edit:** By applying `FullForm`, I see that the variable substitution can be made by the following lengthy expression:               x/(y*z) /. Times[Power[y, -1], Power[z, -1]] -> w^-1      However, this now fails in a case such as the following:               (x + Log[y*z])/(y*z) /. Times[Power[y, -1], Power[z, -1]] -> w^-1      Now one must use something like the following (which does not work).               (x + Log[y*z])/(y*z) /. {Times[Power[y, -1], Power[z, -1]] -> w^-1, Times[y, z] -> w}      Is there a more general way to replace variables with delving into the full form representation?


title: Export matrix to $\LaTeX$ with style

text: Is it possible to export a matrix to $\LaTeX$ with style? For example this code will create a matrix with equal spacing matrix and with background colors in some cell, is it possible to export that to $\LaTeX$ ?               tb = Table[RandomInteger[{0, 10}], {10}, {10}];     Grid[tb, Dividers -> {{{{True, False}}, {-1 -> False,           1 -> False}}, {{{True, False}}, {-1 -> False, 1 -> False}}},       ItemSize -> {4.5, 4}, Spacings -> {0, 0},       Background -> {Automatic, Automatic,         Flatten@{Table[{{2 i + 1, 2 i + 2}, {2 i + 1, 2 i + 2}} ->             Green, {i, 0, 4}],           Table[{{2 i + 1, 2 i + 2}, {2 i - 1, 2 i}} -> Pink, {i, 1, 4}],           Table[{{2 i - 1, 2 i}, {2 i + 1, 2 i + 2}} -> Pink, {i, 1, 4}]}}]       ![enter image description here](http://i.stack.imgur.com/EMIq0.jpg) I tried to copy as $\LaTeX$ and `Export["~/1.tex",%]`, both only give the matrix content without any formattings.


title: Plotting reordered clusters with different colors and joined lines

text: I would like to show how typical days of energy load (found through clustering of a years worth of data) are spread throughout a year in a single graph with a color for each 'typical day' (or cluster). **What I have so far** _Please excuse the probably sloppy coding as I am still getting used to Mathematica's way of thinking (previous R user and some python knowledge)_ Here is the data in pastebin I divided the daily load curves (365 * 24 measurements) into clusters :               loadclust =  FindClusters[load, num]      each list within a cluster represents a daily load curve within a year and each cluster doesn't contain the same amount of days. To these daily loads (lists) I then joined a list which corresponds to the hours in a year (i.e. 1 to 24 for first day, 25 to 48 for second, etc...). I did this by finding the position of each daily list in the original ordered list, since I wanted to keep the different clusters in order.               clustyearh = Flatten[Table[     Table[       Join[       Range[(Flatten[Position[load, loadclust[[j, i]], 1 ]] - 1)*24 +          1, Flatten[Position[load, loadclust[[j, i]], 1 ]]*24]       , {loadclust[[j, i]]}       ], {i, Length [loadclust[[j]]]}      ], {j, Length[loadclust]}     ], 1];      Then I made pairs of the hour in the year and the load at that hour, while still maintaining the order of the clusters (so there are fours lists containing the paired coordinates for each cluster).               pairs = Table[      Transpose[      Join[{Flatten[         Transpose[           clustyearh[[;; Length[loadclust[[i]]]]]][[1]]]}, {Flatten[         Transpose[clustyearh[[;; Length[loadclust[[i]]]]]][[2]]]}]]     , {i, 4}];      giving a list of four lists of pairs `{{{1, 1368}, ...{24, 1428}, {121, 1321}, ...}{clust2}{..}{..}}` **Plotting** This is where I am having problems. First, when I used `Listplot` for `pairs`, it doesn't display all the points (I notice that it's the blue and red clusters especially missing). Second, when I include `Joined -> True` it joins the consecutive days in each cluster, but not in the year. If cluster one has days 1, 2, 5, 59 for example it will join those days. **Question** Is there a way to color each cluster within a line graph for the whole year. As an addition, I would love to be able to apply `Manipulate` to scroll through the year within a week or 2 week window. **Using Simon Wood's solution :** Create a list of indexes for the clustered days.               loadclust = FindClusters[load -> Range[365], 4];      Then make pairs of data to give as coordinates to a ListPlot, while adding data for a 25th hour for each day (i.e. the first hour of the next day) so the plot will be joined at all points :               With[{load2 = Append[load, {{0}}]},       pairs = Map[         Sequence @@            Thread[{24 (# - 1) + Range[25],              Append[load2[[#]], load2[[# + 1, 1]]]}] &, loadclust, {2}]];      Create a manipulate graph to view the graph inside of a window (I have added the colors I originally used for each cluster).               Manipulate[      ListLinePlot[pairs, Frame -> True, Axes -> False,         PlotRange -> {{n, n + win - 1}, All},         PlotStyle -> {Blue, Orange, Red, Green}] /.         Line[pts_] :> Line[Split[pts, #2[[1]] - #1[[1]] == 1 &]], {{n, 1,         "First Hour"}, 1, 24*365 - win, 1}, {{win, 168, "Window Length"},2, 336, 1}]      ![manipulate plot](http://i.stack.imgur.com/DBwQL.png) Big thanks to Simon! Cheers, E


title: Sorting Matrix elements

text: I have matrix `in` as shown, consisting of real numbers and 0. How can I sort it to become `out` as shown?               in ={        {0, 0, 3.411, 0, 1.343},        {0, 0, 4.655, 2.555, 3.676},        {0, 3.888, 0, 3.867, 1.666}        };     out ={        {1.343, 3.411, 0, 0, 0},        {2.555, 3.676, 4.655, 0, 0},        {1.666, 3.867, 3.888, 0, 0}        };      This is related to a question I asked. It is much easier to add the columns by sorting it this way than in previous question, and easier to visualize than trying to take the first non-zero value in a row.


title: Finding the argument set for internal functions in Mathematica v9.0

text: I've recently run into a problem with importing TIF stacks in Mathematica: Slow import of multigigabyte TIF image stacks On the advice of Simon Woods and others, I've been looking into the behavior for functions internal to Import, specifically:               Image`ImportExportDump`ImageReadTiledTIFF[]      Image`ImportExportDump`ImageReadTileTIFF[]      However, I can't seem to find the correct argument set to provide to these functions, and thus, I have no way of seeing how they behave. Just the fact that these functions can be found using ?*` _TIFF_ surprised me (note: you need to add a pair of asterisks, *, around "TIFF" because here, they're being treating it as a formatting instruction and not appearing in the post). Is there any way for me to elucidate the array of arguments that needs to be passed to either function?


title: Self-referential list or table of buttons

text: How could one create a table or list of buttons, such that clicking on a button removes the button itself from the list?


title: How to clear just variables defined in one notebook?

text: I'm trying to set up some notebooks so that I have one "seed" notebook that defines all my values globally when I run it. I have three other notebooks that take these values and run with them to do what they do. Problem is, these notebooks solve for functions and define them locally. I can't re-run these notebooks without running the seed book every time since Solve sees functions that are already defined. Is there a way to clear JUST the variables I have defined in a notebook? Edit: forgot to mention the seed notebook does a `ClearAll["Global``*"]` at the beginning.


title: Errors when plotting Exp[-x]/x for large values of x

text: I am trying to plot a very simple function `f[x_]:=Exp[-x]/x` on a log-log scale like this               LogLogPlot[f[x], {x, 10^(-5), 10^7}]      ![Mathematica graphics](http://i.stack.imgur.com/TmZMH.png) The problem is that for large values of x the plot suddenly jumps to 1 instead of going to zero as it should. I have tried to tabulate the values and increase working precision but it doesn't go away. The problem does not appear if I use               LogLogPlot[Exp[-x]/x, {x, 10^(-5), 10^7}]      ![Mathematica graphics](http://i.stack.imgur.com/9whT3.png) Anyone can explain me what is happening?


title: Symbolic tensor simplifications and the identity matrix

text: How can I get _Mathematica_ to simplify the following expressions, with `$Assumptions` including `Element[n,Integers], n > 0`, and `Element[n, Vectors[Reals]]`:               IdentityMatrix[n].IdentityMatrix[n]          IdentityMatrix[n].x      Neither `TensorReduce` nor `FullSimplify` simplifies the above expressions. Context for this question: I am frequently implementing new Bayesian statistical models that automated tools such as OpenBUGS can't handle, and so I need to work out expressions for various full conditional probability densities from the (large and complex) joint probability distribution. These expressions need to be simplified as much as possible, for computational efficiency. I want to see if I can use Mathematica to do this more quickly and reliably, instead of always doing it by hand. One of my needs is to be able to manipulate and/or simplify various linear algebra expressions that often arise; the dimensionality of these matrices and vectors is itself a parameter of the problem, not a fixed number.


title: Select sublists with second element nearest to zero

text: I've got some big lists from which i need some data (one of the big lists). To be specific, I need to divide this biglists in sublists of the same length (10000), and form a new list with the mean of the fourth column of each sublist, and the element of the third column whose correspongin pair of the second column is closest to zero. That sounds a little weird, but since i can't explain it any other way, here's an example: Suppose i have a list which i divide into sublists that look like this `sublist={{1,2,3,4},{1,.2,17,4.02},{1,.22,14,4.16}}` Then what i need too get from each sublist is `newlist={4.06,17}` (Mean[{4.02, 4, 4.16}]=4.06) EDIT With @David Carraher 's solution, plus @Mr.Wizard 's suggestion (and the use of ReadList):               SetDirectory@NotebookDirectory[];     timetotal := 60;srate := 10000;     T[R_] := R/.381 - (3.81*10^-3)^-1;     rules := {         {x_, y_, z_, w_} -> {x, y, z, T[w/.0016]}          };     strm = OpenRead["data6.txt"];     Skip[strm, Record, 3, NullRecords -> False];     meas = ReadList[strm, Real, RecordLists -> True] /. rules;     lst = Partition[meas, srate];     Table[          {Mean@lst[[i]][[All, 4]],           lst[[i]][[First@Ordering[Abs@lst[[i]][[All, 2]], 1], 3]]},           {i, timetotal}];      This code executes in 8.0484603 seconds, which is a bit more than 10 seconds faster than before. Thanks people!


title: Custom (Frame)Ticks fail when using Mathematica's script engine

text: I want to define my own ticks in a `DateListPlot`. It works quite well when I use the code in a _Mathematica_ Notebook but breaks somehow when using it via _Mathematica_ 's script engine. First of all the code:               Clear[fticks,plot];     fticks[min_, max_] :=        Module[{nTicks = 9}, Table[{min + i (max - min)/nTicks,          DateString[           DateList[min + i (max - min)/nTicks], {"Month", ".", "Year"}]          }, {i, 1, nTicks - 1}]];     plot = DateListPlot[       FinancialData["IBM", "Jan. 1, 2004"],       FrameTicks -> {fticks, Automatic, None, None}       ]     Export[FileNameJoin[{$HomeDirectory, "test-plot.png"}], plot];      In my `fticks` function I generate some ticks depending on the `min`and `max`values of the `DateListPlot`. This can't be completely wrong since the result works quite well. ![Ticks are working when computed in a Mathematica Notebook file](http://i.stack.imgur.com/vzUeI.png) But as soon as I try to calculate it via the _Mathematica_ script engine, the custom ticks fail. (I've saved the code above in a file located at `~/test.m` as _Mathematica_ uses `*.m` files for its scripting engine).               /Applications/Mathematica.app/Contents/MacOS/MathKernel -script ~/test.m       The result comes without any ticks but a red overlay because of an error. The question is now why is it not working? Interesting is also that while editing the `test.m` file there is also the possibility to run the package. I don't know why but this also works. ![Ticks are not working when computed via the Mathematica script engine](http://i.stack.imgur.com/3t0h3.png) I work in _Mathematica_ 9.0.1.0 running on Mac OS X 10.8. This error also occurs in _Mathematica_ 8 as I've tested. Thanks in advance for your help.


title: Defining an Implies operation that works for Boolean matrices

text: I have two Boolean matrices, that both have dimensions m x n. I want to create a function `TableImplies`, which would return `True` if one matrix piecewise implies the other; in other words, given matrices `A = (a_ij)` and `B = (b_ij)`, then               TableImplies[A, B] = true if for all i and j, a_ij => b_ij.      For example:               truePattern = Table[True, {2}, {3}]      > {{True, True, True}, {True, True, True}}               falsePattern = Table[False, {2}, {3}]      > {{False, False, False}, {False, False, False}}               TableImplies[falsePattern, truePattern]      > True               TableImplies[truePattern, falsePattern]      > False               randomPattern = Table[RandomInteger[] == 1, {2}, {3}]      > {{True, True, False}, {True, True, False}}               TableImplies[randomPattern, randomPattern]      > True What I got so far:               ElementWiseImplies[x_, y_] = Implies[x, y]          SetAttributes[ElementWiseImplies, Listable]          ElementWiseImplies[RandomPattern, RandomPattern]      > {{True, True, True}, {True, True, True}} Now this is all good. Next:               Apply[And, %, {0, 2}]      > True That seems to work. But if I do like this:               TableImplies[x_, y_] = Apply[And, ElementWiseImplies[x, y], {0, 2}]      > x && y the result is not what I wish. I understand, why this is happening: _Mathematica_ applies `And` not to the result of `ElementWiseImplies`, but to the expression `ElementWiseImplies[x, y]` itself, so the result becomes `And[x, y]`, which is not what I expected. What should I do? Use local variable `x = ElementWiseImplies[x, y]`; and then `Apply[And, x, {0, 2}]`? Or is there more elegant solution?


title: Isometric 3d Plot

text: I was wondering if its possible to make the following type of plot in Mathematica: I would like to take a 3D object, such as an ellipsoid, and cut out a wedge. I know this can be done using SphericalPlot3D and only plotting through an azimuthal angle phi. But here's the tricky part. Usually, whats left is a hollow shell, but I want to make it seem as if its a solid object with the inside colored according to some function. So what you would see when you cut out the wedge is a flat surface colored according to some function. If this is not possible with Mathematica, can anyone recommend a program where this may be done?


title: How to rewrite this function to be faster: Find sub-matrixes of boolean board which imply a given boolean pattern

text: I have Boolean matrix A (called "board") and Boolean matrix B with smaller dimensions (called "pattern"). I am trying to find sub-matrixes C of A such that C has same dimensions as B, and TableImplies[C, B]. Function TableImplies returns true if matrix A piecewise implies matrix B:               TableImplies[A,B]=true if for all i,j (a_ij => b_ij).      Example:               falsePattern = Table[False, {15}, {15}];     truePattern = Table[True, {15}, {15}];      Here TableImplies[falsePattern, truePattern] == True, but TableImplies[truePattern, falsePattern] == False. I have the following code, but it is not very fast:               tableImplies[a_, b_] := And @@ Flatten@MapThread[Implies, {a, b}, 2]          searchTable[pattern_, board_] :=       Reap[{sizex, sizey} = Dimensions[pattern];         Do[subBoard = board[[i ;; i + sizex - 1, j ;; j + sizey - 1]];          If[tableImplies [subBoard, pattern], Sow[{i, j}]],         {i, 1, 16 - sizex}, {j, 1, 16 - sizey}]][[2]]          board = Table[i != 16 - j , {i, 1, 15}, {j, 1, 15}];          kroneckerPattern = Table[i ==  j, {i, 1, 2}, {j, 1, 2}];          Timing[Do[searchTable[kroneckerPattern, board], {100}]][[1]]/100            (* 0.00873606 *)      How do improve speed of this calculation? How to improve coding style? **UPDATE:** Michael's answer seems to only search for specified sub-matrix inside the given matrix, instead of returning sub-matrixes, that piecewise imply given pattern. I added examples to the beginning of question to better explain what I wanted (see truePattern, falsePattern and how they should be related to each other when using TableImplies). I guess I should have been more clear from the beginning. This compares my algorithm(searchTable) to Michael's (Position[...]). They are clearly not equivalent:               searchTable[truePattern, falsePattern];     Out: {{{1, 1}}}     searchTable[falsePattern, truePattern]     Out: {}     Position[Partition[truePattern, Dimensions@falsePattern, 1], falsePattern]     Out: {}     Position[Partition[falsePattern, Dimensions@truePattern, 1], truePattern]     Out: {}      **Update 2** : I thought I should be more specific in formulating my question. Details matter. As I said before, I want to know, how should this algorithm could be made faster. It is important to mark that the board (containing matrix) will be always of constant size (15x15), but the pattern (searched sub-matrix) will be of varying dimensions, but always smaller than the board. This is relevant because for example in link provided by ssch, http://stackoverflow.com/questions/8364804/a-fast-implementation-in- mathematica-for-position2d, the matrixes are very large and the hard part is finding the position. In my case the number of possible positions is not very large (at most 225), but the slow part is to show whether the pattern matches the board or not. Maybe, if this whole problem could be re-written as boolean expression, that Mathematica could try to solve? Would this approach be faster? Another important note is that the pattern will very likely contain a lot of "True"s in my application. Could this be used to make the algorithm faster? For example, if the pattern contains only 1 False, then the problem is basically finding all instances of "False"s on the board. If the pattern contains more of "False", then the problem still boils down to Boolean expression, but not to an particularly easy one. PS: If my question is partly about algorithms and partly about programming Mathematica, is it correct of me to post this question here? Maybe I should just first ask some algorithms-related StackExchange Q&A for an algorithm and then ask here for how to program this algorithm effeciently in Mathematica? I just thought that maybe Mathematica's potential for symbolic evaluation could lead to algorithms not thinkable in functional programming languages, which is why I asked directly here :)


title: Importing several huge files with headers & footers

text: having here several files in ASCII format http://ge.tt/91rv0Jf/v/0 I want to import, while removing headers and footers and then join the several lists.               strm = OpenRead[".omf"]     Skip[strm, Record, 38, NullRecords  -> True];     mydata = ReadList[strm, Number, 7500*3, RecordLists -> True]     Close[strm];      This correctly removes headers and footers, so I don't know to combine this to a               alldata = Map[Import[ ], FileNames[]]      like command to import all files in the directory.               data = Import[#, "Table", HeaderLines -> 38, NumData ->  7500*3,      AllNumeric -> False, TrailerLines -> 2] & /@ FileNames[]      This works for importing all files, but the footers (or trailers?) are not removed, output:               {{ 755205.327 391367.272 126872.268},{ 638270.884 407054.202 408065.135},{ 621838.43 593464.262 -26779.3974},{ 792199.887 301929.715 -144422.249},{ 827047.904 221093.933 -81909.9342},<<7493>>,{ 638270.884 407054.202 408065.135},     { 755205.327 391367.272 126872.268},{# End: Data Text},{# End: Segment}}      HeaderLines isn't even mentioned in the Math7.0 Doc. In principle I only need the 3 column in every single .omf file               column3 = mydata[[All, 3]];      and those columns from every single file should than be arranged to a columnlenght X filenumber matrix list. Is it possible to apply this already when doing _Import_ or _OpenRead_ to save memory as this is just a example and the real files will be in the 2 digit GB range? Thanks for your tips


title: How to display only a certain part of the content in a Panel?

text: I have a `Panel` of size {850, 400} as `myPanel` with a `Pane` of size {450, 400} and four images assigned to `forwardPicture`, `backwardPicture`, `picture1` and `picture2`.               forwardPicture=      ![enter image description here](http://i.stack.imgur.com/HHkQ6.png)               backwardPicture=      ![enter image description here](http://i.stack.imgur.com/FtXrg.png)               picture1=      ![enter image description here](http://i.stack.imgur.com/KldtQ.jpg)               picture2=      ![enter image description here](http://i.stack.imgur.com/iPCyJ.jpg) Both `picture1` and `picture2` are of size {400, 400},               myPanel = Panel[Row[{picture1, picture2}], ImageSize -> {850, 400}];          Row[{       MouseAppearance[EventHandler[         Framed[backwardPicture,           FrameStyle -> None], {"MouseClicked" :> ""}], "LinkHand"],       Pane[myPanel, ImageSize -> {450, 400}, Scrollbars -> None],        MouseAppearance[EventHandler[         Framed[forwardPicture,           FrameStyle -> None], {"MouseClicked" :> ""}], "LinkHand"]       }]      After evaluation, I get this: ![enter image description here](http://i.stack.imgur.com/FnBk1.png) I want to move the images from right to left within the `Pane` whenever `forwardPicture` is pressed, and move them from left to right whenever `backwardPicture` is pressed. I don't want any scrollbars in the `Pane`. I don't want to move the images at one click: I want to move them a little bit for every click, until the full image is displayed. Can anybody help me?


title: Manipulate with a variable number of sliders

text: I have a function that operates on a **list of parameters of variable-length** $n$. I would like to create a `Manipulate[]` that has $n$ sliders, one for each list element, each considered a separate parameter. The syntax `Manipulate[expr,{u,...},{v,...},...]]` does not lend itself to this, as it is geared toward a **fixed number of parameters** known in advance, and referenced by separate variable names. I have started exploring preparing a list of arguments to `Manipulate[]` and then using `Apply[]`, but this seems tricky and complicated. _Anyone come upon this conundrum before?_


title: Edge problems in a directed graph

text: I want to create the following two graphs. ![Two Feed-Forward Loops](http://i.stack.imgur.com/01uHE.png) So far I tried the following Code               GraphPlot[{"X" -> "Y", "Y" -> "Z", "X" -> "Z"},       VertexCoordinateRules -> {"X" -> {0, 0}, "Y" -> {1, 0},         "Z" -> {2, 0}},       EdgeRenderingFunction -> (If[          Last[#2] == "Z", {Red, Arrow[#1]}, {GrayLevel[0.5],            Arrow[#1]}] &), VertexLabeling -> True, DirectedEdges -> True]      The Output was the following Graphic ![Try of an FFL](http://i.stack.imgur.com/8qOQC.png) My Questions are:   1. How do I get the arrow from X to Z as in the first Picture?   2. How can I add the wavy arrows for $S_X$ and $S_Y$?   3. How can I change the arrow head into an inhibitor sign as required for the Ic1-FFL?


title: Publishing results obtained in Mathematica

text: I've been using Mathematica to solve nonlinear partial differential equations for my doctoral research for the last 2 years or so. I am not an expert in Mathematica or mathematics and I am an engineer trying to express thermodynamic and fluid dynamic phenomena through math equations which subsequently need solving using numerical methods! I find that Mathematica is definitely the way to go and I am a big fan of the `NDSolve[...]` function. With that short background, here's my question: If I am to publish numerical results obtained in Mathematica, how should I go about it? I obviously validate my results against previously published data but here is the thing: say we have a non-linear PDE: `h_t + N[h[x,t]]=0` where `h=h[x,t]` and `N[h[x,t]]` is the nonlinear part. Most scientific publications would mention the method used to solve the equation (Eq: the BDF method, the Newton-Kantorovich method etc.) When I solve this in Mathematica in a _vanilla_ style without using any `Method` options in `NDSolve` thus allowing Mathematica to adapt and select it's own method, how do I cite the method? I haven't come across publications that do, so I ask... I do realize that there is the `Trace` option available that allows for the user to figure out what method was used but it isn't very intuitive! Any suggestions? Inputs?


title: Function to marginalize a table over given parameters

text: Let us say I have generated a table `tab` with entries `{p1,..,pd,chi2[p1,..,pd]}` of dimension `{ngrid[1],..,ngrid[d],d+1}` where `chi2` is a function of `d` parameters. More precisely, `tab` is generated using the following code:               tab = Table[     {p1, p2, p3, p4, p5} = {pTab[1][[i1]], pTab[2][[i2]], pTab[3][[i3]],pTab[4][[i4]], pTab[5][[i5]]};     {p1, p2, p3, p4, p5, chi2[p1, p2, p3, p4, p5]}     , {i1, 1, ngrid[1]}, {i2,1,ngrid[2]}, {i3,1,ngrid[3]}, {i4,1,ngrid[4]}, {i5,1,ngrid[5]}]      where `pTab[i]` are the tables giving the `pi` parameters. Now, I want to marginalize the table over some parameters. More precisely I want to marginalize the corresponding likelihood ($\exp(-\chi^2/2)$). This can be done over all parameters but `p2` in the following way:               newtab = tab[[1, All, 1, 1, 1, {2, 6}]];     Do[     newtab[[j,2]]=-2Log[Total[Exp[-tab[[All,j,All,All,All,6]]/2],4]];     ,{j, 1,ngrid[2]}];      If one wants to marginalize over all parameters but `p1` and `p3`:               newtab = tab[[All, 1, All, 1, 1, {1, 3, 6}]]     Do[     newtab[[j, k, 3]] = -2Log[Total[Exp[-tab[[j,All,k,All,All,6]]/2],4]];     ,{j, 1, ngrid[1]}, {k, 1, ngrid[3]}];      and so on. It would be great to have a function that can do the tasks above and which works for any number `d` of parameters and which can accept any combination of parameters to marginalize over. Something like `marginalize[{p2,p4,p5},tab]` where `tab` is my table and `{p2,p4,p5}` are the parameters to marginalize over. Do you know how to code such a function?


title: How to save all data in all variables so that loading it is fast?

text: I've got this CSV file I've imported that has tens of millions of lines in it. It takes around 20 minutes to import. I've been working with it for a while and have the processed data spread out in a bunch of variables. Now Windows is bugging me that I need to restart the computer. I thought about gathering all the data up in a table and then export and import it, but that would be a lot of hassle and take ages. I also thought about just saving the notebook and re-evaluate it, but with this amount of data that will also take a long time. I wonder what is the best way to save all the data so that I can get it back after having restarted the computer? Something fast and with minimum of hassle would be great. PS. I have no idea how to tag this thing. There is apparently no big-data tag.


title: Calling a function an unspecified number of times

text: I would like to be able to call a function an unspecified number of times. That is, I would like the generalization of something like:                  Sample[yi_, yf_, yinc_, zi_, zf_, zinc_]:=               Table[{y, z}, {y, yi, yf, yinc}, {z, zi, zf, zinc}]      to $n$ variables, all with their own respective initial, finial and incremental values, and so I'd be calling on `Table` $n$ times. Is something like this even possible?


title: Why is  MainEvaluate being used when LinearSolve can be compiled?

text: According to this question `LinearSolve` can be Compiled. However, CompilePrint shows a MainEvaluate but no-warning is generated. It appears that LinearSolve is not compilable, given the MainEvaluate. But the lack of warning is surprising. Something more subtle is going on. Consider the following.               In[1]:= SetSystemOptions[       "CompileOptions" -> "CompileReportExternal" -> True];          In[2]:= << CompiledFunctionTools`          In[3]:= v2 = Compile[{{m, _Real, 2}, {v, _Real, 1}},       LinearSolve[m, v]       ];               In[4]:= CompilePrint[v2]          Out[4]= "             2 arguments             3 Tensor registers             Underflow checking off             Overflow checking off             Integer overflow checking on             RuntimeAttributes -> {}                  T(R2)0 = A1             T(R1)1 = A2             Result = T(R1)2          1   T(R1)2 = MainEvaluate[ Hold[LinearSolve][ T(R2)0, T(R1)1]]     2   Return     "      There are no warnings generated, but I am not sure why there is a `MainEvaluate` in the `CompilePrint`. There is a much clearer warning that Compiling fails when one uses Options within `LinearSolve` while attempting to compile. Consider the following:               In[5]:= v3 = Compile[{{m, _Real, 2}, {v, _Real, 1}},       LinearSolve[m, v, Method -> "Cholesky"]       ]          During evaluation of In[5]:= Compile::extscalar: Method->Cholesky cannot      be compiled and will be evaluated externally.      The result is assumed to be of type Integer. >>          During evaluation of In[5]:= Compile::exttensor: LinearSolve[m,v,Method->Cholesky]     cannot be compiled and will be evaluated externally.      The result is assumed to be a rank 2 tensor of type Real. >>      Also, CompilePrint gives the following:               In[6]:= CompilePrint[v3]          Out[6]= "             2 arguments             1 Integer register             3 Tensor registers             Underflow checking off             Overflow checking off             Integer overflow checking on             RuntimeAttributes -> {}                  T(R2)0 = A1             T(R1)1 = A2             Result = T(R2)2          1   T(R2)2 = MainEvaluate[ Function[{m, v}, LinearSolve[m, v,                      Method -> Cholesky]][ T(R2)0, T(R1)1]]     2   Return     "      Questions: If `LinearSolve` can't be compiled, why is there no warning in the default case? Is there something more subtle going on (e.g. some parts of the process _are_ compiled)? If yes, how can one use the `Method` option within the `Compiled` function to ensure that what can be compiled actually is?


title: Does an equivalent of marks in vim exist for navigating notebooks quickly?

text: Is it possible in the Mathematica front-end to associate a keyboard shortcut with a cursor location in the notebook (kind of like marks in vim) so that one can return to them quickly later? (Just wondering if this functionality exists in some easy-to-use form already or if it would be necessary to build something from scratch using presumably the front-end tokens.)


title: How can I deploy DLL files created by a Fortran function and call them from Mathematica

text: This is my Fortran function, established by Intel visual Fortran 11.1               FUNCTION MYADD(X,Y)      !DEC$ ATTRIBUTES DLLEXPORT::MYADD      REAL(8) X,Y,MYADD      MYADD=X+Y     end FUNCTION      A corresponding `.dll` file is created,`MDLL.dll` (64bit version) and I put this file in the `$Path` directory. In a Mathematica notebook, I input:               Needs["NETLink`"]     fun=DefineDLLFunction["MYADD", "MDLL.dll", "double", {"double", "double"}]     fun[1.0,2.0]      But it gives me an error:                NET::netexcptn: A .NET exception occurred: System.DllNotFoundException:           unable to load DLL"MDLL.dll": can not find corresponding module           (error form HRESULT:0x8007007E).          in Wolfram.NETLink.DynamicDLLNamespace.DLLWrapper1.MYADD(Double , Double).


title: How to record the stream of data (PixelPosition) dynamically?

text: I need to trace the moving of an object and get the coordinates of such movement. The set of coordinates will be used for the subsequent evaluation and analysis. I can easy get the current real-time coordinates by use of the following expression:               Dynamic[ImageKeypoints[EdgeDetect[CurrentImage[], 30], "PixelPosition"]]      But I need to record all these coordinates in the list in the separate cell or in separate file. I need that this list contains an cumulative set of all coordinates, frame by frame. Please, suggest how to resolve this issue.


title: Creating randomly oriented planes

text: I would like to create randomly oriented planes. This is how I'm attempting to do that:   1. I create a 2 random unit vectors, $\mathbf{v}_1$, and $\mathbf{v}_2$, in the $x$-$y$ plane   2. I assume that if I rotate these two vectors around a random vector (in $x$-$y$-$z$) called $\mathbf n$, the plane on which the two vectors lie is random and uniformly distributed over the sphere.    3. So I randomly pick $\mathbf n$, keeping in mind the issues of random point picking on spheres.   4. I then use `RotationMatrix[α, n].v1` (and same for `v2`) to get the new vectors on the rotated and supposedly random plane. There is some question on what to choose for the angle $\alpha$ which gives the angle of the rotation.      * If I choose $\alpha<\pi/2$, the vectors do not encompass the entire sphere.      * If I choose $\alpha=\pi/2$, I get a bunching of vectors at the poles.      * If I choose $\alpha>\pi/2$, there is bunching at various latitudes. I cannot get a uniformly random distribution over the sphere! Is there a fix to the current method I am implementing? Is there another way to do it? * * * My real goal here isn't creating random planes. My goal is to take two vectors with some arbitrary magnitude and direction in $x$-$y$ and then randomly orient them over the sphere while maintaining their relative positions with respect to one another. The steps I have taken above seem like the logical way to do that.


title: How to figure out whether a nonlinear inequality holds or not

text: I have an inequality consisted only of seven parameters as follows: $(1 + g)^{-(m+w)}\big[\big\{a+(1-a)(1 + g)^m\big\}(1 + p q)Q - (1 + g)^w \big\{(1 + g)^m (1 + q)-(1-p)q\big\} Q\big] < 0$ Parameters, $g$, $w$, and $m$, are subject to the following restrictions: $0<g$, $0<w$, $0<m$, $0<Q$ That is, these four parameters are all positive. Now, we can manually verify that this inequality holds under the above parameter restrictions. And I would like to confirm this with Mathematica. My codes for the assumptions:               $Assumptions = 0 < g && 0 < w && 0 < m && 0 < Q      And as for checking if the inequality holds, I used `Refine` and `If` as follows:               Refine[If[(1 + g)^(-m - w) ((a - (-1 + a) (1 + g)^m) (1 + p q) Q - (1 + g)^w ((-1 + p) q + (1 + g)^m (1 + q)) Q)<0, Print[True], Print[False]]]      Since the condition is true, the result I expect is `True`. But what I get is a simple repetition of the `If` bracket:               If[(1 + g)^(-m - w) ((a - (-1 + a) (1 + g)^m) (1 + p q) Q - (1 + g)^w ((-1 + p) q + (1 + g)^m (1 + q)) Q) < 0, Print[Yes], Print[No]]      When I use a little simpler, but similar, type of inequality, it gives me either `True` or `False` depending on the specific form of inequality I use. But it seems Mathematica is not able to figure out whether the above inequality, which is too complex (maybe?), is true or false. Or am I missing something? Can anyone help? Thank you so much.


title: Is there a change in V10 with Solve and exponents?

text: I've encountered a strange problem with V10. I can't quite nail it down, but the `Solve` seems to be unable to solve equations that it could in previous versions. Here is one I'm almost positive I've done before.               Solve[q == l^a ((l w b)/(r a))^b, l]      For those who are wondering this is one of the steps in solving for a cost function using a Cobb–Douglas production function. It can obviously be solved, all _Mathematica_ has to do is group the exponents. Is there a change in the solve assumptions, options? I've also tried being explicit about reals and allowing inverse functions.


title: Inverse function

text: What probably could be the inverse of following function?               y = (x^(1/t)-a^(1/t))*(x^(1/t)-c*b^(1/t))/(x^(1/t)-a^(1/t))*(x^(1/t)-c*b^(1/t))+           (x^(1/t)-   b^(1/t))*x^(1/t)-c*a^(1/t)      a,b,c & t are the parameters. Any help is going to be highly appreciated.


title: Q-Function representation in Mathematica

text: I observed that there is no Q-function representation in Mathematica. The definition of Q-Function is: \begin{align} Q(x) &= \frac{1}{\sqrt{2\pi}} \int_x^\infty e^{-\frac{u^2}{2}}du \\ &=\frac{1}{2} \mathrm{erfc}(\frac{x}{\sqrt{2}}) \end{align} a nother representation of Q-function is: \begin{align} Q(x) = \frac{1}{\pi} \int_0^{\frac{\pi}{2}} e^{\left(\frac{-x^2}{2\sin^2{\phi}} \right)}d\phi \end{align} there is only Complementary Error Function representation Erfc. $\mathrm{erfc}(x) = \frac{2}{\sqrt{\pi}} \int_{x}^{\infty} \exp(-t^2) dt$ Is there any possiblity that define a new function in _Mathematica_? so that it will be a permanent function. Note: In statistics, the Q-function is the tail probability of the standard normal distribution. In other words, Q(x) is the probability that a normal (Gaussian) random variable will obtain a value larger than x standard deviations above the mean.


title: More general pattern fails to match everything the more specific pattern does.

text: When I input this:               MatchQ[x*SF[a,b] + y*SF[c,d], Plus[Times[x,SF[a,b]],Times[y,SF[c,d]]]]       I get "True" as expected. But If I change it to:               MatchQ[x*SF[a,b] + y*SF[c,d], Plus[Times[_,SF[_,_]],Times[_,SF[_,_]]]]       Which ought to be more general, it returns false. Why does this happen? I think it's evaluate the Plus, and return a pattern like Times[2, _,SF[_ ,_]]. But how do I make it stop doing that? My goal is to Match the pattern for expressions like x*SF[a,b] + y*SF[c,d] + z*SF[e,f] ... So what do I have to do to fix this?