title: How can I remove orange-box around the Graphics3D?

text: I don't know whether this is a correct question or not, but I played from two days on this problem and still I didn't find a solution. ![Mathematica graphics](http://i.stack.imgur.com/zKNjo.png) The save button is enabled whenever we have to specify width,length,height and middleheight of a `Graphics3D`. `Graphics3D` appears whenever we have clicked on the save button depending upon width, length, height and middleHeight values. This is my application concept. For this purpose I wrote a huge amount of code, but I show here only a little bit of the code related to `Graphics3D` and also the sizes of the `Buttons`,`InputFields`and the application-window Size.               Dynamic[Pane[                  Manipulate[designSpace, Paneled -> False,AppearanceElements -> None                            ](*Manipulate is closed here*),              Scrollbars -> {Automatic, Automatic},AppearanceElements -> None, ImageSize -> {560, 310},Alignment -> {Center, Center}                 ](*Pane is closed here*)            ](*Dynamic is closed here*)      Note:In the code designSpace is `Graphics3D` related code. The application window size is {580,480}, `Buttons`,`InputFields` sizes {160,60}, pane size {560,310}. Concept-wise it is working fine but the problem is:   1. `InputFields` and `Buttons` are blinking at the `Graphics3D` rotation time.   2. Some orange box appears around the `InputFields`,`Buttons`and `Graphics3D` whenever we have to double click on the application.   3. If we have clicked on any wall of `Graphics3D`.`createDialog` will appear in that we have to specify the positions, some `Image` overlap on that wall depending upon that specification. The third point concept is not working. This overlaps with the concepts that I already asked about in my earlier posts, but I still don't get it.


title: Exclude Sections/Subsections/... from evaluation

text: I'm working on a large notebook and I want to exclude some sections and subsections from being evaluated when I evaluate the whole notebook. Is there a way to exclude specific sections or subsections from the notebook evaluation while maintaining their original format? Or even better, format them e.g. by adding a gray background?


title: "Unflattening" a list

text: Imagine we have a list with some hierarchical structure:               list = {{{2,3},{2,4}},{{{3,4}}},{{5,6},{7,8}}};      Which we then flatten to some level in order to process the data points:               Flatten[list,1]     >> {{2, 3}, {2, 4}, {3, 4}, {5, 6}, {7, 8}}      We then do "something" to change the value of the elements in the list, without increasing or decreasing the number of elements:               >> {{5*10^9, 3}, {2, 4}, {3, 4}, {191991, 6}, {7, 8}}      Can we reverse the flattening procedure to go back to a list of the form:               >> {{{5*10^9,3},{2,4}},{{{3,4}}},{{191991,6},{7,8}}};


title: Creating legends for plots with multiple lines?

text: So I have a graph with multiple lists, for e.g.               data = {{1,2}, {3,4}, {3,5}, {2,3} . . .}      If I then do `ListLinePlot[Table[{#1,Log[b,#2]}&@@@data, {b,1,10,2}]]` I have no way to generate a legend for it, that I see anyway. I cannot put anything inside the `Table` which contains the iterator. Would I do something alone the lines of `Legend-> Log[Range[1,10,2,x]]`?


title: Show Legend with 3D ListPlot

text: > **Possible Duplicate:**   >  Creating legends for plots with multiple lines? I am trying to plot the color bar that shows the data range for the data plotted by `ListPlot3D`. I want to ask if I can use the `ShowLegend` command with the `LisPlot3D`? My code is as the following :               Needs["PlotLegends`"];     s = Import["C10002.xls"]     Rotate[ListPlot3D[s, PlotRange -> {0.048, 0.22}, Mesh -> None,        AxesLabel ->        Style[StandardForm[\[Phi]], FontSize -> 20, FontWeight -> "Bold"]],       30 Degree, {0, 1, 0}]          ShowLegend[       ListPlot3D[s, PlotRange -> {0.048, 0.22}, Mesh -> None,        AxesLabel ->        Style[StandardForm[\[Phi]], FontSize -> 20, FontWeight -> "Bold"]],       LegendPosition -> {1.1, -.4}]      I will be very thankful for your help.


title: Make PlotMarker explanation

text: > **Possible Duplicate:**   >  Creating legends for plots with multiple lines? I have a ListPlot of data points. To distinguish between datapoints coming from different sources, I give them different PlotMarkers, say green triangles for one, and red circles for another. An example could be:               Jones2012 = {{3, 2.5}, {2, 4}};     Adams1999 = {{1, 2}, {4, 4}};     ListPlot[{Jones2012, Adams1999}, Frame -> True,       PlotMarkers -> {{\[FilledCircle], 20}, {\[FilledUpTriangle], 20}},       PlotStyle -> {Red, Darker[Green]},       PlotRange -> {{0, 5}, {0, 5}}]      Now I want to have a small box in the upper right corner explaining what data the different markers correspond to, e.g. Jones 2012 is marked with red circles. I am thinking that the best way to do it would be to make a box as an object first, then insert this object in the graphics afterwards. My best try at making the box so far is:               triangle =       Graphics[{Thick, Darker[Green], Polygon[{{0, 0}, {1, 0}, {0.5, 1}}]},        ImageSize -> 10]     circle = Graphics[{Thick, Red, Disk[{0, 0}]}, ImageSize -> 10];     box = Framed@       Text[Style[triangle "Jones 2012" circle "Adams 1999", 12]]      or               box = Framed@       Text[Style[triangle "Jones 2012 \nAdams 1999" circle, 12]]      But what I would like to do is to have the symbols first on the line, followed by what it represents, then a new line with the next data set. So something like: "green triangle" Adams 1999 "red circle" Jones 2012 Preferably the symbols would be aligned, as well as the left edge of the text. I feel like I should be close, but can't seem to figure out that last little thing to get it how I want it. Thanks so much!


title: Extra lines in the legend of a ParametricPlot

text: > **Possible Duplicate:**   >  Creating legends for plots with multiple lines? Why does the legend of this plot have 5 lines (in mathematica 8, at least) instead of 3?               Needs["PlotLegends`"]     ParametricPlot[      Evaluate[Table[{k Cos[x], k*Sin[x]}, {k, 1, 3}]], {x, 0, 2 \[Pi]},       PlotStyle -> {Directive[Purple, Thick],         Directive[Thick, Orange, Dashing[{.03}]]},       PlotLegend -> Range[1, 3], LegendPosition -> {.5, -.8}]      ![Mathematica graphics](http://i.stack.imgur.com/mpywH.png) How could I plot the legend correctly? --EDIT-- This is not an answer, but it may come handy to someone with the same problem: Creating legends for plots with multiple lines? replacement of `PlotLegend` works.


title: Solving a differential equation with mixed conditions using DSolve

text: I want to solve a differential equation $$ \frac{d}{dx}\left(k_0 \left(\frac{T(x)}{T_0}\right)^n \frac{dT(x)}{dx}\right)=0,$$ with boundary conditions: $T(l)=T_0$, $\;T'(0)=-\frac{q_0}{k_0 T(0)^n}\;$ using `DSolve`, but I cannot get a solution. Can anyone help me?


title: Connect each point in the plot with all adjacent points

text: I have the following simple code. I need to connect each point in the plot with all adjacent points in vertical or horizontal line.               n = 5;     nodes = Flatten[        Table[{i (16 2.54)/n, j (16 2.54)/n}, {i, 0, n}, {j, 0, n}], 1];     dataPlot = ListPlot[nodes, PlotStyle -> PointSize -> Large];     nodelabels =        Table[Text[         Style[i + (n + 1) j + 1, 14, Bold], {0.7 + i (16 2.54)/n,           0.7 + j (16 2.54)/n}], {i, 0, n}, {j, 0, n}];     elementlabels =        Table[Text[         Style[i + (n) j + 1, 14,           Bold], {(16 2.54)/(2 n) + i (16 2.54)/n, (16 2.54)/(2 n) +            j (16 2.54)/n}], {i, 0, n - 1}, {j, 0, n - 1}];     Show[Graphics[{{Red, nodelabels}, {elementlabels}}], dataPlot,       AspectRatio -> 1, Axes -> True, ImageSize -> 600]      I have manually added some lines to show what I am looking for. ![enter image description here](http://i.stack.imgur.com/hRzvG.jpg) **note:** there is a way to do that using ListLinePlot but this method requires to overlay so many ListLinePlot. I would prefer to get solution using Vertex functions.


title: Export results to excel

text: I have the following problem solved in Mathematica               m=Table[For[i = 0, i <= .7, i = i + 0.1,        Print[NMinimize[{i*Abs[(E^-k*(N*p)^k)/k! - k^-g] +            i/3*Abs[p - N^-r] + (1 - (2*i)/3)*            Abs[Log[N]/Log[N*p] - (A*Log[N - B] + CC)], A != 0, B != 0,           CC != 0, N > 0, k > 1, N <= 1000, k <= 100, N - k >= 0,           N - B > 0, BB, g > 2, g < 3, r > 0, r < 1, N^-r < 1, k/N < 1,           p <= 1}, {A, B, CC, N, k, g, r, p},          Method -> "SimulatedAnnealing"]]], {j, 1}]      I want to turn it into a form which can be exportable to excel. I tried:               m//TableForm      but doesn't work. Can you please help me? Thank you in advance


title: Sorting list with variable

text: I want to sort (or sortby) the list. List contains uninitialized variable m and I can assume that `m` is a Natural number that is much larger then any constant. Example input:               a = {-116*m, 0, 3 - 11*m, 1 - m, -20*m - 7, -m}      Example output:               {-116*m, -20*m - 7, 3 - 11*m, -m, 1 - m, 0}      My effort:               MAGICNUMBER = 1000000;     Sort[a, (#1 /. m -> MAGICNUMBER) < (#2 /. m -> MAGICNUMBER) &]


title: Using 'Reduce' to solve a set of inequalities, specified by a list

text: I have a two lists $LHS$ and $RHS$, both of size $n$. I want to solve a system of inequalities of the form: $$LHS[1] \leq RHS[1]$$ $$LHS[2] \leq RHS[2]$$ $$LHS[3] \leq RHS[3]$$ $$\vdots$$ $$LHS[n] \leq RHS[n]$$ We assume that: Each $LHS[i]$ is a linear equation in $m$ variables, say: $\alpha_{1}, \dots, \alpha_{m}$ and each $RHS[i]$ is a linear equation in $m$ variables, say: $\beta_{1}, \dots, \beta_{m}$. We need to solve for $\alpha_{1}, \dots, \alpha_{m}$, $\beta_{1}, \dots, \beta_{m}$, which are positive integers. Take m=2. To solve a single inequality (for some $i$ between $1$ and $n$) I know that I need to enter: > Reduce[LHS[[i]]<=RHS[[i]],{[\alpha]0,[\alpha]1,[\beta]0,[\beta]1}] (I haven't put the constrains to make the code simpler) But, if I need to solve all the inequalities, **how do I input a list in 'Reduce'** ? Thanks a lot in advance.


title: ListPlot filling not appearing when point is out of range

text: In a non-joined `ListPlot` one can specify that a filling line is shown for each point:               ListPlot[Table[{x, Exp[-x^2]}, {x, -2, 2, 0.1}], Filling -> Axis, FillingStyle -> Red]      ![1](http://i.stack.imgur.com/eAUuX.png) But if the points are out of the plot range, the filling line no longer appears:               ListPlot[Table[{x, Exp[-x^2]}, {x, -2, 2, 0.1}], Filling -> Axis, FillingStyle -> Red,        PlotRange -> {0, 0.5}]      ![2](http://i.stack.imgur.com/I9vYi.png) Is there any way to still show the line up the plot range, to show that there is a point there (but you just can't see it)? Or must I draw the lines myself with a `Prolog`?


title: Is there a way to run Python from within Mathematica?

text: I know there is some support for running _Mathematica_ from Python, but is there any way to do the reverse. For example, to import some Python classes and use them in _Mathematica_?


title: Check if a (possibly nested) list is real

text: I have a very large matrix of numbers. I want to check if all its entries are real. At the moment I am using               realQ = And @@ Thread[Flatten[Im @ #] == 0] &      Is there any faster/safer/better way to do it?


title: Calculate one-tailed critical point from a probability distribution

text: I would like to calculate the numerical value of $\xi\in\mathbb{R}_{\geq0}$$$P(|U|<\xi)=0.95$$ where $U$ is standard-normal distributed. How may I do that in Mathematica?


title: up arrow works in math version 9, fails in math version 8 ^[[A

text: I have strange up-arrow behavior on command line Mathematica 8 versus Mathematica 9. Version 9 gives me history, where version 8 fails with escape codes. Any way to make them both work on the same system?               ubuntu@ip-10-45-11-134:~$ math     Mathematica 9.0 for Linux x86 (64-bit)     Copyright 1988-2013 Wolfram Research, Inc.          In[1]:= $KernelCount                                                                                Out[1]= 0         In[2]:= $KernelCount                                                                                Out[2]= 0     In[3]:= ubuntu@ip-10-45-11-134:~$ math8                                                                                Mathematica 8.0 for Linux x86 (64-bit)     Copyright 1988-2011 Wolfram Research, Inc.     In[1]:= $KernelCount         Out[1]= 0         In[2]:= ^[[A         In[2]:=          ubuntu@ip-10-45-11-134:~$


title: How can I truncate only a single vertex of a polygon?

text: One can truncate all the vertices of a polygon at once with `Truncate`. I want to do exactly that -- but only on a single vertex. Is this possible with _Mathematica_ 9? How?


title: Problem with loading my custom package

text: I've been having quite a bit of trouble loading a package I wrote. I've followed the suggestions on related questions on this site, as well as on _Mathematica_ 's own pages, and still nothing has worked. This is my package code:               BeginPackage["errorpropagation`"]     (* General error propagation formula *)          fError::usage =        "Calculate the error in a function f[{x1,x2,...}] with uncertainties {dx1,dx2,...}."          Begin["`Private`"]          fError[f_, xi__, dx__] :=        Sum[(D[f[xi], xi[[i]]]*dx[[i]])^2, {i, 1, Length[xi]}]^(1/2);          fErrorTest[x_] := Module[{a = 3}, x^3 - a];          End[]          EndPackage[]      And then I try to load it as such:               << pathToFile/errorpropagation.m     g[{x_, y_}] := x^2 + x y;     fError[g, {x, y}, {dx, dy}]     fErrorTest[3]      I've tried different variants of whether the `<<` command takes a string or not, and relative and full path names, but had no success. The package has worked for me if I open it and evaluate the cells in the package, but the whole point of writing a package was to avoid manual evaluation every time.


title: Pattern constraint for two or more variables

text: Is it possible to have a pattern constraint for a function with two or more variables where the pattern is a relation between the vars being accepted e.g.               f[x_,y_]:=...      and I want say, x< 10y. I don't think something like               f[x_,y_/; x<10y]      will work, or other variants of this that I have tried.


title: Consistent Plot Styles across multiple MMA files and data sets

text: I am starting to write a thesis for which I want to use MMA for all my plotting needs, mostly because a lot of the basic analysis has been done there. To ensure that I am applying styles consistently (plot colors, image size, label size, etc.), I need a method which I can use across multiple files. There are several types of plots that I will need:   1. `ListPlot` / `Plot`   2. `ListDensityPlot` / `DensityPlot`   3. `ListContourPlot` / `ContourPlot` I can think of several way of doing this:   1. Define my own functions `thPlot`, `thListPlot`, etc which have my default styles applied   2. Define my own style options into a variable, and use some combination of `FilterRules` and `Options` to make sure that options from that variable are applied to the right type of plot   3. Set default options using `Default` for the different types of plots. I am assuming that each of my datasets (which may have one or more plots) will be self-contained mathematica files that I can re-run. So, if I decide to change the style in some central location (via one of the methods above) I can re-run the MMA files and get the plots in the new style. What have people done in the past?


title: How do I get Nsolve to work with hyperbolic functions?

text: This is a rather simple numerical solution, but it simply doesn't work. Does anybody have a solution?               NSolve[x - Sinh[x] - 1 == 0, x]      > NSolve::nsmet: This system cannot be solved with the methods available to > NSolve.


title: 2X slower with ; -- LibraryLink performance problem

text: This is the continued problem of the LibraryLink memory usage question here and here. In the following code, there is a 2X performance difference with only the change of ";".               MMASrc = "       #include <WolframLibrary.h>       #include <WolframCompileLibrary.h>            DLLEXPORT mint WolframLibrary_getVersion(){         return WolframLibraryVersion;       }       DLLEXPORT int WolframLibrary_initialize(WolframLibraryData \     libData){         return 0;       }            EXTERN_C void zspsv_(char* UPLO, const mint* N, mint* NRHS, \     mcomplex* A, mint* IPIV, mcomplex* B, mint* LDB, mint* INFO);                 EXTERN_C DLLEXPORT int lpkSolveAXBS(WolframLibraryData libData, \     mint Argc, MArgument *Args, MArgument Res){              MTensor ta=MArgument_getMTensor(Args[0]);         MTensor tb=MArgument_getMTensor(Args[1]);         mint N=*MTensor_getDimensionsMacro(tb);         mcomplex* A=MTensor_getComplexDataMacro(ta);         mcomplex* B=MTensor_getComplexDataMacro(tb);              MTensor tclone=0;              char U='U';         mint IPIV[N];         mint NRHS=1;         mint LDA=N,LDB=N;         mint INFO;         mint i,j;              mcomplex AP[N*(N+1)/2];              for(j=0;j<N;j++)           for(i=0;i<=j;i++)             AP[i + (j+1)*j/2] = A[i*N+j];              zspsv_(&U,&N,&NRHS,AP,IPIV,B,&LDB,&INFO);              libData->MTensor_clone(tb,&tclone);              MArgument_setMTensor(Res,tclone);         return LIBRARY_NO_ERROR;       }       ";     Needs["CCompilerDriver`"];          CreateLibrary[MMASrc, "lpk", "Debug" -> True,        "TargetDirectory" -> "/tmp", "CompileOptions" -> "-llapack"];          A = {{1. + 0. I, 0. + 0. I, 0. - 6.94908*^-13 I,          0. - 6.94908*^-13 I}, {0. + 0. I, 1. + 0.0352595 I,          0. - 4.51893*^-11 I, 0. - 4.51893*^-11 I}, {0. - 6.94908*^-13 I,          0. - 4.51893*^-11 I, 1. + 0.0376938 I,          0. + 0. I}, {0. - 6.94908*^-13 I, 0. - 4.51893*^-11 I, 0. + 0. I,          1. + 0.0378932 I}};          B = {1. + 0. I, 0. + 0. I, 0. + 6.94908*^-13 I, 0. + 6.94908*^-13 I};           lpkSolve = LibraryFunctionLoad["/tmp/lpk.dylib", "lpkSolveAXBS", {{Complex, 2}, {Complex, 1}}, {Complex, 1}];      Now test the performance and the memory usage:               MemoryInUse[]/1024.^2     Table[LinearSolve[A, B], {40000}]; // AbsoluteTiming          MemoryInUse[]/1024.^2     Table[lpkSolve[A, B], {40000}]; // AbsoluteTiming          MemoryInUse[]/1024.^2     Table[lpkSolve[A, B], {40000}]; // AbsoluteTiming          MemoryInUse[]/1024.^2          (*     32.2057     {0.560369,Null}     32.2242     {0.115091,Null}     37.1101     {0.121534,Null}     41.995     *)      Note that there seems to be a memory leaking problem, and it is identified as a bug by ruebenko. The work around suggested also by ruebenko is to use ";" at the end of each call to the LibraryLink function. While this solves the memory leak, the performance seems decreaed:               MemoryInUse[]/1024.^2     Table[LinearSolve[A,B];,{40000}];//AbsoluteTiming          MemoryInUse[]/1024.^2     Table[lpkSolve[A,B];,{40000}];//AbsoluteTiming          MemoryInUse[]/1024.^2     Table[lpkSolve[A,B];,{40000}];//AbsoluteTiming          MemoryInUse[]/1024.^2          (*     42.0031     {0.675034,Null}     42.0002     {0.241069,Null}     42.0022     {0.232982,Null}     42.0026     *)      using `Do` instead of `Table` doesn't solve the problem:               MemoryInUse[]/1024.^2     Do[LinearSolve[A,B],{40000}];//AbsoluteTiming          MemoryInUse[]/1024.^2     Do[lpkSolve[A,B],{40000}];//AbsoluteTiming          MemoryInUse[]/1024.^2     Do[lpkSolve[A,B],{40000}];//AbsoluteTiming          MemoryInUse[]/1024.^2          (*     42.0102     {0.595506,Null}     42.012     {0.221176,Null}     42.0138     {0.213203,Null}     42.0154     *)      So why there is a 2X performance difference just by adding ";" at the end of function call, or replace `Do` with `Table`? And how to fix it?


title: Recursive formula involving a piecewise function

text: I am trying to construct a recursion, `g[t]`, where   * `g[t] = a[t]` if `g[t-1] = 1`   * `g[t] = b[t]` if `g[t-1] = 2`. Additionally `a` and `b` are defined as:               a[t_] := If[0 <= RandomReal[] <= 0.94, 1, 2]     b[t_] := If[0 <= RandomReal[] <= 0.9, 2, 1]      So then I want (I've also tried it where I replace `a` and `b` with their original defintions):               g[t_]:= Piecewise[{{a[t], g[t - 1] = 1}, {b[t], g[t - 1] = 2}}]     g[1] = 1      This, however, is not working.


title: Using functions to make loops

text: I'm trying to make a simulation of an electron that goes through a magnetic and electric field perpendicular to each other and to the velocity of the electron but I'm running in some troubles with the _Mathematica_ language. I'm a beginner at _Mathematica_ language and I ended up probably using too much procedural programming and I would like suggestions on how I can improve it using real _Mathematica_ language. For those who saw this question before I edited it, the second problem was fixed and it was a simple logic mistake, so I took it of the question.               vel = {0.05*300000000, 0, 0}; (* velocity *)     pos = {0, 0, 0}; (* position *)     acel = {0, 0, 0}; (* acceleration *)     ce = {0, -5000, 0}; (* electric field *)     cm = {0, 0, -0.0003}; (* magnetic field *)     dt = 0.000000000001;     l = 0.05; (* length of the region where there are magnetic and electric fields *)     me = 9.10938*10^-31; (* electrons mass *)     q = -1.60217657*10^-19; (* elementary charge *)     data = Table[0, {i, 1000000}, {j, 2}];     For[count = 1, pos[[1]] <= 1.5*l, count++,          If[Abs[pos[[1]]] <= l, acel = q/me*(ce + (vel\[Cross]cm)), acel = {0, 0, 0}];           pos = pos + vel*dt + (acel*dt^2)/2; vel = vel + acel*dt;          data[[count, 1]] = pos[[1]]; data[[count, 2]] = pos[[2]]        ];     For[r = 100000; s = 0.00001, r > 0.001, r = (r/10); s = (s/10),          While[Abs[vel[[2]]] > r, cm[[3]] = cm[[3]] - s;                   vel = {0.05*300000000, 0, 0};                   pos = {0, 0, 0};                   data = Table[0, {i, 1000000}, {j, 2}];                      For[count = 1, pos[[1]] <= 1.5*l, count++,                           If[Abs[pos[[1]]] <= l, acel = q/me*(ce + (vel\[Cross]cm)), acel = {0, 0, 0}];                            pos = pos + vel*dt + (acel*dt^2)/2; vel = vel + acel*dt;                           data[[count, 1]] = pos[[1]]; data[[count, 2]] = pos[[2]]                         ];               ];         ];      I know that there are duplicate variable declarations and redundant statements in the code, its because I pasted everything together to post here, but it was originally apart.


title: How to Solve/NSolve/Reduce this rationalized equation

text: In this problem I don't know why the system is not solvable. I have just one unknown K0.                  sol[K0_]:=SetPrecision[-(2397273135785684105116286138088240239609486751943174/        6428810371332877606946043738694402071216515377775) - (        7849 Sqrt[-41616 + (        149163411674835586124096205921334157174479655112799 Sqrt[K0])/        35362087636687395438079446898535340978108366770607])/1400 + (       7849 I Sqrt[        41616 + (149163411674835586124096205921334157174479655112799 Sqrt[       K0])/35362087636687395438079446898535340978108366770607])/1400 + (       1752165303140718220448962503 Sqrt[-41616 + (       149163411674835586124096205921334157174479655112799 Sqrt[K0])/       35362087636687395438079446898535340978108366770607])/(       1605413612500000000 K0) - (       1752165303140718220448962503 I Sqrt[       41616 + (149163411674835586124096205921334157174479655112799 Sqrt[       K0])/35362087636687395438079446898535340978108366770607])/(       1605413612500000000 K0) + (       15630469741744099872889401708736470294234641513962455 Sqrt[-41616 + (       149163411674835586124096205921334157174479655112799 Sqrt[K0])/       35362087636687395438079446898535340978108366770607])/(       282585461012870216280087249803974135070469452098 Sqrt[K0]) + (       15630469741744099872889401708736470294234641513962455 I Sqrt[       41616 + (149163411674835586124096205921334157174479655112799 Sqrt[      K0])/35362087636687395438079446898535340978108366770607])/(      282585461012870216280087249803974135070469452098 Sqrt[K0]) + (      5994979010910966184793439691673144599099894289304 Sqrt[      K0])/158612235779223913220534429863991677577574124084351,50];                 NSolve[sol[K0] == 0, K0, WorkingPrecision -> 50]


title: Why are the elements of plots separated in exported PDFs?

text: When I export a plot to a PDF with something like               Export["test.pdf", Plot[Sin[x], {x, 0, 2 Pi}], "PDF"]      I get a file in which the axes have been separated from the rest of the plot in some editors and viewers (e.g., OmniGraffle): ![enter image description here](http://i.stack.imgur.com/YmBWh.png) Why is this happening? Is there a way to prevent it?


title: Is there a way to make the "Details" section of the documentation expand by default?

text: By default, the _Mathematica_ documentation opens with the "Details" section collapsed. ![enter image description here](http://i.stack.imgur.com/E4KRI.png) This is _never_ what I'm looking for — in fact, I've lost count of the times I've sought help on a feature and not found it anywhere on the feature's documentation page (at least not until I remember this shortcoming). Is there a way to configure _Mathematica_ doe that the "Details" section of the documentation opens is expanded by default?


title: Why does Simplify ignore an assumption?

text: Here is the example:               Simplify[x + y, x + y == a]     Simplify[x + y, x + y == 5]      Mathematica 9 output:               x+y     5      I expect the complexity of `a` to be lower than complexity of `Plus[x,y]`, and the result of the first line should be `a`. Even if I specify `ComplexityFunction` explicitly:               Simplify[x + y, x + y == a, ComplexityFunction -> LeafCount]      I still get `x+y` as a result. It's however obvious that `LeafCount[x+y]` is greater than `LeafCount[a]`. Why does Simplify ignore `x+y==a` but uses `x+y==5`? How can I define the former assumption in a right way?


title: Assign one button to two variables

text: I am trying to use the one button to assign to two variables. Here is an example of how I want it to work. expression:               "Magnitude = ", mstar, ", Distance = ", dstar,      sliders:               "Magnitude:", {{mstar, mSun, "Magnitude"}, mSun, 30},     "Distance:", {{dstar, dSun, "Distance"}, dSun, 600},      buttons:               "or Select Star:",      {{mstar&&dstar, mAltair&&dAltair, "Star"},       {mAltair&&dAltair -> "Altair", mCanopus&&dCanopus -> "Canopus",       mEpisilonIndi&&dEpisilonIndi -> "Episilon Indi"},       ControlType -> Setter}      In this example, it would work fine if it was able to assign both variables when pressing the desired button, however `&&` doesn't work like this. My only solution is to have a button for each variable;               "or Select Star:",      {{mstar, mAltair, "Subscript[Star, m]"},       {mAltair -> "Altair", mCanopus -> "Canopus", mEpisilonIndi -> "Episilon Indi"},       ControlType -> Setter},          "or Select Star:",       {{dstar, mAltair, "Subscript[Star, d]"},        {dAltair -> "Altair", dCanopus -> "Canopus", dEpisilonIndi -> "Episilon Indi"},        ControlType -> Setter}      However, this requires me to press both buttons, where my desired effect is to only have to press one. Is there a way I can achieve this?, I am aware that I can assign a variable two values such as;               Sun = {mSun, dSun}      I don't know the correct expression or even if it's possible. Can I do this and have my expression able to choose which value to use? Like this?               "Magnitude = ", star{value1}, ", Distance = ", star{value2},          "Magnitude:", {{star{value1}, Sun{value1}, "Magnitude"}, Sun{value1}, 30},     "Distance:", {{star{value2}, Sun{Value2}, "Distance"}, Sun{value1}, 600},          "or Select Star:",      {{star, Sun, "Star"},       {Altair -> "Altair", Canopus -> "Canopus", EpisilonIndi -> "Episilon Indi"},       ControlType -> Setter}      ## Edit This is the current coding which displays the first image:               Manipulate[     Column[{Row[{"Apparent magnitude = ", mstar, ", distance = ", dstar, "pc"}], Style[Row[{"Star has Absolute Magnitude of ", mstar - 5 ((Log10[dstar]) - 1)}], Bold, 24]}, Spacings -> {0, 1.5}],     "Choose apparent magnitude:", {{mstar, mSun, "m"}, mSun, 30},     "choose distance:", {{dstar, dSun, "d"}, dSun, 600},     "or select desired star:",     {{mstar, mSun, "m"}, {mAltair -> "Altair", mCanopus -> "Canopus", mEpisilonIndi -> "Episilon Indi", mRigel -> "Rigel", mProximaCentauri -> "Proxima Centauri", mSun -> "Sun", mZetaOphiuchi -> "Zeta Ophiuchi"}, ControlType -> Setter},     {{dstar, dSun, "d"}, {dAltair -> "Altair", dCanopus -> "Canopus", dEpisilonIndi -> "Episilon Indi", dRigel -> "Rigel", dProximaCentauri -> "Proxima Centauri", dSun -> "Sun", dZetaOphiuchi -> "Zeta Ophiuchi"}, ControlType -> Setter}]      ![Image 1](http://i.stack.imgur.com/dMDKq.jpg) This is an example of how I want it to be displayed by being able to use a single button to assign both variables. The coding in this second image is a little different using Switch functions for the two variables, however a third variable is required for the actual Switch. I believe this would benefit from being able to assign two individual values to one variable, otherwise the sliders still require two individual variables. Here is the coding of the two variable switches:               Switch[star, Altair, mRigel, Canopus, mCanopus, EpisilonIndi, mEpisilonIndi, Rigel, mRigel, ProximaCentauri, mProximaCentauri, Sun, mSun, ZetaOphiuchi, mZetaOphiuchi]     Switch[star, Altair, dRigel, Canopus, dCanopus, EpisilonIndi, dEpisilonIndi, Rigel, dRigel, ProximaCentauri, dProximaCentauri, Sun, dSun, ZetaOphiuchi, dZetaOphiuchi]      Here is the coding of the buttons:               {{star, Altair, "s"}, {Altair -> "Altair", Canopus -> "Canopus", EpisilonIndi -> "Episilon Indi", Rigel -> "Rigel", ProximaCentauri -> "Proxima Centauri", Sun -> "Sun", ZetaOphiuchi -> "Zeta Ophiuchi"}, ControlType -> Setter}      As there is now a single variable, `star`, which assigns the other two, `mstar` and `dstar`, the sliders require use of the same variable. A `Switch` cannot be placed where the `star` variable is as it's an invalid parameter.               "Choose apparent magnitude:", {{star, mSun, "m"}, mSun, 30},     "Choose distance:", {{star, dSun, "d"}, dSun, 600},      ![Image 2](http://i.stack.imgur.com/Fh8np.jpg) Hopefully this makes a more sense, I am very new to Mathematica and have only been using it for about a week. ## Edit 2 I adjusted the project to substitute the previous buttons with actual `Button` functions, it works flawlessly. The following image is how the new output is displayed: ![Image 3](http://i.stack.imgur.com/AVEUf.jpg) The buttons are now using the following code:               Button["Altair", mstar = mAltair; dstar = dAltair]


title: Trouble picking up package definitions

text: I open a new notebook and type               ClearAll[test];     test[x_] := x + 42;      I save it as `Temp.nb` and _also_ as `Temp.m`, using the menu _Save As... > Wolfram Mathematica Package (*.m)_. I now open up another notebook and type               << "Temp.m"      which succeeds. But the symbol `test` is not defined.               ?? test      > >     Information::notfound: Symbol test not found. >> >                 test[3]      > >     test[3] >   I'm confused, because the documentation for `Get`, a.k.a., `<<`, says > << name reads in a file, evaluating each expression in it and returning the > last one. It should have evaluated the expressions in `Temp.m`, then, I should think, and returned the [value of] the last one, which would be `Null`. One of those expressions is a `SetDelayed` for the symbol `test` and should have installed `test` in the Global namespace, no? Fresh kernel session, fresh reboot of MMA, also fails if file is saved as _Wolfram Language Package (*.wl)_ , yada yada.


title: Images in package Not visible

text: I want to make a package where some variables are initialized to images. but when i save the package, all images are in the form of `ImageData` that are very long. how do i fix it ?


title: Eigenvalues and Determinant of a large matrix

text: Can anybody kindly explain to me what is going wrong regarding a simple problem I have? I can find the eigenvalues of a large matrix using `Eigenvalues[]`, but when I try to find the determinant of the matrix minus eigenvalue times identity matrix, the result is not equal to zero. To make it clear please take a look at the following example:               n = 150;     m = RandomReal[{-5, 5}, {n, n}];     EIG = Eigenvalues[m];     DET = Det[(m - (EIG[[n]])*IdentityMatrix[n])]      For small values of `n`, `DET` equals zero, but when `n` becomes larger `DET` is no longer zero, and for `n = 150` (as in the example) `DET` will be a huge number! Could you please tell me whether the problem is from `Eigenvalues[]` or `Det[]` in _Mathematica_ , and how I can sort it out?


For some reason when you run Math.exe form windows command line, Mathematica disables the AltGr key. This is _a bit_ annoying since my keyboard locale has the keys [, ], {, }, @, $, \, | located under this key. This makes Mathematica unusable for many novice users. Is there a way to workaround this problem other than switching the keyboard locale? I can switch to US keyboard but my students can not since they have hard enough time finding characters that are typed on the keyboard. Is it possible to get AltGr key to work in Math.exe?


title: Simplify $\cos(n \pi)$ and $\sin(n \pi)$ when n is an integer

text: I was trying to calculate this integral in _Mathematica 9_ :               2/π Integrate[ Cosh[a x] Cos[n x], {x, 0, π}, Assumptions -> n ∈ Integers]      I got as a result : $$\frac{2 (a \sinh (\pi a) \cos (\pi n)+n \cosh (\pi a) \sin (\pi n))}{\pi \left(a^2+n^2\right)}$$ That's the same result I obtained manually, but how can I force _Mathematica_ to change $\sin(n \pi)$ into $0$ and $\cos(n \pi)$ into $(-1)^n$ ?


title: Limit of integral gives incorrect output

text: I'm trying to evaluate $\lim_{e\to 0} \, \frac{i}{e}\int_{\pi }^0 \frac{1-\exp (i e \exp (i \theta ))}{\exp (i \theta )} \, d\theta$ with Mathematica 9.0.1.0 on OS X. However, I get "Undefined" for this input:               Limit[I/e Integrate[(1 - Exp[I e Exp[I \[Theta]]])/Exp[I \[Theta]], {\[Theta], \[Pi], 0}], e -> 0]      We can see numerically that the correct answer is $-\pi$ by using this code:               With[{e = 0.000001}, I/e NIntegrate[(1 - Exp[I e Exp[I \[Theta]]])/Exp[I \[Theta]], {\[Theta], \[Pi], 0}] ] // Chop      What goes wrong in this process? Is it possible to get the correct result?


title: How can I change the default output number form to accounting form?

text: By default, large numbers are displayed in scientific form in output like `1.2345 x 10^8` in _Mathematica_ 8.0.4, but I would prefer having numbers in accounting form like `123,450,000` in output. How can I change the default output number form from scientific form to accounting form?


title: I want to define a function that has integer power

text: I am defining this function: `f[x_] = kr*g[x] + (c^l*x^l)/(KIR + c^l*x^l)` But I want to make `l` bigger than 0, so if I evaluate `f[0]` I want to get `kr*g[0]`. However, I get the expression evaluated at `0`, for example `0^l` instead of `0`. Thanks for the help


title: How to maximize a function over a rotation matrix?

text: I have list of pairs of points: $\{(x_i,y_i)\}_{1\le i\le n}$, $x_i \in \mathbb{R}^3$, $y_i \in\mathbb{R}^2$ and would like to optimize over a rotation $R \in SO(3)$, a translation $t \in \mathbb{R}^3$ and scalars $a,b \in \mathbb{R}$ such that $\sum_{i=1}^n{\|f(x_i|R,t,a,b) - y_i\|^2}$ is minimal. The model function $f$ is non-linear and varies in my applications. How can I find optimal parameter values $R,t,a,b$ for a given dataset with Mathematica (v9)? **Edit:** An example for $f$ would be:               f[{x_, y_, z_}, R_, t_, a_, b_] := Module[{qx, qy, qz},       {qx, qy, qz} = R.(z/a {x, y, a}) + t;       b {qx/qz, qy/qz}     ]      Here $a,b>0$ would be an additional constraint. A few data points as an example. A longer list can be found here.               {      {21.389, -24.551, 2.226, -5.25873, 3.72399},      {32.204, -7.055, 0.727, -28.5502, 20.8323},      {11.524, -12.171, 2.116, -9.31497, 13.5392},      {251.154, -8.349, 2.333, 21.8644, -62.8753},      {-12.07, -10.771, 2.09, -1.56909, 11.4189},      {-95.896, 7.367, 1.974, -56.4495, -28.5834},      {87.725, -2.845, 1.108, 4.35673, -6.32492},      {188.811, 99.661, 2.052, -35.3311, -40.9137}     }


title: Attaching the same message to several symbols

text: It is common in many packages, as well as system symbols, that the same message can be issued by several functions. Here's an example: ![Mathematica graphics](http://i.stack.imgur.com/erqUC.png) One mechanism that can be used for this is to define the message only once, and attach it to the `General` symbol. This is how the `infy` messages works as well. `infy` can appear to come from any symbol: ![Mathematica graphics](http://i.stack.imgur.com/cFGlC.png) When writing a custom package, it might not be the best idea to do this though because of the risk of message conflicts. Two packages might attach the same message identifier to `General`, so the one that's loaded last will overwrite the previous one. In fact, looking at the some standard packages (e.g. CUDALink), they do not attach messages to `General` even when the same message can be issued by several functions. Looking at the source code of the package, CUDALink uses a helper function to attach the same message text to several symbols in one go. **The question:** What is the best way to proceed when several functions need to be able to issue the same message, and indicate that it is coming from them? What do you use in your own packages? What's important for me is minimizing the risk of conflict with other packages and the simplicity of implementation.


title: Saving table of plots into a single figure within a pdf file

text: I have following code:                 Table[LogLogPlot[         a + 0.017*k + (-0.014*k)*Tanh[(k - 0.25)*b], {k, 0.1, 10}],           {b, {0.1, 0.2, 0.3, 0.4}}, {a, {1.0, 1.1, 1.2, 1.3}}]      I get then a table of plots and I can click on each of them to save them. But how do I save them all at once into a single PDF? If I instead do:                  GraphicsGrid[          Table[LogLogPlot[            a + 0.017*k + (-0.014*k)*Tanh[(k - 0.25)*b], {k, 0.1, 10}],              {b, {0.1, 0.2, 0.3, 0.4}}, {a, {1.0, 1.1, 1.2, 1.3}}]]      I cannot right click on the figure to save as some image, but rather have to export it. And I am really not satisfied by the result.               Export["grid1", %, "PDF"]      All axes and fonts are completely squeezed, big and unreadable. ![plot](http://i.stack.imgur.com/aiH7P.png) How do I set borders and fonts and all that in an easy manner? The best way would be really being able to right click on the table of plots and save it as it looks like.


title: Summing Multinormal Distributions

text: So, I'll explain the problem first. I have two populations that have values for two different channels (c1,c2). I've modeled these using MultinormalDistribution[]. I would like to add some noise to these distributions, which also exists in channels (c1,c2). I've tried doing this using TransformedDistribution[]:               hiDist = MultinormalDistribution[\[Mu]HiErr, \[CapitalSigma]];     loDist = MultinormalDistribution[\[Mu]LoErr, \[CapitalSigma]];     noiseDist = MultinormalDistribution[\[Mu]Noise, \[CapitalSigma]];          hiNDist =        TransformedDistribution[        h + n, {h \[Distributed] hiDist, n \[Distributed] noiseDist}];     loNDist =        TransformedDistribution[        l + n, {l \[Distributed] loDist, n \[Distributed] noiseDist}];      This works with regular Normal distributions, but fails when I use it with the Multinormal primitives. Any elegant way to do this? **EDIT 1** Changed a typo. "Failure" results when I try to call the thing. In place, the TransformedDistribution[] call will just output something like:                   TransformedDistribution[\[FormalX]1 + \[FormalX]2, {\[FormalX]1 \     \[Distributed]         MultinormalDistribution[{5000,           20000}, {{1000000, 0}, {0,            1000000}}], \[FormalX]2 \[Distributed]         MultinormalDistribution[{2000,           2000}, {{1000000, 0}, {0, 1000000}}]}]      However, when I try to use the distribution, e.g.               RandomReal[hiNDist,100]      Mathematica will throw the error: > RandomReal::udist: "The specification TransformedDistribution[[FormalX]> > 1+[FormalX]2, > {[FormalX]1[Distributed]MultinormalDistribution[{5000,20000},{{1000000,0},{0,1000000}}],[FormalX]2[Distributed]MultinormalDistribution[{2000,2000},{{1000000,0},{0,1000000}}]}] > is not a random distribution recognized by the system" While the code               n1 = NormalDistribution[5000, \[Sigma]];     n2  = NormalDistribution[10000, \[Sigma]];     n3 = TransformedDistribution[       x + y, {x \[Distributed] n1, y \[Distributed] n2}]      Gives the expected               NormalDistribution[15000, 1000 Sqrt[2]]


title: Extend a function defined for integers to a differentiable function of a real variable

text: Here is a function that calculates the probability of randomly landing on a Fibonacci number not greater than $n$:               f[n_Integer] := (Floor[Log[GoldenRatio, Sqrt[5] (n + (1/2))]] - 1)/n        ![1-50](http://i.stack.imgur.com/zRjSe.png) How can I extend/complete it to some differentiable function that agrees with the original values when given an "integer" input?


title: Evaluate in Plot leads to function error

text: Please help - I'm really struggling to understand why this evaluates with errors.               data = RandomReal[10, {4, 1000}];     metric[data_, perc_] := (x = Quantile[#, perc] & /@ data; Accumulate[x]/Total[x]);     Plot[Evaluate@metric[data, p], {p, 0.01, 0.99}, AxesLabel -> {"Percentile", "Proportion"},  PlotLegends -> {"Series A", "Series A+B", "Series A+B+C", "Series A+B+C+D"}]      Basically I need to see the results from the function as 4 separate curves in 4 colours. Placing the "metric" function inside the Plot means that it plots everything as one function, which doesn't help (although it evaluates error free). In line with other answers on here (here and others) I recognise I have to either Evaluate it or Apply the metric to the Plot pure function, but then I get a Quantile error (and critical/"fall over" errors with some of the other more complex metrics I'm using). I've tried using default values, Holds, matching patterns on when perc doesn't exist etc etc but to no avail. I'm losing years off my life trying to get this to work so any help would be really appreciated...


title: Where Statement

text: Is there a "parallel" way to perform these operations?               Indices = {}     For[i = 1, i <= Length[w], i++,      If[w[[i]] < 0, AppendTo[Indices, i]]]      Which gives a list of the Indices where the list w is negative. This is a little slow. Is there a faster cleaner way to get the same answer? This is essentially the Fortran 90 where statement.


title: Is linear interpolation applicable here

text: From my understanding about Linear Interpolation especially of that of Newton's Divided Difference Polynomial, we could get the value of `F(x)` from the given set of coordinates. But would it be possible of the if `x` values itself is an expression, like `0.25X` and having a constant value of `0.5`. I don't know if I get the correct understanding of the NDDP: Linear Interpolation correctly given the scenario. Given the set of coordinates. How would I find the value for `X = 0.4x` where `x = is integer constant to the plane`               X     Y     0     0.25     0.25x 0.5     0.5x  1     0.75x 2     x     4


title: Connecting to a remote linux kernel from Windows 7: SSH error code = 104

text: I have a Windows 7 machine and in my network there is a Linux PC. Both have Mathematica 9 installed. I want to run a remote kernel in the Linux PC, and use the Mathematica front end from my win7 PC, but I am getting the following message: > SSH encountered an error with the local network setup while launching kernel > 'remote_kernel_name'. Error code = 104. It doesn't get to the part where it's supposed to ask for my password on the Linux pc. To configure the connection, I went to: Evaluation >> Kernel Configuration Options... I selected Basic Options, and Remote Machine. In Machine Name I placed the IP address of the remote Linux machine, and in Kernel Program, I wrote "math". Also, I have succesfully used PuTTY from my win7 pc to connect to the remote Linux pc and used Mathematica remotely (command line interface). What's the error code 104 and how do I fix it?


title: Plotting a Spericon and Bipyramid with 100 faces

text: I would like to plot convex polyhedron with 100 faces, which could be used as a die. My first attempt was asking for Conway's Hecatohedron. Unfortunatly, it can not be used as a die. Now there are two objects which would satisfy what I need; and I would like to know how to plot them in Mathematica: 1) A 100 faces Spericon. A picture can be seen here. 2) A Bipyramid with 100 faces. And a follow-up questions: Are there other objects which would represent 100-sided dice? Maybe a generalisation of Archimedean solids?


title: Fast way to get positions of "boxed" array elements?

text: Given a 2D array (arbitrary numeric / evaluates to numeric elements, simplified for examples, and can be arbitrary dimensions so long as the operation makes sense, I'm working with 2K X 2K in my application):               test={{2, 2, 2, 2, 1, 1, 1, 2, 2, 1}, {2, 2, 2, 2, 2, 1, 1, 1, 2, 2}, {2,        2, 2, 1, 1, 1, 1, 1, 1, 2}, {1, 2, 2, 1, 2, 1, 1, 1, 2, 1}, {1, 2,        1, 1, 1, 2, 2, 1, 2, 2}, {1, 1, 2, 1, 2, 1, 2, 1, 2, 1}, {1, 2, 1,        1, 1, 2, 2, 1, 2, 1}, {2, 1, 2, 2, 1, 2, 1, 2, 2, 2}, {2, 2, 1, 1,        1, 1, 1, 1, 2, 1}, {2, 1, 1, 2, 1, 1, 2, 1, 2, 2}};      in `MatrixForm`: ![enter image description here](http://i.stack.imgur.com/Obwm7.png) I need to find the position(s), if any, of elements that are "boxed" by the same value of the element, with corners/edges treated the traditional way (i.e., corners have just 3 neighbors, edges have 5). So, in the example array, the result should be               {{1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {3, 7}}      I'm using               boxed[array_] :=       SparseArray[Unitize[Subtract[MaxFilter[array, 1], MinFilter[array, 1]]],         Automatic, 1]["NonzeroPositions"]      which performs fairly well, curious if there's a more elegant/better performing method. Update: Here are some timings of answers so far on the netbook (for comparison, times for what I've tested on the workstation are ~1/20 of these). Logarithmic scale, else two become noise: ![enter image description here](http://i.stack.imgur.com/2plj1.png) The current scheme I'm fiddling with is ~twice as fast as my current posted above, so there's twenty minutes saved on app. runs, but I'm sure there's some more clever ideas yet to be seen. The nice compiled recent answer is not suitable, since elements can (and often are) out of machine-precision range (and it would be nice to extend this to completely arbitrary elements, e.g. symbols, etc., but not required.)


title: Compiled version of interpolation function slower non-compiled version

text: Consider this code:               ls = Table[{x, Sin[x]}, {x, 0., 10., 0.01}];     f = Interpolation[ls];        g = Compile[{{x, _Real}}, Evaluate@f[x]]       (*        CompiledFunction[{x},InterpolatingFunction[{{0.,10.}},<>][x],-CompiledCode-]     *)          Table[f[x], {x, 0., 10., 0.0001}]; // AbsoluteTiming     (*       {0.293382, Null}     *)          Table[g[x], {x, 0., 10., 0.0001}]; // AbsoluteTiming     (*       {0.436141, Null}     *)      Why the compiled version slower?


title: How to compile gather

text: First question，How to Compile this？               gather[data_]:=Gather[data, Mod[#1, 3] == Mod[#2, 3] &]      I dont know why this is wrong.               cf = Compile[{{data, _Integer, 1}}, Gather[data, Mod[#1, 3] == Mod[#2, 3] &]]     cf[Range[9]]     cf[Range[10]]      Second question，How to Compile this？               gather[data_] := Gather[data, Count[#1, 0] == Count[#2, 0] &]     gather[RandomInteger[{0, 5}, {10, 5}]]


title: 1/0 encountered when solving an ODE

text: What can cause this error to show up?               Clear[lambda, a, b, x, y];     ode = lambda y[x] + a b y'[x] + a (-1 + b x) y''[x] + y''''[x] == 0;     DSolve[ode, y[x], x]      ![Mathematica graphics](http://i.stack.imgur.com/C3R3A.png) Verion 10, windows 7.


title: How to convert data types in a LibraryLink wrapper

text: I have a dynamic library which I want to load into _Mathematica_ using LibraryLink. I don't have access to the source code of the library, so I need a C wrapper to do the job. In the C wrapper, I would recieve arguments from _Mathematica_ using the `MArgument_get*` functions and call my library function to do the computation. Then, the results would be sent back to _Mathematica_ using the `MArgument_set*` functions. Since the data type I receive from _Mathematica_ is a Wolfram Library type such as `mint`, `double`, `MTensor`, etc., and the data types my external library function expects to receive are standard C types like `int` or `float`, my question is: how do we convert between these two different data types in the wrapper so that _Mathematica_ and my external library functions can understand each other? **Update** : Here is an very simple example, following example here. I have defined a external function which add two vectors, in fortran: !addvec.f90               subroutine addvec(a,b)     implicit none     integer,parameter::N=3        integer a(N),b(N)     a(:)=a(:)+b(:)     return     end subroutine addvec      The C wrapper is               //wrapper.cc          #include "WolframLibrary.h"     #include "WolframCompileLibrary.h"          DLLEXPORT mint WolframLibrary_getVersion(){       return WolframLibraryVersion;     }     DLLEXPORT int WolframLibrary_initialize(WolframLibraryData libData){       return 0;     }          extern "C" {       void addvec_(int a[], int b[]);     }           EXTERN_C DLLEXPORT int addvec(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res){            MTensor ta;       MTensor tb;            ta=MArgument_getMTensor(Args[0]);       tb=MArgument_getMTensor(Args[1]);            addvec_((int *)((*ta).data),(int *)((*tb).data));            MArgument_setMTensor(Res,ta);       return LIBRARY_NO_ERROR;       }      Mathematica code               Needs["CCompilerDriver`"]     CreateLibrary[{"wrapper.cc", "addvec.o"}, "myadd", "Debug" -> True, "TargetDirectory" -> "."]     addvec = LibraryFunctionLoad["./myadd", "addvec", {{Integer, 1}, {Integer, 1}}, {Integer, 1}]     addvec[{1, 2, 3}, {4, 5, 6}]      The Mathematica Kernel will crash soon after execute the third line. **Update 2** In `Mathematica` version 9 the above code seems partially work:               addvec[{1, 2, 3}, {4, 5, 6}]     (*{5, 7, 3}*)     addvec[{1, 2, 3}, {4, 5, 6}]     (*{6, 8, 4}*)      The third number in the list is calculated wrong.


title: What is NDSolve`FEM`*?

text: I stumbled on this:               ?"NDSolve`FEM`*"      > >     <list of many functions with names like ...Mesh...,Tetrahedon..., > Triangle..., ProcessBCs, ...> >   I'm tempted to conclude that _Mathematica_ has built-in finite element modelling capability, but the documentation seemingly does not cover it. What does FEM mean in this context? What is an example of an equation that `NDSolve` would use these functions to solve?


title: Bug in LengthWhile?

text: Is this a bug or my MMA went insane or I'm missing something?               LengthWhile[Reverse@IntegerDigits[1000], # == 0 &]      works fine, but with SameQ instead of Equal, or with PossibleZeroQ it doesn't               In[32]:= LengthWhile[Reverse@IntegerDigits[1000], # === 0 &]          Out[32]= 0          In[33]:= LengthWhile[Reverse@IntegerDigits[1000], PossibleZeroQ]          Out[33]= 0      It doesn't particularly happen with 1000, it was just an example.


title: How can I append associations with uneven elements?

text: My dataset is pretty simple so far:               Questions = Dataset[{     <|"Statement" -> "What is the capital of Switzerland?", "Answer" -> "Bern",      "Incorrect Answers" -> {"Zurich", "Berlin", "Vienna"}|>,     <|"Statement" -> "Who is the king of the jungle?", "Answer" -> "Lion",      "Incorrect Answers" -> {"Giraffe", "Mouse", "Monkey"}|>,     <|"Statement" -> "2+2?" , "Answer" -> "4", "Incorrect Answers" -> {"15", "13", "1e15"}|>}]      ![Questions](http://i.stack.imgur.com/Bdcvk.jpg) If I try the following, everything goes right:               NewQuestion1 = <|"Statement" -> "To be...", "Answer" -> "or not to be",      "Incorrect Answers" -> {"or to eat", "continued", "dummy"}|>;     Append[Questions, NewQuestion1]      ![NewQuestions1](http://i.stack.imgur.com/pfT24.jpg) Nevertheless, if I delete the dummy answer of the NewQuestion, it will not work:               NewQuestion2 = <|"Statement" -> "To be...", "Answer" -> "or not to be",      "Incorrect Answers" -> {"or to eat", "continued"}|>;     Append[Questions, NewQuestion2]      ![NewQuestion2](http://i.stack.imgur.com/8drOc.jpg) This issue seems weird since you can declare a data set with uneven lists from the beginning:               Questions = Dataset[{        <|"Statement" -> "What is the capital of Switzerland?",          "Answer" -> "Bern",          "Incorrect Answers" -> {"Zurich", "Berlin", "Vienna"}|>,        <|"Statement" -> "Who is the king of the jungle?",          "Answer" -> "Lion",          "Incorrect Answers" -> {"Giraffe", "Mouse", "Monkey"}|>,        <|"Statement" -> "2+2?" , "Answer" -> "4",          "Incorrect Answers" -> {"15", "13", "1e15"}|>,        <|"Statement" -> "To be...", "Answer" -> "or not to be",          "Incorrect Answers" -> {"or to eat", "continued"}|>        }]      ![QuestionsUneven](http://i.stack.imgur.com/7yEzX.jpg) Any suggestions on how to append NewQuestion2 and/or explanations of why this error is happening?


title: Remove Spacings around each grid item?

text: bar = VerticalGauge[#, {0, 100}, GaugeMarkers -> "ScaleRange",          GaugeStyle -> {Darker@Green, GrayLevel[0.95]}, TicksStyle -> None,          GaugeFrameSize -> None, ScalePadding -> 0, ImageSize -> 50,          AspectRatio -> 1, LabelStyle -> None,          Epilog -> Text[Style[#, FontSize -> 15], Scaled[{0.5, 0.5}]]] &;          Grid[Map[bar, RandomInteger[{10, 90}, {4, 4}], {2}], Frame -> All,       Spacings -> {0, 0}]      How can I remove the tiny space visible around each cell? Using Spacings -> {0, 0} does not seem to work. Thanks.


title: Mathematica can't find constants for this differential equation

text: I am having problems solving this differential equation:               diffeq = m x''[t] == -a E^(b*x'[t]);     sol = DSolve[{diffeq, x[0] == 0, x'[0] == v0}, x[t], t]      The output is {}, that means no solution found, however if I take the first condition out i get:               diffeq = m x''[t] == -a E^(b*x'[t]);     sol = DSolve[{diffeq, x'[0] == v0}, x[t], t]          {{x[t] -> (1/(a b^2))*E^(-b v0) (a b E^(b v0) t + a b^2 E^(b v0)C[2]-m Log[(E^(-b v0) m)/b + a t]-a b E^(b v0) t Log[b (E^(-b v0)/b + (a t)/m)])}}      So I tried to find a value for C[2] that could solve x[0]==0:               solution[y_] = ((x[t] /. sol)[[1]]) /. t -> y;     Reduce[solution[0] == 0, C[2]]          a b != 0 && C[2] == (E^(-b v0) m Log[(E^(-b v0) m)/b])/(a b^2)      I verified the result:               solution[0] /. C[2] -> (E^(-b v0) m Log[(E^(-b v0) m)/b])/(a b^2) // FullSimplify          0      My question is: why couldn't mathematica find this? it can't be because a*b!=0: for this values the solution changes completely and C[2] is easy to find.


title: How can I get a fully functional FittedModel when fitting data to a pointwise function?

text: When I am fitting data with a pointwise function using `NonlinearModelFit`, the produced `FittedModel` fails to calculate variances and errors. Consider a toy example:               Clear[f, data];     data = {{1, 7.4}, {2, 1.9}, {3, 6.}};     f[1.] = 2. a + b;     f[2.] = 3. a/b;     f[3.] = 3. b/a + a;         fit = NonlinearModelFit[data, f[t], {a, b}, t, Method -> NMinimize]      When I take               fit["BestFitParameters"]      it gives a correct result `{a -> 2.19044, b -> 2.95013}`. However, when I try to take               fit["EstimatedVariance"]      it throws exception, since values of `a` and `b` can not be substituted in `fit["Function"]` (that's my guess). I found the following obvious workaround:               Clear[f, g, h];     f[1.] = 1; g[1.] = 0; h[1.] = 0;     f[2.] = 0; g[2.] = 1; h[2.] = 0;     f[3.] = 0; g[3.] = 0; h[3.] = 1;     fit =        NonlinearModelFit[data, (2 a + b) f[t] + 3 a/b g[t] + (3 b /a + a) h[t],         {a, b}, t, Method -> NMinimize]        but it is not elegant at all. What is the best way to obtain a complete `FittedModel` using `NonlinearModelFit` with a pointwise functions?


title: Using Manipulate to dynamically correct the baseline of a signal

text: i have data with a baseline and will correct it with a polynomial fit using `Manipulate` to see immediatly the changes in the resulting spectrum. It works so far, but the problem is the definition of the function `fbaseline` in the `Manipulate` Part. Mathematica keeps calculating until my RAM is full and then the computer freezes. If I leave out the "_" (fbaseline[x]=...) the code doesn't work anymore, because I can't apply the `Map` function. Do you have an idea, how I can avoid this? Here is a minimal working example: Generate Data:                 datafunc = Exp[-0.2 x] + Exp[-0.1 (x - 10)^2/0.2];       data = Table[{x, datafunc + .05 RandomReal[{-1, 1}]}, {x, 0, 25, 0.05}];       ListPlot[data]      Initial values:                 xi = {5, 15};      Manipulate part:                 Manipulate[         baselinedata = Cases[data /. {x_, y_} /; (x > x1 && x < x2) -> 0, {x_, y_}];         fbaseline[x_] = f[x, n] /. FindFit[baselinedata, f[x, n], Array[a, {n + 1}, 0], x];         datablk = Transpose[Join[{data[[All, 1]]}, {data[[All, 2]] - Map[fbaseline, data[[All, 1]]]}]];         Show[ListPlot[{data, baselinedata, datablk}, PlotStyle -> {{Gray, PointSize[Medium]}, {Orange, PointSize[Medium]}, {Red, PointSize[Medium]}}, PlotRange -> All],Plot[fbaseline[x], {x, 0, 25}, PlotStyle -> {Black, Dashed}],         Graphics[{PointSize[Large], Point[{{x1, 0}, {x2, 0}}]}], ImageSize -> 1000],         {{n, 6}, 2, 8, 1}, {{x1, xi[[1]]}, 0, 15}, {{x2, xi[[2]]}, 5, 25}         ]      Another problem is, that the axis at y=0 dissapears for some values. Previous version (not working without the data): Here is the code i have so far:                f[x_Symbol, b_Integer] := Array[a, {b + 1}, 0].x^Range[0, b];´      (*Initial values for excluded ranges*)      xi = {441, 1151};      region1 = {{0, 4000}, {-1000, 25000}};      region2 = {{0, 4000}, {Min[data], Max[data]}};           Manipulate[        baselinedata =         Cases[data /. {x_, y_} /; (x > x1 && x < x2) -> 0, {x_, y_}];        xi = {x1, x2};        fbaseline[x_] = f[x, n] /. FindFit[baselinedata, f[x, n], Array[a, {n + 1}, 0], x];             datablk = Transpose[Join[{rawdata[[All, 1]]}, {data[[All, 2]] - Map[fbaseline, rawdata[[All, 1]]]}]];        Show[ListPlot[{data, baselinedata, datablk},         PlotStyle -> {{Gray, PointSize[Medium]}, {Orange,         PointSize[Medium]}, {Red, PointSize[Medium]}},         PlotRange -> region],        Plot[fbaseline[x], {x, 400, 4000}, PlotStyle -> {Black, Dashed}],        Graphics[{PointSize[Large], Point[{{x1, 0}, {x2, 0}}]}],        ImageSize -> 1000],     {{n, 6}, 2, 8, 1}, {{x1, xi[[1]]}, 400, 600}, {{x2, xi[[2]]}, 800, 1300}, {{region, region2, "Plotregion"}, {region1 -> "Zoom", region2 -> "All"}}      ] ![enter image description here](http://i.stack.imgur.com/ZO0gU.jpg)


title: Problem with Creating Mathematica Package

text: Currently I am working on creating the package on Mathematica version 9 on Windows 7. Here is my code as follows:               BeginPackage["mypackage`"]          Begin["`Private`"]          getColumn[data_,branch_List]:=     Module[{pos},     pos = Position[data,#][[1,2]]&/@branch;     data[[All,pos]]     ];          RemoveMissing[data_]:=DeleteCases[data,{date_,val_}/;!NumberQ[val]];          End[]          EndPackage[]      As you can see from the above that it contains two defined functions. I saved it as mypackage.m on my working directory. To make sure my working directory is the one that contains mypackage.m, I put `SetDirectory[NotebookDirectory[]]` in my notebook. Then, I call the package by using               Needs["mypackage`"]      Evaluating, but it seems not to load, because when I call the function `getColumn`, the letters should turn black if it is loaded (now it's still blue). Also, I tried other ways               `Needs["mypackage`","mypackage.m"]`      and               <<mypackage`      Both are still not working. I have two questions:   1. When we save .m file, is it necessary to have the same name as we defined in the BeginPackage[""]   2. Is there anything missing so my package does not work ? any suggestions ?


title: Clear labelling gray-scale plots

text: I am plotting a number of functions (at least 4 in one plot) with a legend. Needless to say, it is important that it is clear from the legend which line belongs to which function. I tried to play around with the `PlotStyle`, but I'm not getting them to look all that different. The paper it will be published in demands grey-scale pictures, so I can't use different colours. I was hoping to use `PlotMarkers` instead, but I found that these only exist within the `ListPlot` but not in `Plot`. In theory I could overlay a `Plot` with a `ListPlot`, but then it wouldn't show in the legend. What is the best way to add the markers in both the plot and the legend? This is a minimal working example of something to which I'd to add `PlotMarkers`.               Needs["PlotLegends`"];     Plot[{Sin[x], Sin[x + π/4], Sin[x + π/2], Sin[x + 3π/4]}, {x, 0, 2π},          PlotLegend -> {"#1", "#2", "#3", "#4"},          PlotStyle -> {DotDashed, Dashed, Dashing[0.01], Dotted}]


title: What's new in Mathematica 10 that begginers must know?

text: Is there any **new** and **Important** feature in version 10 that the regular not-so-advanced Mathematica user must know? How do the new features of version 10 make the programing more efficient or faster? What are the changes which have led to faster computation?


title: Use elements of Array inside function definition

text: I'm trying to define a function which modifies and sums over the elements of an array. Here is a very simplified version.               myF[kmax_] = Sum[v[[k]]/k, {k, 1, kmax}]      As you can see, each element between 1 and the function argument (`kmax`) is divided by its index and then summed with the others. The problem is that mathematica isn't accepting that `v[[k]]` and complains that `k` isn't an integer.               Part::pspec: Part specification k is neither an integer nor a list of integers.      I tried replacing `k` with `Round[k]`, but the problem remains. I even tried redefining the vector, where the elements are already divided by `k`, and then just summing over the first `kmax` elements:               myF[kmax_] = Total[Take[v, kmax]]      And I'm still getting error messages about the argument not being of the right type               Take::seqs: Sequence specification (+n, -n, {+n}, {-n}, {m, n}, or {m, n, s}) expected at position 2 in Take      So, am I doing something wrong? **Is there any way to access array elements within a function definition?**


title: Applying several patterns to `Split`

text: Please consider the following:               Split[data, patterns &]     patterns=Not[#=="a"]&&Not[#=="b"]&&...&&Not[#=="blabla"];      How can I define `patterns` without typing `&&Not[#=="char"]` for every single pattern?


title: Call Haskell from Mathematica and return the results inside Mathematica

text: I would like to learn Haskell using Mathematica's environment. I know there is the RLink protocol. Is there a similar protocol for Haskell?


title: How to Map a subset of list elements to a function?

text: How would you, given a list `{1, 2, 3, 4}`, apply a function `f` to `1` and `2`, then `2` and `3`, etc.?               {f[1,2], f[2,3], f[3,4]}      More generally, how do you define which parts of a list you want to pass/`Map`/`Apply` to a function that takes multiple arguments?


title: Evaluating a function using arguments from a sliding window over a list

text: > **Possible Duplicate:**   >  How to Map a subset of list elements to a function? I want to evaluate a function using arguments from a sliding window over a list. As an example, lets use `Mean` as the function, window size as `3`, and the list as `Range[1, 10]`. The results I am looking for are:               { Mean[{1,2,3}], Mean[{2,3,4}], ... Mean[{8,9,10}] }      i.e.               {2, 3, 4, 5, 6, 7, 8, 9}      Is there something in `Mathematica` that can do this, or an improvement on the following implementations? * * * ## Implementation #1               Slide1[f_, expr_, n_Integer] :=       Module[{myExpr},        myExpr = RotateRight[expr, 1];        Nest[         Delete[#, -1] &,         Map[(            myExpr = RotateLeft[myExpr, 1];            f[myExpr[[1 ;; n]]]            ) &, myExpr],         n - 1]        ];          In[]:=  Slide1[Mean, Range[1, 10], 3]     Out[]:= {2, 3, 4, 5, 6, 7, 8, 9}      _Rotating can not be that efficient, can it?_               In[]:=  AbsoluteTiming[Slide1[Mean, Range[1, 100000], 3]][[1]]     Out[]:= 3.529240      * * * ## Implementation #2               Slide2[f_, expr_, n_Integer] :=      Module[{result, i},       result = {};       For[i = 1, i <= Length[expr] - n + 1, i++,        AppendTo[result, f[expr[[i ;; i + n - 1]]]];        ];       result       ]          In[]:=  Slide2[Mean, Range[1, 10], 3]     Out[]:= {2, 3, 4, 5, 6, 7, 8, 9}      _Please ...`For` and `AppendTo`_               In[]:=  AbsoluteTiming[Slide2[Mean, Range[1, 100000], 3]][[1]]     Out[]:= 27.811511


title: Refer to next element of list when iterating using Map

text: Is it possible to refer to the next element of the list when I'm using `Map` or should I always use `For` in this case?   For example I can write:               (1 + #1) & /@ {a, b, c, d}      but I can not write:               (1 + #1 + #2) & /@ {a, b, c, d}      The problem with the last element should be also avoided. So in last example I would like to get something like               { 1 + a + b, 1 + b + c, 1 + c + d, 1 + d}


title: Spelling dictionary corrupted

text: I have a problem with the Check Spelling in Mathematica, that I quite don't understand: If I try to use the Check Spelling on any notebook, the check just stop before the first word and in the field " **Reason for stopping:** " is written: " _The spelling dictionary file Mathematica.rws could not be loaded. The file may be corrupted._ " I found nothing about this on the Internet, but after a research on my computer I found that this file is at " _/usr/local/Wolfram/Mathematica/9.0/SystemFiles/SpellingDictionaries/English/Mathematica.rws_ " (I'm on Linux) There is also another directory called _SpellingDictionaries_ at _~/.Mathematica/SystemFiles/SpellingDictionaries_ , but it is empty. I tried by copying the content of the first directory in the second, but it doesn't work. I also tried to use another file _Mathematica.rws_ that I found in _/WINDOWS/Program Files/Wolfram Research/Mathematica/8.0/SystemFiles/SpellingDictionaries_ on another computer (under Windows) that had Mathematica V8 (with which the check spelling worked). I doesn't work either. Can anyone help me ? I would really like to be able to use Mathematica to write my report.


title: A question about derivatives (cubics)

text: Given an equation:               f(z) = a (x + I y)^3 + b (x + I y)^2 + c (x + i y) + d      Which can be re-written as:               real f(z) ax^3 - 3axy^2 + bx^2 - by^2 + cx + d     imag f(z) 3ax^2y - ay^3 + 2bxy + cy                 Am I correct in deriving them this way?               Mathematica: D[a x^3 + 3 a x y^2 + b x^2 + c x + d, x] // TraditionalForm     real f'(z) 3ax^2 + 3ay^2 + 2bx + c      Mathematica: D[3 a x^2 y - a y^3 + 2 b x y + c y, y] // TraditionalForm     imag f'(z) 3 a x^2-3 a y^2+2 b x+c       Some background. While I have dabbled in what I consider the interesting bits of mathematics all my life I am at best an amateur (hopefully in the British sense) at best. It has been a very long time since I took Calculus and that was single variable Calc at that. My current investigation is into just where I made errors in what should have been a simple implementation of Newton's method involving Cubic functions. This in aid of creating the resultant fractal plot. This was in the early 80's when my software and FracInt were pretty much the only ball games in town. Here is the code as written for Ultra-Fractal:               zold = #z     iz = imag(#z)     rz = real(#z)     zr2 = sqr(rz)     zi2 = sqr(iz)     t0 = (rz - iz) * (rz + iz)     t1 = (3.0 * A * t0) + (2.0 * B * rz) + @C     t2 = 2.0 * iz * (3.0 * A * rz + B)     t3 = A * rz * (zr2 - 3.0 * zi2) + (B * t0 + @C * rz) + @D     t4 = rz * (3.0 * A * rz - 2.0 * B) - (A * zi2) + @C     t5 = sqr(t1) + sqr(t2)     zr = (((rz * t5) - (t1 * t3) - (iz * t2 * t4)) / t5)     zi = (((iz * t5) + (t2 * t3) - (iz * t1 * t4)) / t5)     #z = zr + flip(zi)      I am attempting to compare what I should have done with what I did so as to better understand what I'm doing! The formula produces Newton images unlike any others so I do not seek to correct the errors, just comprehend them. BTW, the lack of expression in terms of complex types is based on the lack of a complex type when this was written in the early 80's---complex.h was typically a roll your own affair but even at that, it was the norm to break things up in terms of real and imag and process accordingly.


title: Solve equation containing conditions (If expressions)

text: I want to solve the underneath equation. If I try Solve[AAA,dc], then I get no solution. Can anybody explain this?               AAA = {80000 If[0.1 (0.00005 - dc) + dc <= -0.00175, -35,            If[-0.00175 <= 0.1 (0.00005 - dc) + dc < 0, 20000. (0.1 (0.00005 - dc) + dc),             If[0 < 0.1 (0.00005 - dc) + dc <= 0.00015, 20000. (0.1 (0.00005 - dc) + dc),              If[0.00015 <= 0.1 (0.00005 - dc) + dc < 0.00115,               3.15 - 1000. (0.1 (0.00005 - dc) + dc),               If[0.00115 <= 0.1 (0.00005 - dc) + dc < 1/4,                2.00462 - 4.01849 (0.1 (0.00005 - dc) + dc)]]]]] +          80000 If[0.3 (0.00005 - dc) + dc <= -0.00175, -35,            If[-0.00175 <= 0.3 (0.00005 - dc) + dc < 0, 20000. (0.3 (0.00005 - dc) + dc),             If[0 < 0.3 (0.00005 - dc) + dc <= 0.00015, 20000. (0.3 (0.00005 - dc) + dc),              If[0.00015 <= 0.3 (0.00005 - dc) + dc < 0.00115,               3.15 - 1000. (0.3 (0.00005 - dc) + dc),               If[0.00115 <= 0.3 (0.00005 - dc) + dc < 1/4,                2.00462 - 4.01849 (0.3 (0.00005 - dc) + dc)]]]]] +          80000 If[0.5 (0.00005 - dc) + dc <= -0.00175, -35,            If[-0.00175 <= 0.5 (0.00005 - dc) + dc < 0, 20000. (0.5 (0.00005 - dc) + dc),             If[0 < 0.5 (0.00005 - dc) + dc <= 0.00015, 20000. (0.5 (0.00005 - dc) + dc),              If[0.00015 <= 0.5 (0.00005 - dc) + dc < 0.00115,               3.15 - 1000. (0.5 (0.00005 - dc) + dc),               If[0.00115 <= 0.5 (0.00005 - dc) + dc < 1/4,                2.00462 - 4.01849 (0.5 (0.00005 - dc) + dc)]]]]] +          80000 If[0.7 (0.00005 - dc) + dc <= -0.00175, -35,            If[-0.00175 <= 0.7 (0.00005 - dc) + dc < 0, 20000. (0.7 (0.00005 - dc) + dc),             If[0 < 0.7 (0.00005 - dc) + dc <= 0.00015, 20000. (0.7 (0.00005 - dc) + dc),              If[0.00015 <= 0.7 (0.00005 - dc) + dc < 0.00115,               3.15 - 1000. (0.7 (0.00005 - dc) + dc),               If[0.00115 <= 0.7 (0.00005 - dc) + dc < 1/4,                2.00462 - 4.01849 (0.7 (0.00005 - dc) + dc)]]]]] +          80000 If[0.9 (0.00005 - dc) + dc <= -0.00175, -35,            If[-0.00175 <= 0.9 (0.00005 - dc) + dc < 0, 20000. (0.9 (0.00005 - dc) + dc),             If[0 < 0.9 (0.00005 - dc) + dc <= 0.00015, 20000. (0.9 (0.00005 - dc) + dc),              If[0.00015 <= 0.9 (0.00005 - dc) + dc < 0.00115,               3.15 - 1000. (0.9 (0.00005 - dc) + dc),               If[0.00115 <= 0.9 (0.00005 - dc) + dc < 1/4,                2.00462 - 4.01849 (0.9 (0.00005 - dc) + dc)]]]]]} == 0


title: $1 - \sqrt{5}$ $\in$ $\mathbf{R}$?

text: Why is there a difference in the output of the following codes? First:               ClearAll["Global`*"]          a = {0, -m};     b = {-(Sqrt[-2 + m^2]/Sqrt[m]), -m - (-2 + m^2)^2/m};     c = {-1, 1} b;     d = 1024 m (-2 + m^2)^3;     o = {0, 0};          Reduce[{d > 0, EuclideanDistance[a, o] == EuclideanDistance[b, c]}, m]      > >     m == 2 || m == 1 - Sqrt[5] || m == 1 + Sqrt[5] >   And then with `Reals`:               Reduce[{d > 0, EuclideanDistance[a, o] == EuclideanDistance[b, c]}, m, Reals]      > >     m == 2 || m == 1 + Sqrt[5] >


title: Using subscript in a string

text: I am trying to create a string of the form $0 < d_1 < d_2 < \ldots < d_n$ For a given n. My closest attempt so far is               eqn[n_] :=       For[i = 1; str = "0", i <= n, i++,         str = str <> "<" <> ToString[Subscript[d, i]]];      But for, say n=6, this gives me               "0<d      1<d      2<d      3<d      4<d      5<d      6"      Where it seems to have interpreted the string as `"0<d\n 1<d\n 2<d\n 3<d\n 4<d\n 5<d\n 6"`. Why is it doing this? How can I achieve the result I am looking for?


title: Using Greek letters with subscripts as symbols

text: I'd like to use `Subscript[ϕ, 1]` as a function name:               Subscript[ϕ, 1][x_] = C1 + C2*x + C3*Exp[α*x] + C4*Exp[-α*x]      But as I use               ?Subscript[ϕ, 1]      I get the error meassage               Information::ssym: Subscript[ϕ, 1] is not a symbol or a valid string pattern. >>      How can I define `Subscript[ϕ, 1]` as a symbol so that I get an output?


title: Mathematica comments disappeared

text: I pressed `Ctrl`+`Shift`+`N` by mistake and all my comments in the active cell disappeared! Unfortunately, I missed the chance to undo that operation. Does anyone know how to let them reappear?


title: How to neatly get the sum of symmetric elements in a list?

text: The task is to compute               symmSum[{a, b, c, d, e, f}]          (*==> {a+f, b+e, c+d} *)          symmSum[{a, b, c, d, e}]          (*==> {a+e, b+d, c} *)      My clumsy solution is               symmSum[l_List] := Block[{n = Length@l, res},        res = Last@Last@Reap@Do[Sow[l[[i]] + l[[-i]]], {i, Ceiling[n/2]}];        If[OddQ@n, res[[-1]] /= 2];        res        ];      I feel that this can be done without using `Length`, but how?


title: How to find number of connected components of graph G?

text: Is there a command that can count the number of components of a graph, in the same way that `VertexCount[G]` counts vertices?


title: MathKernel.exe capped to use only 13% of CPU?

text: I am using a Windows machine with 8 cores. No other process than Mathematica 8 is using CPU time right now - still the MathKernel.exe CPU usage does not go beyond 13%. My current computation takes forever and I feel that might be the reason. How can I adjust the CPU usage of Mathematica to use, say, up to 90% of CPU?


title: Solving Thue equations

text: A Thue equation is a 2-variable homogeneous integer polynomial of degree at least 3. It's well-known that such equations have only finitely many solutions over the integers. I'm trying to solve some simple Thue equations with `Reduce` but Mathematica is having trouble (no error, it just runs 'forever', or at least hours). Here's an example I pulled from a test suite:               toSym[P_] := Simplify[y^Exponent[P, x]*P /. x -> (x/y)]     thue[P_, a_Integer] := Simplify[Reduce[toSym[P] == a, {x, y}, Integers]]     thue[x^4 - 13*x^3 - 172*x^2 - 13*x + 1, 9]      I can broaden the scope, asking for rational solutions, in which case it gives > (((x > Root[-20736 - 78978339 #1^4 - 16932890540 #1^8 + 2346433600 #1^12 &, > 2] || x < Root[-20736 - 78978339 #1^4 - 16932890540 #1^8 + 2346433600 #1^12 > &, 1] || Root[-20736 - 78978339 #1^4 - 16932890540 #1^8 + 2346433600 #1^12 > &, 1] < x < Root[-20736 - 78978339 #1^4 - 16932890540 #1^8 + 2346433600 > #1^12 &, 2]) && (y == Root[-9 + x^4 - 13 x^3 #1 - 172 x^2 #1^2 - 13 x #1^3 + > #1^4 &, 1] || y == Root[-9 + x^4 - 13 x^3 #1 - 172 x^2 #1^2 - 13 x #1^3 + > #1^4 &, 2])) || ((x > Root[-20736 - 78978339 #1^4 - 16932890540 #1^8 + > 2346433600 #1^12 &, 2] || x < Root[-20736 - 78978339 #1^4 - 16932890540 #1^8 > + 2346433600 #1^12 &, 1]) && (y == Root[-9 + x^4 - 13 x^3 #1 - 172 x^2 #1^2 > - 13 x #1^3 + #1^4 &, 3] || y == Root[-9 + x^4 - 13 x^3 #1 - 172 x^2 #1^2 - > 13 x #1^3 + #1^4 &, 4]))) && (x | y) [Element] Rationals but this isn't a solution -- it doesn't find whether the polynomials have the indicated rational roots or not. In any case I'm actually interested only in the integral solutions. Any ideas? Edit: I see in Some Notes on Internal Implementation that Mathematica implements the Tzanakis-de Weger algorithm for Thue equations. Can we trace the behavior of the functions to see if this is being called internally with some sort of `Unprotect` scheme? Edit 2: I don't think this should take so long to solve -- other systems can solve it in under a second. But I'd like to do this in Mathematica if possible. I suspect that the problem is that Mathematica is stuck on some aspect of the problem not being given to it in the desired format rather than a lack of ability on its part.


title: How to transform a DumpSaved .mx file to .m file conveniently?

text: I have many `DumpSave`-d `.mx` files under a directory. They are generated under Linux. The `.mx` files are platform dependent, but I want to use the data stored in these `.mx` files under Windows. **So I want a method to transform a batch of`.mx` files into platform independent `.m` files conveniently.**


title: Why can't my new installation of Mathematica 9.0.1 find sysinit.m

text: I have just installed Mathematica 9.0 in a x64 openSUSE 12.3 machine using `sh Mathematica_9.0.1_LINUX.sh` as superuser. I have had Mathematica 8.04 working on the previous 12.2 version with no problem. Now, after installing and running `./math` to register the activation key and get MathID and password, I get the message               `Mathematica could not find its system-wide initialization file "sysinit.m".     The following places were searched:          .           ~           /usr/local/Wolfram/Mathematica/9.0/SystemFiles/Kernel/Binaries/Linux-x86-64/Packages           /usr/local/Wolfram/Mathematica/9.0/SystemFiles/Kernel/Binaries/Linux-x86-64/SystemFiles/KernelInit           /usr/local/Wolfram/Mathematica/9.0/SystemFiles/Kernel/Binaries/Linux-x86-64/SystemFiles/GraphicsInit     Segmentation fault     `      and the same happens when I try to run `/.MathKernel` from terminal. It would also be nice knowing how to uninstall it if I am forced to switch back to the 8.0.4 version


title: How can I export definitions of several symbols to a single file?

text: the problem related to this question What I want to do is to `Export` definition of several symbol into a single file. The reason I choose `Export` is that `Export` supports the `GZIP` function. So here is the example: I have               ff[1, 1] = 1;     ff[1, 2] = 2;     gg[1, 1] = 3;     gg[1, 2] = 4;      if I use `Save`, then it is simply               Save["ffgg.m", {ff, gg}]      the content of `ffgg.m` file               ff[1, 1] = 1     ff[1, 2] = 2     gg[1, 1] = 3     gg[1, 2] = 4      But if I want to `Export`, since the syntax of `Export` is `Export["file", expr]`. It seems that I can only `Export` one `expr` each time. I tried the following code:               Export["ffgg2.m", {FullDefinition @ ff, FullDefinition @ gg}];      the content of `ffgg2.m` will be               (* Created by Wolfram Mathematica 8.0 : www.wolfram.com *)     {ff[1, 1] = 1     ff[1, 2] = 2, gg[1, 1] = 3     gg[1, 2] = 4}      And if I Import `ffgg2.m` back, I only get `ff[1,1]` and `gg[1,1]`. The other two lost. **So how can I`Export` several definitions into a single file at a single time?**


title: How can I plot a hyperbola from its complex representation?

text: How can I plot the hyperbola represented by the following complex equation: $$\left|z-a\right|-\left|z-b\right|=2t\tag{1}$$ Should I convert (1) into the following form?               ContourPlot[x^2 - y^2 == 1, {x, -2, 2}, {y, -2, 2}]      ![contour plot of hyperbola](http://i.stack.imgur.com/L7Wbz.png)


title: CUDALink not working on Mac OS X

text: On my MacBook Pro, I have a CUDA enabled video card, yet _Mathematica_ does not seem to recognize this. For example, following the `CUDALink` Setup, I get               Needs["CUDALink`"]     CUDAQ[]     (* False *)     CUDADriverVersion[]      (* CUDADriverVersion::nodriv message raised. *)      Additionally, according to the documentation, my card is not listed, despite NVidia saying otherwise. How do I convince _Mathematica_ that my card supports CUDA?


title: Need more float precision

text: I have a Physics problem which huge and tiny numbers and Mathematica just gives me a speed of my particles which is the speed of light. Then $1/\sqrt{1-v^2/c^2}$ becomes singular. If I use smaller values for my radius `r`, it works, but with the radius of 300 light years, I just get error messages. Is there some way to increase the precision or something like that? ![](http://wstaw.org/m/2012/06/16/Bildschirmfoto4.png)


title: CUDALink not working on Linux-64 and Asus GTX460

text: On my hardware I have a CUDA enabled video card an ASUS GTX460, yet Mathematica does not seem to recognize this. I have:   * CUDA Toolkit 4.1   * CUDA SDK 4.0    * NVIDIA Driver 295.49 on Sabayon Linux 64 bit with Mathematica 8.0.0. For example, following the CUDALink Setup, I get               Needs["CUDALink`"]     CUDAQ[](* False *)     CUDADriverVersion[] (* CUDADriverVersion::nodriv message raised. *)      The NVIDIA command `/opt/cuda/sdk/C/bin/linux/release/deviceQuery` finds the card and reports "passed" as well as listing the card capabilities. Examples from /opt/cuda/sdk/C/bin/linux/release directory, such as `smokeParticles`, `scan`, `randomFog`, run well. The relevant shell variables are set as follows: `export CUDA_LIBRARY_PATH=/usr/lib64/libcuda.so` `export NVIDIA_DRIVER_LIBRARY_PATH=/usr/lib64/opengl/nvidia/lib/libnvidia- tls.so.*` **Additional Information** _Supported Hardware_ The Wolfram CUDA reference page CUDA Reference does not explicitly list the GTX 460 GPU. It does list the GTX 460M, the mobile version, and a mysterious GTS 460. The Wolfram linked NVIDIA CUDA GPUs lists the popular GTX 460 but has no entry at all for the GTS 460. Perhaps this is a typo in the Wolfram documentation, as it would seem unlikely that they wouldn't support a commonplace NVIDIA GPU whilst supporting a seemingly non-existent GPU. If this isn't the case - I'm clearly stuck. **Problems finding the NVIDIA driver** Some poking around suggests that one sticking point is that               GPUTools`Internal`$NVIDIADriverLibraryVersion      is set to `$Failed`. Would anyone know where this is set? From trying to `Trace` `CUDADriverVersion` it isn't obvious to me where things go wrong. How do I convince Mathematica that my card supports CUDA?


title: RSolve not returning known solution

text: I have the following recurrence relationship for which I know the solution is given by a binomial distribution:               reccurance =  A (i + 1) v[i + 1] + (n - i - 1) v[i - 1] == (n - i) v[i] + A i v[i]      But when I use RSolve I get RSolve[{reccurance}, v, i]               {{v -> DifferenceRoot[         Function[{\[FormalY], \[FormalN]}, {(-2 - \[FormalN] +                 n) \[FormalY][\[FormalN]] + (1 + \[FormalN] (1 - A) - A -                 n) \[FormalY][               1 + \[FormalN]] + (2 A + \[FormalN] A) \[FormalY][               2 + \[FormalN]] == 0, \[FormalY][0] ==             C[1], \[FormalY][1] == C[2]}]]}}      Putting in the appropriate boundary conditions does not help things at all. e.g.               RSolve[{reccurance, v[-1] == 0, v[n + 1] == 0}, v, i]      Does not do anything at all (well, it returns the input). Nor does adding the constraint for all values to sum to one, or the first value equal to a yet-to- be-determined constant. How do I make this result in something that is clearly a binomial distribution?


title: An easier and more efficient way to combine lists?

text: I currently have a two lists. The first list contains independent variables $x$, and the second list contains dependent variables in the form of $\{\{f[1][x]\},\{f[2][x]\},...,\{f[n][x]\}\}$. I want to combine them in the form $$\{\{\{x1,f[1][x1]\},\{x2,f[1][x2]\},...,\{xn,f[1][xn]\}\},\{\{x1,f[2][x1]\},\{x2,f[2][x2]\},...,\{xn,f[2][xn]\}\},...,\{\{x1,f[n][x1]\},\{x2,f[n][x2]\},...,\{xn,f[n][xn]\}\}\}$$ ...an easy format for `ListPlot`. For some example data:               a = Range[10];     b = a^2;     c = (a + 1/2)^2;     fa = {b,c};      Now one can easily do this with `Table`:               Table[{a[[j]], fa[[i, j]]}, {i, Length[fa]}, {j, Length[c]}]      but knowing _Mathematica's_ many functions I thought there might be an easier way. I tried this as well:               Transpose@MapThread[Tuples@{{#1}, #2} &, {a, Transpose@fa}]      but with the multiple `Transpose` calls, I figured there would be a slight performance hit. And there was (2.854 vs 3.261 seconds for vectors with 1MM elements on my machine). Is there an easier and more efficient way to combine these lists?


title: One-dimensional heatmap

text: I want to plot a heatmap of a set of real points of the interval [0,1] - i.e., to display their linear density in the sense of a smoothed histogram. The idea I have come up so far is to use the heatMap function introduced here:               heatMap[data_, opts : OptionsPattern[]] := Module[     {n, size, xRange, pr},     n = "Points" /. {opts} /. {"Points" -> 100};     pr = PlotRange /. {opts} /. {PlotRange :>          Map[{Min[#], Max[#]} &, Transpose[data]]};     xRange = -Subtract @@ pr[[1]];     size = Floor[       n ("Radius" /. {opts} /. {"Radius" -> xRange/6})/xRange];     Graphics[{       Inset[        ArrayPlot[         Rescale@GaussianFilter[           ImageData@ColorNegate@ColorConvert[              Rasterize[Graphics[Point[data],                Background -> White,                PlotRangePadding -> 0,                ImagePadding -> 0,                ImageMargins -> 0,                PlotRange -> pr],               "Image", ImageSize -> n], "GrayScale"],           {3 size, size}, Padding -> 0],         ColorFunction ->            (ColorFunction /. {opts} /.            {ColorFunction ->             ColorData["LakeColors"]           }          ),         ImagePadding -> 0,         PlotRangePadding -> 0, Frame -> False],        pr[[All, 1]], {0, 0}, xRange]},      PlotRange -> pr, Frame -> True, PlotRangePadding -> Scaled[.02]      ]     ]      and converting the one dimensional data to two dimensions:               data = RandomReal[{0, 1}, 100];     data = {#, 0} & /@ data;          heatMap[data, "Points" -> 300, "Radius" -> .01, PlotRange -> {{0, 1}, {0, .05}}]      ![sample plot](http://i.stack.imgur.com/1nlcw.png) How do I have to modify heatMap to draw rectangles instead of points that blur at the edges? Or perhaps is there a shorter and more elegant way to draw a "heatline"?


title: How to evaluate this product

text: I was trying to evaluate this product $$ \sin (1^\circ) \sin (2^\circ) \sin (3^\circ) ... \sin (88^\circ) \sin (89^\circ) \sin (90^\circ) $$ But I think it got weird results with this `Product[Sin[i], {i, pi/180, pi/2}]` Can anyone suggest me something??


title: Pattern that matches colors

text: Suppose I'm writing a function that takes a color as a parameter; for example:               drawShape[color_] := Graphics[{Style[Disk[], color]}];      But if the caller inputs an invalid color, bad things happen: ![Bad](http://i.stack.imgur.com/GbPLm.png) So I want to use a pattern to define `drawShape` only for values that are actually colors. Conceptually,               drawShape[color_Color] := ...      The problem is that unlike (say) `List`s, `Integer`s, `Real`s, `Complex`es, or `Graphics`es, color objects do _not_ share a `Color` head. That is,               In[1]:= Red // Head     Out[1]= RGBColor     In[2]:= Hue[0.5] // Head     Out[2]= Hue     In[3]:= GrayLevel[0.5] // Head     Out[3]= GrayLevel     In[4]:= CMYKColor[0, 1, 1, 1/2] // Head     Out[4]= CMYKColor     In[4]:= Opacity[0.5, Purple] // Head     Out[4]= Opacity     In[5]:= Transparent // Head     Out[5]= GrayLevel      So that won't work. I also don't see any `ColorQ` function, with which I could write `drawShape[color_ ? ColorQ] := ...`. **How can I write a pattern that matches any valid color object?** Is there a more robust way than just testing for each of these heads?


title: In InputField, how to prevent Shift-Return from generating a new cell?

text: When running the following in a notebook (not a deployed `CDF` file), it can sometimes be annoying that accidentally pressing `Shift`-`Return` breaks out of the user interface:               Panel@DynamicModule[{input = ""}, InputField[Dynamic[input], String]]      I would like to know if one can (programmatically) prevent such a cell from being "evaluated" when `Shift`-`Return` is pressed, so that the user stays in the `InputField` instead of being thrown out of it while seeing a new generated cell appear.


title: How can I deploy only the output in Player Pro

text: I want to know how can I see only the output when I deploy the `Mathematica` notebook in `Player Pro` as in `CDF Player`? I have gone through this screencast on How to Encrypt Your Code for Deployment, but I haven't understood it properly.


title: ItoProcess function

text: While looking in the help manual of Mathematica concerning the ItoProcess function I found the following: ItoProcess[{a,b,c},x,t]: represents an Ito Process **y(t)=c(t,x(t))** , where **dx(t)=a(t,x(t))dt+b(t,x(t)).dw(t)** In order to replicate and Plot this, I entered the following code:               (*Defining a process y(t)=c((xt)), where \[DifferentialD]x(t)=μ\     \[DifferentialD]t+σ\[DifferentialD]w(t)*)          ItoProcess[\[DifferentialD]x[         t] == μ \[DifferentialD]t + σ \[DifferentialD]w[t],       c[x[t]], {x, 0}, t, w \[Distributed] WienerProcess[]]      Then I wanted to Plot one process by implementing drift and volatility.               (*Simulation of one Ito Process with μ=0.1 and σ=0.2, \     starting value x=0*)          testprocess5 =       ItoProcess[\[DifferentialD]x[t] ==         0.1 *\[DifferentialD]t + 0.2 *\[DifferentialD]w[t],     c[x[t]], {x, 0}, t, w \[Distributed] WienerProcess[]]       Concerning this code I got the same output like in the Mathematica help manual just the drift and the volatility were substituted by 0.1 and 0.2 respectively. However, when I tried to plot the process it did not work out.               ListLinePlot[      Table[RandomFunction[         testprocess5, {0 (*startis from t=0*), 5 (*ends at t=5*),           0.01 (*Δt*)}] ["Path"], {1(*number of paths*)}],       Joined -> True, AxesLabel -> {"time", "value"}, ImageSize -> 400,       PlotRange -> All]      I am not sure, why it is not workling, maybe it could be due to y (t) = c ((xt)). Does anyone of you have a solution for this problem or a suggestion how to change the code? thanks


title: Colors in ExclusionsStyle

text: I have the following Plot: ![enter image description here](http://i.stack.imgur.com/D3j8p.png) Apparently MMA uses `ColorData[1,1]` for the edges in all graphs. I already tried adding               ExclusionsStyle -> {ColorData[1, 1], ColorData[1, 2], ColorData[1, 3]}      but that doesn't help; it only uses the first listed color. Adding `Directive' only uses the _last_ listed color:               ExclusionsStyle -> Directive[{ColorData[1, 1], ColorData[1, 2], Red}]]      Any idea how I can Plot the edges in the same colors as the graphs? **edit**   The code, upon request:               sqw[x_, f_] := SquareWave[x f]/3;       Plot[{sqw[x, 1] + 2.5, sqw[x, 0.95] + 1.5, -3 sqw[x, 1] sqw[x, 0.95] + 0.5}, {x, -1, 4},       Axes -> False, PlotStyle -> {AbsoluteThickness[2]},       ExclusionsStyle -> {ColorData[1, 1], ColorData[1, 2], ColorData[1, 3]}]


title: Integrating and plotting pde system solution

text: I have a trouble with plotting a pde system solution. I'm solving a PDE system in 2-dimensional space and then I want to integrate the solution along one dimension and build a log plot along the other. I tried the following piece of code:               rules = NDSolve[{Eqs, Append[{Cond0, Cond00, Cond1}, Cond]},                      U[t, x], {t, 0, 0.01}, {x, 0, H}];     F = (NIntegrate[First[U[#, x] /. rules], {x, 0, H}]) &     F[0.1]      which produces an error > "Integrand has evaluated to non-numerical values". I assume it happens because _Mathematica_ is trying to integrate the function before substituting `0.1`. I thought that putting it into the pure function that evaluates its body only after substitution would fix the problem, but it didn't. How to make it work?


title: Differing behaviour of GeneratingFunction with different numbers of parameters

text: When given a single variable sequence, `GeneratingFunction` is automatically expressed in the most "direct form", for example,               GeneratingFunction[(i + 1) v[i - 1], i, x]      returns something like               2 x GeneratingFunction[v[i], i, x] + v[-1] + x^2 D[GeneratingFunction[v[i], i, x],x]      But, if I add an extra variable that does not otherwise affect the result               GeneratingFunction[(i + 1) v[i - 1, j], {i, j}, {x, y}]      then the function is not evaluated in the same way, although, it would seem that it would be correct to return               2 x GeneratingFunction[(i + 1) v[i - 1, j], {i, j}, {x, y}] + v[-1,j]      + x^2 D[GeneratingFunction[(i + 1) v[i - 1, j], {i, j}, {x, y}],x]      what is happening here, how can I make it behave in a way that would fit this intuition?


title: Computing closest set of points to each point in large set -- running out of memory (arrays unpacking)

text: I have a large set of points in 3D and I'm trying to identify all the points that lie within a certain distance of each point. Then using this data store the vector between the pairs of points. I have about 1M points and this results in millions of vectors. It seems that when I `Map` `Nearest` over my set of points it is unpacking the array (because it becomes ragged?) and this appears to take up all my memory. At the end I `Flatten` the array to a specific depth and can manually pack it again and I estimate it should fit in memory. `closepointsvectors` finds all the points within 1 unit of point x and then returns the vector between the point x and the "close" points. I then `Map` this over all the points in the dataset. This generates many many vectors. Here is a minimal (non)working example.               data = RandomReal[10, {10^6, 3}];     nearestfunction = Nearest[data];     closepointsvectors[x_] := (x - #) & /@ nearestfunction[x, {Infinity, 1}]          (*lets try on a small subset of the data*)     smalltest = Flatten[Map[closepointsvectors, data[[1 ;; 10000]]],2]; // AbsoluteTiming          (*{1.5870908, Null}*)          Developer`PackedArrayQ@data          (*True*)          Developer`PackedArrayQ@smalltest          (*False*)          ByteCount[smalltest]          (*40818664*)          packedsmalltest = Developer`ToPackedArray@smalltest;     Developer`PackedArrayQ@packedsmalltest          (*True*)          ByteCount[packedsmalltest]          (*10204824*)      Is there a way to reduce memory usage, possibly keeping the array packed the whole time. Can I pad the array with zeroes as I go to prevent it from becoming ragged? I tried to take advantage of compile but it doesn't appear to work with `Nearest`.


title: Defining functions in stylesheets

text: Is there a way to define functions in a stylesheet? So far I have managed to write my stylesheets without the need to use my own custom functions or definitions. For instance, maybe I have some color that I wish to use throughout my stylesheet.               myColor = RGBColor[.5,.5,.5];      The reason I would like to do this is that later on, if I change the color, every style that depends `myColor` will automatically change. This can apply to other functions that you might create. I know that I can use any built-in function I want in the stylesheets. Is there a way to define custom functions to use in a stylesheet without making a package? If making a package is the only way, how can we make sure the stylesheets that use such package load the package first so that the styles are properly defined?


title: Mapping data on Archimedes' spiral

text: I would like to map my data on Archimedes' spiral and preserve the distance between points on the curve. The test data consists of 20 evenly spaced `{x,y}` coordinates:               data = Table[{i, i}, {i, 20}]      When I map the data to a spiral, the points are not evenly spaced anymore:               Show[ListPlot[{#[[2]] Sin[#[[1]]], #[[2]] Cos[#[[1]]]} & /@ data,        AspectRatio -> 1, PlotRange -> {{-20, 20}, {-20, 20}}],       ParametricPlot[{t Sin[t], t Cos[t]}, {t, 0, 20}]]      ![Mathematica graphics](http://i.stack.imgur.com/CEaCg.png) I found this question that links to the algorithm that iteratively generates evenly distributed points on a spiral, but how can I apply this to my set of data points? The final goal that I'm trying to achieve is to create a function that I can use with `ImageTransformation` that will remap an image that roughly resembles a line to an Archimedes' spiral.