Function to preserve evaluation on display?

I'm looking for a function that applies the following behavior to an expression: -When the expression is given as the full input, or as part of a function that cannot be evaluated, it remains in unevaluated form. -When the expression is used for a function, it is evaluated.  `Defer[]` won't evaluate it in a function. `Unevaluated[]` leaves itself in evaluated when used directly as output. Essentially, I need a function `F[]` that will output the following:   * `F[1-1/2]` outputs `1-1/2`, NOT `1/2`   * `Times[F[1-1/2],5]` outputs `5/2`, NOT `(1-1/2)5`   * `Times[F[1-1/2],x]` outputs `(1-1/2)x`, NOT `x/2` If the solution only works for a specific internal expression, that works, because I only need this for one function.


How to get the total intensity of a certain frequency range in an audio file?

Does anyone know how to get the total intensity of a certain frequency range in an audio file? Let's say an audio file has a frequency range from 0Hz to 20KHz, and I want to extract the total intensity of every 100Hz, then I can have the intensity of 0 to 100Hz, 100 to 200Hz....etc.


Modify this code using Module and While

I have written a recursive function and would like to re-write the code using **Module** _AND_ **While** to compare the timings. Here is my recursive function for f[n], where 6 n f[n] = f[n-1] + n! for n>0 and f[0]=7.               Clear[f]       f[0] = 7;       f[n_Integer /; n>0] := f[n-1]/(6 n) + n!        Now I want to write it using **Module** AND **While** , I could write using **Module** ONLY, but I am struggling when I need to combine it using **While** loop.   Here is my code using **Module** only:                fm[n_] := Module[{f}, f[0] = 7; f[i_] := f[i-1]/(6 i) + i!; f[n]]      Then if I want to use **Module** AND **While** , I get into trouble, here is my code:                fm[n_] := Module[{fw}, While[n>=0, fw[0] = 7; fw[i_] := fw[i-1]/(6 i); fw[n] ] ]        The code is not working and I couldn't figure out where does it go wrong. Do I still need to write recursively inside the While loop? And how could I write the correct code?   Any detailed explanations are greatly appreciated. Thanks in advance!


Pulling out common terms when simplifying complicated equations

I have a complicated expression where common terms are apparent but Simplify[] and FullSimplify[] don't appear able, even with plenty of assumptions added, to reduce down to a simpler form with common terms recognised so that I can give them a symbol and simplify the expressions acordingly. A simpler example which demonstrates is               h (140 + Current -         lastU1 + (lastV1 +            1/2 h (140 + Current - lastU1 + (5 + 0.04 lastV1) lastV1)) (5 +            0.04 (lastV1 +               1/2 h (140 + Current - lastU1 + (5 + 0.04 lastV1) lastV1))))      with obvious common terms being               140 + Current - lastU1   -> Alpha     (5 + 0.04 lastV1) lastV1 -> Beta      With these and one further common term which contains them both recognised               (lastV1 + 1/2 h (Alpha + Beta)) -> Gamma      this expression can be reduced to               h (Alpha + Gamma (5 + 0.04` Gamma))      I have played with Factor[], Collect[] and many others but nothing seems to do what I need. I am sure that Mathematica is capable of doing what I am looking for, so I am asking the experts here for tips for how best to go about it. As a matter of interest, these expressions are going to be compiled into C eventually and I have found this to produce output of interest in terms of structuring the algebraic reduction               Experimental`OptimizeExpression[ expression , OptimizationLevel -> 2]      but I would still like more control over the manipulation before I get to this stage. Many thanks in advance Michael


Tricky selection of elements based on their position

I need to make a list of some elements from a 4D array with dimensions 4x4x4x4. I need to select the elements based on their position in the following way: name an element e(x,y,z,w); I need all the elements where x≥y and z≥w. This basically excludes all the upper triangular part of each submatrix and all the submatrices in the upper triangular part of the tensor. The array in question is this one:               b={{{{12, 0, 0, 0}, {-18 Sqrt[2], 0, 0, 0}, {12 Sqrt[3], 0, 0, 0}, {-6,      0, 0, 0}}, {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0,      0}}, {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0,      0}}, {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0,      0}}}, {{{-18 Sqrt[2], 0, 0, 0}, {84, 0, 0, 0}, {-48 Sqrt[6], 0, 0,      0}, {54 Sqrt[2], 0, 0, 0}}, {{0, 0, 0, 0}, {0, 60, 0,      0}, {0, -90, 0, 0}, {0, 18 Sqrt[10], 0, 0}}, {{0, 0, 0, 0}, {0, 0,      0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}, {{0, 0, 0, 0}, {0, 0, 0,      0}, {0, 0, 0, 0}, {0, 0, 0, 0}}}, {{{12 Sqrt[3], 0, 0,      0}, {-48 Sqrt[6], 0, 0, 0}, {276, 0, 0, 0}, {-186 Sqrt[3], 0, 0,      0}}, {{0, 0, 0, 0}, {0, -90, 0, 0}, {0, 240, 0,      0}, {0, -90 Sqrt[10], 0, 0}}, {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0,      168, 0}, {0, 0, -84 Sqrt[6], 0}}, {{0, 0, 0, 0}, {0, 0, 0, 0}, {0,      0, 0, 0}, {0, 0, 0, 0}}}, {{{-6, 0, 0, 0}, {54 Sqrt[2], 0, 0,      0}, {-186 Sqrt[3], 0, 0, 0}, {648, 0, 0, 0}}, {{0, 0, 0, 0}, {0,      18 Sqrt[10], 0, 0}, {0, -90 Sqrt[10], 0, 0}, {0, 600, 0, 0}}, {{0,      0, 0, 0}, {0, 0, 0, 0}, {0, 0, -84 Sqrt[6], 0}, {0, 0, 504,      0}}, {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 360}}}}      I tried in many ways but I can't figure it out. Thanks in advance.


Integer partitions in all orderings

I want to partition an integer into $k$ integers all possible orderings. This can be done in the following way               integerPartitions[n_, {k_}] := Select[FrobeniusSolve[Table[1, {k}], n], FreeQ[#, 0] &]      For example,               integerPartitions[4, {2}]      gives               {{1, 3}, {2, 2}, {3, 1}}      But this is very slow if the partition number is large as compared to `IntegerPartitions`, which gives partitions in reverse lexicographic order. For instance, `integerPartitions[60, {5}]` will take more than 4 seconds in my laptop in contrast to 0 seconds of `IntegerPartitions[60, {5}]`. So my question is: what would be the most efficient Mathematica code for this problem?


How to express an integer number in English words?

How do I convert a number to a readable string? I would like to implement a function, `inWords[]`,                   inWords[n_]:= ?      which should return a readable English string. A few expected results:               inWords[123456]     " one hundred twenty three thousand four hundred fifty six"          inWords[1000000001]     "one billion one"          inWords[123456789123456789]          "one hundred twenty three quadrillion four hundred fifty six trillion \     seven hundred eighty nine billion one hundred twenty three million \     four hundred fifty six thousand seven hundred eighty nine"      On the other hand, how do I implement a function to do exactly the reverse of this? That is, to read and parse string and convert the string to a number? **Note** The Stack Overflow post _Express a number using words in Mathematica_ tries to answers second part of my question. However, it uses `WolframAlpha` which expects one to be connected to the Internet, and there are restrictions on number of calls made so, a non- WolframAlpha answer would be much nicer.


Efficient way to solve equal sums $x_1^k+x_2^k+\dots+x_5^k=y_1^k+y_2^k+\dots+y_5^k$ with Mathematica?

I need to solve the system of equations, call it $S_1$, in the integers $$x_1x_2x_3x_4x_5 = y_1y_2y_3y_4y_5$$ $$x_1^k+x_2^k+\dots+x_5^k=y_1^k+y_2^k+\dots+y_5^k,\;\; k= 2,4,6$$ I used a very primitive code using _KSubsets_ [], _Table_ [], _Sort_ [], and _Do_ [], and with $x_i, y_i\le 50$ found one, $$2\cdot16\cdot25\cdot45\cdot48 =3\cdot9\cdot32\cdot40\cdot50$$ $$2^k+16^k+25^k+45^k+48^k = 3^k+9^k+32^k+40^k+50^k$$ Using this single example, I managed to find a parametrization, so $S_1$ has an infinite number of primitive solutions. However, I would like to find other small solutions to $S_1$, perhaps $x_i, y_i\le 300$, (which hopefully belongs to other families). Is there an efficient way to do it with _Mathematica_? The code I used takes forever if I extend the range > 50. :( P.S. The system $S_1$ leads to an $11$th degree identity, in case one is wondering why I am interested in it.


Converting polygon to graph in V7

I've unsuccessfully tried many ways of converting polygon points into a graph using _Mathematica_ 7, and I am frustrated. I looked at this post, but it doesn't work:               Needs["Combinatorica`"];     crds = {{1, 10}, {2, 4}, {10, 5}, {20, 10}};     vertices = Range[Length[crds]];     edges = Thread[vertices \[DirectedEdge] RotateLeft[vertices]];          Graph[vertices, edges]      produces errors:               Syntax::sntxf: "\!\(\*StyleBox[\"\\\"\\\\\\\"\\\"\", \"MT\"]\)\!\(\*StyleBox[\!     \(vertices\), \"MT\"]\)\!\(\*StyleBox[\"\\\"\\\\\\\" cannot be followed by \\\\\\\"     \\\"\", \"MT\"]\)\!\(\*StyleBox[\!\(\(\(\\[ DirectedEdge]\)\) \(\(RotateLeft[vertices]     \)\)\), \"MT\"]\)\!\(\*StyleBox[\"\\\"\\\\\\\".\\\"\", \"MT\"]\)\!\(\*StyleBox[\!     \(\"\"\), \"MT\"]\)"          Syntax::tsntxi: "\!\(\*StyleBox[\"\\\"\\\\\\\"\\\"\", \"MT\"]\)\!\(\*StyleBox[\!\(\\[      DirectedEdge]\), \"MT\"]\)\!\(\*StyleBox[\"\\\"\\\\\\\" is incomplete; more input is      needed.\\\"\", \"MT\"]\)\!\(\*StyleBox[\!\(\"\"\), \"MT\"]\)"          Syntax::sntxi: Incomplete expression; more input is needed.      Any ideas?


CorrelationTest small bug?

Consider two Normally distributed random variables:               x1 = RandomVariate[NormalDistribution[], {1000}];     x2 = RandomVariate[NormalDistribution[], {1000}];      I want to test $H_0 : \rho = 0$ against $H_1 : \rho \neq 0$. If I use               CorrelationTest[Transpose[{x1, x2}], 0, {"TestDataTable", All}]      I get, for instance, > \begin{array}{l|ll} \text{} & \text{Statistic} & \text{P-Value} \\ \hline > \text{Pearson Correlation} & 0.00505234 & 0.873251 \\ \text{Spearman Rank} & > 0.00983509 & 0.756138 \\ \end{array} However, if I use               PearsonCorrelationTest[x1, x2, "TestDataTable"]      I get > \begin{array}{l|ll} \text{} & \text{Statistic} & \text{P-Value} \\ \hline > \text{Pearson Correlation} & 0.00505234 & 0.87322 \\ \end{array} and, finally, if I use               SpearmanRankTest[x1, x2, "TestDataTable"]      I get > \begin{array}{l|ll} \text{} & \text{Statistic} & \text{P-Value} \\ \hline > \text{Spearman Rank} & 0.00983509 & 0.756081 \\ \end{array} Now **compare** the P-Values of the tests... they are slightly different, although they are supposed to be exactly the same test. Can anyone confirm this? If yes, could it be a small bug in _Mathematica_?


What kind of hypergeometric function is it?

I found a formula for an integral of a product of three Bessel functions at The Wolfram Functions Site: ![Bessel function integral](http://functions.wolfram.com/Bessel- TypeFunctions/BesselJ/21/02/02/0007/MainEq1.gif) I cannot understand what kind of hypergeometric function it is. The _Mathematica_ code given for it is:               HypergeometricPFQ[{{(α + λ + μ + ν)/2, (α + λ + μ - ν)/2}, {}, {}},                       {{}, {λ + 1}, {μ + 1}}, a^2/c^2, b^2/c^2]      When I try to evaluate it in _Mathematica_ 9, the last argument is highlighted in red and I get an error message: > HypergeometricPFQ::argrx: HypergeometricPFQ called with 4 arguments; 3 > arguments are expected. >>


Computing a series in terms of exponential function

Is there any way to compute the following series in terms of exponential function ? $$\sum_{k=0}^\infty Y_1(k)\;x^k$$ where $$Y_1(k) = \frac{(k - 1)!}{k!}Y_3(k - 1)$$ $$Y_2(k) = \frac{(k - 1)!}{k!}Y_4(k - 1)$$ $$Y_3(k) = \frac{(k - 1)!}{k!}(1/2Y_3(k - 1) + 1/2Y_1(k - 1))$$ $$Y_4(k) = \frac{(k - 1)!}{k!}(1/2Y_4(k - 1) + 1/2Y_2(k - 1))$$ such that: $\;Y_1(0)= 2 + r,\; Y_2(0) = 4 - r,\; Y_3(0) = 2 + r,\; Y_4(0) = 4 - r$               Y1[0] := 2 + r;     Y2[0] := 4 - r;     Y3[0] := 2 + r;     Y4[0] := 4 - r;     Y1[k_] := (k - 1)!/(k!)*(Y3[k - 1]);     Y2[k_] := (k - 1)!/(k!)*(Y4[k - 1]);      Y3[k_] := (k - 1)!/(k!)*(1/2*Y3[k - 1] + 1/2*Y1[k - 1]);      Y4[k_] := (k - 1)!/(k!)*(1/2*Y4[k - 1] + 1/2*Y2[k - 1]);          Sum[ Y1[k] x^k, {k, 0, Infinity}]


Where do those nulls come from?

I have seen discussions of unwanted nulls in the output in the context of building lists with conditions on the elements, but that is not involved here. I would like to know where the nulls come from and how to avoid generating them.               Clear["Global`*"]          localGroup =       AstronomicalData["LocalGroup"];          properties = {        "AlphanumericName",        "StandardName",        "AlternateStandardNames",        "NGCNumber",        "ApparentMagnitude",        "Constellation",        "Declination",        "RightAscension",        "DistanceLightYears",        "GalaxyType",        "HubbleType",        "RadialVelocity",        "Redshift"        };          lgTable = {#, Table[           {            properties[[n]],            AstronomicalData[#, properties[[n]]]            },           {n, 1, Length[properties]}           ]          } & /@ localGroup;               displayTable[record_] := Module[{},       Print[          #[[1]] <> ": ", #[[2]]          ] & /@ record[[2]];       Print["\n"]       ]          (* display two records for illustration *)          displayTable[#] & /@ lgTable[[1 ;; 2]]


Is it possible to specify the direction of rotation in VectorAngle function?

If I use the function VectorAngle[{1,0},{1,-1}], is it possible to obtain the angle generated by rotating around the axis counter clock wise? In other words, I would move from the first vector to the second in the positive direction. My output would be (7/4)*Pi instead of Pi/4.


Calling Mathematica from Visual Studio - example

I am trying to set up a connection between Visual Studio 10 and _Mathematica_ 8.0 on a Windows system. I found several sources of information on the Wolfram website, but I get entirely lost. Most of the info deals with calling C++ functions from within _Mathematica_ , but I would like it the other way round. I have quite a lot of functionality in my C++ code and I just call _Mathematica_ to make some integral calculations. Is there a good step-by-step approach to set up this connection? What files should I include in my project? What settings need to be changed? Does anyone have a complete example of pieces of code that gives insights in the general approach? That would be a great help. I followed the standard instructions to add the `lib`, `bin` and `include` to the Visual Studio directories. More specifically, I was also wondering whether in this case I also need to make a `.tm` file? Should it be empty then? The example here looks very clear, but this is approached from a Linux/Mac perspective. I hope someone could bring me some guidance. * * * Taking into account your suggestions, I have developed the following program, but there seems to be a problem with retrieving the packages. I have put the entire code here. The program first sends some variables to _Mathematica kernel_ and then it should perform the integral calculation. I am only interested in the final payoff that is calculated by Mathematica. While debugging, it seems to be that the program gets stuck in the removal of all the packages (in the loop just after sending the integral function). There is no problem with the function, I guess, because it performs the calculation perfectly when I just use _Mathematica_.               #include <stdio.h>     #include <stdlib.h>          #include "mathlink.h"          static void init_and_openlink( int argc, char* argv[]);     static void error( MLINK lp);               MLENV ep = (MLENV)0;     MLINK lp = (MLINK)0;               int main(int argc, char* argv[]){         int pkt;         float payoff;              init_and_openlink( argc, argv);      Now, I send the different parameters and the final function of interest:                   MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "mue");             MLPutReal(lp,0.25);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "mui");             MLPutReal(lp,0.25);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "lambdae");             MLPutReal(lp,0.25);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "lambdai");             MLPutReal(lp,0.25);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "sigmap");             MLPutReal(lp,0.05);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "betae");             MLPutReal(lp,0.05);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "betai");             MLPutReal(lp,0.05);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "gammae");             MLPutReal(lp,0.05);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "gammai");             MLPutReal(lp,0.10);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "d");             MLPutReal(lp,0.2);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "experience1");             MLPutInteger(lp,2);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "experience2");             MLPutInteger(lp,3);         MLEndPacket(lp);              MLPutFunction( lp,"EnterTextPacket",1);             MLPutString(lp,"expectedpayoff1bis[i1_, b1_,i2_,b2_] := NIntegrate[PDF[NormalDistribution[(1 + (betae*Exp[-mue*experience1] + betai*Exp[-mui*i1]))*(1 + b1/100), (1 + (betae*Exp[-mue*experience1] + betai*Exp[-mui*i1]))*(1 + b1/100)* Sqrt[sigmap^2 + (gammae*Exp[-lambdae*experience1])^2 + (gammai*Exp[-lambdai*i1])^2]], x]*(1 - CDF[NormalDistribution[(1 + betae*Exp[-mue*experience2] + betai*Exp[-mui*i2])*(1 + b2/100), (1 +  betae*Exp[-mue*experience2] + betai*Exp[-mui*i2])*(1 + b2/100)*Sqrt[sigmap^2 + (gammae*Exp[-lambdae*experience2])^2 + (gammai*Exp[-lambdai*i2])^2]], x]), {x, 0, 2}]*(NIntegrate[(x*PDF[NormalDistribution[(1 + (betae*Exp[-mue*experience1] + betai*Exp[-mui*i1]))*(1 + b1/100), (1 + (betae*Exp[-mue*experience1] + betai*Exp[-mui*i1]))*(1 + b1/100)* Sqrt[sigmap^2 + (gammae*Exp[-lambdae*experience1])^2 + (gammai*Exp[-lambdai*i1])^2]], x]*(1 - CDF[NormalDistribution[(1 + betae*Exp[-mue*experience2] + betai*Exp[-mui*i2])*(1 + b2/100), (1 + betae*Exp[-mue*experience2] + betai*Exp[-mui*i2])*(1 + b2/100)*Sqrt[sigmap^2 + (gammae*Exp[-lambdae*experience2])^2 + (gammai*Exp[-lambdai*i2])^2]], x])/NIntegrate[PDF[NormalDistribution[(1 + (betae*Exp[-mue*experience1] + betai*Exp[-mui*i1]))*(1 + b1/100), (1 + (betae*Exp[-mue*experience1] + betai*Exp[-mui*i1]))*(1 + b1/100)*Sqrt[sigmap^2 + (gammae*Exp[-lambdae*experience1])^2 + (gammai*Exp[-lambdai*i1])^2]], x]*(1 - CDF[NormalDistribution[(1 + betae*Exp[-mue*experience2] +betai*Exp[-mui*i2])*(1 + b2/100), (1 + betae*Exp[-mue*experience2] + betai*Exp[-mui*i2])*(1 + b2/100)*Sqrt[sigmap^2 + (gammae*Exp[-lambdae*experience2])^2 + (gammai*Exp[-lambdai*i2])^2]], x]), {x, 0, 2}]), {x, 0, 2}] - (1 + (betae*Exp[-mue*experience1] + betai*Exp[-mui*i1])) - d*i1/100) - (1 - d)*i1/100");         MLEndPacket(lp);      I don't need any of the information retrieved from the above packages, so I try to get rid of everything. This is were the debugging is in a loop (When I pause the debugging, I get the screen with "no source available".                   while ((pkt=MLNextPacket(lp),pkt)&&pkt!=RETURNPKT) {             MLNewPacket(lp);             if (MLError(lp)) error(lp);         }         MLNewPacket(lp);      Afterwards I want to evaluate the function and the result needs to be printed on the screen. This is the only output I am interested in:                   MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"expectedpayoff1bis",4);             MLPutInteger(lp,2);             MLPutInteger(lp,10);             MLPutInteger(lp,4);             MLPutInteger(lp,12);         MLEndPacket(lp);              while( (pkt = MLNextPacket( lp), pkt) && pkt != RETURNPKT) {             MLNewPacket( lp);             if (MLError( lp)) error( lp);         }         MLGetReal( lp,&payoff);                   printf( "payoff: %f", payoff);                   MLPutFunction( lp, "Exit", 0);              return 0;     }      The rest of the code is retrieved from the examples               static void error( MLINK lp){         if( MLError( lp)){             fprintf( stderr, "Error detected by MathLink: %s.\n",MLErrorMessage(lp));         }         else{             fprintf( stderr, "Error detected by this program.\n");         }         exit(3);     }               static void deinit( void){         if( ep) MLDeinitialize( ep);     }               static void closelink( void){         if( lp) MLClose( lp);     }               static void init_and_openlink( int argc, char* argv[]){         #if MLINTERFACE >= 3         int err;         #else         long err;         #endif /* MLINTERFACE >= 3 */              ep =  MLInitialize( (MLParametersPointer)0);         if( ep == (MLENV)0) exit(1);         atexit( deinit);              #if MLINTERFACE < 3         lp = MLOpenArgv( ep, argv, argv + argc, &err);         #else         lp = MLOpenArgcArgv( ep, argc, argv, &err);         #endif         if(lp == (MLINK)0) exit(2);         atexit( closelink);      }


Deleting selected rows from data table

I'm an intermediate Mathematica user and the _select_ function presented on Data Table Manipulation in Mathematica: Step 2 was very useful in helping me manipulate a 36Mb data file - 13 columns and 180k rows. The challenge I'm having is writing a similar function that will remove rows based on selected column entities, returning the subset of data as a new data table. Any assistance will be appreciated. Thanks.


TableForm behavior change

In an older version NoteBook, I was able to specify some options for `TableForm`, which enabled the printing of an expression in a simple fashion:               MyExpression//TableForm      I used this:               optsinit1 := SetOptions[TableForm,       TableHeadings -> {rowHeadings, columnHeadings},       TableAlignments -> Left,       TableSpacing -> 1]      where rowHeadings and columnHeadings were defined. Before using `TableForm` I would evaluate optsinit1:               optsinit1;          MyExpression//TableForm      would print the array (MyExpression) with the headings defined by rowHeadings and columnHeadings. In V9Ii have to issue               TableForm[MyExpression,optsinit1]       to get the previous behavior. I prefer the old behavior. Any hints on how this is done? Note that when I issue `Options[TableForm]` the return is               {TableAlignments -> Left, TableDepth -> \[Infinity],       TableDirections -> Column,       TableHeadings -> {rowHeadings, colHeadings}, TableSpacing -> 1}


Triggering actions when a variable is set

Some built-in variables trigger actions when their values are changed:               In[17]:= $Assumptions=1         During evaluation of In[17]:= $Assumptions::bass: 1 is not a well-formed assumption. >>     Out[17]= 1          In[18]:= $Assumptions:=2         During evaluation of In[18]:= $Assumptions::bass: 2 is not a well-formed assumption. >>      (Interestingly the message doesn't trigger if it's set again to the _same_ value.) How can we safely implement something like this? Are the any built-in hooks for value changes? * * * This is what I currently have. Does it look safe? Does anyone foresee problems? (There's always the least expected thing that goes wrong with these...)               $var /: Set[$var, value_] :=         Block[{$in = True},               Print["$var set to ", value];  $var = value] /; Not@TrueQ[$in]          $var = 6          (*       $var set to 6       6      *)      `$in` would of course be in a private context and the same needs to be done for SetDelayed as well.


Runaway MathKernel!

I was running a simulation and everything went south (my fault, stupid coding error). So I quit the kernel. Everything was running very slowly, as if it were doing some kind of large calculation. Eventually I quit Mathematica. Everything continued to run slowly. So I opened up the terminal to see what processes are running (I'm on Mac OS 10.6.8, Mathematica 9.01) and observed that there was a "Mathkernel" process, using about half (and sometimes more - 57.2% in the sceenshot) of my CPU. I tried the "Kill" command, and even "sudo Kill" but it didn't even blink. I tried logging out and back in, but it was still there. Finally, I restarted my computer, and it was gone. My question: is there a more elegant way of recovering from such a runaway process? ![enter image description here](http://i.stack.imgur.com/xfm4Z.png)


Registering/detecting an importer by file name extension

I've developed an importer and exporter for FreeSurfer's `MGH`/`MGZ` file format; the specific format isn't important, but I was wondering if there is a 'correct' way to tell _Mathematica_ that file names ending with ".mgh" should be automatically imported using my MGH importer? _Mathematica_ obviously does this for its built-in importers (e.g., `Import["abc.csv"]` is equivalent to `Import["abc.csv", "CSV"]`), so it seems like it should be possible, but I haven't been able to find any information about this in _Mathematica_ 's documentation. One solution, which seems inelegant to me, is this:               Unprotect[Import];     Import[name_String /; StringMatchQ[name, __ ~~ ".mgh" ~~ EndOfString]] :=        Import[name, "MGH"];     Import[name_String /; StringMatchQ[name, __ ~~ ".mgz" ~~ EndOfString]] :=        Import[name, {"GZip", "MGH"}];     Protect[Import];      Is there a more principled way of going about this?


What do these error messages mean when numerically solving differential equations?

I am using _Mathematica_ to numercially solve the following equations:               2 D[f0[r], r]/r + D[f0[r], r, r] == -2 A f1[r]/r^4 +  2 A D[f1[r],      r]/r^3 -2 f1[r]/r^2 + 2 D[f1[r], r]/r + D[f1[r], r, r] == 2 A D[f0[r], r]/r^3      And my boundary condition is               f0[10] == 0.01, f1[10] == 0.01,      (D[f0[r], r] /. r -> 1) == 10^-3 A,      (D[f1[r], r] /. r -> 1) == 0      When I take A to be small, say 1, everything is fine. However, if I take A to be large, e.g. 100, _Mathematica_ complains and gives me crazy results. Here are the error message I get: > NDSolve::bvluc: The equations derived from the boundary conditions are > numerically ill-conditioned. The boundary conditions may not be sufficient > to uniquely define a solution. The computed solution may match the boundary > conditions poorly. >> > > NDSolve::berr: There are significant errors {-5.55116*10^6,-7.26312*10^6,0., > 0.} in the boundary value residuals. Returning the best solution found. >> Can anyone help me to deal with this issue? I appreciate your help!


How to remove duplicates from set of machine precision 2D points?

I have a set of 2D points with machine precision coordinates. I need to remove all duplicates. Performance is important. This is the most obvious fast solution:               Union[points]      Unfortunately it turns out that unlike `Equal` and `SameQ`, `Union` has no tolerance for any difference with machine precision numbers, which makes it unusable for this purpose.               In[1]:=      a = 1.;     b = a + $MachineEpsilon;          In[3]:= a == b     Out[3]= True          In[4]:= a === b     Out[4]= True          In[5]:= Union[{a, b}]     Out[5]= {1., 1.}      Using the `SameTest` option of `Union` works, but it is not a good option because it makes the complexity $n^2$ again. So what is the fastest way to get rid of duplicates while allowing for a tolerance of comparisons, and preferably being able to control it (`Internal`$EqualTolerance`, `Internal`$SameQTolerace`)?


Adjacency List representation of a graph

I am looking to draw a graph knowing a simple adjacency representation of the graph like:                A = {{1, 3}, {2, 3}, {3, 4, 5}, {4, 5}, {5}}      Where `A` is my Adjacency List. I was thinking I could use `Graph[]` and maybe some kind of pattern matching:                Graph[{_\[DirectedEdge]_}]      I am also not familiar with patterns in mathematica (the "_" that gets used a lot but has been hard for me to understand).


Define a color function using Piecewise

How can I define a `ColorFunction` for my `ContourPlot` using `Piecewise`? For example after making a `ContourPlot` for such this function:               p[x_,y_]:=1-Sin[x]^2*Sin[y]^2;      I want to define my `ColorFunction` in a way that for example for `0<p<0.1` the plot have a different color than `0.1<p<0.2`. An example of what I need is in the following plot: ![enter image description here](http://i.stack.imgur.com/c3hUs.png) Which the color column at the right shows that each color corresponds to what value of `p`.


How can you link Parallel Mapping and Error tracking

Following this question and the comments made, together with the information in this question, the following code allows error tracking and debugging very nicely.               SetAttributes[withTaggedMsg, HoldAll];          withTaggedMsg[sym_] := Function[,       Internal`InheritedBlock[{MessagePacket},         Unprotect[MessagePacket];         MessagePacket[name__, BoxData[obj_, form_]] /; ! TrueQ[$tagMsg] :=               Block[{$tagMsg = True},             Identity@MessagePacket[name, BoxData[RowBox[{               ToBoxes @ Style[                 Row[{"At iteration", HoldForm[sym], "=", sym, Spacer[5]}, " "],                 Black],             obj}], form]]           ];         #       ], HoldAll];          f[var : _] :=         Block[{arg},         arg = var;         1/arg     ];          Map[f[#] &, Range[-2, 1, 1]] // withTaggedMsg[arg]          (*At iteration arg=0  Power::infy : Infinity expression 1/0 encountered.     {-(1/2), -1, ComplexInfinity, 1}*)      Now, the big problem is **how to use`withTaggedMsg` together with `ParallelMap`** instead of `Map`.               ParallelMap[f[#] &, Range[-2, 1, 1]] // withTaggedMsg[arg]          (*At iteration arg=arg Parallel`Protected`PacketHandler::default: Unhandled packet MessagePacket[Power,infy,BoxData[RowBox[{StyleBox[RowBox[{Power,::,infy}],     MessageName],: ,"Infinite expression \!\(1\/0\) encountered."}],StandardForm]] received and discarded from KernelObject[6,local].     {-(1/2), -1, ComplexInfinity, 1}*)      I don't see how I could do it, and would appreciate immensely if I could get some input in this. Thanks!


How to code the following product?

I am trying to examine the properties of the following product for a given tuple $\vec \lambda = (\lambda_1, \lambda_2, \dots, \lambda_n)$, then the product is as follows: $$ \dim \Gamma_\lambda = \prod_{i < j} {(l_i^2 - l_j^2) \over (m_i^2 - m_j^2)} = 2^{n-1} {\prod_{i < j} (l_i^2 - l_j^2) \over (2n - 2)!\cdot (2n - 4)! \cdots 2!} $$ where $l_i = \lambda_i +n - i$ and $m_i = n- i$. The function `dim_calc(n, lambda)` might take a tuple `lambda` and the length of the tuple, `n`, and then define the $l_i$ and $m_i$'s accordingly? I'm not really sure how to write this though...any hints for this symbolic computation? Thanks!


Duplex Printing from button inside DialogNotebook on Mac

All, I have the following code which generates a window containing the variable _PrintOut_ and a Print button. When the print button is pressed the contents of the window are sent to the printer and simultaneously a pdf is generated.               PrintOut = "Some stuff - plots, tables etc.";          DialogInput[       DialogNotebook[        Column[{PrintOut,           Row[{Button["Print",              DialogReturn[NotebookPrint[PrintOut, "filename.pdf"];              NotebookPrint[               CreateDocument[PrintOut, Visible -> False,                 PageHeaders -> {{"a", "b", DateString[]}, {"a", "b",                    DateString[]}}]]]], CancelButton[]}]}]],        ShowStringCharacters -> False,        WindowTitle -> "This Window " <> DateString[]];      The problem arises when _PrintOut_ contains enough stuff to be spread over multiple pages. I wish to have the pages print on both sides but can't figure out how to do it. I have the print settings within MMA set to duplex and when I print a notebook using the front end I get duplex but it does not work for DialogNotebook. I am using MMA8 Help appreciated.


Installing R packages using RLink on Mac OS X

Is there any updates regarding installing CRAN packages via RLink in Mathematica 10 on Mac OS X? Or are we still stuck with the base R package and that's it? I was able to point to my R distribution using this answer but using external packages led to errors. Here is my code:               Needs["RLink`"]     SetEnvironment[     "DYLD_LIBRARY_PATH" ->      "/Library/Frameworks/R.Framework/Resources/lib"];          InstallR["RHomeLocation" ->      "/Library/Frameworks/R.Framework/Resources"];          REvaluate["R.version.string"]          REvaluate["library(GA)"]          REvaluate["f <- function(x)  abs(x)+cos(x)                fitness <- function(x) -f(x)                ga(type='real-valued',fitness=fitness,min=-20,max=20)                summary(GA)"]          Out[15]= $Failed      and the error message:               REvaluate::rerr: Failed to retrieve the value for variable or piece of code f<- function(x)  abs(x)+cos(x)     fitness <- function(x) -f(x)     ga(type='real-valued',fitness=fitness,min=-5,max=5)     summary(GA). The following R error was encountered: Error in typeof(myRandomVar123456740025) :      object 'myRandomVar123456740025' not found >>


Help understanding overloading of Atomics within Block

Usually `h @@@ {f[1, 2], f[3, 4]} === {h[1, 2], h[3, 4]}` but this is not the case when `f` is `Complex`: `h @@@ {1 + 2I, 3 + 4I } === {1 + 2 I, 3 + 4 I}` Since `Complex`is an atomic and as documentation for `Apply` states: _Applying to atomic objects that do not have subparts effectively does nothing_ Using `Block` to replace `Complex` with `complex` gives result as expected for non-atomic case:               Block[{Complex = complex},      List @@@ {Complex[1, 2], Complex[3, 4]}      ]     (* {{1, 2}, {3, 4}} *)      But then how come replacing `Complex` with `List` while not `Apply`-ing does not give the same result?               Block[{Complex = List},      {Complex[1, 2], Complex[3, 4]}      ]     (* {Complex[1, 2], Complex[3, 4]} *)      As it would have for a non-atomic head:               Block[{f = List},      {f[1, 2], f[3, 4]}      ]     (* {{1, 2}, {3, 4}} *)


Gridlines of a framed plot with a background cannot be white?

Looking at this question, I am reminded of a problem that I was never able to solve with obtaining a particular plot format. The issue is that `GridLines` sit _behind_ anything in `Prolog`. You can have gridlines with a colored background by giving the background a non-zero `Opacity`.               Framed@Plot[Sin[x], {x, 0, 2 \[Pi]}, Frame -> True,        Prolog -> {LightGray, Opacity[0.5],          Rectangle[Scaled[{0, 0}], Scaled[{1, 1}]]},        GridLines -> {None, Automatic}]      ![enter image description here](http://i.stack.imgur.com/OkpGL.png) But if the gridlines are to be white, this isn't feasible, it seems.               Framed@Plot[Sin[x], {x, 0, 2 \[Pi]}, Frame -> True,        Prolog -> {LightGray, Opacity[0.5],          Rectangle[Scaled[{0, 0}], Scaled[{1, 1}]]},        GridLines -> {None, Automatic},        GridLinesStyle -> Directive[AbsoluteThickness[2], White]]      ![enter image description here](http://i.stack.imgur.com/3aeVP.png) Yes, you can use the undocumented option `Method -> {"GridLinesInFront" -> True}`, as described in this answer, but then the gridlines go on top of the plot line as well as the background.               Framed@Plot[Sin[x], {x, 0, 2 \[Pi]}, Frame -> True,        Prolog -> {LightGray, Opacity[0.5],          Rectangle[Scaled[{0, 0}], Scaled[{1, 1}]]},        GridLines -> {None, Automatic},        GridLinesStyle -> Directive[AbsoluteThickness[2], White],        Method -> {"GridLinesInFront" -> True}]      ![enter image description here](http://i.stack.imgur.com/IREBO.png) Is there a way to reorder the `Prolog` background or the gridlines somehow, so that white gridlines shock, but the gridlines don't go over the plotted function? Try as I might I was never able to replicate this format (the axis numbers _inside_ the frame are a whole other question). ![enter image description here](http://i.stack.imgur.com/9REBg.png)


Evaluating double Integral

While trying to evaluate the integral $\int_{y=0}^{x_2}\int_{x=0}^{min(x_1,y)} n (n - 1) (1 - y)^{(n - 2)}dxdy $ , Mathematica does not seem to yield any results.                Integrate[n (n - 1) (1 - y)^(n - 2), {y, 0, x2}, {x, 0, Min[y, x1]}]      Wolframm alpha also fails saying standard computation time exceeded. Is there anyway to evaluate the integral? I also tried this,               Assuming[0 < x1 < x2 < 1,       Integrate[n (n - 1) (1 - y)^(n - 2), {y, 0, x2}, {x, 0, Min[y, x1]}]]


from complex function to a series

How can I express this complex function as a series?               Log[      (1 - E^((I Pi (1 - a))/(b - a)) z)/      (1 - E^(-((I Pi (1 - a))/(b - a))) z)     ]      Where `z` is the complex number, `a` and `b` are real numbers, `a < 1` and `b > 1`.


Brackets in output make unable to use output to identify matrix element

I'm trying to write a code where each matrix element swaps with a randomly selected neighbor (cardinal directions only) to redistribute the matrix. So far I've been able to replace an element with its neighbor, making the elements twins, but I want to preserve the relative amount of "-1"s to "1"s. What you see below is what I have currently, which shows how I identify the neighbors of each element, and how I randomize which one switches with it. The output of this process gives me something in the form of `{i,j}`, which means I can't use `Si[[choice]]`, because that would be effectively saying `Si[[{i,j}]]`, which isn't correct syntax. I'm pretty new to Mathematica, so any help would be greatly appreciated! :) Input:               Si = {{-1, -1, -1}, {1, -1, -1}, {-1, 1, -1}};          Off[General::stop];          ii = 3;         jj = 3;          For[i = 1, i <= ii, i++,      For[j = 1, j <= jj, j++,            choices = {{i, Mod[j - 1, ii, 1]}, {Mod[i - 1, ii, 1], j},          {i, Mod[j + 1, ii, 1]}, {Mod[j - 1, ii, 1], j}};(*identifies neighbors*)            choice = choices[[RandomInteger[{1, 4}]]]; (*randomly chooses a neighbor*)            Si[[i, j]] = choice;(****************)            Print[choices];       Print[choice];       Print[Si]       ]      ]      Output:               {{1,3},{3,1},{1,2},{3,1}}          {3,1}          {{{3, 1}, -1, -1}, {1, -1, -1}, {-1, 1, -1}}          {{1,1},{3,2},{1,3},{1,2}}          {1,2}          {{{3, 1}, {1, 2}, -1}, {1, -1, -1}, {-1, 1, -1}},      etc. and so forth. Okay, so if I replace               Si[[i, j]] = choice;      with               Si[[i, j]] = Extract[Si, choice];       I can get the output to have replaced my original element, but I still don't know how to replace the neighbor with the value of the original element then.


Stylesheet modifications mimicking Stack Exchange styles

I find myself frequently highlighting and formatting portions of text cells in a _Mathematica_ notebook. Bold and Italic typesetting is easy to handle but I would like to use `backticks` to provide formatting similar to the SE editor or perhaps use underscores and asterisks to auto-format in other ways (say for example, text within ** here ** would be red and text within _ here _ would be highlighted yellow. Is it possible to customize a stylesheet to afford this type of formatting?


Mathematica Can't Evaluate This?

I am trying to find the inverse function of $\frac{\ln{x}}{x^2}$ in Mathematica. I am using the `Solve[]` function to find the inverse (yes, I know about `InverseFunction[]`, but I was told to solve it with `Solve[]`). Why doesn't the following output evaluate correctly? I know that I shouldn't get imaginary values: ![enter image description here](http://i.stack.imgur.com/OtChM.png) Plugging the equation into `Solve[]` directly also gives me the same result: ![enter image description here](http://i.stack.imgur.com/cB5GZ.png) However, if I drop the `x` from the `Log[]` function, I get something that looks more plausible: ![enter image description here](http://i.stack.imgur.com/FCeK1.png) Does `Log[x]` and `Log` evaluate to the same thing? Thank you for your time!


_**How to get the coordinates of the point that the mouse touch?_** When my mouse touch the picture that the _Mathematica_ touch ,I hope it can return the coordinates?


Calculating probabilities symbolically

Is there a way to solve for statistical quantities analytically/symbolically in _Mathematica_? **example 1:**   Lets say that I want to do a calculation that requires Bayes theorem. I know p(a), p(b) and p(a | b). I want to calculate p(b | a). Now, for this simple example, I know the solution, so I could write the relationship myself, but what about more complicated examples? Surely _Mathematica_ is able to solve probability problems like it can solve algebraic ones? I want to stay away from simulation. I want _Mathematica_ to do the five pages of math that I normally do on paper. Can _Mathematica_ do this for me? I'd like to type something like               Solve[p(a) == a1 && p(b) == a2 && p(a|b) == a3, p(b|a)]      and get > >     p(b|a) -> (a3*a2)/a1 >   **example 2:**   I want to use the law of total probability: I know `p(a|b)`, `p(a|!b)`, and `p(b)` and I want to calculate `p(a)`. I'd like to type something like               Solve[p(a|b) == a1 && p(a|!b) == a2 && p(b) == a3, p(a)]      and get > >     p(a) -> a1*a3 + a2*(1-a3) >


Using CellPrint with a TraditionalForm string

I am trying to use CellPrint to print a cell that asks a user to solve an equation. This equation is randomly generated right beforehand, and I would like to have it print in Blue. The whole Cell should be in the "Section" style. Here is my first attempt:               equat = ToString[     Expand[Product[(x - RandomInteger[{-10, 10}]), {i,        3 + RandomInteger[]}]], TraditionalForm];     CellPrint[     Cell[TextData[     RowBox[{StyleBox["Solve the equation "],        StyleBox[equat, FontColor -> Blue]}]], "Section"]];      This does in fact create the cell, and the last part is blue, but it is hindered by the TraditionalForm "markup": I won't put any color here, but the command above gives the output               Solve the equation \!\(TraditionalForm\`\(x\^4 - \(\(73\ x\^2\)\) - \(\(72\ x\)\)\)\)      Is there a simple way to fix this? I have tried using ToBoxes, but then I don't see how to color the output Blue. Any tips or pointers would be much appreciated.


Can't force UnitConvert to be evaluated in Plot

I'm trying to use new units support in _Mathematica 9_. When I `Plot` `Quantity` functions everything is OK.               v[e_] := Quantity[0.001, "m^3"] e     Plot[Evaluate@v[e], {e, 0, 1}]      But when I `UnitConvert` them, I get only an empty image with axes only.               v1[e_] := UnitConvert[v[e], "Liters"]     Plot[Evaluate@v1[n], {n, 0, 1}]      And no error message at all. By the way, `Plot` likes to do this very much - to draw nothing and not to tell why, and that sucks. Other standard functions seem to be plottable even with `Quantity` arguments.               v2[e_] := Sqrt[v[e]]     Plot[Evaluate@v2[n], {n, 0, 1}]      I can't figure out, what is the difference. The only difference I see is a `NumericFunction` attribute.               In[84]:= Attributes[Sqrt]          Out[84]= {Listable, NumericFunction, Protected}          In[85]:= Attributes[UnitConvert]          Out[85]= {Listable, Protected}      But `Quantity` values aren't numeric themselves, so this shouldn't make difference, should it?               In[1]:= NumericQ[Quantity[1, "L"]]          Out[1]= False      Can anyone explain this, please? Or is it some kind of bug? **EDIT:** I think, I can answer this myself now. As for Plot function, there is no sign in documentation and tutorials that using it with units supported. But there is also no sign that it isn't. Everywhere plotting with units is mentioned with different List*Plot functions. And they work fine with some good features:               v0[e_] := Quantity[0.001, "m^3"] e     es = Range[0, 1, 0.1];     cubes = v0 /@ es;     liters = UnitConvert[cubes, "L"];     ListLinePlot[cubes]     ListLinePlot[Transpose@{es, cubes}, AxesLabel -> Automatic]     ListLinePlot[Transpose@{es, liters}, AxesLabel -> Automatic]      or even               ListLinePlot[Transpose@{es, cubes}, AxesLabel -> Automatic, TargetUnits -> "Litres"]      It seems like Plot supports units, but "not very much". There is no TargetUnits parameter, and AxesLabel -> Automatic doesn't place unit names in labels. But still it can be used somehow. For my case, I found two solutions (thanks to @Anon for one of them and for direction to think to another). This               Plot[Evaluate@UnitConvert[e Quantity[0.001, "Meters"^3], "L"], {e, 0, 1}]      doesn't work. But this               Plot[Evaluate@UnitConvert[Quantity[0.001 e, "Meters"^3], "L"], {e, 0, 1}]      works. And this (a bit esoteric) variant too:               Plot[Evaluate@UnitConvert[Quantity[e, "m/m"] Quantity[0.001, "Meters"^3], "L"], {e, 0, 1}]      The reason for all these troubles may be the fact that Mathematica lacks a "truly" dimensionless units:               In[774]:= Clear[a]          In[775]:= QuantityUnit[a] (* this is OK, we don't know if 'a' has any \     units at all *)     Out[775]= QuantityUnit[a]          In[776]:= (* but we know that 1 doesn't have any *)     QuantityUnit[1]     Out[776]= "DimensionlessUnit"          In[777]:= (* and surely 1m has *)     QuantityUnit[Quantity[1, "m"]]     Out[777]= "Meters"          In[778]:= (* and this ratio is correctly dimensionless *)     QuantityUnit[Quantity[1, "m"]/Quantity[1, "m"]]     Out[778]= "DimensionlessUnit"          (* this ratio is dimensionless by its nature, but it isn't in Mathematica *)     QuantityUnit[Quantity[a, "m"]/Quantity[1, "m"]]     Out[779]= QuantityUnit[a]      The core of the problem seems to be here:               In[780]:= Quantity[Quantity[1, "m"], "m"]     Out[780]= Quantity[1, ("Meters")^2]      According to physics (and common sence) "1 meter of meters" is nonsense. No way it can be 1 square meter.


Number of edges to each polygon of a graph constructed from an image

I have an image which looks like ![](http://i.stack.imgur.com/cET4A.png) from How to convert an image to a graph and get the positions of the edges? which by using `MorphologicalGraph` becomes a graph that is a collections of polygons:               i = Import["http://i.stack.imgur.com/cET4A.png"];     g = MorphologicalGraph[i,           EdgeStyle -> Directive[Orange, Opacity[.5], Thickness[.01]],          GraphStyle -> "ThickEdge"];     Show[ColorNegate@Dilation[i, 1], g]      I am wondering if, for each polygon, it is possible to extract the number of edges?


Why does my attempt at parallelization not work?

I want to run some function with different parameters, parallel on 4 cores (i5). When I run it without using `Parallelize`, processor has ~25% utilization. It's a little time consuming (a couple of minutes), so I tried run it 4x with different parameters on each core. I tried: `Parallelize[{f[a1,b1,c1],f[a2,b2,c2],f[a3,b3,c3],f[a4,b4,c4]}]` (also with different methods like: "FinestGrained"/"CoarsestGrained"/"EvaluationsPerKernel" -> 1) and still, total utilization of cpu is 30% top).   1. Each variant is processed within a few minutes, at least 4 minutes.   2. In Parallel Kernel Status window all 4 kernels have status _busy_ , after the start of the calculation. I used Parallelize earlier and it worked just fine (~100% utilization).  So, what is the reason? My configuration: Mathematica 9.0.0/Win8 x64/i5 2500k, 4GB RAM


Contour plot doesn't look right

I have an implicit function expression               F[x, y] :=        -E^(-2 a) (-1 + (c (1 - 1/y^2))/a)          (-1 + (b (1 - 1/y^2))/(2 a)) + (1 + (c (1 - 1/y^2))/a) (1 + (b (1 - 1/y^2))/(2 a))      where               a = Sqrt[x^2 - (1 - 1/y^2) y^2]          b = Sqrt[x^2 - 2 y^2]          c = Sqrt[x^2 - y^2]      I plot the expression `F[x, y] == 0` with `ContourPlot`, and I get something like this: ![](http://i.stack.imgur.com/t2E41.png) I need to obtain a plot like this: ![](http://i.stack.imgur.com/LrUIy.png) If I try to plot `Re[F[x,y]]==0` and the result looks like this: ![enter image description here](http://i.stack.imgur.com/WajU3.png) But there is one more solution(branch in the left) that I don't need. How can I separate there solutions?


Extension of harmonic number to the real domain

What is exactly the domain of validity of the identity:               Sum[1/(k + j - 1), {j, 1, i}] == HarmonicNumber[k - 1 + i] - HarmonicNumber[k - 1]        when `k` is a real number? More generally, could I have a reference about the way `HarmonicNumber[x]` is calculated when `x` is not an `Integer`?


Reading Early Version Notebooks

I have some very old Mathematica notebooks file (.m) files from Version 2. When I try to open them using Mathematica 8.0 (on a Linux system) Mathematica instantly shuts down (no error message - just closes). However they open and format correctly using WolframCDFPlayer. I can copy from the player but not as cell expressions so a lot of hand editing is required to split and format the cells in the new notebook. Is there any, perhaps undocumented, way to read or import these files into the current version of Mathematica that would retain some degree of the original formatting?


Finding corresponding vertex from 3d to 2d

I have this simple 3d data points:               v = {{0.`, 0.016821`, -0.5`}, {0.353553`, -0.75`, -0.353553`}, {0.`, -0.75`, -0.5`},         {0.353553`,  -0.013361`, -0.353553`}, {0.5`, -0.75`,         0.`}, {0.5`, -0.020719`, 0.`}, {0.353553`, -0.020719`,          0.353553`}, {0.353553`, -0.75`, 0.353553`}, {0.`, -0.020719`,          0.5`}, {0.`, -0.75`, 0.5`}, {-0.353553`, -0.020719`,          0.353553`}, {-0.353553`, -0.75`, 0.353553`}, {-0.5`, -0.020719`,          0.`}, {-0.5`, -0.75`, 0.`}, {-0.353553`, -0.043838`, -0.353553`}, {-0.353553`,          -0.75`, -0.353553`}};      and                polys = {{2, 3, 4}, {4, 3, 1}, {5, 2, 6}, {2, 4, 6}, {8, 5, 6}, {6, 7, 8},                {10, 8,  7}, {7, 9, 10}, {12, 10, 9}, {9, 11, 12}, {14, 12,                11}, {11, 13, 14}, {1, 3, 15}, {15, 3, 16}, {14, 13, 15}, {16, 14, 15}};      Same data, in 2d representation: following are 2d points                uv = {{0.2505`, 0.500001`}, {0.2505`, 0.624988`}, {0.009907`,           0.500001`}, {0.00005`, 0.624988`}, {0.2505`,           0.375013`}, {0.012311`, 0.375013`}, {0.2505`,           0.250026`}, {0.012311`, 0.250025`}, {0.2505`,          0.125038`}, {0.012311`, 0.125038`}, {0.2505`,          0.00005`}, {0.012311`, 0.00005`}, {0.2505`, 0.874962`}, {0.2505`,          0.99995`}, {0.012312`, 0.99995`}, {0.012312`,          0.874963`}, {0.019862`, 0.749975`}, {0.2505`, 0.749975`}};      and                npolys = {{1, 2, 3}, {3, 2, 4}, {5, 1, 6}, {1, 3, 6}, {7, 5, 6}, {6,                 8, 7}, {9, 7, 8}, {8, 10, 9}, {11, 9, 10}, {10, 12, 11}, {13, 14,                 15}, {15, 16, 13}, {4, 2, 17}, {17, 2, 18}, {13, 16, 17}, {18, 13, 17}};      I am trying to find corresponding vertex order from 3d to 2d. Coordinates are different in both 3d and 2d view. is it possible to do in mathematica?


Breaks in plot & blank plots

Almost as a follow on from this old question, I am having similar problems again, with slight difference, that if the values are small enough, a completely blank plot is produced.               ξ[z_] := ((z - 1) Gamma[z/2 + 1] Zeta[z])/Sqrt[π^z]          ContourPlot[{Im[ξ[σ + b I]], Re[ξ[σ + b I]]}, {σ, -2, 3}, {b, 100, 120},                 PlotPoints -> 500]      ![enter image description here](http://i.stack.imgur.com/Bnsno.gif) Even with `PlotPoints->500` there are still breaks in the plot. I know I am dealing with very small numbers here, but is there anything I can do to create a clean plot? The plot above is not too bad, but I would really like to look at plots for values of `{b,7000,7010}` - but it just produces a blank plot above `1000`. Is there anything I can to to avoid this? # Update Have tried `Exclusions->None` but creates a plot that is just wrong! ![enter image description here](http://i.stack.imgur.com/QPcuL.gif)


How to get rid of all complex numbers and functions?

For almost esthetical reasons, I always have been fascinated by infinite sums of series and I always wonder if theyhave a closed form. A couple of days ago, I found on MSE a question related to the convergence of $$S=\Sigma_{n=0}^{\infty}{\frac{n^2 x}{1+n^4 x^2}}$$ where $x$ is a real number. So, I gave the problem to one of my former colleagues who ran Mathematica for this summation. He sent me back the following (surprizing result) $$\frac{\sqrt[4]{-1} \pi \left(\cot \left(\frac{(-1)^{3/4} \pi }{\sqrt{x}}\right)+i \cot \left(\frac{\sqrt[4]{-1} \pi }{\sqrt{x}}\right)\right)}{4 \sqrt{x}}$$ telling that he did not find any way to make it simpler. For sure, the result is a real. I tried to simplify manually, expanding the $cot$ functions and ... arrived nowhere after pages of manual calculations (being almost blind does not make things easier). Could any one tell me what should be the appropriate syntax to be used in order to remove all the complex numbers from this expression ? Any help will be really appreciated.


Plot producing many error messages when given complicated function

I'm new to _Mathematica_ and am running in to all sorts of silly difficulties with coding in it. I'm trying to calculate a function `f[x, k]`, normalise it with another function `n[k]` and then calculate and plot a thrid function `en[k]` that depends on the first two. Unfortunately, _Mathematica_ won't plot it, and I can't see what I did wrong. I'm sure it's a trivial mistake on my part and I'm sorry to have to ask. Here's my code:               L = 8;     f[x_, k_] :=        Cos[Pi k/(2 L)]^2  Exp[(-(x - k)^2)/2] - Sin[Pi k/(2 L)]^2 (x - L) Exp[(-(x - k)^2)/2];     n[k_] := Integrate[f[u, k]^2, {u, -L, L}];     en[k_] := Integrate[f[v, k] (-f''[v, k] + (v - k)^2  f[v, k]), {v, -L, L}]/n[k];     Plot[en[k], {k, 0, L}]


Multiple NIntegrate (again)

Basically I have the same question as here: Multiple NIntegrate but since I don't have enough "reputation" I cannot comment there. I want to solve the following multiple Integral numerically at given Points R, m:               Qb[R_, m_] := 3/m^2 + 8/(Sqrt[Pi] m)     NIntegrate[Exp[-c^2] (-4 m^2/(R Sqrt[Pi]) Integrate[     Exp[-x^2] x^2, {x, 0, Infinity}] - 2 m^2/(R Sqrt[Pi])     Integrate[Exp[-x^2] x^2 Integrate[If[R < Sqrt[c^2 + x^2 - 2 c x z],      R/Sqrt[c^2 + x^2 - 2 c x z], 1], {z, -1, 1}], {x, 0, Infinity}])     (3 c^2 - 2 c^4), {c, 0, Infinity}]      But I get error messages: _NIntegrate::inumr: "The integrand (3\ c^2-2\ c^4)\ E^-c^2\ (-44.7156-50.4562\ !(*SubsuperscriptBox[([Integral]), (0), ([Infinity])](*SuperscriptBox[(E), (-Power[ <<2>>])]\\ *SuperscriptBox[(x), (2)]\\ (*SubsuperscriptBox[([Integral]), (-1), (1)]If[Less[<<2>>], Times[<<2>>], 1] [DifferentialD]z) [DifferentialD]x))) has evaluated to non- numerical values for all sampling points in the region with boundaries {{[Infinity],0.}}."_ What is the right way to do this with Mathematica? Edit: To make the problem slightly simpler you can leave out all constants and get rid of the x-integration:               Qb[R_] :=      NIntegrate[     Exp[-c^2] NIntegrate[     If[R < Sqrt[c^2 - 2 c z], R/Sqrt[c^2 - 2 c z], 1], {z, -1, 1}],     {c, 0, Infinity}];     Qb[3.7]      or as an even simpler example               NIntegrate[NIntegrate[y, {x, 0, 1}], {y, 0, 1}]      In **this** case it works to replace the inner NIntegrate by Integrate, but if the inner integral is too complicated for analytic evaluation Mathematica cannot handle it.


Integrate equations of motion when force depends on position

I'm fairly new to _Mathematica_. I'm trying to test my C++ implementation of a fourth order Runge Kutta method for Newton's equations of motion. I want to test my integrator when the applied force is dependant on the position. I tried to implement Newton's equations of motion in _Mathematica_ as below:               iMass = 4     iVel0 = {1.0, 1.0, 1.0}     iTime = 1.0     iMagn = Dot[iPos, iPos]^0.5     iForce = ((12.3/iMagn) - 1.2)*Normalize[iPos]       (* Applied force is 12.3 / distance from 0 0 1.2 minus 1.2 and pointing towards 0,0,0 *)     iAccel = iForce/iMass     iVel = iVel0 + Integrate[iAccel, time]     iPos = {0.0, 10000, 0.0} + Integrate[iVel, time]}]      _Mathematica_ ran for a couple of hours until I aborted the calculation. How can I get _Mathematica_ to integrate Newton's equations of motion when the applied force is a function of position?


Conditional Check on Matrix

Suppose I have the following matrix (i,j):               mat = {{19.8134, 54.7015, 64.1866, 75.5597, 88.8358, 83.7313, 93.0299,        88.2537, 101.03, 108.873, 91.8731, 88.097, 82.0075, 88.7164,        83.5672, 69.9254, 56.0149, 31.4328, 19.4179, 6.40299, 1.48507,        0.410448, 0.171642, 0, 0}, {24.2741, 52.6815, 64.4667, 74.8593,        87.6222, 87.1926, 96.3407, 90.0667, 98.2519, 103.496, 89.7926,        85.1259, 83.4889, 88.7111, 86.1852, 75.4296, 53.7778, 34.0667,        19.6889, 7.40741, 2.16296, 0.348148, 0.00740741, 0, 0}, {18.4632,        50.6544, 60.5735, 72.5441, 86.0956, 84.9485, 91.1103, 84.8603,        94.3897, 100.463, 83.6324, 82.9412, 77.4853, 79.6324, 77.9485,        61.9118, 48.7574, 27.8309, 13.8824, 5.96324, 1.60294, 0.529412,        0.0294118, 0, 0}, {19.1212, 59.0985, 71.6818, 86.8182, 96.553,        91.5455, 100.402, 92.6515, 111.068, 111.909, 95.7803, 94.3864,        92.75, 90.8182, 95.3561, 86.197, 73.6136, 51.5682, 40.6742, 15.1515,        3.30303, 0.848485, 0.0757576, 0.030303, 0.030303}, {19.6083,        55.5917, 66.5583, 75.575, 87.6, 89.1417, 96.1083, 92.6917, 108.375,        117.3, 96.7333, 91.8167, 86.6583, 91.7333, 93.45, 79.5333, 60.275,        36.95, 24.3583, 9.60833, 1.76667, 0.416667, 0.00833333, 0.0333333,        0}}      The following is my criteria vector that each element corresponding to each row of the above matrix:               check = {7.94021, 7.95033, 7.44576, 8.83645, 8.38877}      Here is my criteria. If the element in `mat[[i,All]]` is less than the corresponding element in `check[[i]]` vector, I want to replace with the following vector               replacevec = {79.4021, 79.5033, 74.4576, 88.3645, 83.8877}      where each element `(replacevec[[i]])` correspond to each row in `mat` . Could you give me suggestions? Thank you for help.


Visualization of matrix transformations

I define the "matrix transformation" here as follows: $\left[ \begin{matrix} x_1' \\ x_2' \\ \end{matrix} \right]=\left[ \begin{matrix} a & b \\ c & d \\ \end{matrix} \right]\left[ \begin{matrix} x_1\\ x_2\\ \end{matrix} \right]$, therefore this is a transformation between point and point. it moves $(x_1,x_2)$ to $(x_1',x_2')$ So is there any way to visualize it when you're trying to deform a grid by this?


How can I have an axis label automatically positioned below the X-axis?

I'm attempting to generate some histograms, and I'd like to automatically label the X-axis. `However, Histogram[. . ., AxesLabel -> {"X", "Y"}]` places the "X" label on the RHS of the axis. How do I direct that the "X" label should be positioned below the axis? I need some automated method (I can of course move it by hand), since I'm going to be generating hundreds of diagrams.


webMathematica evaluation gives unexpected results when imported dynamically

Let me know if this should be posted on StackOverflow instead - I'm not quite sure where it belongs When calling a page via the JSTL `<c:import>` tag or the JSP Include action, webMathematica gives results that are not consistent with the other components of the page. Consider the following example: page1.jsp:               ...     <c:url value="page2.jsp" var="x">         <c:param name="a" value="4" />     </c:url>     <c:import url="${x}"/>     ...      page2.jsp               1. ${param.a}          2. <%= request.getParameter("a")  %>          3. <msp:evaluate>MSPValueQ[$$a]</msp:evaluate>          4. <msp:evaluate>$ServletRequest@getParameter["a"]</msp:evaluate>          5. <%= request.getAttribute("javax.servlet.include.query_string") %>          6. <msp:evaluate>$ServletRequest@getAttribute["javax.servlet.include.query_string"]</msp:evaluate>      1 and 2 both return the correct value of 4. However, 3 and 4 both evaluate to the empty string. Furthermore, 5 gives the correct string "a=4", but 6 evaluates to the empty string. My best guess is that webMathematica does not update it's parameters when the import is done, so $ServletRequest does not get updated with the new attribute and value of the new GET parameter is not set. What is actually going on here?


Why does Dynamic output cause CPU usage when onscreen?

I write such a line in _Mathematica_ :               {Slider[Dynamic[s]], Dynamic[f[x_] := s*x]}      After evaluation, the CPU immediately runs at full power. And if you scroll the page, it turns out that as soon as this line appear on the screen, the CPU begin to work. This really confused me a lot. Can anyone help?


How can I highlight the points lying between two lines in a ListPlot?

I have a list of numbers like the following:               list = Table[RandomInteger[1000], {i, 1000}];      And I plot them so:               ListPlot[list]      ![enter image description here](http://i.stack.imgur.com/1Q9Wd.png) I have drawn the black lines on the plot myself. I'd like to have `min` and `max` variables as a function of `y`, which once set, produce these lines in the chart and highlight the data between the lines. How can I do this?


TreeForm expression that will automatically spread nodes vertically so labels do not overlap

My deeply and unevenly nested lists and equations generate a TreeForm image which is too small and compressed to use. Then we must expand it manually by grabbing the edge of the image, and sometimes this requires irritating time and effort, and huge expansions. Will some clever person please show me how to force the size of the TreeForm image to be large enough that no cells in the image overlap vertically? So no level will vertically overlap any other level? Then, in some instances, but not as important, a second option to force the image also to be large enough so no two cells on the same level overlap horizontally? (This latter must be an option only, not the default, because the span may be extremely large horizontally for large databases. Also, it might be best that partial overlaps be permitted.) I imagine running TreeForm with these options, and then being able to use the vertical and horizontal scroll bars to see any part of the nested structure. This would solve a lot of the problems being addressed by other solutions and questions about TreeForm.


How can I save a Manipulate's control settings to a dataset?

This is probably an extremely simple question. I have a manipulate that sets variables used to define an offset, amplitude, frequency and phase of a trigonometric function.               Manipulate[       Module[{Vac,Vdc, ω, ϕ, f},         Vac = ctrlVac;                      (* AC Voltage *)         Vdc = ctrlVdc;                      (* DC Offset *)         f = ctrlf;                          (* Frequency *)         ω = 2 π f;         ϕ = ctrlPhi;                        (* Phase Offset *)         gFunc = ctrlgFunc;                  (* Function *)         Plot[ Vdc + Vac  gFunc[ ω t + ϕ],{t,0, 0.4}]],       {{ctrlgFunc,Sin,""},{Sin,Cos, Tan, Cot }},Delimiter,       {{ctrlVac,1.5,Subscript["V","ac"]}, -10,10},       {{ctrlVdc, 0.5, Subscript["V","dc"]}, -1,1},Delimiter,       {{ctrlf, 10, "Frequency"}, 0.001,100},       {{ctrlPhi, 0, "ϕ"}, 0, 2 π},       ControlPlacement->Left, Paneled->True]      I would like to use the `Manipulate` as an editor that sets the values of the variables in the code snippet above and then passes them on as parameters to a function along with other sets of variables. Is there a way to add a button to save the current values to a dataset?


Draw plot with locator & slider

I would like to create a plot whereby both the slider and the locator 'draw' the plot. In the following code, the locator & the slider act independently:               f[x_] := Sin[x];     Manipulate[With[{x0 = Clip[p[[1]], {0, 20}]}, Plot[f[x], {x, 0, t},      ImagePadding -> 20, PlotRange -> {{0, 20}, {-2, 2}}, LabelStyle -> (FontFamily ->      "Ariel"), Epilog -> {PointSize[Large], Red, Tooltip[Point[#], #] &@{x0, f[x0]}}]],      {t, 0.001, 20}, {{p, {0, 0}}, Locator, Appearance -> None}, AppearanceElements -> None]      I would like to get both to work together, so the slider 'draws' the plot, as does the locator when it is dragged. Here is an illustration of what I am trying to achieve: ![enter image description here](http://i.stack.imgur.com/eRRQn.gif)


Why does repeating an equation help in FindRoot?

I'm trying to understand this behavior of `FindRoot`. Consider a sample function (the one I'm actually interested in is far more complicated, but has similar issues) and the following arguments:               crazyFunction[x_, y_] := N@Norm[{x + 2 y}]     yact = RandomReal[{-10, 10}, 2]~Join~{RandomReal[{100, 250}]};     gv = yact + RandomReal[{-.1, .1}, 2]~Join~{RandomReal[{-5, 5}]};     sampledata = crazyFunction[#, {a, b, c}] == crazyFunction[#, yact] & /@      {{1, 2, 3}, {2, 3, 4}, {4, 5, 6}};      Basically, I'm applying the sample function for a particular `yact` value, at three `x` values, and setting it equal to the function evaluated with three "unknown" `y` values `{a,b,c}`. To solve for the "unknown" values, I used `FindRoot` with initial guessed value `gv` randomly perturbed from the actual values:               sol = FindRoot[sampledata, Transpose@{{a, b, c}, gv}, MaxIterations -> 1000]      Note, this likely will throw a warning `(* FindRoot::lstol: The line search decreased the step size to within tolerance specified by AccuracyGoal and PrecisionGoal ... *)`. To evaluate the quality of the solution, I compare the `Norm` of the difference between the actual `yact` and the solved `y` (normalized to the `Norm` of `yact`):               Norm[yact - {a, b, c} /. sol]/Norm[yact]     (* Out[]:= 0.0540657 *)      which isn't a terrible value. My thinking here is, I have three unknowns -- `a`, `b`, and `c` -- and three different equations for the different `x` values, so that should be enough to solve the problem. In fact, without three equations `FindRoot` won't work. I.e.:               FindRoot[sampledata[[1]], Transpose@{{a, b, c}, gv}, MaxIterations -> 1000]     (* FindRoot::nveq: The number of equations does not match the number of variables in... *)      But, if instead of using three, different equations, I simply repeat the same equation three times:               sampledata = Table[crazyFunction[#, {a, b, c}] == crazyFunction[#, yact] &@{1, 2,3}, {3}];     sol = FindRoot[sampledata, Transpose@{{a, b, c}, gv}, MaxIterations -> 1000];      Not only does it not give the `lstol` warning, but it actually gets a more accurate result! Consider:               dat=Table[yact=RandomReal[{-10,10},2]~Join~{RandomReal[{100,250}]};      gv=yact+RandomReal[{-.1,.1},2]~Join~{RandomReal[{-5,5}]};      sampledata=crazyFunction[#,{a,b,c}]==crazyFunction[#, yact]&/@{{1,2,3},{2,3,4},{4,5,6}};      sol=Quiet@FindRoot[sampledata,Transpose@{{a,b,c},gv},MaxIterations->1000];      Norm[yact-{a,b,c}/.sol]/Norm[yact],{1000}];          datSamedata=Table[      yact=RandomReal[{-10,10},2]~Join~{RandomReal[{100,250}]};      gv=yact+RandomReal[{-.1,.1},2]~Join~{RandomReal[{-5,5}]};      sampledata=Table[crazyFunction[#,{a,b,c}]==crazyFunction[#, yact]&@{1,2,3},{3}];      sol=Quiet@FindRoot[sampledata,Transpose@{{a,b,c},gv},MaxIterations->1000];      Norm[yact-{a,b,c}/.sol]/Norm[yact],{1000}];          Histogram[{dat, datSamedata}, "Log"]      ![Mathematica graphics](http://i.stack.imgur.com/4cnFL.png) Note the log-binning. Using the same equation three times is far more accurate than using three different equations! So, my question is: **Why is repeating the same equation three times far more accurate than using three different equations?**


How to get all leaves from a graph's specific node

Let's say I have this graph (The code to generate the graph is at the end) ![sample graph](http://i.stack.imgur.com/B0JH4.png) How can I extract all the leaves comming from, let's say "cluster3"?, i.e. {100, 92, 87, 89} ![sample graph](http://i.stack.imgur.com/ON89L.png) I guess I have to first extract the subgraph with "cluster3" as root vertex ![sample graph](http://i.stack.imgur.com/oyNJ0.png) and then filter the result. This last part should be easy. What I'm finding hard to get is extracting the subgraph. I tried using the Subgraph functions doing like: Subgraph[myGraph, UndirectedEdge[_, cluster3]] But I don't get what I want ![sample graph 2](http://i.stack.imgur.com/mhwlW.png) Probably this is trivial and I'm just not seeing it. Any kind of help would be super useful. Thanx! This is what I used to create the graph               Needs["HierarchicalClustering`"];          MakeClusteredTree[data_,leaves_,opts:OptionsPattern[]]:=Module[{clusters,expr,ett,edges,optsGraph=FilterRules[opts,Options[Graph]],optsAgglomerate=FilterRules[opts,Options[Agglomerate]]},clusters=Agglomerate[data->leaves,optsAgglomerate];expr=(i=1;Replace[clusters,Cluster[a_,b_,___]:>Symbol["cluster"<>ToString[i++]][a,b],{0,Infinity}]);ett=SparseArray`ExpressionToTree[expr];edges=UndirectedEdge@@@(ett[[All,All,1]]);Graph[(UndirectedEdge@@@edges),GraphLayout->{"LayeredEmbedding","RootVertex"->(UndirectedEdge@@@edges)[[1,1]]},VertexLabels->"Name",optsGraph,ImagePadding-> Full]]          data = {100, 43, 87, 1, 49, 32, 79, 42, 89, 92};          MakeClusteredTree[data, ToString /@ data, {Linkage -> "Average"}]      ====Final Notes==== The MakeClusteredTree function is completely based on this post (highest of high fives to kguler). I just changed it a little bit for my original purpose and another little bit for this post (I'm using more complicated data, huge trees and originally, I only visibly label the leaves. I changed the VertexLabels for this example so I can show you the names of all nodes.


How to use filling in ContourPlot

I want to fill region between different contours, e.g. `ContourPlot[{c1 = f1, c2 = f2}, ...]` a la the filling options for `Plot` like `Filling -> {1->{2}}`. Is it an easier way than superimposing two contour plots then manually excluding regions?


How do I transform a rasterized graphic's coordinates back to its original ListPlot data coordinates?

From this question I successfully made an elliptical fit for my data. However, when I try and collect the datapoints within the ellipse via this question the coordinates of my ellipse correspond to an ellipse of a rasterized image of my listplot data and not the original. How can I transform or scale the ellipse that fits the rasterized image to the original listplot. Ok, with all that said heres an example.               data = RandomReal[NormalDistribution[], {100000, 2}]     p = ListPlot[data, ImageSize -> 4000];     f = FillingTransform@ColorNegate@Binarize@p // DeleteSmallComponents     {c, s, t} = 1 /. ComponentMeasurements[f, {"Centroid", "SemiAxes", "Orientation"}]     Show[Rasterize[p], Graphics[{Red, Rotate[Circle[c, s],t]}]]      where I get a nice image: ![example data](http://i45.tinypic.com/34tej38.jpg) however, the coordinates c, s, t of the ellipse are pixle coordiantes corresponding to the rasterized image rather than data coordinates. So when I need the ellipses parameter to do any calculations I get bunk results. The image processing approach would be the best as I am filtering out the most dense cluster of data. Thanks so much.


How to import a text file into Classify?

I have a text file like as follows.               {     "XXX" -> "A",      "YYY" -> "A",     "ZZZ" -> "B"     }       I'd like to import this so I can send it directly to `Classify[]`. I've tried importing as `CSV` and `Text` but neither work. Example (That doesn't work):               data = Import["sample.txt", "CSV"];     c = Classify[data];      Although I'd settle for a normal CSV if that isn't possible.


Mathematica cannot find the c compiler

I installed Microsoft Windows SDK for Windows 7 and .NET Framework 3.5 SP1 Then, I installed Mathematica 10 trial version. I did:               Needs["CCompilerDriver`"]          $CCompiler = {"Compiler" -> GenericCCompiler,      "CompilerInstallation" ->      "C:\\Program Files (x86)\\Microsoft Visual Studio 9.0\\VC\\bin",      "CompilerName" -> "cl.exe"};          Compile[{{x}}, x^2 + Sin[x^2], CompilationTarget -> "C"];      I got:               CreateLibrary::badcomp: Compiler specification "Compiler" -> GenericCCompiler does not specify a compiler driver listed by CCompilers[Full]. >>          Compile::nogen: A library could not be generated from the compiled function. >>      How can I set up c compiler which I installed for Mathematica?


Why does the name of a pattern affect the result of a transformation rule?

I was playing a little dirty, trying to get a template for defining a `Curl[]` operator. I wrote the following rule, which I knew was going to spit out a few errors, because all symbols there (including the lists), were undefined:               Cross[{d[1], d[2], d[3]}, {2, 3, 4}] /. Times[a_, b_] -> b[[a]]      Notwithstanding the errors, the result I got was what I wanted:               (* {d[2][[4]] + d[3][[-3]], d[1][[-4]] + d[3][[2]], d[1][[3]] + d[2][[-2]]} *)      with a few more replacements, you can almost see the `Curl[]` operator materializing. Sadly, I forgot that the symbol `a` was already in use in may main `.nb`, so I changed it to `c`. Look:               Cross[{d[1], d[2], d[3]}, {2, 3, 4}] /. Times[c_, b_] -> b[[c]]      But now the results are completely different!               (* {(-3)[[d[3]]] + 4[[d[2]]], (-4)[[d[1]]] + 2[[d[3]]], (-2)[[d[2]]] + 3[[d[1]]]} *)      Wow! I `Traced` the evaluation, and could easily find out where the both processes started to differ, but I couldn't understand why. Any ideas?


Efficiently importing XPM matrix data into Mathematica

The XPM file format is an image file format. Although it is primarily intended for icon pixmaps, it can also be used to store matrix data. For example, the GROMACS chemical simulation package uses it in the program g_hbond to export hydrogen bond existence matrices. A sample XPM file, generated by **g_hbond** is below:               /* XPM */     /* Generated by g_hbond_d */     /* This file can be converted to EPS by the GROMACS program xpm2ps */     /* title:   "Hydrogen Bond Existence Map" */     /* legend:  "Hydrogen Bonds" */     /* x-label: "Time (ps)" */     /* y-label: "Hydrogen Bond Index" */     /* type:    "Discrete" */     static char *gromacs_xpm[] = {     "201 2   2 1",     "   c #FFFFFF " /* "None" */,     "o  c #FF0000 " /* "Present" */,     /* x-axis:  0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 3 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 4 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 5 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 6 6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 6.9 7 7.1 7.2 7.3 7.4 7.5 7.6 7.7 7.8 7.9 */     /* x-axis:  8 8.1 8.2 8.3 8.4 8.5 8.6 8.7 8.8 8.9 9 9.1 9.2 9.3 9.4 9.5 9.6 9.7 9.8 9.9 10 10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8 10.9 11 11.1 11.2 11.3 11.4 11.5 11.6 11.7 11.8 11.9 12 12.1 12.2 12.3 12.4 12.5 12.6 12.7 12.8 12.9 13 13.1 13.2 13.3 13.4 13.5 13.6 13.7 13.8 13.9 14 14.1 14.2 14.3 14.4 14.5 14.6 14.7 14.8 14.9 15 15.1 15.2 15.3 15.4 15.5 15.6 15.7 15.8 15.9 */     /* x-axis:  16 16.1 16.2 16.3 16.4 16.5 16.6 16.7 16.8 16.9 17 17.1 17.2 17.3 17.4 17.5 17.6 17.7 17.8 17.9 18 18.1 18.2 18.3 18.4 18.5 18.6 18.7 18.8 18.9 19 19.1 19.2 19.3 19.4 19.5 19.6 19.7 19.8 19.9 20 0 */     /* y-axis:  0 1 0 */     "ooooooooooooooo oooooooooooooooooooo oo oooo ooooooooooo  oooooooooooooooooooooooooooooooooo   o oooooooooooooooo ooo oooooooooooooooooooooooooooooooooooooo ooooo ooo  oooooo  o oooooooo   ooooo oooooo",     "                                                                                o o                       "      This file is also available here, on Google Docs. The last two lines provide the matrix data. If there is an `"o"` character, then that particular hydrogen bond (each line represents a different hydrogen bond) exists at that time. Do you know if there are any functions or add-on packages for Mathematica that can read in XPM files? In particular, I would like to read in the last two lines:               "ooooooooooooooo oooooooooooooooooooo oo oooo ooooooooooo  oooooooooooooooooooooooooooooooooo   o oooooooooooooooo ooo oooooooooooooooooooooooooooooooooooooo ooooo ooo  oooooo  o oooooooo   ooooo oooooo",     "                                                                                o o                       "      and store the result as a `List`, `Array`, or `SparseArray`. Probably `SparseArray` would be desirable because the values in the matrix are binary -- a particular hydrogen bond either exists at a certain time or it doesn't. Also, it doesn't really matter what character we use to represent existence (in the above, they use `"o"`) and absence (in the above, they use `" "`). Do you have any advice on the best way to read in this data? The sample above is only very small; however, the files can get _much_ larger, so I probably will not be able to import the entire file at once using `Import`. Probably I will have to read the file piecewise, perhaps using `Stream`. Thanks for your time.


How to check if a database connection is open?

In[32]:= SQLConnections[]          Out[32]= {SQLConnection["db", 1, "Closed", "<>"],       SQLConnection["db", 2, "Closed", "<>"],       SQLConnection["db", 3, "Open", "Catalog" -> "db",        "ReadOnly" -> True]}          In[33]:= Cases[SQLConnections[], SQLConnection[__, "Open", __]]          Out[33]= {}      doesn't work. Why it doesn't match the one open connection expression?


How to properly handle mutual imports of multiple packages?

I'm new to the mathematica platform and I am developing a simulation framework as my first exercise and have been tearing my hair figuring how to make packages interact with each other. Ill explain a minimum package experiment I developed to understand my problems and please I would like a theoretical explanation of why this happens, if it is a bug or if I am just dumb with mathematica. The thing is that if I have packages that use each others exported symbols or functions inside their functions, after the first package is loaded he loads the others declared as needed as well, but then only that package that was loaded first can reference all other exported stuff, and the others for some reason can only look at the exported data of later packages/contexts in the context path. To make every package able to see every other exports I need to load them again individually. This makes no sense to me, I thought the whole point of having needs in any package constructor is to avoid loading myself every package of my packages set. Is this a bug? Btw, the exported symbols from different packages are found right away by mathematica is just the symbols inside functions that cant reference each other. So basically I defined three packages, ja1,ja2,ja3. All have the same structure like this: **Package ja1**               BeginPackage["SimulationsSystem`ja1`", { "SimulationsSystem`ja2`", "SimulationsSystem`ja3`"}]          shadow::usage="shadow"     var1::usage = "var1"     pro1::usage = "pro1"     (* Exported symbols added here with SymbolName::usage *)            Begin["`Private`"] (* Begin Private Context *)           shadow=1;     var1=1;     pro1[]:=var1+var2+var3          End[] (* End Private Context *)          EndPackage[]      **Package ja2**               BeginPackage["SimulationsSystem`ja2`", { "SimulationsSystem`ja1`", "SimulationsSystem`ja3`"}]          shadow::usage="shadow"     var2::usage = "var2"     pro2::usage = "pro2"     (* Exported symbols added here with SymbolName::usage *)            Begin["`Private`"] (* Begin Private Context *)           shadow=2;     var2=1;     pro2[]:=var1+var2+var3     End[] (* End Private Context *)          EndPackage[]      **Package ja3**               BeginPackage["SimulationsSystem`ja3`", { "SimulationsSystem`ja1`", "SimulationsSystem`ja2`"}]          shadow::usage="shadow"     var3::usage = "var3"     pro3::usage = "pro3"     (* Exported symbols added here with SymbolName::usage *)            Begin["`Private`"] (* Begin Private Context *)           shadow=3;     var3=1;     pro3[]:=var1+var2+var3     End[] (* End Private Context *)          EndPackage[]      **Commands run** : so after defining the packages I tried to run each pro function, called each var and called shadow to see the nearest Package/context working. And here is the result:               In[2]:= << SimulationsSystem`ja2`     $ContextPath          Out[5]= {"SimulationsSystem`ja2`", "SimulationsSystem`ja1`", \     "SimulationsSystem`ja3`", "SimulationsSystem`SimulationsSystem`", \     "SimulationsSystem`Models`Basic`", \     "SimulationsSystem`SimulFunctions`", \     "SimulationsSystem`TurnPackages`", \     "SimulationsSystem`EventFunctions`", "SimulationsSystem`Classes`", \     "PacletManager`", "WebServices`", "System`", "Global`"}          In[6]:= pro1[]          Out[6]= 2 + SimulationsSystem`ja1`Private`var2          In[7]:= pro2[]          Out[7]= 3          In[8]:= pro3[]          Out[8]= 1 + SimulationsSystem`ja3`Private`var1 + \     SimulationsSystem`ja3`Private`var2          In[9]:= var1          Out[9]= 1          In[10]:= var2          Out[10]= 1          In[11]:= var3          Out[11]= 1          In[12]:= shadow          Out[12]= 2          In[13]:= << SimulationsSystem`ja3`     $ContextPath          Out[14]= {"SimulationsSystem`ja3`", "SimulationsSystem`ja2`", \     "SimulationsSystem`ja1`", "SimulationsSystem`SimulationsSystem`", \     "SimulationsSystem`Models`Basic`", \     "SimulationsSystem`SimulFunctions`", \     "SimulationsSystem`TurnPackages`", \     "SimulationsSystem`EventFunctions`", "SimulationsSystem`Classes`", \     "PacletManager`", "WebServices`", "System`", "Global`"}          In[15]:= pro1[]          Out[15]= 2 + SimulationsSystem`ja1`Private`var2          In[16]:= pro2[]          Out[16]= 3          In[17]:= pro3[]          Out[17]= 3          In[18]:= var1          Out[18]= 1          In[19]:= var2          Out[19]= 1          In[20]:= var3          Out[20]= 1          In[21]:= shadow          Out[21]= 3          In[22]:= << SimulationsSystem`ja1`     $ContextPath          Out[23]= {"SimulationsSystem`ja1`", "SimulationsSystem`ja3`", \     "SimulationsSystem`ja2`", "SimulationsSystem`SimulationsSystem`", \     "SimulationsSystem`Models`Basic`", \     "SimulationsSystem`SimulFunctions`", \     "SimulationsSystem`TurnPackages`", \     "SimulationsSystem`EventFunctions`", "SimulationsSystem`Classes`", \     "PacletManager`", "WebServices`", "System`", "Global`"}          In[24]:= pro1[]          Out[24]= 3          In[25]:= pro2[]          Out[25]= 3          In[26]:= pro3[]          Out[26]= 3          In[27]:= var1          Out[27]= 1          In[28]:= var2          Out[28]= 1          In[29]:= var3          Out[29]= 1          In[30]:= shadow          Out[30]= 1      You can see in the output that only after packages are loaded by themselves they are able to recognize every other packages' exported symbols and functions.


Efficient way of finding shortest distance between two sets of points in mathematica

I have two sets of 3D points, say               a = RandomReal[1, {10, 3}];     b = RandomReal[1, {10, 3}];      I wanna find the first N pairs that have shortest distance between the two sets, my current approach is to form a `NearestFunction` from the first list and map it to the second(say, N=3):               f = Nearest[a];     c = Flatten[f/@b, 1];      Then get the result:               N=3;     Transpose[{c[[#]], b[[#]]}]&@ Ordering[Norm/@(c-b),N]          Output={{1st pair},{2nd pair},{3rd pair}}      **Question:What is the more efficient way of finding shortest distance pairs of two sets in mathematica?** -edit- In my actual case, I want to determine the intersection of two shapes(manifolds), but the analytic form of these shapes are not available. I can only compute points on these shapes through numerical process(`NDSolve`). So I want to use enough many points to approximate these shapes, and use `Intersection`-like operation to find points that lay approximately on both shapes. The number of points is very large(eg. 10^7), and the points may in high dimensional space(eg. 4D). Excuse me for my crippled English. I am greatly appreciate any suggestions, thank you very much!


Zooming the interval arround $0.333\cdots $, whats wrong?

I'm trying to zoom the interval arround $0.333\cdots$ with:               Manipulate[      ListLinePlot[Table[{n, Sum[3/10^x, {x, n}]}, {n, 1, 20, 1}],        Mesh -> All,        PlotRange -> {{0, 20}, {(Sum[3/10^t, {t, g}] - 1/10^g), (Sum[3/10^t, {t, g}] + 1/            10^g)}}], {g, 2, 20, 0.001}]      I know that I can use the interval `(Sum[3/10^t, {t, g}] - 1/10^g), (Sum[3/10^t, {t, g}] + 1/10^g)` because I've evaluated this:               Table[N[Sum[3/10^t, {t, n}] - 1/10^n, n], {n, 2, 10}]      Which yields:               (* {0.32, 0.332, 0.3332, 0.33332, 0.333332, 0.3333332, 0.33333332, 0.333333332, 0.3333333332} *)      And:               Table[N[Sum[3/10^t, {t, n}] + 1/10^n, n], {n, 2, 10}]      which yields:               (* {0.34, 0.334, 0.3334, 0.33334, 0.333334, 0.3333334, 0.33333334, 0.333333334, 0.3333333334} *)      But something weird is happening and the plot is jumping in a weird way. I have no clue of what's going on.


Is there a way to get user input when running a script on a Linux terminal?

I have access to a node of a Linux cluster, on which Mathematica is installed. However, I do not have access to a Linux GUI. Typically I write and test Mathematica scripts on my Windows personal computer (with the typical GUI/front end). Then, I run the scripts on the Linux terminal because the terminal is significantly faster than my desktop computer (my scripts read and write a _lot_ of data). I use the command:               math < test.txt      where `test.txt` is a text file containing Mathematica code. I have been using this command successfully to run my scripts. I just always need to make sure that I do not try to print graphics to the screen, since I don't have a Linux GUI. However, now I would like to write a script that prompts the user for input. For example, this code works fine on the Windows GUI: Print["start"]; str = InputString[]; Print["string: " <> str]; Print["finish"]; But, it fails on the Linux terminal, generating this console output: > Mathematica 7.0 for Linux x86 (64-bit) Copyright 1988-2008 Wolfram Research, > Inc. > > In[1]:= start > > In[2]:= ? > > In[3]:= finish > > In[4]:= Is there any way I can prompt the user for input on a Linux terminal? The input does not necessarily need to be interactive. For example, I can imagine there being a way to pass an input string to `math` by a command like:               math -input "This is my input string." < test.txt      but I am not sure what is the syntax to do this. **Addendum:** `InputString[]` works on the terminal if I simply **enter** a terminal using the command:               math      and then type `InputString[]` in the input prompt. However, this is _not_ how I want to run my scripts, since this (I think) would require me to retype **every** command, line by line.


How do I use the ShowLegends function to produce a legend for my framed graphic?

I'm new to this site and new to Mathematica as you can see from my question. I'm also new to programming, btw. I'm trying to produce a legend for my plot which I've coded as follows:               Needs["PlotLegends`"]     ds1 = {{0, 0.53}, {10, 1.00}, {20, 2.19}, {35, 3.61}};     ds2 = {{0, 0.52}, {10, 0.91}, {20, 1.97}, {35, 3.09}};     ds3 = {{0, ds1[[1, 2]] - ds2[[1, 2]]},             {10, ds1[[2, 2]] - ds2[[2, 2]]},             {20, ds1[[3, 2]] - ds2[[3, 2]]},             {35, ds1[[4, 2]] - ds2[[4, 2]]}           };     mf1 = LinearModelFit[ds1, x, x];     mf2 = LinearModelFit[ds2, x, x];     mf3 = LinearModelFit[ds3, x, x];     m1 = mf1["BestFit"]; m2 = mf2["BestFit"]; m3 = mf3["BestFit"];          Show[       {         ListPlot[{ds1, ds2, ds3},             PlotMarkers -> Automatic, PlotStyle -> {Blue, Red, Orange}         ],          Plot[{m1, m2, m3}, {x, 0, 35}, PlotStyle -> {Blue, Red, Orange}]       },        Frame -> True,        FrameLabel -> {"Time (min)","Inorganic Phosphate Concentration (mM)"},       ImageSize -> {400, 300}     ]      So, I'd like to use the `ShowLegend` function to have the legend displayed outside of the frame. I know that I can use the `LegendPosition` function to do this. My problem, however, is the tags. How do I get the legend to show the names of the plots (ds1, ds2, ds3, m1, m2, and m3)?


Manually launching remote kernel results local process frozen

I'm trying to launch a Linux (Ubuntu latest) machine as a slave of my local PC (Windows 8). Both machine have Mathematica 9 installed. However, I'm behind a router, so I think it's a little more complicated. I found out that mathematica uses port ranging from 58000 to 59000 (at least at the moment I ran it, because actually it just asks the system for one, which increases constantly), so I forwarded the router's port 58000~59000 to my PC. Following this FAQ, I went ahead and set up my local kernel, and start to listen. The prompted window said > Link created on: 58917@104.xx.xxx.xxx,58918@104.xx.xxx.xxx so I went ahead, opened up putty, connected to the remote machine, started mathematica kernel using `math`, and ran               $ParentLink = LinkConnect["58917@104.xx.xxx.xxx,58918@104.xx.xxx.xxx", LinkProtocol->"TCPIP"]      Immediately, on my local machine, a message box pops up that says:               Out[1]= LinkObject[58917@104.xx.xxx.xxx,58918@104.xx.xxx.xxx, 60, 1]      which I suppose means that the connection is successful. However, on my local PC, the entire mathematica process freezes and becomes "not responding". ![screenshot](http://i.stack.imgur.com/XGYEN.png) Has anyone ever encountered the same problem? Why is that? * * * **Update** : After a long _long_ time, the message box finally printed something new: ![enter image description here](http://i.stack.imgur.com/tKFNs.png) Not a good news huh? Again what might be happending?


lists of conditions

I have got coordinates in two list of Latitude and Longitude and would like to check if those coordinates are in a certain grid Example lists are:               qLon={-7.48333, -10.4667, -8.66667, -7.48333}     qLat={53.5, 52.5, 53.1167, 51.9833, 51.0167}      Grid borders:                 SLat=47       NLat=55       ELon=-15       SLon=-5      My idea was:               If[ELon <= # <= WLon, "","Outside Grid"] & /@ qLon     If[SLat <= # <= NLat, "","Outside Grid"] & /@ qLat      I would like to merge them, to do the test in one go, like:               If[ELon <= #1 <= WLon && SLat <= #2 <= NLat,...      but could not get it working. Another thing is the output; it should only show something if there is a point outside the grid.


How can I open an Excel file and modify it in Mathematica?

I wanted to ask how can I view an Excel file from a _Mathematica_ notebook and modify it. I have seen a similar question, Open Excel file with Mathematica, but the answer involves .NET. Is there any other way to open an Excel file and modify it?


Find all roots of an interpolating function (solution to a differential equation)

I'm trying to find all the roots of the solution to a differential equation. Using NSolve or Reduce I don't get the roots, so I'm using an iterative method which I found in physicsforums.com. This method solves my problem, but you have to choose the increment and thus in some cases it might give headaches. I wonder if there is any more general approach. Following is a sample code:               data = NDSolve[{1.09 x''[t] - 0.05 x'[t] + 1.1759 Sin[x[t]] == 0,              x[0] == Pi/3, x'[0] == 0}, x, {t, 0, 50}]       > {{x->InterpolatingFunction[{{0.,50.}},<>]}} First attempt with no success:               sol = NSolve[x'[t] == 0 /. data , t]       > NSolve::ifun: Inverse functions are being used by NSolve, so some solutions > may not be found; use Reduce for complete solution information. >> > > {{t->InverseFunction[InterpolatingFunction[{{0.,50.}},<>],1,1][0.]}} Second attempt with no success:               sol = Reduce[x'[t] == 0 /. data , t]       > Reduce::inex: Reduce was unable to solve the system with inexact > coefficients or the system obtained by direct rationalization of inexact > numbers present in the system. Since many of the methods used by Reduce > require exact input, providing Reduce with an exact version of the system > may help. >> > > Reduce[{InterpolatingFunction[{{0.,50.}},<>][t]==0},t] Third attempt, works fine, but manually choosing `dt` could cause problems with some equations:               dt = 0.1;      tmin = 0.;      tmax = 50.;           Union[Table[t /. FindRoot[x'[t] == 0 /. data ,{t, tInit, tmin, tmax}],         {tInit, tmin + dt,tmax - dt, dt}], SameTest->(Abs[#1 - #2] < 10^-2&)]       > {0., 3.26812, 6.58301, 9.95657, 13.4054, 16.9538, 20.6403, 24.533, 28.7857, > 34.2571} Is there any more elegant method to find all roots in a range?


How can I randomize the elements of a list?

Is there a straightforward way to go from an ordered list like:               ord = {a, b, c, d, e, f, g, h}      to a disordered list like:               randompos = {c, h, d, g, a, b, f, e}      I can use something like:               DeleteDuplicates @ RandomChoice[ord, 50]      but it's not really robust. Is there an easier way?


Assigning a particular value to array elements

I have an array of 10000 elements. I want to randomly assign energy to these 10000 elements using Gaussian or Exponential distribution, such that each time a particular element is selected its energy should also be shown in the output. Can anyone suggest me how to solve this problem? Let's say, I have 10 elements in the array {8,4,6,2,9,0,5,1,7,3} and I am assigning energy to these 10 elements randomly. After that I am selecting one of the element in the array, say 7, when I select this number I also want to know the energy that number possesses. This is the program I wrote to generate 1000 elements.               l = 0;     For[i = 0, i < 10, i++,      For[j = 0, j < 10, j++,       For[k = 0, k < 10, k++,        Xarray[l] = A[i, j, k];        Print[Xarray[l]];        l++;        ]       ]      ]     Xarray[5]      When `Xarray[5]` is given it will show the coordinate it possesses. In addition to this I want to know the energy when I am giving `Xarray[5]`, `Xarray[998]`, etc.


How to get rid of nested matrices

If I type into Mathematica               TensorProduct[IdentityMatrix[2],IdentityMatrix[2]]      It gives me a result that has nested matrices. How do I turn that into a normal matrix without any nesting? Thanks


Controlling CDF window size

I want to ask how can I control the `CDF` `WindowSize` in such a way that the end user can minimise its size upto some extent only. For example, If the `WindowSize` is less than or equal to {300,200}, then it should not be minimised but, it can be maximised.               Dynamic[(width = CurrentValue["WindowSize"][[1]];             height = CurrentValue["WindowSize"][[2]];      If[width <= 300, (width = 301), (width = CurrentValue["WindowSize"][[1]])];      If[height <= 200, (height = 201), (height = CurrentValue["WindowSize"][[2]])];      Panel[Button["Click1"], {width, height}, ImageSize -> {width, height}])]


Problem with using the results of ParametricNDSolve in a ParametricPlot3D

I new to _Mathematica_ and I have a problem with certain equations. I want to plot a trajectory in spherical coordinates given by the equations:               (1 + α^2)*(Abs[γ])^-1*θ'[t] == (Sin[2*θ[t]]*Subscript[H, d]*α)/                2 + ((Cos^2)[ϕ[t]]*Sin[2*θ[t]]*α - Sin[2*ϕ[t]]*Sin[θ[t]])*Subscript[H, k]/                2 - (α*M*(Cos[β]*Cos[θ[t]]*Cos[ϕ[t]] - Sin[β]*Sin[θ[t]]) +            M*Cos[β]*Sin[ϕ[t]])*Subscript[α, j]      and               (1 + α^2)*(Abs[γ])^-1*ϕ'[t] == -Cos[θ[t]]*Subscript[H, d]*α - (2*(Cos^2)[ϕ[t]]*Cos[θ[t]] -                  α*Sin[2*ϕ[t]])*Subscript[H, k]/2 - Cos[θ[t]]*(α*M*(Cos[β]*Cos[θ[t]]*Cos[ϕ[t]] -              Sin[β]*Sin[θ[t]]) -              M*Cos[β]*Sin[ϕ[t]])*Subscript[α, j]      My (crude) code is:               sol = ParametricNDSolve[{(1 + α^2)*(Abs[γ])^-1*θ'[t] == (Sin[2*θ[t]]*Subscript[H, d]*α)/            2 + ((Cos^2)[ϕ[t]]*Sin[2*θ[t]]*α - Sin[2*ϕ[t]]*Sin[θ[t]])*Subscript[H, k]/            2 - (α*M*(Cos[β]*Cos[θ[t]]*Cos[ϕ[t]] - Sin[β]*Sin[θ[t]]) +             M*Cos[β]*Sin[ϕ[t]])*Subscript[α, j], (1 + α^2)*(Abs[γ])^-1*ϕ'[t] ==                  -Cos[θ[t]]*Subscript[H, d]*α - (2*(Cos^2)[ϕ[t]]*Cos[θ[t]] - α*                  Sin[2*ϕ[t]])*Subscript[H, k]/2 -             Cos[θ[t]]*(α*M*(Cos[β]*Cos[θ[t]]*Cos[ϕ[t]] - Sin[β]*Sin[θ[t]]) -             M*Cos[β]*Sin[ϕ[t]])*Subscript[α, j], ϕ[0] == 0, θ[0] == 0},            {ϕ[t], θ[t]}, {t, 0, 100},            {α, Subscript[H, d], Subscript[α, j], Subscript[H, k], M, γ, β}]      and I try to plot it:               ParametricPlot3D[      Evaluate[{M*Cos[ϕ[t]]*Sin[θ[t]] /. sol,          M*Sin[ϕ[t]]*Sin[θ[t]] /. sol,          M*Cos[θ[t]] /. sol} /. {α -> 1,          Subscript[H, d] -> 1, Subscript[α, j] -> 1,          Subscript[H, k] -> 1, M -> 1, γ -> .1, β -> .1}, {t,         0, 100}]]      but the plot isn't displayed and I don't get any errors. Does anyone know what am I doing wrong? Thanks in advance!