Death of parallel sub-kernels

EDIT : Finally, the new Mathematica 10.0 seems to fix it. I have a little parallelization problem. I wrote a code to generate a quasicrystal by dynamical generation. Here the code:               (*===================================================================================*)         time1 = DateList[] ;         Print[time1];     (*Constants*)     (*===================================*)     ITERMAX = 9; (* Maximum = 9 *)     (*===================================*)     MIN ={0.9999999999999999`, 0.6180339887498947`, 0.3819660112501049`,      0.38196601125010465`, 0.23606797749978875`, 0.23606797749978836`,         0.23606797749978836`, 0.14589803375031407`, 0.14589803375031385`}[[       ITERMAX]];     MAX = {1.`, 0.618033988749895`, 0.38196601125010554`,          0.38196601125010576`, 0.23606797749979036`, 0.2360679774997906`,          0.23606797749979072`, 0.1458980337503173`, 0.1458980337503173`}[[ITERMAX]];      Clear[x, xx, zz]     x = 0;     sig := Exp[2*Pi*I/5];     tau := N[GoldenRatio];     CiT := 2*tau^4;          (*Functions*)     complexSplit := Function[z, {Re@z, Im@z}, Listable];     dP[w_, z_] := 1/2*(w*z\[Conjugate] + w\[Conjugate]*z);     zGen[x_] :=       Module[        {         zPlus = Table[x + Exp[2*Pi*I*j/5], {j, 0, 4, 1}],         zMinus = Table[x - Exp[2*Pi*I*j/5], {j, 0, 4, 1}]         },        Return[Join[zPlus, zMinus]]        ];      fctTest[seed_] :=        1/11*(1 + Sum[Exp[2*Pi*dP[dP[I, sig^i], dP[CiT, seed]]], {i, 4}] +           Sum[Exp[-2*Pi*dP[dP[I, sig^i], dP[CiT, seed]]], {i, 4}]);     zTest[x_] :=       If[Re[fctTest[x]] >= 0.38232,        x]; (*Real part for the computation error*)          Generator[x_] := Generator[x] = zTest /@ zGen[x];          (*Point generation*)     zz[0] := {x};     For[i = 0, i < ITERMAX, i++,       zz[i + 1] = DeleteDuplicates[Flatten[ParallelMap[Generator, zz[i]]]];       ];     z = DeleteDuplicates[Flatten[Table[zz[k], {k, 0, ITERMAX}], 1]];          (*Line generation*)     Lz = Length[z];     zCart = ParallelTable[{N[Re[z[[i]]]], N[Im[z[[i]]]]}, {i, 1, Lz}];     zline = Cases[Flatten[ParallelTable[          Table[           If[zCart[[i]] != zCart[[j]] &&              MIN <= EuclideanDistance[zCart[[i]], zCart[[j]]] <=               MAX, {zCart[[i]], zCart[[j]]}, 0]           , {j, i, Lz}],          {i, 1, Lz}], 1],        Except[0]];          (*PLOT*)     quasicrystal =        Graphics[{{PointSize[0.004], Red,           Point[complexSplit@z]}, {Thickness[0.00009], Line[zline]}},         ImageSize -> {2000, 2000}];         time2 = DateList[];         time3 = DateDifference[time1, time2, "Second"];         Show[quasicrystal]         Print[time2];         Print[time 3];     (*===================================================================================*)      So when I try to run my code for nine or more iterations, I have the following sequence of errors :               LinkObject::linkd: Unable to communicate with closed link LinkObject[/usr/local/Wolfram/Mathematica/9.0/Executables/math -subkernel -noinit -mathlink,250,9]. >>     KernelObject::rdead: Subkernel connected through KernelObject[6,local] appears dead. >>     Parallel`Developer`QueueRun::req: Requeueing evaluations {1162} assigned to KernelObject[6,local,<defunct>].     LaunchKernels::clone: Kernel KernelObject[6,local,<defunct>] resurrected as KernelObject[6,local]. >>     LinkObject::linkd: Unable to communicate with closed link LinkObject[/usr/local/Wolfram/Mathematica/9.0/Executables/math -subkernel -noinit -mathlink,249,8]. >>     KernelObject::rdead: Subkernel connected through KernelObject[5,local] appears dead. >>     Parallel`Developer`QueueRun::req: Requeueing evaluations {1163} assigned to KernelObject[5,local,<defunct>].     LaunchKernels::clone: Kernel KernelObject[5,local,<defunct>] resurrected as KernelObject[5,local]. >>     LinkObject::linkd: Unable to communicate with closed link LinkObject[/usr/local/Wolfram/Mathematica/9.0/Executables/math -subkernel -noinit -mathlink,251,10]. >>     General::stop: Further output of LinkObject::linkd will be suppressed during this calculation. >>     KernelObject::rdead: Subkernel connected through KernelObject[7,local] appears dead. >>     General::stop: Further output of KernelObject::rdead will be suppressed during this calculation. >>     Parallel`Developer`QueueRun::req: Requeueing evaluations {1161} assigned to KernelObject[7,local,<defunct>].     General::stop: Further output of Parallel`Developer`QueueRun::req will be suppressed during this calculation. >>     LaunchKernels::clone: Kernel KernelObject[7,local,<defunct>] resurrected as KernelObject[7,local]. >>     General::stop: Further output of LaunchKernels::clone will be suppressed during this calculation. >>      My PC can also crash and I don't understand the problem because I can run my code without problem on institutional version, but not on my computer with the student version. Not having any idea, I hope someone will have an idea.


JacobiCN inaccuracy

For my calculations I need `JacobiCN[s,k]` for `s` near 0 from the left and `k` near 1 from the left. The function $(s,k) \mapsto \mathrm{cn}(s,k)$ is smooth on $]{-1},0[ \times ]0,1[$, yet Mathematica 7 gives me very different plots for `k=0.999` and values of `k` above:               Plot[JacobiCN[s, 0.999], {s, -1, 0}]     Plot[JacobiCN[s, 0.9990001], {s, -1, 0}]      ![k=0.999](http://i.stack.imgur.com/Bjf67.png) ![k=0.9990001](http://i.stack.imgur.com/voEAV.png) WolframAlpha does not seem to have this problem. Is this a numerical artifact in Mathematica 7 that you can circumvent somehow, or do I have to reimplement $\mathrm{cn}$?


Resources on Mathematica and strong AI (a.k.a. AGI)

David Deutsch (physicist / quantum computing theorist) wrote an article for _Aeon Magazine_ last year: On Artificial Intelligence that got me thinking. The article assesses and critiques the achievements in AI and articulates criteria one needs to meet to realize strong AI or what he calls Artificial General Intelligence (AGI). Some key ideas from the article:   * _What is needed is nothing less than a breakthrough in philosophy, a new epistemological theory that explains how brains create explanatory knowledge and hence defines, in principle, without ever running them as programs, which algorithms possess that functionality and which do not._   * _...the ability to produce new explanations._   * _...brain in a vat_.    * _Because genuine knowledge, though by definition it does contain truth, almost always contains error as well._   * _...it is simply not true that knowledge comes from extrapolating repeated observations. Nor is it true that ‘the future is like the past’, in any sense that one could detect in advance without already knowing the explanation._ The article inspired a number of discussions among my colleagues. We see a thread of rather obscure work across the entire history of information theory that looks like it addresses many of Deutsch's concerns. We use this stuff in a variety of sequential decision problems. **Mathematica and AGI** So naturally the question came up: > _Can we model AGI in Mathematica?_ This is a broad question, however, so below the question will be narrowed down. But first, here are some reasons why I think _Mathematica_ may be suitable for this purpose. A lot of work in AGI gets programmed in Lisp and other homoiconic and/or functional languages. Homoiconic languages internally represent code and data in the same way. This could provide a program the capability to modify itself, perhaps even to evolve or adapt to a new problem. _Mathematica_ sees everything as an expression. It has the ability to generate functions. Wolfram Alpha certainly has some kind of AI calculation/search underpinning it, but I don't see it as attempting AGI. **The question is** : Can anyone direct me to: >   * _examples of Mathematica used in work on AGI_ ; >   * _individuals using Mathematica for work on AGI_ ; >   * _resources about using Mathematica for work on AGI_ ; > Also, if anyone has an interest in thinking through this in greater detail, just ping me (email in my profile) and I'll forward more background information on our ideas.


clean functional way to get first n rows that yield maximum rank

I have a matrix A and want the matrix consisting of the first n rows of A, having the same rank as A, where n is minimal. More generally, I want the shortest "start piece" of a list, such that some criterion on the start piece gives True. For the more general problem, I wrote myTake below, but I'm very dissatisfied with the procedural nature of my implementation.               myTake[list_, crit_] := Catch[         Do[With[{candidate = list[[Range[i]]]},              If[crit[candidate], Throw[candidate]]]         , {i, Length[list]}];      "fail"     ];     firstFullRank[matrix_] := With[{fullRank = MatrixRank[matrix]},          myTake[matrix, MatrixRank[#] == fullRank &]     ];     firstFullRank[{{1,0,0},{0,1,0},{2,3,0},{1,2,3},{9,8,7}}]          (gives {{1, 0, 0}, {0, 1, 0}, {2, 3, 0}, {1, 2, 3}})      In short, I'm looking for a **fast** and functional one liner implementation of myTake and/or firstFullRank **Edit** Please assume that the matrix has lots of rows (> 1000) and not many columns (<10), and that the result has significantly fewer rows than the full matrix. Is there a way to do this functionally without using Range[Length[matrix]] or (even worse) a table of all start pieces.


Failed to connect remote Mathematica kernel using J/Link

I'm trying to connect to a remote _Mathematica_ 8 kernel (on a Windows machine) using J/Link. On the client machine, I put the `JLinkNativeLibrary.dll` file in `C:\Documents and Settings\User\My Documents`. But, it gives me the error message "cannot find the required native library named `JLinkNativeLibrary`". Here is my code               public static void main(String[] args) {             KernelLink link;             try {                 String jLinkDir = "C:\\Documents and Settings\\User\\My Documents";                 System.setProperty("com.wolfram.jlink.libdir", jLinkDir);                             link = MathLinkFactory.createKernelLink("-linkmode connect -linkprotocol tcpip -linkname 8080@172.20.48.113");             } catch (MathLinkException ex) {                 ex.printStackTrace();             }         }      Exception : > Fatal error: cannot find the required native library named > JLinkNativeLibrary. Exception in thread "main" > java.lang.UnsatisfiedLinkError: > com.wolfram.jlink.NativeLink.MLOpenString(Ljava/lang/String;[Ljava/lang/String;)J > at com.wolfram.jlink.NativeLink.MLOpenString(Native Method) at > com.wolfram.jlink.NativeLink.(NativeLink.java:117) at > com.wolfram.jlink.MathLinkFactory.createMathLink0(MathLinkFactory.java:281) > at > com.wolfram.jlink.MathLinkFactory.createMathLink(MathLinkFactory.java:194) > at > com.wolfram.jlink.MathLinkFactory.createKernelLink0(MathLinkFactory.java:171) > at > com.wolfram.jlink.MathLinkFactory.createKernelLink(MathLinkFactory.java:65) > at mathematica.Sample.main(Sample.java:21) I also wrote the following code where `KernelLink` gets created but there is some problem with establishing the connection. It gives an error "MathLinkException: 1: MathLink connection was lost."               public static void main(String[] args) {             KernelLink ml = null;             try {                 ml = MathLinkFactory.createKernelLink("-linkmode connect -linkprotocol tcp -linkname 1234@172.20.48.113");             } catch (MathLinkException ex) {                 Logger.getLogger(MathematicaSample.class.getName()).log(Level.SEVERE, null, ex);                 return;             }             try {                 ml.connect(1000000); // Wait at most 10 seconds             } catch (MathLinkException e) {                 // If the timeout expires, a MathLinkException will be thrown.                 e.printStackTrace();                 ml.close();                 return; // Or whatever is appropriate.             }                 try {                 // Get rid of the initial InputNamePacket the kernel will send                 // when it is launched.                 ml.discardAnswer();                 ml.evaluate("<<MyPackage.m");                 ml.discardAnswer();                 ml.evaluate("2+2");                 ml.waitForAnswer();                 int result = ml.getInteger();                 System.out.println("2 + 2 = " + result);                         } catch (MathLinkException e) {                 System.out.println("MathLinkException occurred: " + e.getMessage());             } finally {                 ml.close();             }         }     }      Does anyone know how to connect to the kernel?


How can I log in to my Wikipedia account and access my watch list?

Wikipedia's "Edit Watchlist" page (for logged in users) has a list of hyperlinks to the user's watchlist (here is an example from my account). ![enter image description here](http://i.stack.imgur.com/7bYtZ.png) I've tried to use `URLFetch` and `URLSave` as follows               URLFetch["http://en.wikipedia.org/wiki/Special:EditWatchlist"]     URLSave["http://en.wikipedia.org/wiki/Special:EditWatchlist","test.html"]      but it seems that they cannot grab the links in the watchlist. I thought `URLSave` is the same as saving a webpage as a HTML file by hand in Internet Explorer... Am I wrong? Even `Import`, with               Import["http://en.wikipedia.org/wiki/Special:EditWatchlist","Hyperlinks"]      (and also with `"Source"`), cannot get the hyperlinks. How can I log into Wikipedia and get these links using _Mathematica_?


Using MatchQ (or other means) to parse an expression using sums of COS or SIN correctly

I am writing a function that will take an expression as input. I want to make sure the expression is valid first before processing it. Looking for a correct to use `MatchQ` (or if you have better method) to use which will return `True` or `False` when given the expression. ## Specifications The expression will have the following form               a1 Cos[x+b1] + a2 Cos[x+b2] + a3 Cos[x+b3] + ....      _OR_               a1 Sin[x+b1] + a2 Sin[x+b2] + a3 Sin[x+b3] + ....      So if you can parse one, then with some trick, can use the same parser with the other using `OR`. There can one or more terms there. Also, the amplitudes (the $a_i$) can be there or not there. Also, there is no need to check what is used for argument to the trig functions. So if expression is `Cos[Cos[x]]` then that is ok, only FIRST level needs to be validated. The expression will be passed by `TrigReduce[]` before. Your parser only needs to check for the above top level form. Hence the following are all valid expression and should return `True`               Sin[x]     a Sin[x]     a Sin[x] + Sin[x +b]     Sin[x] + Sin[x + b] + c Sin[x]      These are NOT valid:               Sin[x] + Cos[x]  (*mixed*)     a + Sin[x]  (*first term has no sin nor cos *)     Sin[x]+ b + Sin[x + v]       So the function needed will have this specification               parse[expr_]      and will return either `True` or `False`. What is the most efficient way to do this? ## Test suite To help you in making the parser, here are few expressions that should return `True` and another set that should return `False`               ClearAll[x, a1, b1, a2, b2, a3, b3];     trueTests = {       3 Cos[x],       a1 Cos[x + b1],       Cos[x] + a1 Cos[x + b1],       a1 Cos[x] + a1 Cos[x + b1] + a2 Cos[x + b2],       3 Sin[x],       a1 Sin[x + b1],       Sin[x] + a1 Sin[x + b1],       a1 Sin[x] + a1 Sin[x + b1] + a2 Sin[x + b2]       }          falseTests = {       a1,       a1 Cos[x + b1] + Sin[x],       Cos[x] + b1,       a1 Cos[x] + a1 Cos[x + b1] + a2 Sin[x + b2],       Cos[x] + Sin[x]       }


NestWhile application

I have the function which take the last list in nested list, reduce it somehow in several ways so the length of list reduces and output new list wherein input list appended with defferent reduced lists. Maybe my explanation a little bit illegible but here is an example code:               cov = {{0, 3, 1, 2}};     l = 2;     detach = Function[{cov, l},        s = Last[cov];        Table[Append[cov,           Delete[ReplacePart[s, i -> l + Total[s[[i ;; i + 1]]]],            i + 1]], {i, 1, Length[s] - 1}]        ];     detach[cov, l]          Output: {{{0, 3, 1, 2}, {5, 1, 2}}, {{0, 3, 1, 2}, {0, 6, 2}}, {{0, 3, 1, 2}, {0, 3, 5}}}      Now I need to apply recursively the same function to all lists of output list so for proposed example I shoud get the following result:               {{{0, 3, 1, 2}, {5, 1, 2}, {8, 2}, {12}},       {{0, 3, 1, 2}, {5, 1, 2}, {5, 5}, {12}},       {{0, 3, 1, 2}, {0, 6, 2}, {8, 2}, {12}},       {{0, 3, 1, 2}, {0, 6, 2}, {0, 10}, {12}},       {{0, 3, 1, 2}, {0, 3, 5}, {5, 5}, {12}},       {{0, 3, 1, 2}, {0, 3, 5}, {0, 10}, {12}}}      I tried to apply NestWhile or FixedPoint but did not succeed to get desired result.


Calculating error of the approximate formula in calculations

I have an exact equation: \begin{equation} a = \sqrt{1 + x^2 - \sqrt{(1 + x^2)^2 - 2 x^2 \cos^2\theta}}\tag{1} \end{equation} and its approximation: \begin{equation} a = \dfrac{x \cos^2\theta}{\sqrt{1 + x^2}}\tag{2} \end{equation} I'm doing most theoretical calculations using equation $(2)$ and to check the outcomes I'm doing numerical calculations of $(1)$ in Mathematica. For example, finding $\left.\frac{da}{dx}\right|_{x = 0}$ dividing by $\left.\frac{da}{d\theta}\right|_{\theta = 0}$ and integrating: \begin{equation} \int\limits_{0}^{A}\frac{\left.\frac{da}{dx}\right|_{\theta = 0}}{\left.\frac{da}{d\theta}\right|_{\theta = 0}}dx \end{equation} And I want to check that this (or any other) procedure doesn't differ much from the same for precise and approximate function. How can I verify that the use of the approximate formula doesn't make the calculations inaccurate?


Change the behaviour of a LocatorPane

Normally, `LocatorPane` detects any single click as in the following example:                   DynamicModule[{pt = {1, 1}/2},           {LocatorPane[Dynamic[pt], Graphics[{Gray, Disk[]}]], Dynamic[pt]}]      My goal is to redefine the behaviour of `LocatorPane` to detect only double clicks (i.e., the value of `pt` is returned only when the user double-clicks in the `LocatorPane`) I tried the following definition, but with no success!               doubleclickPane[pt_, back_, opts : OptionsPattern[]] :=        DynamicModule[{ptt = pt},         Deploy @ EventHandler[           LocatorPane[Dynamic@ptt, back, ,Evaluate[FilterRules[{opts}, Options[LocatorPane]]]],           {"MouseDown" :> (             ptt = MousePosition["Graphics"];              If[Mod[CurrentValue["MouseClickCount"], 2] == 0, pt = MousePosition["Graphics"]]           )}         ]       ]


Smoothing/Averaging 2D Vector Fields

I have a list of 2D vectors defined by `{{x,y},{u,v}}` and would like to smooth or average the vectors. For example here are 2 vector fields, the second has noise added to the orientation of each list item:               f = Sin[2 x + 2 y];     data = Flatten[Table[{{x, y}, {Cos[f], Sin[f]}}, {x, -1, 1, 0.1}, {y, -1, 1, 0.1}], 1];     noisydata = Flatten[ Table[         theRand = RandomReal[{-π/6, π/6}];         {{x, y}, {Cos[f + theRand], Sin[f + theRand]}}         , {x, -1, 1, 0.1}, {y, -1, 1, 0.1}], 1];     {ListVectorPlot[data], ListVectorPlot[noisydata]}     {ListStreamPlot[data], ListStreamPlot[noisydata]}      ![enter image description here](http://i.stack.imgur.com/Cj4Mh.png) Any suggestions about smoothing the field in _Mathematica_? I am trying to interpolate the data (creating an interpolating function using `Interpolation`), but the resulting vector fields are very noisy. Any help would be appreciated!


Tridiagonal symmetric matrix eigenvalue using bisection

I know that `Eigenvalues` is already quite well implemented in Mathematica, nor am I foolishly trying to improve on it. In order to improve my programming skills, I am trying to write Mathematica-style code to locate eigenvalues of a tridiagonal symmetric matrix using bisection. This is what I came up with.               tridiagbisec[diag_List, subdiag_List, tol_Real] :=       Module[{diagonals =           Split[Transpose[{diag, Join[{0}, subdiag]}], #2[[2]] =!= 0 &]},        Flatten[         bisecnonzero[-myNorm[Sequence @@ Transpose[#]],             myNorm[Sequence @@ Transpose[#]], tol, #] & /@ diagonals]] /;        Length[diag] - Length[subdiag] == 1      `tridiagbisec` is the main function I will be calling. It builds an array (`diagonals`) from the arrays containing the matrix elements of both the leading diagonal and the subdiagonal, then `Split`s it wherever a zero is found so that each block is evaluated separately, using `bisecnonzero`.               bisecnonzero[\[Lambda]min_Real, \[Lambda]max_Real, tol_Real, diagonals_List] :=       Module[{\[Lambda]med = (\[Lambda]min + \[Lambda]max)/2,         nmin = numeig[diagonals, \[Lambda]min],         nmax = numeig[diagonals, \[Lambda]max], nmed},       nmed = numeig[diagonals, \[Lambda]med];       {Which[(nmin > nmed) && (\[Lambda]med - \[Lambda]min > tol),          bisecnonzero[\[Lambda]min, \[Lambda]med, tol, diagonals],         (nmin > nmed) && (\[Lambda]med - \[Lambda]min <= tol),          ConstantArray[(\[Lambda]med + \[Lambda]min)/2, nmin - nmed],         True, {}],        Which[(nmed > nmax) && (\[Lambda]max - \[Lambda]med > tol),          bisecnonzero[\[Lambda]med, \[Lambda]max, tol, diagonals],         (nmed > nmax) && (\[Lambda]max - \[Lambda]med <= tol),          ConstantArray[(\[Lambda]max + \[Lambda]med)/2, nmed - nmax],         True, {}]}       ]      This, I believe, is where I may have built my program in a suboptimal way. Are two `Which` the right way to iterate bisection?               numeig[diagonals_, \[Lambda]_] :=        numeig[diagonals, \[Lambda]] =         Unitize[#].UnitStep[#] &@         Rest@FoldList[           If[Not@PossibleZeroQ@#1, #2[[               1]] - \[Lambda] - #2[[2]]^2/#1, +\[Infinity]] &, 1, diagonals];      `numeig` computes the number of eigenvalues greater than `\[Lambda]` (cfr. (5) in Barth, Martin and Wilkinson (1967).               myNorm = Max[Abs@#1 + Abs@#2 + RotateLeft@Abs@#2] &;      I know that I am also reimplementing `Norm[#,Infinity] &`, but for scholastic purposes I think it may be useful, since for a tridiagonal matrix it has a particularly simple form and this way I can avoid building a `SparseArray` structure at all. Since I am trying to be performance-conscious, how could the whole algorithm be improved upon with reasonable effort? ...Besides using `Eigenvalues`, that is! :D


Can I limit PlotRange for 1 function in a Plot?

I have a 2D Plot of 3 functions               Plot[ { f1[x], f2[x], f3[x] }, { x, 8, 18 } ]      where I want f3[x] only plotted for the range [10, 18] instead of [8, 18]. Is that possible?


Integral returns function of variable that was integrated over

When I enter               Integrate[1/Sqrt[(y1)^2 + (y2)^2 + (y3)^2]*1/(1 + (y3)^2)     * Exp[-2*((y1)^2 + (y2)^2)/(1 + (y3)^2)],      {y1, -\[Infinity], \[Infinity]}, {y2, -\[Infinity], \[Infinity]}, {y3, -10, 10}]      into Mathematica, I get the result               ConditionalExpression[(      E^((2 y3^2)/(1 + y3^2)) \[Pi]^(3/2) Sqrt[y3^2] (-1 + Sqrt[1/y3^2] y3       + Erfc[(Sqrt[2] y3)/Sqrt[1 + y3^2]]))/(Sqrt[2] y3 Sqrt[1 + y3^2]), Re[y3^2] > 0]      However, this is a function of y3, which can't possibly be right. Apparently when other people execute this, they get a different and more sensible result. Does anybody know what setting in Mathematica might be causing this? If it helps, I am using Mathematica 9 on Ubuntu 14.04.


remove quotes in a combination of a text with graphics in the JournalArticle Style

I have a puzzling and very specific question. It may be of limited interest to community. I apologize in advance in this case. Let us see. I am making an illustration to a text that I write in the StyleSheet _Journal Article_. Here is the code:               Column[{   Row[{Rotate[Text[Style["Name of y variable", 18, Bold]], \[Pi]/2], im}],     Row[{Spacer[50], Text[Style["Name of x variable", 18, Bold]]}]   }]      Here is an image with `ImageSize->200` copied from somewhere. For example this: ![enter image description here](http://i.stack.imgur.com/mevtv.png) It is fine, while I keep the result of the above code as an output. However, for the sake of numeration of images through the long document I transform the output cell style into the Figure cell style. Such a cell style does not exist in the default stylesheet, but one finds it in the document prepared with the help of the JournalArticle StyleSheet. My problem is that as soon as I transform the output into the Figure style, the texts "Name of y variable" and "Name of x variable" appear with explicit quotes. It is not unacceptable, but boring, since the unnecessary information is misleading to the reader. I would be grateful for a suggestion, if there is an easy way to remove the quotes.


How to change the base of logarithmic-scale plots?

Mathematica provides a score of convenient functions to make plots with various logarithmic scale axes, for instance I am using `ListLogLinearPlot` to have a discrete plot with a logarithmic x-axis and a linear y-axis. My issue however is that I would like the x-axis to be on a binary logarithmic scale, instead of the default logarithmic scale (natural? with decimal ticks?). In particular I need 2, 4, 8, 16, 32, etc. to be equally spaced on the x-axis to highlight the periodic nature of the function I'm plotting. How may I proceed?


Using LaunchKernels to launch kernels with lower priorities

On windows the kernels launched with `LaunchKernels` are starred with "Below Normal" priority. **Is there a way to start them with even lower priority (eg. "Idle")?** I'm doing some intensive numerical analysis on my computer, which becomes really unresposive while the analysis is running. If I manually lower the priority of the kernels (eg from ProcessExplorer) then I'm able to work normally. But manually finding the processes every 10 minutes becomes tedious. Of course I could just launch fewer kernels than I have cores, but that seems inelegant. Bonus points for a cross-platform solution:)


Mathematica Plot: Inconsistency when plotting large values

I am working with a function in Mathematica and I am getting some inconsistencies when I plot it. As I really need to understand were this comes from I would appreciate any help. I am working with a function of the following form: `f2b[b_] = Exp[-1000 - 2 Sqrt[1000*b] - b]*(Erfi[Sqrt[1000]] - Erfi[Sqrt[1000] + Sqrt[b]])` From my understanding this function should go to zero for very small b because both parts, the Exp function as well as the difference between the imaginary error functions, should vanish. Mathematica calculates: `f2b[E^-30] // N = -3.4517046881*10^-7` as expected. BUT if I plot this function: `Plot[{f2b[E^b], 0}, {b, -50, 0}, PlotStyle -> {{Blue, Thick}, {Red, Thick}}]` ![Mathematica graphics](http://i.stack.imgur.com/TH6M2.png) Mathematica shows me a plot which is approaching a value of about -0.0175 for small b and has therefore an absolute value much larger the the value at E^-30 calculated above. If I tabulate, interpolate and plot the function: `t = Table[{b, f2b[E^b] // N}, {b, -50, 0}]; f = Interpolation[t]; Plot[{f[b], 0}, {b, -50, 0}, PlotStyle -> {{Blue, Thick}, {Red, Thick}}]` ![Mathematica graphics](http://i.stack.imgur.com/w86Nb.png) The plot is looking much different and is approaching zero as expected. I am wondering whether this has to do something with overflow problems in graphics but I am not sure.


CDF Infokit question

In the _CDF Infokit_ , one finds the `BriggsCochraneCalculus.cdf` document, which shows a textbook on calculus. I've got two questions about how it was made:   1. How has the bar at the top been made? Instead of the usual _CDF_ commands, like zoom, etc., one finds the title ( _Calculus_ , etc), the name of the author,...   2. How have the different subsections been made, so they could open and close while clicking on the text of the subsection (`"Tangent Lines"`, `"Tangent Lines and Rates of Change"`, etc)? I have tried looking into the `Opener` and `Button` documentation, but I couldn't remake this functionality...


decomposing a complex equation

I have an equation such as:               a*z^2 + b*(z - c)^2 == d       where `z` is a complex variable and `a`, `b`, `c`, `d` are all complex parameters. I want to put `x+I*y` instead of `z` and decompose this equation into two pure real and imaginary part for further analysis, but I don't know how to do it by _Mathematica_! Can anybody help me? Thanks in advance


Filling Between Curves

I want to fill in the region between the curves. So far I have this:               Plot[{x + 7, 9 - x^2}, {x, 0, 1.5}, Filling -> {1 -> {2}}]      ![enter image description here](http://i.stack.imgur.com/ma4uA.png) But I want something like this: ![enter image description here](http://i.stack.imgur.com/b6DHN.png)


Filling the area between two curves, only where and if the second lies above the first one

I would like to make a filling of a plot between two curved dynamically.I have two lines depending upon parameters. They may cross one another, and may not in different domains of the parametric space. I would like to plot them and make filling between these lines, but only if the line 2 lies above the line one, and not otherwise. To be specific, consider a simplistic example:                k = -0.5;     Plot[{0.5*x^2, x^2 + k}, {x, -2, 2}, Filling -> {1 -> {2}}]      here k is parameter. This yields the expected plot where the area between the two curves is filled everywhere. I need, however, that it would be filled only at x>1 and x<-1. Further I would like to wrap all this with Manipulate statement varying k to have all in dynamics. In addition the real problem that I have is rather complex. These two curves can have none or multiple intersection points depending upon parameters. Thus, the idea to divide the curves into parts between points does not help. This:                   k = -0.5;     Plot[{0.5*x^2, x^2 + k}, {x, -2, 2},       Filling -> If[0.5*x^2 < x^2 + k, {1 -> {2}}]]      makes no filling. Any other ideas?


Filling only when one curve is below the other

I want to fill the area between two curves only when curve-1 (Black) is _below_ curve-2(Blue). So In this example, I don't want the middle portion shaded but just the left and right tails to be shaded. It is not possible for me to always solve for the points of intersection since it might involve using `FindRoot` and stuff and may not be worth the trouble. Can someone please tell me how to do that. Thanks.               Plot[{0.8333*H + 16.928*H^0.25 - 85,        Max[-9 + Max[H - 80, 0], H - 80]}, {H, 0, 700},       PlotStyle -> {Directive[Black, Thick], Black}, Filling -> {1 -> {2}}]      ![enter image description here](http://i.stack.imgur.com/Lv6oB.jpg)


An error in converting matrix to quaternion

Here is an old quaternions package. There is a function named `MatrixToQuaternion`, References are here Matrix in that document is `1 2 3 4 5 6 7 8 9 10 11 12 13 14 15`; you can see it in the top of the page. `m1` is a test matrix               m1={{-0.825927,-0.56376,0.00445629,-166.077},{-0.56376,0.825813,-0.0144323,-109.866},{0.00445629,-0.0144323,-0.999886,200.868},{0.,0.,0.,1.}};      Part of the `MatrixToQuaternion` function in the package `Quaternions.m` You can check this according the web page.               S =  2*Sqrt[1 + m1[[2,2]] - m1[[1,1]] - m1[[3,3]]];               Quaternion[m1[[1,3]] + m1[[3,1]],              m1[[1,2]] + m1[[2,1]],                      1/2, m1[[2,3]] + m1[[3,2]]         ]/S      gives value1 (you can simply `Total[#^2]&` to see it's wrong unit quaternion)               Quaternion(0.00233201,-0.29502,0.130827,-0.00755253)      The right value should be some order of value2               {-0.29502,0.955461,-0.00755253,0.}      It looks two components of value1 are wrongly calculated. Where does it go wrong?


A faster way to do sums?

I found out that,it is INCREDIBLY(like 100 times) faster to use `Dot` instead of `Sum`,to perform long sums. But I have not been able to use this alternative to perform the following sum:               a={{b,c},{d,e}};          a[[1]]+a[[2]]      I want to get this output: > >     {b,c}+{d,e}={b+d,c+e} >   I tried:               a.{1,1}      but did not work. The easy way to do it is:               Sum[a[[i]],{i,1,2}];      But I want to avoid this slow way. Any faster alternative?


Dynamic [ NotebookEvaluate ["_"] ]

A nice way to centralize various tasks in one notebook is the `NotebookEvaluation` function. For instance I can evaluate ten notebooks from a single notebook (e.g. allnotebooks.nb) like this:               NotebookEvaluation["nbpath_1.nb"]     NotebookEvaluation["nbpath_2.nb"]     ...     NotebookEvaluation["nbpath_10.nb"]      I would like to update this automatically, e.g. every six hours, but it doesnt work. My idea is to create a master notebook with the following code (here: 15 seconds):               Dynamic[NotebookEvaluate[       "C:\\Users\\myname\\Desktop\\allnotebooks.nb"],       UpdateInterval -> 15]      And it works without using dynamic. Using dynamic gives the following error: > >     An unknown box name (ToBoxes) was sent as the BoxForm for the > expression. >     Check the format rules for the expression. >   Does someone have an idea about the reason? Is `Dynamic` not an adequate function to do this? Thanks a lot for any ideas! P.S. I tested it with this code for the sub notebooks, e.g. for nbpath_1.nb:               path = "C:\\Users\\myname\\Desktop\\";     time = DateString[{"YearShort", "Month", "Day", "_", "Hour", "Minute",          "Second"}];     data = Table[RandomInteger[{1, 10}], {10}];     Export[path <> "nb1_" <> time <> ".xls", data];


Blank VectorPlot

I'm trying to draw a `VectorPlot` of a function that admittedly probably is not very well suited for such a plot. But at the moment I just get a white sheet and I would expect something more than that. Some definitions:               G = 6.67 10^-11;     Subscript[m, sun] = 1.988425 10^30;      Subscript[m, 1] = 0.1 Subscript[m, sun]; Subscript[m, 2] = 0.4 Subscript[m, sun];     Subscript[x, 1] = -7 10^5/(Subscript[m, 1]/Subscript[m, 2] + 1);      Subscript[x, 2] = -(Subscript[m, 1]/Subscript[m, 2]) Subscript[x, 1];     ω = {0, 0, Sqrt[G (Subscript[m, 1] + Subscript[m, 2])/Abs[Subscript[x, 1] - Subscript[x, 2]]^3]};      I'm sorry about the amount of subscripts (if there is an easy way to convert them I don't know about it, though `Hold[expr]` will render the subscripts.) Here's the plot:               ϕ[r_] := -(G Subscript[m, 1])/Norm[r - {Subscript[x, 1], 0, 0}] - (G Subscript[m, 2])/Norm[r - {Subscript[x, 2], 0, 0}] - 0.5 (ω\[Cross]r).(ω\[Cross]r)          VectorPlot[Evaluate[-Grad[ϕ[{x, y, 0}], {x, y}]], {x, -10^6, 10^6}, {y, -10^6, 10^6}]      The function has singularities in it so I've considered what's been said in this post and have also been playing with the various options, but haven't been able to get anything other than the blank, white sheet: ![blank](http://i.stack.imgur.com/q30LP.png) In so far that the gradient i orthogonal to level sets, the contour plot can tell us a bit about what kind of arrows we could expect to see. The contour plot: ![contourplot](http://i.stack.imgur.com/JwJZ0.png) There is something fishy about the `Grad` which makes me suspect `VetorPlot`, though it does not complain, does not get any values:                   N[Grad[ϕ[{x, y, 0}], {x, y}] /. {x -> 1, y -> 2}]      > `{-193.335 + 2.70673*10^9 Derivative[1][Abs][-139999.] + 4.22919*10^7 > Derivative[1][Abs][560001.], -386.67 + 38818.9 Derivative[1][Abs][2.]}` It leaves a derivative in there.


How to use Assumptions in a Series Expansion

I want to series expansion the expression $\frac{1}{2} \left(e_1+e_2-\sqrt{e_1^2-2e_1e_2+e_2^2+4V_{12}^2} \right)$ up to second order in $V_{12}$ using the assumption $e_1>e_2$. So I tried               Series[1/2 (e1 + e2 - Sqrt[e1^2 - 2 e1 e2 + e2^2 + 4 V12^2]), {V12, 0, 2},      Assumptions -> e1 > e2] // FullSimplify      But there is still $\sqrt{(e_1-e_2)^2} $ terms in the results. What should I do to make the assumption $e_1>e_2$ work?


?function-name does not return function help

For some reason when I use ? _function-name_ to ask for help on a function, I got a very clinical breakdown of that function with its options and attributes instead of the blurb about the function: ![?Function](http://i.stack.imgur.com/QjGUv.png) To fix this, I evaluated `ClearSytemCache[]`, killed the kernel (Evaluation > Quit Kernel > Local), and restarted _Mathematica_ \-- it's possible that I had to do only one of these steps -- after which the problem went away. ![?Function fixed](http://i.stack.imgur.com/4z7Eo.png) However, I was just curious about what brought it on.


How to determine numeric equivalent of Tiny, Small, etc. image sizes for Graphics?

Is there a way to find the numeric equivalents of `Tiny`, `Small`, `Medium`, and `Large` for for `ImageSize`? In other words, what are the integers `t`, `s`, `m`, and `l` such that, for `Graphics` objects, the directives               ImageSize -> t     ImageSize -> s     ImageSize -> m     ImageSize -> l      are equivalent, respectively, to the directives               ImageSize -> Tiny     ImageSize -> Small     ImageSize -> Medium     ImageSize -> Large      ?


How to nest the output of FindRoot in a table of Derivative evaluations?

I am using ParametericNDSolveValue to numerically solve an ODE system, which I then use to find the definite integral of one of the variables in the solution for different values of a parameter. Here is a simpler (and faster!) version of my code:               eqns={y''[t] + d y[t] == 3 a Sin[y[t]], y[0] == y'[0] == 1};     pfun[din_]:=ParametricNDSolveValue[eqns/.{d-> din}, With[{b=1},b NIntegrate[y[t],{t,0,5}]],{t,0,5},{a}];      which if plotted for three values of "d" looks like this ![enter image description here](http://i.stack.imgur.com/aDPye.png) I am using FindRoot to find the "a" values at which these curves meet the line y=3.               Table[a /. FindRoot[pfun[din][a] == 3.0, {a, 0, 2}], {din, 1, 3, 1}]      What I would like to do next is find the value of the first derivative at each of these points (with the ultimate aim of plotting the derivatives w.r.t. the d parameter values used to make each curve). What I'm stuck on is: do I (1) first generate a list of "a" values using the code above and then somehow plug each element into code like this               Evaluate[Table[Derivative[1][pfun[din]][a], {din, 1, 3, 1}]]      (I'm not clear how to get the derivative function to call a subsequent element in the list for each din value). or do I (2) embed the FindRoot function somehow into the derivative function? (I don't know how to do this, or do I use Table or Map?)


What is the principle behind Dispatch?

I want to know what `Dispatch` actually does to rule the list. Why is it so fast? The documentation says > Dispatch generates a dispatch table which uses hash codes to specify which > sets of rules need actually be scanned for a particular input expression. What is a hash table? How does it specify which sets of rules need actually be scanned for a particular input expression? What about `DeleteCases`? Since it is fast too, Does it use hash table too?


Can a LatticeData image be displayed in a space filled fashion

I'd like a FaceCenteredCubic image as in the in LatticeData docs, but space packed, and cropped on all the boundaries, so that it illustrates the geometry of the calculation that leads to the $\pi/\sqrt{18}$ density result. The call that produces the plot is               LatticeData["FaceCenteredCubic", "Image"]      but this has small spheres, and probably doesn't have a way to crop on the boundaries. I see that there's a PackingRadius listed in the documentation. I thought it might be possible to use the PackingRadius property, to display the spheres in the lattice in a space packed fashion (so that they touch), but that wouldn't handle the cropping part of the problem. Is there any easy way to do this, perhaps using the lattice data to draw spheres using the Graphics drawing options, and then using the various ViewAngle type options to crop that appropriately?


How can I make CurrentValue for font characteristics pick up the font of the output not the input cell?

The command `CurrentValue` (documentation) allows you to access various properties of fonts, such as x-height, line height, and various measures of width such as n-width and m-width. This has obvious applications in determining appropriate sizes of objects so that the text contained within them fits. However it is not obvious how to pick up the characteristics of the font of styled output. For example, the following uses the width of the font in the input cell, not the selected style in the code (example adopted from this question).                Framed @ Graphics[Text[       Style["how quickly daft jumping zebras vex",         FontFamily -> "Verdana", FontSize -> 20]],       ImageSize -> CurrentValue["FontNWidth"]*35]      ![enter image description here](http://i.stack.imgur.com/CnHLj.png) If I select the whole input cell (by its bracket, not just the text) and change the font, it works better, although of course `"FontNWidth"` is not a perfect indicator of actual width of characters: ![enter image description here](http://i.stack.imgur.com/cMrfw.png) How can I concisely get the `CurrentValue` dimensions from an arbitrarily chosen font?


How to improve the accuracy of this Monte Carlo simulation

A friend of mine went on an interview and he was asked to calculate the angle between the hour hand and minute hand of an analog clock when the time was **3:15**. Arguably, this is a trivial problem that can be easily solved analytically. 15 minutes is the 1/4th of an hour, and an hour is the 1/12th of a full circle, therefore the angle is $(1/4)\times(1/12)\times 360 = 7.5 \deg$. I was wondering whether a Monte Carlo simulation could do well. **EDITED** : As suggested by @kuba here is the image of a **"real"** clock hopefully at **3:15** precisely. ![enter image description here](http://i.stack.imgur.com/oSIqP.png) Source: http://etc.usf.edu/clipart/33000/33069/clock-03-15_33069.htm My code that follows operates on the mask of an **ideal** clock at **3:15** (angle between two hands at `7.5` degrees) and **not** on a mask generated by the above image. It takes more than $10^6$ points to derive an answer of $\sim 7 \deg$. Could the experts here improve the accuracy of the simulation?               ClearAll["Global`*"];     (* Generate some random points. Use 0.98 instead of 1.00 or otherwise        some points will be half-inside the circle and half-outside.        This will hurt our results in left untreated. *)     points = Show[       Graphics[{Pink,         Point /@          Select[           Partition[RandomReal[{-1, 1}, 10000], 2],           ({a, b} = #; a^2 + b^2 <= 0.98) &]}]]      ![enter image description here](http://i.stack.imgur.com/oCrJb.png)               (* In reality the mask below should have been generated by a real clock *)     disk = Graphics[{Pink, Disk[{0, 0}, 1, {0, 2π - 7.5π/180}]}]      ![enter image description here](http://i.stack.imgur.com/HI1TE.png)               finalImage = ImageSubtract[disk, Show[disk, points]]      ![enter image description here](http://i.stack.imgur.com/wmdCB.png)               (* Count the number of points inside the slice and outside the slice.        If I use "Count" as the property in ComponentMeasurements[], I get worse results.        EDITED: As noted by @MichaelE2 the following statement for 'outArea'        might calculate the whole rectangular area and not only the points! *)     inArea  = Last /@ ComponentMeasurements[finalImage, "Area"] // Total;     outArea = Last /@ ComponentMeasurements[points, "Area"] // Total;          (inArea/outArea) * 360 // N      **EDITED** : With the point set by @DanielLichtblau, I get $\sim 7.3$ degrees with $10^4$ points! `finalImage` looks like this: ![enter image description here](http://i.stack.imgur.com/MCGzg.png)


Functions that remember their values

Can someone explain what is going on with the following ...               func[y_] := func[y] = (Print["Hello world !!!"];)          func[1]      > Hello world !!!               func[2]      > Hello world !!!               func[1] (*nothing printed*)          func[2] (*nothing printed*)      As I understand it () are used so the function remembers its values, but as you see when I repeat `func[1]`, nothing. If I take out the `y` in `f[y]`, it prints. If I define the function as `f[y_] := (...)` (without `f[y] =` ), it prints. I'm sure there is a simple explanation, any help is appreciated.


ListPlot multiple datasets over same x-values

Is there a better way to enter my data into a list plot?               ListPLot[{{{1.1, 2.2}, {2.3, 4.3}, {2.9, 5.5}},               {{1.1, 2.1}, {2.3, 4.6}, {2.9, 5.9}},               {{1.1, 2}, {2.3, 4.8}, {2.9, 6.2}}}]      I think there should be a more efficient way, but cannot find it. I've read the documentation on `ListPlot` and `DataRange`.


Better code to find Narcissistic number

My code finding Narcissistic numbers is not that slow, but it's not in functional style and lacks flexibility: if $n \neq 7$, I have to rewrite my code. Could you give some good advice?               nar = Compile[{$},        Do[         With[{            n = 1000000 a + 100000 b + 10000 c + 1000 d + 100 e + 10 f + g,            n2 = a^7 + b^7 + c^7 + d^7 + e^7 + f^7 + g^7},           If[n == n2, Sow@n];           ],          {a, 9}, {b, 0, 9}, {c, 0, 9}, {d, 0, 9}, {e, 0, 9}, {f, 0, 9}, {g, 0, 9}],        RuntimeOptions -> "Speed", CompilationTarget -> "C"        ];          Reap[nar@0][[2, 1]] // AbsoluteTiming          (*{0.398023, {1741725, 4210818, 9800817, 9926315}}*)


Expected sum of largest 3

I pick 4 numbers from the Uniform Distribution. I need the expected value of the sum of the 3 largest. I am pretty sure that the answer is 9 / 5 which agrees with a simulation. I would like to get mathematica to do this. I have tried this:               Assuming[a >= b >= c >= d,        Expectation[a + b + c, {a, b, c, d} \[Distributed] UniformDistribution[{{0, 1},{0, 1}, {0, 1}, {0, 1}}]]]      which returns 3 / 2. What am I doing wrong?


Linear interpolation of a list between periodic anchorpoints

I have a list of the form:               list = {1,1,1,2,2,2,3,3,3,4,4,4,7,7,7,19,19,19};      Where we can see that there are an ordered set of integer values that repeat themselves some fixed number of times N. Is there a nice one-liner to transform this list into something like:               transformedList = {1,1+1/3,1+2/3,2,2+1/3,2+2/3,3,3+1/3,3+2/3,4,4+1/3,4+2/3,7,7+1/3,7+2/3,19,19+1/3,19+2/3}      Where we essentially choose each new element we come by in the list as an anchorpoint, and replace the repeats of that element as equispaced points along a line the anchor integer value and the next higher integer?


Draw graph wherein vertices are ArrayPlots

I need to place ArrayPlots in the vertices of graph. i.e. in graph                Graph[{1->2, 2->3, 3->1}]      I have to replace vertex 1 with ArrayPlots[{{0,0,1}}] and so on basing on the following list               {{1,{0,0,1}},{2,{0,1,0}},{3,{1,1,0}}}


implement the ZOH in mathematica

well I'm trying to implement the ZOH in Mathematica, but I can't. Take a look, this is my script:               utt[t_] :=        Sum[If[k <= t < k + 1,          k*T*UnitStep[k*T] - (k*T - 6 T)*UnitStep[k*T - 6 T], 0], {k, 0,          10}];      And when I plot: ![zoh](http://i.stack.imgur.com/ZkhYx.jpg) the problem is that in wanting to continue working with the new function you can not, because this is a function of the conditioning "if", please look at the output of utt [t]:               If[0 <= t < 1, k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T],        0] + If[1 <= t < 2,        k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T], 0] +       If[2 <= t < 3, k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T],        0] + If[3 <= t < 4,        k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T], 0] +       If[4 <= t < 5, k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T],        0] + If[5 <= t < 6,        k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T], 0] +       If[6 <= t < 7, k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T],        0] + If[7 <= t < 8,        k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T], 0] +       If[8 <= t < 9, k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T],        0] + If[9 <= t < 10,        k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T], 0] +       If[10 <= t < 11, k T UnitStep[k T] - (k T - 6 T) UnitStep[k T - 6 T],        0]      I want an answer in one expression (not "if"), in order to continue working with her freely. If anyone can calculate the ZOH otherwise, I would appreciate forever. Thanks and sorry for my bad English.


Plotting velocity vectors for pressure driven pipe flow

So I find the velocity profile for Pressure driven pipe flow and it looks like: $$u = \frac{h^2}{2 \mu} \frac{\mathrm{d}P}{\mathrm{d}x}\left[1 - \left(\frac{y}{h}\right)^2\right]$$ Here, a fluid flows between two walls separated by a distance $h$. The pressure gradient $\mathrm{d}P/\mathrm{d}X$ drives the flow. The vertical coordinate axis is $y$. How do I plot this as a velocity profile (`VelocityPlot`)? When I try do plot this with               μ = 0.02; Px = -0.5; h = 1.0;     VectorPlot[{(h^2/(2 μ)) Px (1 - (y/h)^2), 0}, {x, 0, 3}, {y, -3, 3}]      I get the following figure: ![enter image description here](http://i.stack.imgur.com/9kLPr.jpg) However, the velocity profile is parabolic and should look like: ![enter image description here](http://i.stack.imgur.com/xBl12.png) I apologize for the low quality vector plot from ansys but what went wrong with my `VectorPlot[...]` definition?


Border on part of ArrayPlot

I need to outline with border the group of cells in ArrayPlot. More precisely in my case I would like to outline all blocks of two black squares in the following line.               ArrayPlot[{{0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1}}, Mesh -> True]


Use Style on list elements

I have a list like this:               list = {0, 0, 0, 1, 1, 1}      I want to color all the 0's in red, but I dont want to count through all the elements, like in my solutions, which seems awefully complicated:               Table[If[list[[x]] == 0, Style[list[[x]], Red], list[[x]]], {x, 1, Length@list}]      How else could I do this without using Table? In other words, a simpler way, if possible.


How can the behavior of InterpolationOrder->0 be controlled?

In `ListPlot` and `Interpolation`, the option `InterpolationOrder->0` uses two different conventions. `Interpolation` gives the y-value from the nearest _greater_ x-value.               Plot[Quiet@Interpolation[{{0,0},{1,1},{2,2}},InterpolationOrder->0][x],{x,-1,3}]      ![enter image description here](http://i.stack.imgur.com/fJmLg.png) `ListLinePlot` gives the y-value from the nearest _smaller_ x-value.               ListLinePlot[{{0,0},{1,1},{2,2}},InterpolationOrder->0,PlotRange->{{-1,3},All}]      ![enter image description here](http://i.stack.imgur.com/Gl11k.png) How can I make `Interpolation` use the `ListPlot` convention?


Limitations of ParametricNDSolve family w.r.t objective functions

**Observation:** I can see even for very simple modification in case of an scalar objective involving an definite integral in time `ParametricNDSolve` fails. Here is an example!               eqns = {y''[t] + y[t] == 3 a Sin[y[t]], y[0] == y'[0] == 1};     pfun =ParametricNDSolveValue[eqns,Integrate[y[s] - a s, {s, 0, 5}], {t, 0, 5}, {a},     Method -> {"ParametricSensitivity" -> "ForwardSensitivity"}];     pfun[1.5]      > Meaningless output! Same kind of output for `pfun'[1.5]` but from `pfun''[1.5]` onwards for higher derivatives we get numerical values which I guess are totally wrong. However everything will be fine if one uses `Integrate[y[s], {s, 0, 5}]`! So I tried `{"ParametricSensitivity" -> "AdjointSensitivity"}` which is most suitable for integrated objective functions. Again failure but this time for both the cases. We get the following error > ParametricNDSolveValue::adjsens: The adjoint sensitivity method cannot be > used for the output function {t,0,5}. It can only be used for output > functions that are at a particular time or are a definite integral over > time. >> I feel this is a major inconsistency of implementation internal. Using `Trace` I found some esoteric `Integrate`ImproperDump`` and`Internal`DependsOnQ`. **What should be`pfun[1.5]`:** We know               Distribute[Integrate[y[s] - a s, {s, 0, 5}], Plus] ===      Integrate[-a s, {s, 0, 5}] + Integrate[y[s], {s, 0, 5}]      > True So we first can find `pfun[1.5]` using               eqns = {y''[t] + y[t] == 3 a Sin[y[t]], y[0] == y'[0] == 1};     pfun = ParametricNDSolveValue[eqns,      Integrate[y[s], {s, 0, 5}], {t, 0, 5}, {a},      Method -> {"ParametricSensitivity" -> "ForwardSensitivity"}];     (pfun[1.5] + Integrate[-a s, {s, 0, 5}]) /. a -> 1.5      > -7.86673 and the first order sensitivity will be               (pfun'[1.5] + D[Integrate[-a s, {s, 0, 5}], a]) /. a -> 1.5      > -7.87591 Crosschecking the first order sensitivity below!               fun1[aval_?NumericQ] :=NIntegrate[Block[{a = aval},      Evaluate@(y /. First@NDSolve[Evaluate@eqns, y, {t, 0, 5}])[t] -a t] , {t, 0, 5}];     Needs["NumericalCalculus`"];     ND[fun1[x], x, 1.5]      > -7.87604 Pretty much as expected. **Question:**   * It will be great to know if we can use `ParametricNDSolve` family to find parameter dependency of integrated objective like the following: $$ G(p)=\int_a^{b} g(y(s),s,p) \,ds$$ where $g$ is a function of the dependent variable $y(s)$ of the underlying differential equation system and $p$ represents the parameter with respect to which the sensitivity $\frac{dG}{dp}$ is sought (i.e `a` in the above example).   * Also why `{"ParametricSensitivity" -> "AdjointSensitivity"}` fails in the above example? For some math reference check here. BR


What range of ports do remote kernels use?

I'm trying to run a remote kernel, but my local system administrator is wary of opening up ports for incoming connections. > Is there are particular range of ports that Mathematica uses to communicate > with remove kernels? Even if it's a wide range (e.g. 40000-70000), such an answer would still be helpful to me.


NExpectation behaves oddly with EmpiricalDistribution

Note: this is fixed in version 9. * * * My question concerns the usage of `NExpectation` and `Expectation` and why I see the behavior I see in the following example. First take some data and derive an `EmpiricalDistribution`:               data = {4, 104, 96, 80, 22, 76, 106, 18, 98, 44, 112, 78, 50, 120, 2, 6,              100, 10, 68, 80, 42, 66, 100, 58, 4, 76, 18, 102, 6, 16, 52, 32, 62,              36, 18, 4, 54, 98, 38, 74, 16, 22, 102, 2, 2, 4, 22, 72, 100, 82, 48,              16, 34, 44, 130, 50, 48, 74, 60, 96, 8, 118, 30, 58, 84, 4, 70, 66,              40, 14, 92, 68, 42, 56, 56, 16, 40, 12, 22, 26, 98, 4, 80, 100, 36,              88, 48, 26, 28, 94, 22, 26, 78, 16, 52, 8, 10, 2};          dist = EmpiricalDistribution[data];      You can plot `PDF`s and `CDF`s of the distribution:               Row[{DiscretePlot[PDF[dist, x], {x, data}, Joined -> True, ImageSize -> 300],           DiscretePlot[CDF[dist, x], {x, 0, Max@data, 1}, Joined -> True, ImageSize -> 300]}]      They look like this: ![PDF & CDF plots](http://i.stack.imgur.com/ft7hC.png) That covers the background. Now execute the following and it gets a little odd:               Expectation[X \[Conditioned] X > 4, X \[Distributed] dist]     NExpectation[X \[Conditioned] X > 4, X \[Distributed] dist]     N[Expectation[X \[Conditioned] X > 4, X \[Distributed] dist]]          620/11     NExpectation[X \[Conditioned] X > 4, X \[Distributed]DataDistribution[<<"Empirical">>, {51}]]     56.3636      So, what gives? How come `NExpectation[...]` doesn't calculate an answer, but `N[Expectation[...]]` does? Clearly, `Expectation` handles `EmpiricalDistribution` without a problem. One would think that `NExpectation` would as well. Doesn't this seem odd? Just hoping that understanding why Mathematica does this might yield additional insights into Mathematica itself.


Extracting the coordinates of a point of interest from a ListDensityPlot

How can I extract coordinates from a list density plot. Example plot of interest: ![1](http://i.stack.imgur.com/VAcSs.png) I need to place two points on either side of the center white circle and calculate the distance between them. My idea was to use two locators that gives their dynamic coordinates and connect a straight line between them. And calculate the different between them and output it to the user. How can I do this with? So far the only thing I figured out is to use a locators as a line to give me dynamic position.               Module[{v1 = {0, 0}, v2 = {2, 0}},       Graphics[{Locator[Dynamic[v1]], Line[{Dynamic[v1], Dynamic[v2]}],         Locator[Dynamic[v2]]}, PlotRange -> 3, Frame -> True]]      Screenshot of output: ![2](http://i.imgur.com/Ql0xoeF.png)


NMaximize problem

Could anybody explain to me why the following code fails ?                Reap[      NMaximize[{x1^2 + x2^2 + x3^2, 0.001 <= x1 <= 0.002,         0 <= x2 <= 0.002, 1 <= x3 <= 10, x3 \[Element] Integers }, {x1, x2,         x3}, Method -> "SimulatedAnnealing",        EvaluationMonitor :> Sow[{x1, x2, x3}]]      ]      In fact it outputs :               {{-\[Infinity], {x1 -> Indeterminate, x2 -> Indeterminate,         x3 -> Indeterminate}}, {}}      If i put x1's lower bound to 0 then it works but it uses only 0 values for x1 I suppose it has something to do with the integer x3. Thanks in advance.


Graph from binary matrix (not adjacency) respecting the original matrix positions

![What to do](http://i.stack.imgur.com/pTuzi.png) I have a binary matrix. My objective is to connect every close (without "jump") elements with value equal to 1, but I must keep the point positions, just like it's shown at the image. Can somebody help me with it, please? Test input thanks to @hftf:               {{0,1,0,0,1,0,1,0},      {0,1,0,0,1,0,1,0},      {0,0,1,0,1,0,1,0},      {0,0,0,1,0,0,1,0},      {0,0,0,0,1,1,0,0},      {0,0,0,0,1,0,0,0}}


Extract the real components from a very large expression

Suppose I have a very long expression (>500,000 characters) which contains a mixture of real and imaginary terms. e.g `x = g*m*o*p*q*s*v + a*c*f*g*m^2*o*p*q*s*v + c*g*h*m^2*o*p*q*s*v - a*c*g*h*m^2*o*p*q*s*v - B*g*m*o*p*q*s*v*w - g*m*o*p*s*v*x - (1-I*Sqrt[3])*(2*g*o*p*s*v + 2*a*c*f*g*m*o*p*s*v) + 2*c*g*h*m*o*p*s*v + (1+I*Sqrt[3])*(2*g*p*q*v + m*g*f*q*m*o*s*v)...` etc. I would like to seperate the real and imaginery terms and work with the real terms only. I am using `ComplexExpand[Re[x],TargetFunctions->(Re)}]` but I keep getting the message 'No more memory available. Mathematica has shut down.Try quitting other applications and then retry'. Is there a better way to discard the imaginary terms and group the real terms together without this problem?


Plot data from txt file?

I have data in file.txt which can be expressed by 20000x11 matrix. I do not want to import all of these data. How can I plot graph of the column 1 & column 4?


Solving a polynomial equation with a condition of equality on roots

Let the following equation have two equal roots:               f[x_] := x^3 - p x^2 + q x - r       And I want to find out what the three roots are. Not knowing how to put this condition within a Solve or Reduce, I have to rely on transcribing some algebra into MMA. So if the above equation has two equal roots, then               fr[x_] := 3 x^2 - 2 p x + q      has one of them, out of a theorem on the depression of equations. If I put this into Solve this leads to:               Solve[x^3 - p x^2 + q  x - r == 0   && 3 x^2 - 2 p  x + q == 0, x]      No error message but MMA is unable to give here one the the duplicate solution. So I put more algebra into the code:               PolynomialRemainder[f[x], fr[x], x]    (* the remainder must he equal to zero *)     rootduplicate = x /. Solve[% == 0, x]  (* gives the value of the two equal roots *)      The third root is within the third factor of f[x]:               PolynomialQuotient[f[x], (x - rootduplicate[[1]])^2, x] // FullSimplify     Solve[% == 0, x]     root3 = x /. {%}      Let's check it up with an example:               Solve[(x^3 - p x^2 + q  x - r /. {p -> 4, q -> 5, r -> 2}) ==  0   && (3 x^2 - 2 p  x + q /. {p -> 4, q -> 5}) == 0, x]    (* now MMA finds a double root *)     Solve[(x^3 - p x^2 + q  x - r /. {p -> 4, q -> 5, r -> 2}) ==  0   , x]      rootduplicate /. {p -> 4, q -> 5, r -> 2}     root3 /. {p -> 4, q -> 5, r -> 2}     root3 == {(p - 2 rootduplicate)} // FullSimplify (* another verification out of algebra   - is there a way with MMA to find out this relation without hardcoding it? *)      My questions:   * Why MMA (V8) is unable to find a solution in my first Solve ?    * Is there a better way relying less on algebra to get these solutions?


Issue with setting up docked cells

Normally I try to stay away from asking RTFM- questions but concerning docked cells I am currently groping in the dark. The documentation examples tell me how to create a new window containing a docked cell, but not how to setup a cell as docked cell in my existing .nb file. Am I to use (edit) the notebooks stylesheet or is there a command like e.g. SetOptions for that matter?


Compiling a spatial predator-prey model and optimising it for speed

I just made a spatial predator-prey model but it runs a little slow and I am seeking some advice on how to compile it to optimise it for speed. I first define matrix with 0 for an empty site, 1 for a predator and 2 for a prey present:               e = 0;r = 1;y = 2;     initSpace[n_] := RandomInteger[{0, 2} , {n, n}];     space = initSpace[10];      I then defined a `getCell` function which looks for a neighbour at cell position $(i,j)$ in a matrix `sp` with a certain value `x`, and returns the coordinates of that cell; if it doesn't find a cell with that value it returns coordinates $(i,j)$.               getCell =       Compile[{{sp, _Integer,          2}, {i, _Integer}, {j, _Integer}, {x, _Integer}},        Block[{n, m, k2, l2, cells}, {n, m} = Dimensions[sp];        cells = {{i, j}};        Do[k2 = Mod[i + k, n, 1]; (* This is the neighborhood *)         l2 = Mod[j + l, m, 1];         If[(k2 != i || l2 != j) && sp[[k2, l2]] == x,           AppendTo[cells, {k2, l2}]], {l, -1, 1}, {k, -1, 1}];        If[Length[cells] == 1, {i, j}, RandomChoice[Rest[cells]]]],        CompilationTarget -> "C", Parallelization -> True,        RuntimeOptions -> "Speed"]      I then define a module step which calculates the space matrix in the next time step based on a given birth rate `b` and death rate `mu` after one event at a random location in the space.               step[b_, mu_] := Block[{i, j, k, l, dim},       dim = Dimensions[space];       i = Random[Integer, {1, dim[[1]]}];       j = Random[Integer, {1, dim[[2]]}];       Which[        (* Predator *)        space[[i, j]] == r,        If[Random[Real] < mu,         (* Predator dying *)         space[[i, j]] = e,         (* Predator eating *)         {k, l} = getCell[space, i, j, y];         space[[k, l]] = r;         ],        (* Prey *)        space[[i, j]] == y,        If[Random[Real] < b,         (* Prey reproducing *)         {k, l} = getCell[space, i, j, e];         space[[k, l]] = y         ]        ]       ]      Finally, I do many iterations                gridsize = 200;     space = initSpace[gridsize];     nrsteps = 100;     stepsize = 5000;     b = 0.9; mu = 0.4;     population = Table[0, {nrsteps}];     Do[Do[step[b, mu];, {stepsize}];       population[[i]] = space;       , {i, 1, nrsteps}];         Animate[          ArrayPlot[population[[i]], ColorRules -> {e -> Black, r -> Red, y -> Blue}],          {i, 1, nrsteps/stepsize, 1}, AnimationRepetitions -> 1,           AnimationRunning -> False]      Ideally I would like to have the latter two modules compiled as well, but when I tried to put `Compile[]` around them I got a bunch of errors. Does anyone know what I might be doing wrong? Or have any other advice on how I should optimise my code for speed? Or should I try to put everything in a single compiled `Module`?


How combine pure functions of several slots?

How can one define _in a functional way_ a 1st-order linear differential operator involving several independent variables that can then be applied to a function of that many variables? Consider an example with two variables, where one wants to form `D[f[x, y], x] + 3 D[f[x, y], y]` from a function `f`. Of course one could define                   diff[f_][x_, y_] := D[f[x, y], x] + 3 D[f[x, y], y]      so that for a function such as                   g[x_, y_] := x^2 y + Cos[x + 2 y]      we just evaluate:                   diff[g][x, y]     2 x y + 3 (x^2 - 2 Sin[x + 2 y]) - Sin[x + 2 y]   (* desired final output *)      But how can such an operator be defined functionally, that is, _without_ explicitly using variables initially? We could try                   diffOp[y_] := Derivative[1, 0][y] + 3 Derivative[0, 1][y]      and then                   diffOp[g]     3 (-2 Sin[#1 + 2 #2] + #1^2 &) + (-Sin[#1 + 2 #2] + 2 #1 #2 &)      But now how does one use such a combination of pure functions of several variables so as to produce the same result as from `diff[g][x,y]`? The crux of the difficulty appears in the following simpler problem. Consider two functions of two variables:                   g1 = (#1^2 + #2) &         g2 = Cos[#1 #2] &      How can one produce the same result as, say,                   g1[x, y] + 3 g2[x, y]     (* x^2 + y + 3 Cos[x y] *)      directly from the functional linear combination `g1 + 3 g2` \-- by forming an expression of the form `oper[g1 + 3 g2][x, y]`? By contrast with the single-variable situation, where a simple `Through` would serve as the `oper',`Through` will _not_ work in the multi-variable situation here:                  Through[(g1 + 3 g2)[x, y]]     (* x^2 + y + (3 (Cos[#1 #2] &))[x, y] *)      A pure function embedded in that output. Note that a simple sum `g1 + g2` instead of the linear combination `g1 + 3 g2`, `Through` will work (just as it does for a single variable):                   Through[(g1 + g2)[x, y]]     (* x^2 + y + Cos[x y] *)


How to form a block-diagonal Matrix from a list of matrices?

like this: ![enter image description here](http://i.stack.imgur.com/3E6A8.jpg) I know join[...] works, but it is a bit troublesome for multiple matrices.I tried DiagonalMatrix[...], but DiagonalMatrix can only form matrix from a list of elements.


Direct sum of matrices

Is there a simple way (perhaps even a built-in function) that allows one to compute the direct sum of two square matrices?


How can I adjust matrices into the same ItemSize and aligned well in Notebook?

![enter image description here](http://i.stack.imgur.com/F2KWJ.png) I typed three matrices, but they are not aligned well, and the `Items` in one matrix are also not aligned well and with differenct `ItemSize`. How can I adjust them into the same `ItemSize`? Better is that I can click the buttons/menus to do the thing something like `align paragraph` in `writing assistant`. And I found the matrix typed is `GridBox`, so I can adjust them by options of Grid.


Is "MaxMessageCount" broken or is its function counter-intuitive?

As noted by kguler the Front End option: `MessageOptions -> "MaxMessageCount"` does not appear to have any affect on the number of times a Message is repeated before `General::stop` is issued and that particular Message is suppressed. I would like to know if supposed to have this effect but is broken, or if it does something else entirely. I cannot find any documentation for this Option, and I cannot find any examples of its use either here or in the MathGroup archives.


Errors in Compile

I defined a function               getCell[sp_, i_, j_, x_] := Block[{target, n, m, k, l, k2, l2, cells},       n = Dimensions[sp][[1]];       m = Dimensions[sp][[2]];       cells = {};       Do[        Do[         (* This is one neighbor *)         k2 = Mod[i + k, n, 1];         l2 = Mod[j + l, m, 1];         If[(k2 != i || l2 != j) && sp[[k2, l2]] == x,           AppendTo[cells, {k2, l2}]],         {l, -1, 1}],        {k, -1, 1}];       If[Dimensions[cells][[1]] != 0,        target = RandomSample[cells, 1][[1]],        (* The default, if none was found, is to return the cell itself,         just for convenience *)        target = {i, j}        ];       Return[target];       ]      `getCell` given a square matrix `sp` filled with Integers attempts to find a cell neighboring `[[i,j]]` that contains a value equal to `x`. If it finds such a cell, it returns the coordinates of that cell; if not, it returns the input coordinates `{i,j}`. I now wanted to compile `getCell` to try to speed it up, but when I do so by putting `Compile` around the function and inserting type definitions, I get several error messages:               Compile::cset: Variable cells of type {_Integer,1} encountered in assignment of type {_Integer,2}. >>          Compile::cpts: The result after evaluating Insert[cells,{k2,l2},-1] should be a tensor. Nontensor lists are not supported at present; evaluation will proceed with the uncompiled function. >>          Compile::cset: Variable target of type {_Integer,2} encountered in assignment of type {_Integer,0}. >>          Compile::cset: Variable target of type {_Integer,2} encountered in assignment of type {_Integer,1}. >>      Does anyone know what I might be doing wrong, and how I could get this simple function compiled?


What algorithm is Mathematica using for FirstPassageTimeDistribution[]?

What algorithm is _Mathematica_ 9 using for `FirstPassageTimeDistribution[]`? Is it attempting to use `PseudoInverse[]` on the Laplacian of the graph underlying the discrete Markov process?


Peirce's quincuncial projection

The Peirce quincuncial projection is the cartographic projection of a sphere onto a square. In short, I would like to see it implemented in _Mathematica_. Here is my code:               Clear[InversePeirceQuincunicalMapping];      InversePeirceQuincunicalMapping[x_Real, y_Real] :=       Module[{cn, m = 1/2, th, phi},             cn = JacobiCN[x 2 EllipticK[m] + I 2 y EllipticK[1 - m], m];             {th, phi} = {2 ArcTan[Abs[cn]], Arg[cn]};             {th, phi}]          zf[{th_, phi_}] := Cos[th]     xf[{th_, phi_}] := Sin[th] Cos[phi]     yf[{th_, phi_}] := Sin[th] Sin[phi]      The contours that correspond to the equation $\theta=\frac{\pi}{2}$, besides the expected tilted square, also includes the diagonal and anti-diagonal. This is not an artifact and can be proven. ![contour of inverse Peirce mapping](http://i.stack.imgur.com/IQF89.png) These lines make me suspect that I am not doing the projection the right way. I would be glad to see a prototype implementation of it in _Mathematica_. Thank you.


How do you draw a straight line with PolarPlot?

I can't figure how to draw a line with `PolarPlot`. A vertical line through a is $r \cos(\theta) = a$, so               PolarPlot[a/Cos[theta], {theta, -Pi, Pi}]      works. A horizontal line through b is $r \sin(\theta)=b$, so               PolarPlot[b/Sin[theta], {theta, -6, 6}]       works. (Using `{theta, -Pi, Pi}` doesn't work because of dividing by $\sin(0)=0$ I guess.) How do I draw a radial line with $\theta = \pi/3$? Should be a line with slope $\tan(\pi/3)$. Can it be done with `PolarPlot`? I guess not since you have to give a function of $r$.


iterate method to find roots

This code gives the roots (lambda-values) of `eq1` by using iteration.               eq1[n_, β_, λ_] := Hypergeometric1F1[1/4 (2 - λ/β), n + 1, β]     rootslist[n_Integer, k_Integer, β_] :=        Rest @ FoldList[FindRoot[eq1[n, #2, λ] == 0, {λ, #1}][[1, 2]] &          BesselJZero[n, k]^2, Range @ β]     Table[rootslist[n, 1, 30], {n, 0, 4}]      The table contains all the λ-values for each β from 1 to 30. Using this I want to know how to find a table with $\frac{\lambda}{\beta}$ values? For example, I have produced the following table > {6., 6.63583, 7.64905, 8.97767, 10.5495, 12.2936, 14.1498, 16.0735, 18.0349, > 20.0161, 22.0073, 24.0032, 26.0014, 28.0006, 30.0003, 32.0001, 34., 36., > 38., 40., 42., 44., 46., 48., 50., 52., 54., 56., 58., 60.}, for $n=0$. How can I get $\\{\frac{6.}{1}, \frac{6.63583}{2}, \frac{7.64905}{3}, \frac{8.97767}{4}, \frac{10.5495}{5}, \frac{12.2936}{6}, \frac{14.1498}{7}, \frac{16.0735}{8},\frac{ 18.0349}{9}, \frac{20.0161}{10}, \frac{22.0073}{11}, \frac{24.0032}{12}, \frac{26.0014}{13},\frac{ 28.0006}{14}, \frac{30.0003}{15},\frac{ 32.0001}{16}, \frac{34.}{17}, \frac{36.}{18}, \frac{38.}{19}, \frac{40.}{20}, \frac{42.}{21}, ..., \frac{60.}{30}\\}\text{?}$


How to solve two non-linear equations in two variables

I am a new user of _Mathematica_. I have the following non-linear equations in two variables: ![enter image description here](http://i.stack.imgur.com/hGz6z.png) How can I solve this system with _Mathematica_?


How do you add options to a function that is being mapped?

Simple example: Normally: `ListPlot[list, Joined->True]` If I want to map `ListPlot` how do I keep the `Joined` option? thanks.


Eliminate some temporaries from a set of equations

I have a long set of equations, mostly obtained by introducing physics related quantities which stand for some kind of temporary variables:               eqns = {       lx == Log[10., en] + 0.3,       xmax == 0.849 + 0.0537 lx,       nmu == 1.37 en^-0.04,       fem == ((s - xmax + 0.689)/0.802)^(0.802/0.113) Exp[(0.113 - s + xmax)/0.113],       fmu == ((s - xmax + 0.228)/0.573)^(0.573/1.267) Exp[(0.345 - s + xmax)/1.267],       cic == 22.3 fem + 15.6 nmu fmu,       en == (s1000/cic)^(1/0.97)     };      This is 7 equations with 9 variables. I would like to eliminate all of the variables except for `{en, s, s1000}` and then obtain the solution in the form `en[s, s1000]`. I tried Solve, Reduce, Eliminate, tried taking them pairwise etc. but while there are some results for equation pairs, for the whole system Mathematica just runs for ever... For example, while this works as expected               Eliminate[eqns[[{1, 2}]], lx]      giving `0.86511 + 0.0233216 Log[en] == xmax`, trying one more               Eliminate[eqns[[{1, 2, 4}]], {lx, xmax}]      returns a result which imho does not make any sense. Looking around StackExchange one finds Mathematica (at least in v9) has a hidden 3rd argument for elimination               Solve[eqns[[{1, 2}]], xmax, lx]      which gives a warning that `lx` is not a proper domain specification and that `lx` will be used for elimination. Unfortunately, trying this trick on three equations               Solve[eqns[[{1, 2, 4}]], fem, {lx, xmax}]      returns an empty list while we would like to see a rule for `fem` expressed in terms of `en` and `s`. Please, help! I remember in older versions `Solve` used to be more flexible and more like a universal tool for solving. How particularly equation-solving cases are divided into usage of `Solve`, `Eliminate`, `Reduce` etc. is also not very clear, neither from the Help nor from tutorials, mostly since too simple examples are used as illustrations. A word from an expert on this subject is very welcome...


How can I use Pick[] to select items in one list when a value in a corresponding list is $\leq$ some value?

Imagine I have two list:               List1 = {0, 1, 0.6, 0.5, 1.2, 0.4};     List2 = {"a","b","c","d","e","f"};      How can I use Pick to return a third list consisting of items in List2 that have a array position corresponding to an array position with a value $\leq N$ in the first list? Here, for example, for $N = 0.5$ we should have:               List3 = {"a", "d", "f"}


Working with functions

I am required to write a function that takes a function as a parameter.               moveTwoPoints[function_, {sliderMin_, sliderMax_}] :=       DynamicModule[       {sliderValue = sliderMin,        plot},       f[x_] := function;       Column[        {     (*Display slider *)     Slider[Dynamic[sliderValue], {sliderMin, sliderMax}],     (*Display updating slider value *)     Dynamic[sliderValue],     (*Display the graph with points moving*)     Dynamic[      Show[       Plot[f[x], {x, sliderMin, sliderMax}],        Graphics[        {Red, PointSize[Large], Point[{sliderValue, f[sliderValue]}],          Green, PointSize[Large], Point[{0, f[sliderValue]}]             }            ]           ]          ]         }        ]       ]      The problem I am running into is the fact that when I try f[sliderValue] is won't return a point just the value of function. Is there a way I can manipulate this function?


How to plot an Operating Characteristic Curve using Hypergeometric distribution?

I"m trying to plot an OC curve (y-axis Probability of acceptance, x-axis Lot Percent Defective) and there should be a way to plot using a hypergeometric distribution.               In[117]:= NProbability[x <= 0,       x \[Distributed] HypergeometricDistribution[8, 7, 500]]          Out[117]= 0.89262      is great for one point. The 7 in the distribution is the number defective in the lot of 500, I'd like to plot this for 1, 2, etc. Then alter the x-axis labels to represent the percent defective in the lot of 500, .1%, 1%, 2%, etc.... I can get the individual values as above, yet not able to get a plot. I can do this using `PoissonDistribution`               Plot[{N[Probability[x <= 0,          x \[Distributed] PoissonDistribution[13*lpd]]],        N[Probability[x <= 0,          x \[Distributed] PoissonDistribution[8*lpd]]]}, {lpd, 0, .5}]      which assumes a very large lot size. I have the situation with smaller lot sizes and using hypergeometric is the right way to do the calculation for the OC curve - just not able to sort out the plotting. Any suggestions? cheers, Fred


How to make the imaginary part of a +0. I zero globally?

Values like a +0. I are really annoying. Answers from How to reduce expressions with complex coefficients in the form of a+0.*I？ Is there a way to globally set when to treat a very small number as zero? give me some clue, but I find `$Post = Chop[#, 10^-16] &;` doesn't work, for example :               Print[MatrixForm[FourierDCT[FourierDCT[{0, 0, 1, 0, 0}, 2], 3]]]      gives (0. -5.55112*10^-17 1. 1.38778*10^-17 1.38778*10^-17 ), which means the small digits still exist.


Why is arithmetic faster for inexact arithmetic?

I have been trying to compute eigenvalues of a rather sizable matrix `A`, about $500 \times 500$ (but sparse). I asked Mathematica to compute `Eigenvalues[A]`, and left it to work. After a night of computation, Mathematica still failed to produce the answer. Just out of curiousity, I tried to see what happens if I replace `A` by it's numeric approximation (before, `A` had integer entries, hence exact). (I didn't quite expect it to make a difference, but I was trying some random things). Much to my surprise, the answer appeared immediately. Hence my question: How does it happen that Mathematica produces the answer so much faster for inexact input? To what extent can this output be trusted?


What's wrong with my calculation of the expectation of the Laplace distribution?

f2[x_, mu2_, sigma2_] =  1/Sqrt[2*sigma2^2]*Exp[-Sqrt[2]*Abs[(x - mu2)/sigma2]]          Integrate[x*f2[x, mu, sigma], {x, -Infinity, Infinity},  Assumptions -> sigma > 0]      I am pretty sure that the above should produce `mu`, but it doesn't. What's wrong with it? I did the same thing in Sage, and it worked all right.


how to Compile user-defined function like this

the following function can be compiled successfully               Clear[mat]         mat = Compile[{e, kx, {ii, _Integer}, {label, _Integer}, η},            Inverse[{{e - I η,               -E^(-I kx), 0, -E^(((I kx)/2)), 0, 0, 0, 0, 0, 0, 0, 0, 0,                0}, {-E^(I kx), e - I η, -E^(-((I kx)/2)), 0, 0, 0, 0, 0,                0, 0, 0, 0, 0, 0}, {0, -E^(((I kx)/2)),                e - I η, -E^(-I kx), 0, -E^(((I kx)/2)), 0, 0, 0, 0, 0, 0,                0, 0}, {-E^(-((I kx)/2)), 0, -E^(I kx),                e - I η, -E^(-((I kx)/2)), 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0,                0, 0, -E^(((I kx)/2)), e - I η, -E^(-I kx),                0, -E^(((I kx)/2)), 0, 0, 0, 0, 0, 0}, {0, 0, -E^(-((I kx)/2)),                0, -E^(I kx), e - I η, -E^(-((I kx)/2)), 0, 0, 0, 0, 0, 0,                0}, {0, 0, 0, 0, 0, -E^(((I kx)/2)), e - I η, -E^(-I kx),                0, -E^(((I kx)/2)), 0, 0, 0, 0}, {0, 0, 0, 0, -E^(-((I kx)/2)),                0, -E^(I kx), e - I η, -E^(-((I kx)/2)), 0, 0, 0, 0,                0}, {0, 0, 0, 0, 0, 0, 0, -E^(((I kx)/2)),                e - I η, -E^(-I kx), 0, -E^(((I kx)/2)), 0, 0}, {0, 0, 0,                0, 0, 0, -E^(-((I kx)/2)), 0, -E^(I kx),                e - I η, -E^(-((I kx)/2)), 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0,                0, 0, -E^(((I kx)/2)), e - I η, -E^(-I kx),                0, -E^(((I kx)/2))}, {0, 0, 0, 0, 0, 0, 0, 0, -E^(-((I kx)/2)),                0, -E^(I kx), e - I η, -E^(-((I kx)/2)), 0}, {0, 0, 0, 0,                0, 0, 0, 0, 0, 0, 0, -E^(((I kx)/2)),                e - I η, -E^(-I kx)}, {0, 0, 0, 0, 0, 0, 0, 0, 0,                0, -E^(-((I kx)/2)), 0, -E^(I kx), e - I η}}][[            2*(ii - 1) + label, 2*(ii - 1) + label]], CompilationTarget -> "C"]      as you can see the function calc the one of the matrix element of the inverse matrix. the result of the above code is               CompiledFunction[{e,kx,ii,label,\[Eta]},Block[{Compile`$498,Compile`$502,Compile`$503,Compile`$507,Compile`$508,Compile`$509,Compile`$510,Compile`$504,Compile`$505,Compile`$506,Compile`$514,Compile`$515,Compile`$516,Compile`$511,Compile`$512,Compile`$513,Compile`$518,Compile`$519,Compile`$520},Compile`$498=I \[Eta];Compile`$502=-Compile`$498;Compile`$503=e+Compile`$502;Compile`$507=1/2;Compile`$508=I kx Compile`$507;Compile`$509=E^Compile`$508;Compile`$510=-Compile`$509;Compile`$504=-I kx;Compile`$505=E^Compile`$504;Compile`$506=-Compile`$505;Compile`$514=-Compile`$508;Compile`$515=E^Compile`$514;Compile`$516=-Compile`$515;Compile`$511=I kx;Compile`$512=E^Compile`$511;Compile`$513=-Compile`$512;Compile`$518=ii-1;Compile`$519=2 Compile`$518;Compile`$520=Compile`$519+label;Inverse[{{Compile`$503,Compile`$506,0,Compile`$510,0,0,0,0,0,0,0,0,0,0},{Compile`$513,Compile`$503,Compile`$516,0,0,0,0,0,0,0,0,0,0,0},{0,Compile`$510,Compile`$503,Compile`$506,0,Compile`$510,0,0,0,0,0,0,0,0},{Compile`$516,0,Compile`$513,Compile`$503,Compile`$516,0,0,0,0,0,0,0,0,0},{0,0,0,Compile`$510,Compile`$503,Compile`$506,0,Compile`$510,0,0,0,0,0,0},{0,0,Compile`$516,0,Compile`$513,Compile`$503,Compile`$516,0,0,0,0,0,0,0},{0,0,0,0,0,Compile`$510,Compile`$503,Compile`$506,0,Compile`$510,0,0,0,0},{0,0,0,0,Compile`$516,0,Compile`$513,Compile`$503,Compile`$516,0,0,0,0,0},{0,0,0,0,0,0,0,Compile`$510,Compile`$503,Compile`$506,0,Compile`$510,0,0},{0,0,0,0,0,0,Compile`$516,0,Compile`$513,Compile`$503,Compile`$516,0,0,0},{0,0,0,0,0,0,0,0,0,Compile`$510,Compile`$503,Compile`$506,0,Compile`$510},{0,0,0,0,0,0,0,0,Compile`$516,0,Compile`$513,Compile`$503,Compile`$516,0},{0,0,0,0,0,0,0,0,0,0,0,Compile`$510,Compile`$503,Compile`$506},{0,0,0,0,0,0,0,0,0,0,Compile`$516,0,Compile`$513,Compile`$503}}][[Compile`$520,Compile`$520]]],-CompiledCode-]      I want to speed it a little, So I defined a function                Clear[invmat]     invmat[m_?MatrixQ, i_, j_] :=       Det[Drop[m, {j}, {i}]]*(-1)^(i + j)/Det[m]      which gives (i,j)th element of the inverse matrix of m directly with calc the whole matrix inverse. and then I compile the function below               Clear[mat2]     mat2 = Compile[{e, kx, {ii, _Integer}, {label, _Integer}, η},        invmat[{{e - I η,          -E^(-I kx), 0, -E^(((I kx)/2)), 0, 0, 0, 0, 0, 0, 0, 0, 0,           0}, {-E^(I kx), e - I η, -E^(-((I kx)/2)), 0, 0, 0, 0, 0, 0,           0, 0, 0, 0, 0}, {0, -E^(((I kx)/2)), e - I η, -E^(-I kx),           0, -E^(((I kx)/2)), 0, 0, 0, 0, 0, 0, 0, 0}, {-E^(-((I kx)/2)),           0, -E^(I kx), e - I η, -E^(-((I kx)/2)), 0, 0, 0, 0, 0, 0,           0, 0, 0}, {0, 0, 0, -E^(((I kx)/2)), e - I η, -E^(-I kx),           0, -E^(((I kx)/2)), 0, 0, 0, 0, 0, 0}, {0, 0, -E^(-((I kx)/2)),           0, -E^(I kx), e - I η, -E^(-((I kx)/2)), 0, 0, 0, 0, 0, 0,           0}, {0, 0, 0, 0, 0, -E^(((I kx)/2)), e - I η, -E^(-I kx),           0, -E^(((I kx)/2)), 0, 0, 0, 0}, {0, 0, 0, 0, -E^(-((I kx)/2)),           0, -E^(I kx), e - I η, -E^(-((I kx)/2)), 0, 0, 0, 0, 0}, {0,           0, 0, 0, 0, 0, 0, -E^(((I kx)/2)), e - I η, -E^(-I kx),           0, -E^(((I kx)/2)), 0, 0}, {0, 0, 0, 0, 0, 0, -E^(-((I kx)/2)),           0, -E^(I kx), e - I η, -E^(-((I kx)/2)), 0, 0, 0}, {0, 0, 0,           0, 0, 0, 0, 0, 0, -E^(((I kx)/2)), e - I η, -E^(-I kx),           0, -E^(((I kx)/2))}, {0, 0, 0, 0, 0, 0, 0, 0, -E^(-((I kx)/2)),           0, -E^(I kx), e - I η, -E^(-((I kx)/2)), 0}, {0, 0, 0, 0, 0,           0, 0, 0, 0, 0, 0, -E^(((I kx)/2)),           e - I η, -E^(-I kx)}, {0, 0, 0, 0, 0, 0, 0, 0, 0,           0, -E^(-((I kx)/2)), 0, -E^(I kx), e - I η}},         2*(ii - 1) + label, 2*(ii - 1) + label], CompilationTarget -> "C"]      **But`mat2` cannot be compiled because the output is the same. I think at least it should compile the matrix variable in `invmat`** the output of `mat2` is               CompiledFunction[{e,kx,ii,label,η},invmat2[{{e-I η,-E^(-I kx),0,-E^(((I kx)/2)),0,0,0,0,0,0,0,0,0,0},{-E^(I kx),e-I η,-E^(-(1/2) (I kx)),0,0,0,0,0,0,0,0,0,0,0},{0,-E^(((I kx)/2)),e-I η,-E^(-I kx),0,-E^(((I kx)/2)),0,0,0,0,0,0,0,0},{-E^(-(1/2) (I kx)),0,-E^(I kx),e-I η,-E^(-(1/2) (I kx)),0,0,0,0,0,0,0,0,0},{0,0,0,-E^(((I kx)/2)),e-I η,-E^(-I kx),0,-E^(((I kx)/2)),0,0,0,0,0,0},{0,0,-E^(-(1/2) (I kx)),0,-E^(I kx),e-I η,-E^(-(1/2) (I kx)),0,0,0,0,0,0,0},{0,0,0,0,0,-E^(((I kx)/2)),e-I η,-E^(-I kx),0,-E^(((I kx)/2)),0,0,0,0},{0,0,0,0,-E^(-(1/2) (I kx)),0,-E^(I kx),e-I η,-E^(-(1/2) (I kx)),0,0,0,0,0},{0,0,0,0,0,0,0,-E^(((I kx)/2)),e-I η,-E^(-I kx),0,-E^(((I kx)/2)),0,0},{0,0,0,0,0,0,-E^(-(1/2) (I kx)),0,-E^(I kx),e-I η,-E^(-(1/2) (I kx)),0,0,0},{0,0,0,0,0,0,0,0,0,-E^(((I kx)/2)),e-I η,-E^(-I kx),0,-E^(((I kx)/2))},{0,0,0,0,0,0,0,0,-E^(-(1/2) (I kx)),0,-E^(I kx),e-I η,-E^(-(1/2) (I kx)),0},{0,0,0,0,0,0,0,0,0,0,0,-E^(((I kx)/2)),e-I η,-E^(-I kx)},{0,0,0,0,0,0,0,0,0,0,-E^(-(1/2) (I kx)),0,-E^(I kx),e-I η}},2 (ii-1)+label,2 (ii-1)+label],-CompiledCode-]      So how to Compile `mat2`?


why there is a small imaginary part

I encountered a problem. I have a eigenvector `eigvsI[1]`               eigvsI[1]={0.0161028 - 0.0119647 I, 0.111551 - 0.0828846 I, 0.20484 - 0.1522 I,      0.249467 - 0.185359 I, 0.28268 - 0.210037 I,      0.301895 - 0.224314 I, -0.190871 + 0.141821 I, -0.271275 +      0.201562 I, -0.244686 + 0.181807 I, -0.204743 +      0.152128 I, -0.148422 + 0.11028 I, -0.0281275 + 0.0208993 I}      and a hermite matrix `hI[1]`                   hI[1]={{0, Sqrt[5]/2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {Sqrt[5]/2, 0, Sqrt[2],     0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, Sqrt[2], 0, 3/2, 0, 0, 0, 0, 0, 0,      0, 0}, {0, 0, 3/2, 0, Sqrt[2], 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, Sqrt[     2], 0, Sqrt[5]/2, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, Sqrt[5]/2, 0, 0,      0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, Sqrt[5]/2, 0, 0, 0, 0}, {0, 0,     0, 0, 0, 0, Sqrt[5]/2, 0, Sqrt[2], 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0,      Sqrt[2], 0, 3/2, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 3/2, 0, Sqrt[2],      0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, Sqrt[2], 0, Sqrt[5]/2}, {0, 0, 0, 0,     0, 0, 0, 0, 0, 0, Sqrt[5]/2, 0}}      theoretically               Conjugate[eigvsI[1]].hI[1].eigvsI[1]      should be Real number. But _MMA_ gives               -0.253172 - 8.00544*10^-18 I      where does this small imaginary part come from? On the other hand,               Conjugate[eigvsI[1]].eigvsI[1]      gives perfect zero imaginary part               0.811081 + 0. I


A question about transforming one List into two Lists with additional requirements

Background: I create geometric patterns by applying many linear transformations on geometries, I need functions to weed out the exponentially increasing number of ( unnecessary ) points involved which slow down the production of Graphics code. The problem: Suppose I have the following array of arrays, for example two 2D vectors, a 2-by-2 matrix and one 3D vector in an array as follows: This format is not fixed however. ( Originates from reading data stored in Excel which can be 'dirty'. )                 { {1,2},{1,3}, {{1,0},{0,1}}, {10,20,30} } This format is invalid.       ( Because it contains {10,20,30} , a 3D vector at the lowest level. )            { {1,2},{1,3}, {{1,0},{0,1}}, {1,2} } This format is valid       ( Because it contains only 2-D vectors at the lowest level, note the 2-by-2 matrix )      I want to replace the valid array with:                 { {1,2},{1,3},{1,0},{0,1} }        ( a list of 2D vectors. )       { 1, 2, {3,4}, 1 }       a list with the position of the row vectors in the list above.      Key part of the problem =>: Note that (1,2) is stored only once in the first list while it occurs twice in the original array. <= Ideally I seek a validQ function that validates the input and a toGraph function that splits a valid row into two new rows. ( Although not a Graph Theory problem, there are similarities. I attempt to make the geometric pattern independent from its ( Cartesian ) coordinates. ) A complication is that the numbers are real ( square roots ) or involve Pi, and / or originate from spreadsheet calculations. Rounding or cutting to two places behind the decimal point is not a problem. My attempts to solve this involved Map and Position, but my attempts failed, I can show no working snippet to start with. I hope that the example data suffices. **Question: Is there a clean functional style code to tackle this problem ?**


How to create a composite function from a variable number of components?

Background of the problem: A patient takes a drug every $X$ hours with a half- life of $Y$ hours. How much of the drug will be (exactly) in his system after $h$ hours? For $X=24$, and $Y=24$ I made the following function showing the concentration of the drug for the first 96 hours.                Clear[m]      m[h_] := Exp[-(h/48)] /; h < 24      m[h_] := Exp[-(h/48)] + Exp[-((h - 24)/48)] /; ( h >= 24 && h < 48)      m[h_] := Exp[-(h/48)] + Exp[-((h - 24)/48)] +           Exp[-((h - 48)/48)] /; ( h >= 48 && h < 72)      m[h_] := Exp[-(h/48)] + Exp[-((h - 24)/48)] + Exp[-((h - 48)/48)] +          Exp[-((h - 72)/48)] /; ( h >= 72 && h < 96)      m[h_] := Exp[-(h/48)] + Exp[-((h - 24)/48)] + Exp[-((h - 48)/48)] +          Exp[-((h - 72)/48)] + Exp[-((h - 96)/48)] /; ( h >= 96 && h < 120)      Plot[m[h], {h, 0, 120}, AxesOrigin -> {0, 0}]      This is exactly what I want. But now I want to optimize the code, so that I can also `Plot[]` for periods up to several weeks. Question: How can I rewrite `m[h]` such that there will only be one line involved, i.e. add the `Exp[-((h - 72)/48]` type of terms automatically?


Cropping a Voronoi diagram

Someone know how can I get the correct crop of this Voronoi image using `RegionFunction`? ![Voronoi Diagram](http://i.stack.imgur.com/K6ATs.png) As you can see, there is a lot of undesired white regions inside the left polygon. Some clue on how to correct it? Here is the code using `PointInPoly` and `RegionFunction`:               PointInPoly[{x_, y_}, poly_List] :=       Module[{i, j, c = False, npol = Length[poly]},        For[i = 1; j = npol, i <= npol, j = i++,         If[((((poly[[i, 2]] <= y) && (y <                   poly[[j, 2]])) || ((poly[[j, 2]] <= y) && (y <                   poly[[i, 2]]))) && (x < (poly[[j, 1]] -                   poly[[i, 1]])*(y - poly[[i, 2]])/(poly[[j, 2]] -                    poly[[i, 2]]) + poly[[i, 1]])), c = \[Not] c];];       c]          pts=MapIndexed[Flatten[{##}]&,RandomReal[{0,1},{20,2}]];          poli={0.5,0.5}+#&/@Table[0.3{Cos[2\[Pi] k/6],Sin[2\[Pi] k/6]},{k,0,6}];     opt={ColorFunction->Hue         ,InterpolationOrder->0         ,ImageSize->500         ,PlotRange->{{0,1},{0,1}}         ,Epilog->{PointSize[.01],Point[Most/@pts],Line[poli]}         };          g1=ListDensityPlot[pts         ,Sequence@@opt         ,RegionFunction->Function[{x,y,z},PointInPoly[{x, y}, poli]]         ];          g2=ListDensityPlot[pts         ,Sequence@@opt         ];          GraphicsRow@{g1, g2}      Important point, I can't use image manipulate functions. What I really need is the list of polygons inside the cropped area. I get it using `g1[[1]]`


Using perpendicular offsets in FindFit

I want to use perpendicular offsets in the built-in `FindFit` function. Are there any possible ways or do I have to code everything by myself?


How to save animation in mp4 format instead of avi?

I'd like to save `Manipulate[]` output so that I can embed an mp4 in my pdf document (using the media9 latex package). I've done this successfully in the past by manually constructing a table of Graphics objects, and then saving that to .avi format. That .avi can then be converted to .mp4 by ffmpeg. A cleaner way to do this is pointed out in this answer but the .avi file that is generated causes ffmpeg to choke:               Output #0, mp4, to 'MyAutorun.mp4':         Stream #0:0: Video: h264, yuv420p, 412x345, q=-1--1, 90k tbn, 15 tbc     Stream mapping:       Stream #0:0 -> #0:0 (rawvideo -> libx264)     Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as     bit_rate, rate, width or height      I'm not really sure what this tool is complaining about, but wondered if there was a way to avoid using external tools to do this conversion and just export the animation data in mp4 format directly from Mathematica?


using Mathematica's matrix multiplication in C++

Is there any way that I can utilize Mathematica's matrix multiplication in a C++ program? I'm making a 3D graphics engine (for class) in C++ and I would really like to use Mathematica for all of my math. Thank you. I have Mathematica 8, and Visual Studio 2010 that I am using to develop with.


How can I mix the behaviors of StringReplace and ReplaceAll in a single rule?

I'm trying to take a list of the form `{ {"65 + 3 months", 75}, {"65 + 4 months", 75.1} }`, and transform the string part to a number such as 65.25 or 65.333, respectively. What I really want to do is something like:               list = { {"65 + 3 months", 75}, {"65 + 4 months", 75.1} };     list /. {y:NumberString~~" + "~~m:NumberString,p_}:>{y+m/12,p}      That form doesn't work, I believe, because I need to use StringReplace to cause the `StringExpression` to do any matching. So since I can't make that work, I tried something like:               list /.{ys_String, p_} :>         {StringReplace[ys, y:NumberString~~" + "~~m:NumberString~~" months":>y+m/12], p}      But in that case, I'm getting `{ { StringExpression[3/12 + 65], 75}, {StringExpression[4/12 + 65], 75.1} }`, and have no idea where the `StringExpression` heads came from in that case or what to do with them without making my expression uglier and even further from just describing the patterns that I'm trying to transform from/to. Is there a simple way to compose a pattern that does some string matching and some structure matching? If not, what's the best way to write the `StringReplace` version for the problem above.


Random Geometric Graphs

I'm trying to implement an application which uses random geometric graphs in Mathematica, but it seems Mathematica lacks the functionality. I need the following functionalities:   1. Generate a set of uniformly distributed vertices on $[0,1]^2$ with certain properties (this really helps)   2. Add an edge in between the vertices that are closer than a given radius $d$   3. Display the graph (this is not like a regular graph display since the location of each vertex is important)   4. Generate some random source-destination pairs and find the shortest path between them   5. Highlight the path on the displayed graph. Note that, Mathematica has all of the required functionality for non-geometric graphs. However, when it comes to the geo-graphs, the functionality is quite useless. Here is the code I already have:               Module[      {nOld, kOld, v, edges},      nOld = -1;      kOld = -1;      Manipulate[       If[        n != nOld,        v = RandomReal[{0, 1}, {n, 2}];        nOld = n        ];            edges =         Select[Flatten[Table[{a, b}, {a, v}, {b, v}],           1], (#[[1, 1]] > #[[2, 1]] &&             EuclideanDistance[#[[1]], #[[2]]] < d) &];            Graphics[        {Red, Point[v],         Blue, Thin, Line /@ edges         }        ]       ,       {n, 10, 100, 10},       {d, 0, 1}       ]      ]      ![Mathematica graphics](http://i.stack.imgur.com/Fw8Rz.png) It generates and shows the random graph. But generating and highlighting the shortest paths are not so simple since I don't have any data-structure to keep the graph. What is the best way to implement a geo-graph in Mathematica? `Sparse matrices` or `System`Graph` or `Combinatorica`Graph`? Can I use some of the built-in graph functions of Mathematica to implement geo-graphs?


Exporting images as .avi

Here's a list of images:               images = Table[ExampleData[i], {i, ExampleData["TestImage"]}];      And according to the reference "Export exports a list of graphics, images, or arbitrary expressions, taking each element to be an animation frame." This is on the reference page for .avi. However,               Export["animation.avi", images]      causes this: > Export::errelem: "The Export element !(\"ImageList\") contains a malformed > data structure and could not be exported to !(\"AVI\") format." What's the problem? (Export["film.avi", ListAnimate[images]] works, but I want to know why the above doesn't work...)


LibraryFunctionLoad hangs under Windows

I'm running the Wolfram Finance Package version of Mathematica 8, under Windows 7 Professional. Any time I attempt to call `LibraryFunctionLoad`, the Kernel seems to hang; I have to kill it (Evaluation->Quit Kernel->Local) in order for any further input in the notebook to be taken into account. (When I kill it, it leaves an orphaned `java.exe` still running, which I have to kill using the Task Manager.) I originally thought it might be something to do with the way I generated the DLL, but even when giving it the name of an non- existent file, it hangs (rather than giving an error message). I was able to load and execute my program under Linux (with a demo version of Mathematica 8). What is different, and why don't I at least get an error message when the file doesn't exist? Also, I get similar symptoms when I use a `\` as a path separator, rather than a `/`, even for simpler operations like               Join[$LibraryPath, {"C:\Users\jkanze"}]