Is linear interpolation applicable here

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


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

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?


Plotting a Spericon and Bipyramid with 100 faces

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?


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

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.)


Compiled version of interpolation function slower non-compiled version

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?


How to compile gather

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}]]


1/0 encountered when solving an ODE

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.


How to convert data types in a LibraryLink wrapper

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.


What is NDSolve`FEM`*?

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?


Bug in LengthWhile?

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.


How can I append associations with uneven elements?

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?


Remove Spacings around each grid item?

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.


Mathematica can't find constants for this differential equation

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.


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

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?


Using Manipulate to dynamically correct the baseline of a signal

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)


Problem with Creating Mathematica Package

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 ?


Clear labelling gray-scale plots

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}]


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

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?


Use elements of Array inside function definition

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?**


Applying several patterns to `Split`

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?


Call Haskell from Mathematica and return the results inside Mathematica

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


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

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?


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

> **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


Refer to next element of list when iterating using Map

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}


Spelling dictionary corrupted

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.


A question about derivatives (cubics)

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.


Solve equation containing conditions (If expressions)

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


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

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] >


Using subscript in a string

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?


Using Greek letters with subscripts as symbols

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?


Mathematica comments disappeared

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?


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

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?


How to find number of connected components of graph G?

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


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

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?


Solving Thue equations

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.


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

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.**


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

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


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

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?**


How can I plot a hyperbola from its complex representation?

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)


CUDALink not working on Mac OS X

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?


Need more float precision

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)


CUDALink not working on Linux-64 and Asus GTX460

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?


RSolve not returning known solution

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?


An easier and more efficient way to combine lists?

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?


One-dimensional heatmap

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"?


How to evaluate this product

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??


Pattern that matches colors

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?


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

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.


How can I deploy only the output in Player Pro

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.


ItoProcess function

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


Colors in ExclusionsStyle

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]}]


Integrating and plotting pde system solution

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?


Differing behaviour of GeneratingFunction with different numbers of parameters

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?


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

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`.


Defining functions in stylesheets

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?


Mapping data on Archimedes' spiral

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.


Errors in evalauting an expression

I have the following: **Constants:**               b3b = 2;     G = (1/eps^2);     a1 = 3;     a3 = 4;     xc = 0.3;      **Functions:**               y[x_] := (x*a1 - x^3*a3)/G     n[x_] := (y[x]^2)      **I want`g[x], gp[x], gpp[x]` as functions of `eps` only and all of these three functions should be evaluated at `x=xc` :**               g[x_] := (G*(-y[x]/eps)*Exp[-n[x]] - (b3b/eps)*          NIntegrate[(y[s])^4*Exp[-n[s]], {s, 0, xc}])      Please note that in the **integrand** above --> both `n[x]` and `y[x]` are functions of `eps` and so I can use `NIntegrate` since I am using `:=` for `g[x]` even though `eps` is not given a numerical value as yet. Everything is perfect till this point as I am able to get a numerical value for `g[xc]` for a `eps` value. The problem happens when I take the following derivatives:                gp[x_] := D[g[x], x]      gpp[x_] := D[gp[x], x]      since when I evaluate `gp[xc]` and `gpp[xc]` for a particular `eps` value, I get errors: `NIntegrate::inumr` and `General::ivar`. Therefore, I need a way to get around this. I must be doing something wrong. Any help would be greatly appreciated. Thanks!


Revert Notebook to earlier version using Notebook History

Is it possible to revert a notebook to its earlier version via the Mathematica's Notebook History panel? It would be nice if I could select a point in time in the bottom graph and revert back to that version: ![enter image description here](http://i.stack.imgur.com/wyPoB.png) When hovering over the blue dots on the upper graph, you can see the previous and the current contents of the changed cells, so Mathematica must store this somewhere. Maybe this could even be used instead of a better undo implementation.


Highlighting text with StringReplacePart but also using Style, Subscript

For a Natural Language Processing analysis task it's desirable to highlight a text string programmatically according to XML tags that reference specific words or phrases. The XML tags specify the character ranges in the input string as well as give other information such as identifiers and other codes. Since character ranges are provided in the XML markup, originally I thought `StringReplacePart` would do the job, but it doesn't seem possible to transform the string into more general expressions, eg using Subscript or Style. For example (please excuse I'm showing only a fragment due to Protected Health Information), given the (partial) input text:               In[566]:= StringTake[I2B2[1, text], -500]          Out[566]= " pain and was treated with Percocet . She went for a \     debridement of her left calf lesion on 10/2/93 and was started \     empirically on IV ceftriaxone which was changed to po doxycycline on \     the day of discharge . A follow-up CT scan was done which did not \     show any evidence for splenomegaly or hepatomegaly . The 1 cm cyst \     which was seen in 10/92 was still present . There was a question of a \     cyst in her kidney with a stone right below the cyst , although this \     did not seem to be clinically significant ."      And the XML tag:               In[581]:= Cases[I2B2[1, tags],       XMLElement[       "EVENT", {id_, start_, end_, text_ -> "a stone", modality_,         polarity_, type_}, _]]          Out[581]= {XMLElement[       "EVENT", {"id" -> "E75", "start" -> "2476", "end" -> "2483",         "text" -> "a stone", "modality" -> "POSSIBLE", "polarity" -> "POS",         "type" -> "PROBLEM"}, {}]}      The following `StringReplacePart` works (to ALL CAPS) since the output is still a string:               In[577]:=  StringReplacePart[      StringTake[I2B2[1, text], -500],      "A STONE", {2476,         2483 - 1} - ((I2B2[1, text] // StringLength ) - 500)]          Out[577]= " pain and was treated with Percocet . She went for a \     debridement of her left calf lesion on 10/2/93 and was started \     empirically on IV ceftriaxone which was changed to po doxycycline on \     the day of discharge . A follow-up CT scan was done which did not \     show any evidence for splenomegaly or hepatomegaly . The 1 cm cyst \     which was seen in 10/92 was still present . There was a question of a \     cyst in her kidney with A STONE right below the cyst , although this \     did not seem to be clinically significant ."      But the following does not since I'm trying to highlight in Red using Style:               In[578]:=  StringReplacePart[      StringTake[I2B2[1, text], -500],      Style["a stone",        Red], {2476, 2483 - 1} - ((I2B2[1, text] // StringLength ) - 500)]          Out[578]= StringReplacePart[" pain and was treated with Percocet . \     She went for a debridement of her left calf lesion on 10/2/93 and was \     started empirically on IV ceftriaxone which was changed to po \     doxycycline on the day of discharge . A follow-up CT scan was done \     which did not show any evidence for splenomegaly or hepatomegaly . \     The 1 cm cyst which was seen in 10/92 was still present . There was a \     question of a cyst in her kidney with a stone right below the cyst , \     although this did not seem to be clinically significant .", \!\(\*     StyleBox["\<\"a stone\"\>",     StripOnInput->False,     LineColor->RGBColor[1, 0, 0],     FrontFaceColor->RGBColor[1, 0, 0],     BackFaceColor->RGBColor[1, 0, 0],     GraphicsColor->RGBColor[1, 0, 0],     FontColor->RGBColor[1, 0, 0]]\), {413, 419}]      Are there functions similar to StringReplacePart that can output more general expressions? Or in any case how to perform the desired highlighting with Subscript and Style?


How to do the log scale plot for ListContourPlot

My current code is:               data = {{0.1, 0.1, 2}, {0.1, 0.2, 1}, {0.2, 0.1, 1}, {0.2, 0.2, 2}};     ListContourPlot[data, Mesh -> None, PlotRange -> All,       InterpolationOrder -> 3,       ColorFunction -> ColorData[{"LakeColors", "Reverse"}]]      It produces the following figure: ![enter image description here](http://i.stack.imgur.com/ju78p.png) I want to scale the linear x and y axes to a log scale without converting to log units. There is a ListLogLogPlot function but no corresponding ListLogLogContourPlot function. I have read several relevant threads:   * How does one set a logarithmic scale in a ContourPlot?: How does one set a logarithmic scale in a ContourPlot?   * Scale ContourPlot axes: http://forums.wolfram.com/mathgroup/archive/2006/Jun/msg00585.html However, they are all for ContourPlot rather than ListContourPlot. I tried to use way suggested by How does one set a logarithmic scale in a ContourPlot?:               data = {{0.1, 0.1, 2}, {0.1, 0.2, 1}, {0.2, 0.1, 1}, {0.2, 0.2, 2}};     pl = Normal@       ListContourPlot[data, Mesh -> None, PlotRange -> All,         InterpolationOrder -> 3,         ColorFunction -> ColorData[{"LakeColors", "Reverse"}]]     ListLogLogPlot[Cases[pl, Line[a_, b___] :> a, Infinity],       Joined -> True, Frame -> True, PlotRange -> All, AspectRatio -> 1,       PlotStyle -> ColorData[1][2]]      However, it only produces the following, in which the density color background is lost, leaving only lines: ![enter image description here](http://i.stack.imgur.com/o7e0U.png) The way suggested by http://forums.wolfram.com/mathgroup/archive/2006/Jun/msg00585.html by using FrameTicks functions seems promising. But, it is for ContourPlot. I do not know how to adopt it to be used in ListContourPlot. Helps are much appreciated.


Manipulate inside a function definition slows down when passed a large data set

I'm working with large data sets (>1gb) which I'm visualizing with `Manipulate[]`. The following example works fine for me with no additional memory overhead:               data = RandomReal[{0, 1}, {500, 500, 500}];     (* no memory overhead and fast response time *)     Manipulate[Image[data[[All, All, i]]], {i, 1, 500, 1}]      However, if I wrap the above code into a separate function definition, memory usage rises and evaluation does'n complete in a reasonable time:               vizData[dataVar_] := Manipulate[Image[dataVar[[All, All, i]]],{i, 1, 500, 1}]     (* very high memory usag and slow evaluation! *)     vizData[data]      How can I wrap the functionality of `Manipulate` into a function without this high memory utilization? Working with global variables is not an option because I'm dealing with multiple data sets.


Storing result from nested Table in a File for further computations

Consider the following:                Table[Table[x = 20; y = 30; 2 i x + 3 j y , {i, 10}], {j, 3}]      Suppose I want the result of this nested Table to be stored to an appendable file, I could do something like:               Table[Table[x = 20; y = 30; 2 i x + 3 j y >> test.dat, {i, 10}], {j, 3}]      Where `test.dat` has been previously opened using `OpenAppend["test.dat"]` However, this doesn't work as I would like it to as the answer is stored differently than the actual output shown below and _Mathematica_ returns Null for every element of the output.               {          {130, 170, 210, 250, 290, 330, 370, 410, 450, 490}, {220, 260, 300,           340, 380, 420, 460, 500, 540, 580}, {310, 350, 390, 430, 470, 510,           550, 590, 630, 670}        }      My question is this. How can I save the output of the Nested Table to a file for every iteration of the outer `Table` and prevent any `List` from being returned by _Mathematica_?. That is, I don't want _Mathematica_ to return the following `List` as it currently does:               { {Null, Null, Null, Null, Null, Null, Null, Null, Null, Null}, {Null,        Null, Null, Null, Null, Null, Null, Null, Null, Null}, {Null, Null,        Null, Null, Null, Null, Null, Null, Null, Null} }      I will also like the data stored in the file to be exactly as the output shown above, since I will use it for further calculations in _Mathematica_. This is basically a way to prevent excessive memory usage. If there are better ways to achieve the same thing please feel free to post that as an answer.


Write nth line to file

I have a code that I am running on a supercomputer. Currently the algorithm must finish before I can export any results from the algorithm. What I would like to do is to have the algorithm write out the results for every nth line of the loop. Could someone help me write this into the algorithm below. I currently use the Reap and Sow construct to store the data and collect it all at the end. Sometimes the code crashes for during the run, in which cases I get nothing out of the run before it stops. If I could also write to a file while the code is running, at least I'd have better starting points to begin the next run. Thanks!                      If[             u[[i]] < v[[i]],(*If u<v always accept that parameter set,             else accept with probability u<v*)                  ka[[i + 1]] = ka[[i]];             kb[[i + 1]] = kb[[i]];             Sow[{True, decayscore[[i]], v[[i]], ka[[i]], kb[[i]], i}],            (* These quantities are written to bestParamSets *)                  ka[[i]] = ka[[i - 1]];             kb[[i]] = kb[[i - 1]];             ],            ka[[i]] = ka[[i - 1]];            kb[[i]] = kb[[i - 1]]            ],


Using ANOVA with a "Repeated measures" / "Within-subjects" design

Repeated measures designs or "Within-Subjects" designs are very important in live sciences and social sciences. Unfortunately, _Mathematica's_ ANOVA package is not able to analyze those designs. It only handles "Between- Subjects" type of analyses. During my whole research career I haven't been able to use _Mathematica_ to analyze most of the studies I performed, which really is a pity. In an e-mail exchange I had with WRI's Andy Ross in the beginning of this year he confirmed that I wasn't overlooking built-in functionality. The question is: is any one aware of third party packages that handle these types of ANOVAs?


Open parent cell groups of selected cell

I wrote a small script for a palette, which allows me to highlight a specific cell in a notebook by using `SelectionMove[mycell, All, Cell]`. The cell is selected as expected, but sometimes this cell is part of a cell group (section, subsection etc.) which is currently closed, so the cell itself is hidden, and `SelectionMove` does not reveal it. So far, I didn't find a way to open all parent groups of this cell programatically so that this cell will be shown... Is this possible?


How can I make a list plot with bars?

Can anyone help me please? I don't want a Histogram; I don't want a BarChart, not even a ListPlot with drop down lines. I want a list plot with drop down columns/bars: please see the link. ![Mathematica graphics](http://i.stack.imgur.com/EQGkc.png) It is basically a histogram but of a different kind. The data structure contains two variables for example in the above figure it was energy and standard deviation. And the frequency distribution was done based on two cut- offs {0.5,2.0} and finally it was plotted along the energy axis. Therefore, it contains overlapping bars/columns. A projection of a 3D histogram in two dimensions.


How to bend a logarithmic number line into a circle

One way to plot a sequence of numbers on a logarithmic number line is this:               LogLogPlot[0, {t, 8, 16}, Axes -> {True, False},       Ticks -> {{8, 9, 10, 11, 12, 13, 14, 15, 16}}]      ![logarithmic number line values 8 to 16](http://i.stack.imgur.com/xf4bo.png) How can the line be bent into a circle, or how can these values be plotted on a circle? ![logarithmic values 8 to 16 on circle](http://i.stack.imgur.com/7vscl.png) The `ParametricPlot` function plots a circle around the coordinates when using `[{Sin[2 u], Cos[2 u]}, {u, 0, 2 Pi}]` and `Graphics[Circle[]]` draws a circle but I can't figure out how to put `Ticks` on them.


Mapping a pure function with multiple slots

Here is a pure function with multiple slots:               (#1^2 + #2^2)&[3, 4]      > 25 But how can I map that pure function over lists of values? For example, say I want to map `(#1^2 + #2^2)&` over `x = {1, 2, 4}` and `y = {3, 4, 6}`. I have tried the following expressions, but none of them work:               Map[(#1^2 + #2^2) &, {1, 2, 4}, {3, 4, 6}]     Map[(#1^2 + #2^2) &, {{1, 2, 4}, {3, 4, 6}}]     Map[(#1^2 + #2^2) &, {{1, 3}, {2, 4}, {4, 6}}]      The result I expect is obviously `{10, 20, 52}`. Could some one help me with this?


Logical operations on a list

> **Possible Duplicate:**   >  Applying And to lists of Booleans I have two lists filled with logicals:               demondata = {True, True, False, True}     numerdata = {True, False, True, True}      I would like to find which corresponding cells positions are both `True`. The only code I could come up with is:               toInclude = MapThread[And, {demondata, numerdata}];      Is there a way to do something like:               demondata && numerdata      Not that there is something wrong with `MapThread`, it just seems more complicated than I thought it would be. In MATLAB, I can do:               list1 & list2  _or_  list1 > 10   etc ...


Applying And to lists of Booleans

I'd like to take `{True,True,False}` and `{True,False,False}` and apply `And` to get `{True,False,False}`. Right now I'm using               And @@ # & /@ Transpose[{{True, True, False}, {True, False, False}}]      Is that really the best way? I would like `And[{True, True, False}, {True, False, False}]` to work but it does not.


Numerical solution of coupled ODEs with boundary conditions

I have to solve the following set of ODEs and just can't get good results using Mathematica $$ r\frac{d}{dr}\left(\frac{1}{r}\frac{d}{dr}A(r)\right)-\xi^2F(r)^2\left(A(r)-1\right)=0 $$ $$ \frac{1}{r}\frac{d}{dr}\left(r\frac{d}{dr}F(r)\right)-\frac{n^2}{r^2}F(r)\left(A(r)-1\right)^2-\frac{1}{2}F(r)\left(F(r)^2-1\right)=0 $$ There are two parameters $\xi\in\mathbb{R}^+$ and $n\in\mathbb{Z}$. There also are boundary conditions at $0$ and at $\infty$. $$F(0)=A(0)=0$$ $$F(\infty)=A(\infty)=1$$ These gave me the first puzzle: how to implement boundary conditions at infinity? I solved this by taking a finite number (in my case 5) instead of infinity. Do you think it is a good approach or is there a more elegant way to implement boundary conditions both at zero and infinity?   Next I want to solve these equations numerically. Here is the Mathematica code for $\xi=1$ and $n=1$               paramND = {         r D[1/r D[A[r], r], r] - \[Xi]^2 F[r]^2 (A[r] - 1) == 0,         1/r D[r D[F[r], r], r] - n^2/r^2 F [r] (A[r] - 1)^2 -            1/2 F[r] (F[r]^2 - 1) == 0,         A[5] == 0.99, A[0.01] == 0,         F[5] == 0.99, F[0.01] == 0} /. {\[Xi] -> 1, n -> 1};          numSol = NDSolve[paramND, {A[r], F[r]}, {r, 0.01, 5}] // Flatten;          paramPlot = {A[r], F[r]} //. numSol;          Plot[Evaluate@paramPlot, {r, 0.01, 5}, PlotRange -> {0, 1},       PlotStyle -> {{Black, Thick}, {Red, Thick}},       PlotLegends -> {"A(r)", "F(r)"}]      For $\xi=1$ and $n=1$ this works fine and I get a result that I expect:   ![xi=1,n=1](http://i.stack.imgur.com/cm13c.png)   The problem is that the numerical solution only works if both parameters $\xi$ and $n$ are close to $1$. Changing these parameters to values different from $1$ produces somewhat awkwrd results: $\xi=3$, $n=1$:   ![xi=3,n=1](http://i.stack.imgur.com/xvz79.png) $\xi=1$, $n=5$:   ![xi=1,n=5](http://i.stack.imgur.com/RQJWI.png)   As you can see, the last two plots don't even respect the boundary conditions! Why is this so? All solutions should look more or less like the first plot, which clearly isn't the case.   I suppose that I lack some fundamental knowledge about how to use NDSolve to produce results which I expect. Can you suggest a good strategy in order to obtain good solutions to these ODEs? I've also tried using the "Shooting" algorithm, which, however, didn't give any useful result either. Maybe you can point out to me what the exact reason is, why NDSolve fails here so I know what to cure. Up to now it was rather a try and error procedure.   So, to sum up, my two questions are:   1. How to implement boundary conditions at infinity?   2. How to choose a good strategy for NDSolve to obtain results one expects?


Bug in TreeForm: "Plot" formatted as True

I believe I have come across a rather curious bug in `TreeForm`:               {"foo", "bar", "Plot"} // TreeForm      ![enter image description here](http://i.stack.imgur.com/tWLuC.png) Note that the string `"Plot"` is formatted as `True`. Unless I have accidentally changed something in my configuration this must be a bug. I am using version 10.0.0 under Windows.


Does new MMA9 Time Series support obsolete the old TimeSeries Package?

MMA9 includes a fair number of functions and symbols that seem to overlap with the old TimeSeries package. The new features are documented here and the old material is documented here. Some of the names are 'same-only-different:' for example, the old package has `ARMAModel` and the new built-in has `ARMAProcess`. The argument list and meaning appear to be the same. I'd like to know if the old package is obsoleted by the new features, or is there still enough utility in the old package to justify its price (around $300)? I can't find a try-before-buy option on the package, so this question seems difficult to answer on my own.


Minimizing a potential using Solve

I am having problems minimizing a potential: $\text{V}(h,\eta)=\gamma \left(-h^2\right) \left(\eta ^2 \cos ^2(\theta )+\eta \cos (\delta ) \sqrt{-\eta ^2-h^2+1} \sin (2 \theta )+\left(-\eta ^2-h^2+1\right) \sin ^2(\theta )\right)$ (Input code below)               V = -h^2 γ (η^2 Cos[θ]^2 + (1 - h^2 - η^2) Sin[θ]^2 + η Sqrt[1 - h^2 - η^2] Cos[δ] Sin[2 θ])      I try to minimize simply using:               sol = Solve[{D[V, h] == 0, D[V, η] == 0}, {h, η}]      It seems to solve quickly and with no problems giving me 9 solutions, these solutions depend on the parameters $\theta, \delta, \gamma$. However if for example I try to calculate:               Chop[N[D[V,h] /. sol /. θ -> 1 /. δ -> 1 /. γ -> 1]]      The output it gives is: > >     {0, -0.104069, 0, 0, -0.484451, 0.104069, 0, 0, 0.484451} >   As you can see extrema `2`, `5`, `6` and `9` are not even close to zero! It seems _Mathematica_ is solving this incorrectly, or maybe the solutions are only valid in specific regions (not the full domain)? Does anyone have any ideas? I thought maybe the problem was with the square root in the function (otherwise it's a simple polynomial) but have tried solving it using the Lagrange multiplier method taking a function $V(h,η,s)$ and $s=\sqrt{1-h^2-η^2}$ but it also doesn't seem to give me all zero solutions when I sub it in to the Lagrange equation $\frac{\partial V}{\partial h}+\lambda \frac{\partial g}{\partial g}$, where $g=s-\sqrt{1-h^2-η^2}=0$, the constraint applied to this function. Any ideas what's happening ? Has anyone encountered this problem before?


Is there a way to programmatically set global preferences?

Can I set global preferences that are accessible via "Edit"->"Preferences" programmatically from within a notebook? As learned from this question, turning off anti-aliasing can make a huge difference in the maximum allowable `ImageSize`. This can be done via menu: ![Mathematica graphics](http://i.stack.imgur.com/jV486.png) The slider is setting the value of `HardwareAntialiasingQuality` that can be found with the option inspector: ![Mathematica graphics](http://i.stack.imgur.com/gmKrK.png) Question: Is there a way to set/reset the value of `HardwareAntialiasing` (and others) programmatically? I´d like to set this with a line only in those notebooks that benefit from this setting and have proper antialiasing for the rest. Footnote: this answer does help with setting the rendering method directly within a `Graphics3D` expression, and as @Sjoerd's answer shows this also works in more global way.


EventHandler not working within DateListPlot (?)

I have some `{date, value}` data:               data = Transpose[{AbsoluteTime /@ Thread[{2012, Range[12], 15}],         RandomInteger[10, 12]}]      Normally I do initial tests with `DateListPlot` and then implement with `ListPlot` or `ListLinePlot` for efficiency. However I just tried this:               DateListPlot[      Table[With[{i = i},        EventHandler[data[[i]], "MouseClicked" :> {Print["hello"]}]], {i,         12}]      ]      and got this error message `DateListPlot::dtvals: Unable to automatically determine horizontal coordinates for the given data and DataRange.` ![enter image description here](http://i.stack.imgur.com/7jME6.png) Whereas if I switch to `ListPlot` or `ListLinePlot` it works fine:               ListPlot[      Table[With[{i = i},        EventHandler[data[[i]],          "MouseClicked" :> {Print["hello " <> ToString[i]]}]], {i, 12}]      ]      ![enter image description here](http://i.stack.imgur.com/oUxLb.png) Can anyone explain why `EventHandler` would not work within `DateListPlot` (hopefully this is not a RTFM question!)? Problem exists with 8.0.4 and 9.0.1 on Mac 10.6.8


Extracting equations from Piecewise expressions

Say I have a PDF:               PDF[LogNormalDistribution[1.75, 0.65], x]      Calculating it, Mathematica gives me an expression that looks like this: ![enter image description here](http://i.stack.imgur.com/el6TK.png) I want to extract the equation itself so I can use it in other calculations. On a one off basis, I can do that with `Part[]`:               PDF[LogNormalDistribution[1.75, 0.65], x][[1, 1, 1]]      which gives me the following: ![enter image description here](http://i.stack.imgur.com/uzIdI.png) That's fine, but I need something more universal. For instance, for a different PDF that looks like this: ![enter image description here](http://i.stack.imgur.com/QrZ7u.png) I could get what I need with:               %[[1, 2, 1]]       You see my dilemma. How do I extract the business part of such expressions in a more universal way so I can use them in other calculations and functions that may need to deal with a variety of such expressions?


Passing large list by reference

I have the following problem: I would like to control evaluation of a variable that points to a list. For example, frequently in the code I have functions of the form that are supposed to work on large lists (modifying them frequently):               updateList[list_, newvalue_, index_]:= (list[[index]] = newvalue)      to be used (many times) as               list = {1, 2, 3};     While[...     updateList[list, -2, 2];     ]      and I should get immediately               list = {1, -2, 3}      The problem is that the list gets evaluated immediately if one is not careful and the assignment statement fails. I have tried to solve this by defining               Attributes[updateList] = {HoldAll}      It works, but I realized that this can get very complicated since I am passing the list quite a bit around in a rather big package. Some function have Hold, some not, on some I would actually like to have the second and the third argument Holding while others not... To tell you the truth, I do not feel I have the control of this behavior; sometimes it evaluates and sometimes it does not, and it is driving me crazy. The reason why I am doing this is to save memory. One could, of course, use the following definition               updateList[list_, newValue_, index_] := (newList = list; newList[[index]] = newvalue)      and use it like               list = updateList[list, -2, 2]      to the same effect, but this will consume quite a bit of memory (my list are huge). So I am trying to control memory usage by updating storage. I guess I am trying to use them as pointers. A more serious example would be               updateList[list_, args__] :=         Block[{indicies, newvalues},            indicies = figureOutIndiciesToChange[args];           newvalues = figureOutValuesToChange[args];           list[[indicies]] = newvalues        ];      or even a more nasty example (actually happens):               updateList[list_, args__] :=         Block[{indicies, newvalues},            indicies = figureOutIndiciesToChange[args];           nestedCallToUpdateTheList[...., list, ...];           newvalues = figureOutValuesToChange[args];           list[[indicies]] = newvalues        ];      where               (* here list can be third argument, or even last *)          nestedCallToUpdateTheList[...., list_, ...] :=                  While[a big loop,           list[[dynamicIndicies] = dynamicValues]];        ]      So I have a principle (open) question: how to update long lists (parts of it) in the most efficient way if such lists are passed through several layers of functional calls? Is there a way to achieve this without using HoldAll? Perhaps using more direct Hold functionality? Anyway, I would like to learn how to be in control... EDIT1: Based on the comments below, I would like to add another requirement; Assume that all this has to be done within the function. Is this possible at all? A bullet-proof way would be               updateLilst[___] := fail["please used Hold on the list argument"];     updateList[...,list_Hold,...] := do the work on the list;      Or...? EDIT2: By the way, how to test whether an argument is evaluated in the function? p.s. I tried with Hold, but it is tricky since it is not make the assignment with a Held variable...


How can I scale tick marks without scaling my function?

Take this plot for instance: ![enter image description here](http://i.stack.imgur.com/iNYGc.png) It shows power in W, but I'd like to see it in µW, so that I get 200, 400, 600,..., which is much more readable. Is there a way to do this without scaling my function and PlotRange by a factor 10$^6$? **edit** re _szabolcs_ 's comment   I already tried               Ticks -> {Automatic, Table[200 x, {x, 5}]}        but that seems to put those tick marks where they belong, namely at 200 W, 400 W, etc.(which is 240 km up the graph), not at the gridlines.


Evaluating Abs'[2 x] gives different results than evaluating D[Abs[2 x], x]

I noticed the following difference               Assuming[x ∈ Reals, FullSimplify[D[Abs[2 x], x]]]          (* 2 Sign[x] *)          Assuming[x ∈ Reals, FullSimplify[Abs'[2 x]]]          (* Sign[x] *)      While it is clear that the first line of code above returns the correct result, I wonder why the call of `Derivative` fails? A little further investigation shows that               f[x_] := Abs[2 x]      f'          (* 2 Derivative[1][Abs][#1] & *)      which is correct and implies that the difference might come from with or without `SetDelayed`. But I still do not fully understand why the second code failed.


how to improve efficiency when I want to classify a list according to certain laws

I have a function that generates lists:               f[n_] := Join @@ Permutations /@ PadLeft@IntegerPartitions[n];      For example               f[3]      > >     {{0, 0, 3}, {0, 3, 0}, {3, 0, 0}, {0, 2, 1}, {0, 1, 2}, >      {2, 0, 1}, {2, 1, 0}, {1, 0, 2}, {1, 2, 0}, {1, 1, 1}} >   `f[3]` returns 10 lists of three elements, which I want to classify this according to certain laws; `{0, 0, 3}, {0, 3, 0}` and `{3, 0, 0}` belong one class with 3 members because `RotateLeft` can transform any one of these into any of the others. Similarly, `{0,1,2}, {1,2,0}` and `{2,0,1}` belong one class with 3 members. `{0, 2, 1}, {2, 1, 0}` and `{1, 0, 2}` belong one class with 3 members. `{1, 1, 1}` belongs to a class of which it is the only member. So the result I want is ![enter image description here](http://i.stack.imgur.com/uHWOG.jpg) I have code that will generate the desired result               m = AbsoluteTime[];     f[n_Integer] := Join @@ Permutations /@ PadLeft@IntegerPartitions[n];     f2[list_] := Module[{n = 1, m = 0},       While[n <= Length[data1],         If[Or @@ (SameQ[data1[[n, 1]], #] & /@             NestList[RotateLeft, list, Length[list] - 1]), data1[[n, 2]]++;          m++; Break[]];        n++];       If[m == 0, AppendTo[data1, {list, 1}]]]     data1 = {{First@f[7], 1}};     f2 /@ Drop[f[7], 1];     Length[f[7]]     data1 // Length     AbsoluteTime[] - m      but it's too slow. When `n = 7`, it takes about 11 seconds, but I want to work with `n` is the range from 14 to 20. how can I improve efficiency the efficiency of my code?


How to expand terms within an integral?

> **Possible Duplicate:**   >  Why aren’t these additions of integrals and summations equal? I am trying to expand all the terms in a sum in order to apply assignment rules later, but can't figure out how to do it. I've tried pretty much the commands I've seen around here. I have the following integral: $$\iint(x^2+y^2) f(x,y)dxdy$$ and I would like to extend it to $$\iint x^2 f(x,y)dxdy+\iint y^2 f(x,y)dxdy$$ in order to apply rules like $\iint x^2f(x,y)dxdy \to a$ and so on. I would like to do this in a generic way since the integrand would not always look like the one in the example here. Any idea?


Sum rule in integration not working

I am new to _Mathematica_ and I just tried to play around with some integrals. But the sum rule in integration doesn't work. Here a simple example: Mathematica doesn't recognize that $\int_0^h (1-f(x)) \, dx$ and $h-\int_0^h f(x) \, dx$ are the same. With               Reduce[Integrate[1 - f[x], {x, 0, h}] == h - Integrate[f[x], {x, 0, h}]]       I just get the output of > Reduce::nsmet: This system cannot be solved with the methods available to > Reduce. >> Is that normal? If not, where is the error?


Print indexed (by subscript) variable name systematically

I have some variables : Subscript[S, 1], Subscript[S, 2]...etc. But they are defined in a for loop like `For[g = 1, g < 4, g++, Subscript[S, g] = g];` Later, I need to print each of the variable name, i.e `Subscript[S, 1], Subscript[S, 2]`...etc. But I can't find a systematic way to do this. `For[g = 1, g < 4, g++, Print[HoldForm@Subscript[S, g]]];` doesn't work because it prints `Subscript[S, g]` always. Any idea? Just look at the code:               For[g = 1, g < 4, g++, Subscript[S, g] = g];     Print[Subscript[S, 1]]     Print[Subscript[S, 2]]     Print[Subscript[S, 3]]     For[g = 1, g < 4, g++, Print[Subscript[S, g]]];     Print[HoldForm@Subscript[S, 1]]     Print[HoldForm@Subscript[S, 2]]     Print[HoldForm@Subscript[S, 3]]     For[g = 1, g < 4, g++, Print[HoldForm@Subscript[S, g]]];     For[g = 1, g < 4, g++, Subscript[S, g] =.];      And this is the result: ![enter image description here](http://i.stack.imgur.com/jEDSy.png)


Can we use letter with a subscript as a variable in Mathematica?

I tried                   In[1]:= Subscript[a, 0] = 1         Out[1]= 1              In[2]:= Clear[Subscript[a, 0]]         During evaluation of In[452]:= Clear::ssym: Subscript[a, 0] is not a symbol or a string. >>              In[3]:= Clear[a]              In[4]:= Subscript[a, 0]         Out[4]= 1      Any idea?


Clear complains that a subscripted variable is not a symbol or a string?

Here's a small listing where I've used `Esc``q``Esc` to typeset `θ` in the notebook:               Clear[ f, θ, Subscript[x, r] ]     Subscript[x, r] := 3     f[θ_] := Subscript[x, r] Cos[θ]          Plot[f[θ], {θ, 0, Pi}]      (in my notebook this looked like $x_r$, not `Subscript[x, r]` for example). This produces a message from `Clear` of the form:               Clear::ssym : x_r is not a symbol or a string      What is curious is that I appear to be able to assign to this variable $x_r$ without any trouble, yet it is apparently treated differently than my other symbols `f` and `θ`. How exactly does Mathematica define a symbol. Why can I use $x_r$ like a variable, yet it does not have this symbol characterization?


How to assign (and retrieve) variables with subscripts?

I like to give subscripts to my variable names when the variables are related. I.e.,               Subscript[r, i] = 3      > 3 A problem arises when I later assign `r` to a value and want to use `Subscript[r,i]` again.               r = 6      > 6               Subscript[r, i]      > Subscript[6, i] Is there any way for me to get the value I assigned to `Subscript[r,i]`? Is this the wrong way to use Mathematica?


How do I clear all variables with subscripts?

> **Possible Duplicate:**   >  Clear complains that a variable is not a symbol or a string? `Clear["Global`*"]` Works for most variables, however if i do something like $ \delta_a = \alpha_a \Delta T d $ Then the `Clear` or `ClearAll` will not clear $ \delta_a $, short of `Quit[]` is there anything that can be done to clear variables with subscripts?


Solve with v9 (issues with Subscript, Overscript, Superscript etc)

The way `Solve` works has changed in v9 ... in essence, to get the answers that one obtained under v8, one now often has to specify a lot more information about all the variables and parameters, in order to get the desired neat solution. In providing this extra detail on Input, across the board, so to speak, I have discovered that, rather unfortunately, the `Solve` function has a poor understanding of notational forms such as Subscript, Superscript, OverBar, OverHat, OverDot, OverTilde etc etc ... causing `Solve[]` to fail on even the simplest examples when such notation is used. As a quick illustration: ![solvebug](http://www.tri.org.au/SolveBug.gif) ... when, of course, Mathematica can trivially solve such examples. Two clarifications on the above:   1. The solution here is certainly _not_ to use the Notation package ... I must confess that the point of the latter has mostly escaped me, because the very beauty of using Subscript etc notation in Mathematica is to be able Thread or Map over the index etc ... essentially getting the best of both worlds: a wonderfully flexible symbolic structure, even if not strictly a Symbol. The Notation package, by contrast, does the opposite ... by symbolising the structure, all flexibility is lost.   2. Some years ago, back in the days of Mathematica 3 or 4, a very similar issue occurred with Integrate when using Subscript notation ... causing it to fail horribly when certain Subscript variables were used on Input. And there were problems with Plot when using Subscript notation too. I recall raising these issue at the time, and if I recall correctly, these issues ... which effect the way thousands of people use Mathematica on a daily basis, were rectified in subsequent revisions of mma. It would be very helpful if a similar fix was adopted for the Solve case, so that Solve was aware that Subscript[y,1] is _not_ the same as say Sin[y] ... That Subscript[y,1] notation does not denote a mathematical function of y ... but rather just denotes a typesetting function of y. Do others have thoughts as to whether this behaviour in Solve is inconsistent? Or as they expect it to be? Or different to the way other Mma functions treat Subscript notation?


How to Clear a symbol with subscript in Mathematica?

> **Possible Duplicate:**   >  Clear complains that a variable is not a symbol or a string? I want to clear $\lambda_0$ which is assigned to be $\lambda_0=1$. From the reference here, Clear complains that a variable is not a symbol or a string? This could be done by                    << Notation`                Symbolize[NotationBoxTag[\(\[Lambda] \_ 0\)]]      or possibly                     Unset[Subscript[\[Lambda], 0]]      But then when I tried to reassign a value to $\lambda_0$, I got warning "Cannot assign to raw object Subscript[[Lambda], 0]"                     Subscript[\[Lambda], 0]= 1                During evaluation of In[252]:= Set::setraw: Cannot assign to raw object Subscript[\[Lambda], 0]. >>                Out[252]= Subscript[\[Lambda], 0]      When I enter $1$, it output $\lambda_0$                     In[25]:= 1                Out[25]= Subscript[\[Lambda], 0]      No help with following commands:                      Clear[Subscript]                  RemoveSymbolize[NotationBoxTag[\(\[Lambda] \_ 0\)]]      The "DownValues[Subscript]" is empty.                         In[26]:= DownValues[Subscript]                    Out[26]= {}                        In[28]:= Subscript[\[Lambda], 0]=.                    During evaluation of In[28]:= Unset::usraw: Cannot unset raw object Subscript[\[Lambda], 0].                 >> Out[28]= $Failed      **EDIT:** Tried to avoid using the subscript in the Module, but failed with $\lambda[0]$.                        In[119]:= Module[{\[Lambda][0] = 1},\[Lambda][0]]                   During evaluation of In[119]:= Module::lvset: Local variable specification {\[Lambda][0]=1} contains \[Lambda][0]=1, which is an assignment to \[Lambda][0]; only assignments to symbols are allowed. >>                  Out[119]= Module[{\[Lambda][0] = 1}, \[Lambda][0]]`


Why the variable cannot use subscript?

Today,I use the Lagarange method to deduce the robot 's dynamic equation .I use the mma to help me calculate. I want to use $$x_B,y_B, v_{Bx}, v_{By}, v_B ^2$$ to represent the point B 's displacement ,velocity and square of velocity ,respectively . However ,the mma give the warning information " Set::Tag Plus in the …is Protected" My code               Subscript[x,B][t]=l1 Sin[theta 1[t]]+l2 Sin[theta 1[t]+ theta 2[t] ]      But when I subscribe Subscript[x,B][t] to xB[t],it goes well. So my question is how to wtite variable like the form that we calculate by hand.


WinBUGS Interface

Has anyone created on WinBUGS (Bayesian inference Using Gibbs Sampling) interface with Mathematica similar to BugsXLA for Excel? I'd like to setup the model, define the evidence in a notebook and then analyze the results of the MCMC (Markov chain Monte Carlo) runs.


Security of Mathematica Demonstrations

Apologies if this is overly paranoid. I recently discovered the Wolfram Demonstrations Project and intend to play with them to understand some of the power of Mathematica. I have one slight concern: given that Mathematica has all types of system access, what guarantees do I have about these demonstrations (i.e. that they don't maliciously modify my file system, steal ssh keys, install trojans, etc ... ) I would prefer an answer of the form: "option XYZ lets you disable all of that for specific notebooks" rather than an answer of the form "everyone loves each other and would never do that!"


How to compare power towers in Mathematica?

First I tried it directly, but it overflowed:               In[1]:= 2^3^2^3^5^8 < 3^2^2^7^6^7     During evaluation of In[1]:= General::ovfl: Overflow occurred in computation. >>     During evaluation of In[1]:= General::ovfl: Overflow occurred in computation. >>          Out[1]= Indeterminate < Indeterminate      Using double `Log` did not help either:               In[2]:= Log[Log[2]] + Log[3] 2^3^5^8 < Log[Log[3]] + Log[2] 2^7^6^7       During evaluation of In[2]:= General::ovfl: Overflow occurred in computation. >>     During evaluation of In[2]:= General::ovfl: Overflow occurred in computation. >>          Out[2]= Overflow[] < Overflow[]      Then I tried to use the `WolframAlpha` function, and it seemed to be able to handle this and even much higher towers:               In[3]:= WolframAlpha["2^3^2^3^5^8 < 3^2^2^7^6^7", "MathematicaForms"][[2, 1]]     Out[3]= True          In[4]:= WolframAlpha["2^2^5^2^7^4^9^3^7^6^9^9^9^9^3^2 < 3^3^6^3^9^4^2^3^2^2^2^2^2^3^3^3", "MathematicaForms"][[2, 1]]     Out[4]= True      But then I discovered that it failed to perform certain comparisons:               In[5]:= WolframAlpha["4^6^8^8^9 < 3^2^3^3^3", "MathematicaForms"]     Out[5]= {}      And sometimes even gave wrong answers, even in seemingly trivial cases:               In[6]:= WolframAlpha["3^3^3^3^3 < 4^4^3^3^3", "MathematicaForms"][[2, 1]]     Out[6]= False      Can anybody suggest a correct and robust method to compare two expressions given in the form `Hold[a^b^...^z]`, where `a,b,...,z` are positive integers?


How to separate a vector into two vectors, one having the first half of my original vector and the other having the second half

I have a set of `n` vectors with an even length. Let us make an easy example with 3 vectors of length=4:                a={a1,a2,a3,a4}      b={b1,b2,b3,b4}      c={c1,c2,c3,c4}      I want to create the vectors:                d1={a1,a2}      d2={a3,a4}           e1={b1,b2}      e2={b3,b4}           f1={c1,c2}      f2={c3,c4}      I suppose I have to use `GatherBy`, but I have not found the way to get what I want.


Plotting a graph

Could anyone help me with plotting the following graph?               Integrate (-Inf, Inf) (exp(-i*x*t))/((4*pi)((x-1)^2 +25)(exp(-100x) +1))      It's not a code obviously, but I don't need a code, it's simple enough. Mathematica times out when I try to pot this. Is there a way around it? Could anyone try and plot it? Further info: Plot for t = 0 to 100. And the integration is over x.


Is it possible to create a output cell without generating a cell tag from the input cell

I give a CellTag to my Input Cell, but the output cell would also inherit the CellTag. Is it possible to control not inherit the CellTag? Sometimes I need the output cell with the CellTag, but sometimes I don't need... * * * ### Application I found another method is use another tags to do the same thing. I want to select some cells with some tags, cells with "Ignore" tag will be omitted, only Input Style Cells with"Ignore1" tag will be omitted, Output Style Cells with "Ignore1" tag will be kept. for example, I select the cells without "Ignore" and "Ignore1" tags.               Select[NotebookRead@Cells[EvaluationNotebook[]],      FreeQ[#, CellTags -> "Ignore"]&&FreeQ[#, CellTags -> "Ignore1"] &]      but this omit the output cells with "Ignore1", how to include these output cells? This is my sub question, if the original question is unsolvable. * * * so the condition could be.               condition=FreeQ[#, CellTags -> "Ignore"] && (#[[2]] === "Output" &&      MemberQ[#, CellTags -> "Ignore1"]) &      * * * ### One method We've add a `CellTags->"Ignore"` in the Input cell, just add a new CellTag, the the Output cell by CellPrint will tagged by new tag `Hello` !               CellPrint@Cell["Test",CellTags->"Hello"]      ![enter image description here](http://i.stack.imgur.com/IQSib.jpg)