title: Running out of memory when filtering a large data set

text: My goal is to read `list0.dat`, filter the data with a function `f`, and then write the transformed data to `list1.dat`, as in the following:               input = <<list0.dat;     output = Map[f[#]&, input];     output >> list1.dat;      However, `input` and `output` are both very large lists. (The format is just the usual anlytical expression.) So "No more memory available" always appears. How can I deal with this problem? I need some suggestions for memory control and how to export the transformed data to an external file in real time.


title: How can I get Mathematica to recognize the documentation for a newly installed package?

text: To install a new package on one's machine, one first downloads and unpacks the package into the `$BaseDirectory/Applications` directory. The tutorial Installing NewAddons of Version 5.2 then recommends one go to Menu > Help and click on the Rebuild Help Index menu item. However, the tutorial was written for the version 5.2. S0 now I cannot find the Rebuild Help Index item under the Menu > Help. What should I do instead in version 9.0.1.0?


title: Error with minimization of NProbability

text: I'm trying to solve the following problem:               Minimize[{NProbability[(1 - 2 g)*y + g^.5 + s <      x, {x, y} \[Distributed] UniformDistribution[{{0, 1}, {0, 1}}]], 0 < g < 1 && 0 < s < 1}, {g, s}]      This code gives an error message from NIntegrate (`NIntegrate::izero`) Any ideas why the error message? How can I solve the problem? If I run a contour plot of the objective over the constrained area I get something that looks well behaved:               ContourPlot[NProbability[(1 - 2 g)*y + g^.5 + s < x, {x, y} \[Distributed] UniformDistribution[{{0, 1}, {0, 1}}]], {g, 0, 1}, {s, 0, 1}]      ![enter image description here](http://i.stack.imgur.com/wnvNX.jpg)


title: workbench: how to see values of global variables during debugging

text: Consdier the following package               BeginPackage["packageName`"];        exportedFunction::usage = "...";        Begin["`Private`"];           globalVariable = Null;           initializePackage[args___] := (globalVariable = workOn1[args]);           exportedFunction[args___] :=               Block[{localVariable},                 If[globalVariable===Null, Abort[]];                 localVariable = workOn2[globalVariable, args];                 workOn3[localVariable]              ];           workOn1[args___] := ...;           workOn2[gv_, args___] := ...;           workOn3[lv_] := ...;        End[];     EndPackage[];      and assume that is being debugged in a workbench session, and that a break point has been set somewhere in exportedFunction. The debugger reports on the values of localVariable, but I can never see the value of globalVariable. Is there a way to inspect the value of globalVariable as well?


title: Problem with exporting a plot with a legend to PDF

text: I've found a simple example that illustrates my problem:               ContourPlot[x^2 - 1 == y, {x, -1, 1}, {y, -1, 1}, PlotLegends -> "Expressions"]      When I try to export this to PDF, I get the following: ![Contour plot with legend and bug](http://i.stack.imgur.com/AmdpK.png) and in the legend, the expression is misspaced and unreadable. Is this a known bug? Is there a known work around?


title: How do I create a function pointer typedef using SymbolicC

text: I am just getting started with the SymbolicC package, and am trying to figure out how to handle function pointer typedefs, like, say:               typedef double (*rhs)(double, double);      The problem is that the `CTypedef` function expects its arguments to be `CTypedef[type, var]`, which isn't really how function pointer declarationss in C work. An ordinary pointer typedef is done using `CDereference`, as:               CTypedef["double", CDereference["xp"]]      I'm not sure how to make that work in the context of `CFunction`.


title: Conditional options in Plot

text: I was hoping to incorporate an `If` function into a `Plot` option, as in               Plot[Sin[t], {t, 0, 2 Pi}, Filling -> Axis,       FillingStyle -> If[Sin[t] > 0, LightGreen, LightRed]]      or               Plot[Sin[t], {t, 0, 2 Pi}, PlotStyle -> If[Sin[t] > 0, Dashed, Thick]]      to no avail. Is it possible to pass an `If` to the plot options? I know that I can manually accomplish the effect via `Piecewise`, but I have more complicated applications in mind where I would not want to manually precompute the interval(s) on which my piecewise defined function would need to be defined.


title: How to evaluate all the essentially distinct polynomials in 4 variables over $F_2$ on points of $F_2 ^ 4$

text: I am a beginner with _Mathematica_. For my research purpose I would like to get a list of all the polynomials in $F_2[x,y,z,w]$ and for each polynomial I would like to know the result that it gives then it is applied on each point on $F_2 ^ 4$. More concretely, F_2={0,1}.Take 2 variables x and y. Consider all possible polynomials, where degree of both x and y are less than or equal to 1.you have usual multiplication and addition modulo 2.(that means whatever you get by adding or multiplying elements of F_2 take the remainder when divided by 2). The desired answer would be like, Polynomials (0,0) (0, 1) (1,0) (1,1)                x         0     0     1     1       likewise consider all other polynomials with the property given above and I would like to get a table of what values the polynomial takes at the given point, like I have mentioned for the polynomial x. Any help will be appreciated.


title: Why does Thread FileDate give an error message?

text: I tried for example               Thread[FileDate[FileNames["new*", "h:\\temp\\", 1]]]      It gives > FileDate::fstr: File specification > {h:\temp\NEWEA7D.tmp,h:\temp\NEWEA7E.tmp,h:\temp\NEWEAAE.tmp} is not a > string of one or more characters. >> but still gives the right answer               Out[13]= {{2013, 11, 18, 23, 14, 32.}, {2013, 11, 18, 23, 14,        32.}, {2013, 11, 18, 23, 14, 32.}}      Why is there a error message? How to avoid it?


title: Why do I see the error "only assignments to symbols are allowed" when using a Module and not otherwise?

text: When I type               Remove["Global`*"]     foo[] := Module[{Subscript[a, 1] = "x"}, 0];      foo[]      I get the expected error "only assignments to symbols are allowed". I understand the error. ![enter image description here](http://i.stack.imgur.com/CWYl1.png) But why I do not get the same error when I type the same assignment in the notebook?               Remove["Global`*"]     Subscript[a, 1] = "x"      No error and no beep. ![enter image description here](http://i.stack.imgur.com/R2jXs.png) What is the difference? I'm using version 8.04 on Windows. * * * ## Update The non-localized trick shown by Szabolcs answer worked for me on a demo. Here is a screen shot of the result. What I was trying to do is to typeset some information about a solver, some matrix equation, and I thought why not take advantage of `MatrixForm` and `Grid`'s nice way of typesetting things, and display the information right there in the demo screen as an option? This is easier than putting it in the text section below where it can hard to get to as I have so many such things. Here is an example of the code and the result. You can see I did not localized these symbols in the module which builds this expression. I just started trying this idea, but so far I am happy that it worked. This below is only an example, not cleaned up, just wanted to see if the demo will work. ![enter image description here](http://i.stack.imgur.com/dqwg6.png)


title: Resume/continue interrupted evaluation

text: I interrupted an evaluation to quickly do something else. How do I resume the interrupted evaluation? I cannot open the "Interrupt evaluation" window, as it is disabled. There is no "Resume" button to press...


title: Different results for integration using Mathematica and MATLAB

text: I have the following integration: $$\text{y}=2 \sqrt{\frac{1}{\pi }} \int_0^{\infty } \frac{e^{-z} \left(1-e^{-\frac{z}{b}} \left(\frac{a}{a+c z}\right)^L\right)}{\sqrt{z}} \, dz$$ I get different results when I use _Mathematica_ and MATLAB. The _Mathematica_ code is:               L=2;     sn=1;     a=10^(0.1*sn);     b=10^(0.1*sn);     c=0.01*a;     result = 2*Sqrt[1/Pi]*       Integrate[        (1/(E^z*Sqrt[z]))*(1 - (a/(a + c*z))^L/E^(z/b)),         {z, 0, Infinity}       ]      which gives me `2.37664*10^66`, whereas MATLAB's result is `0.51515243`. What is the reason for this discrepancy?


title: The value of an option inside a native function

text: I'm looking for something similar to `AbsoluteOptions` but that can be evaluated inside the function. That is, I want to read the absolute settings of options specified in the current context. For example, instead of:               AbsoluteOptions[      Plot[       Sin[x]       , {x, 0, 2 Pi}       , PlotRange -> Automatic       ]      , PlotRange]      > {PlotRange -> {{0., 6.28319}, {-1., 1.}}} I would like to have something like               Plot[      Sin[x]      , {x, 0, 2 Pi}      , PlotRange -> Automatic      , Epilog -> Inset[        "PlotRange is " <> ToString@AbsoluteOptions[PlotRange]        , {4, 1}]      ]      > ![Mathematica graphics](http://i.stack.imgur.com/mt4I6.png) is it possible to read the absolute settings for options associated with the current function environment?


title: Are there suitable versioning systems for Mathematica notebooks?

text: I am considering a project using _Mathematica_ and openCL. I know that the openCL C source code can be tracked. Has anyone used a versioning site or software so multiple developers can modify a common notebook? Is it possible to:   * check out a notebook non-exclusively?   * check out a notebook exclusively?   * change the notebook?   * merge a notebook locally?   * check in a notebook?


How can you compute Itō Integrals with Mathematica? I tried searching through the documentations but I didn't find anything. P.S. I was not at all sure how to tag this question. I had to put in at least one tag, and I do not have enough reputation to create a new one. Somebody with more rep can feel free to tag it appropriately.


title: Creating ordered triplets from an Excel sheet

text: I have an Excel sheet of the form:                   " "  a  b  c          1   R  S  T          2   U  V  W          3   X  Y  Z      Where every entry is a number (except the blank quotes, which is just a blank cell). These are supposed to be `{x,y,z}` coords but Mathematica imports them as `{" ",a,b,c},{1,R,S,T},...`. I get that I need to transpose them but I'm not sure how. Essentially for this example the end result should be `{a,1,R},{b,1,S},{c,1,T},{a,2,U}...`. This is similar but without the extra lines which is kind of the issue I'm having: Import Excel sheet into 3D array?


title: How to "ignore" an element of Map or MapIndexed

text: Say I have some function that I'm applying every element in a list to... if that element matches some criteria:               If[#==<condition>,{#}, <Do nothing> ] & /@ LongList      Is there a way to do something like this? I want the result to just not have that element.


title: Is there any way to stop calculation of unimodular matrix in HermiteDecomposition

text: I want to calculate Hermite normal form of a matrix. But I do not want the unimodular transformation matrix. Is there any way to stop the calculation of unimodular matrix? HermiteDecomposition function return both matrices. The reason I want to stop calculation of unimodular matrix is I think It will save some memory and computation also may little faster. My matrix size is around (45000 * 3000) Any comment appreciated.


title: Export to mat file does not work

text: I use this command from the _Mathematica_ documentation center               Export["1.mat", {"t" -> {{1,2,3}},"u" -> {{4,5,6}}}, "LabeledData"]      to save data as mat file with two variables `t` and `u`, and it does not work. The file is empty! The command `Export["1.mat",{{1,2,3}}]` works fine. How to solve this problem? I'd like to save in single file plenty variables. I am using Mathematica 7.


title: Adding a circle to an already existing drawing

text: With reference to my earlier post: Adding a point to an already existing graphic I would like to add an outer circle to the whole drawing. This outer circle is a fixed one of `radius 40`. Something like this is helpful:               Graphics[Circle[{0, 0}, 40]]      But I do not know exactly where to put it in my code so that it remain a fixed circle in the background. Thanks a lot...


title: Splitting words into specific fragments

text: I am looking into splitting words into a succession of chemical elements symbols, where possible. For example: > Titanic = Ti Ta Ni C _(titanium, tantalum, nickel, carbon)_ A word may or may not be decomposable under those rules, and if it is the decomposition might not be unique. I did two things: the first is a function checking if a decomposition is possible. I relied on the trivial regular expression to do so:               elements = ToLowerCase /@        Select[Table[ElementData[i, "Symbol"], {i, Length@ElementData[]}], StringLength[#] < 3 &]     regexp = RegularExpression["(" <> StringJoin@Riffle[elements, "|"] <> ")+"];     decomposable[s_] := StringMatchQ[ToLowerCase@s, regexp];     decomposable /@ {"Mathematica", "archbishop"}      which gives: `{False, True}`. Slightly harder was to implement a function returning possible decompositions. I recently learnt of the existence of `Sow` and `Reap` via this very website, so I implemented the most naïve, greedy algorithm with a recursive function:               beginsWith[s_, sub_] := (StringTake[s, Min[StringLength[s], StringLength[sub]]] == sub);     decompose0[s_, pre_] := Module[{list, remains},        If[StringLength[s] == 0, Sow[pre]];        list = Select[elements, beginsWith[s, #] &];        remains = StringDrop[s, StringLength[#]] & /@ list;        If[Length[list] >= 1, decompose0[remains[[1]], pre <> " " <> list[[1]]]];        If[Length[list] >= 2, decompose0[remains[[2]], pre <> " " <> list[[2]]]];      ];     decompose[s_] := Reap[decompose0[ToLowerCase@s, ""]][[2, 1]];      This works nicely:               In:= decompose["archbishop"]     Out= {" ar c h b i s h o p", " ar c h b i s ho p", " ar c h bi s h o p", " ar c h bi s ho p"}     In:= decompose["titanic"]     Out= {" ti ta n i c", " ti ta ni c"}      So, the question is: **in which way could I use Mathematica’s higher-level functions, e.g. the pattern-matching ones, to improve the algorithm or the code simplicity?** I'm not into code-golfing, so it's not about making the code shorter, but about using a better-optimized algorithm or writing higher- level code. (The above I could pretty much have written in C, C++ or Fortran, my usual languages.)


title: Computing intersections between a large number of sets: doing it sequentially vs. sending everything to Intersection[...]

text: Say we want to compute the largest common subset among a very large number of sets $Q_i$. One option would be to simply run the command:               Intersection[Q1, Q2, Q3, Q4, Q5, Q6, Q7, ...];      However, this seems to choke for very large numbers of input sets ($10^4$ or so with on-order $10^2$ elements each). Another option would be compute `Q12 = Intersection[Q1,Q2]`, then `Q123 = Intersection[Q12,Q3]`, then `Q1234 = Intersection[Q123,Q4]`, and so forth. Are these two procedures equivalent? Is there a better way?


title: How do you get Weisstein’s Hyphenate package to run?

text: I've put Eric Weisstein's `Hyphenate.m` package in `$UserBaseDirectory/Utilities`; installed the requisite `texhyphj` files in my local `texmf` tree; run its `Makefile` to create the Java classes corresponding to the distributed `.java` source files; and in `Hyphenate.m` set `$HyphenPath` to the path for `texhyphj`. Yet when I load the package, I get a Java `ClassNotFoundException` error for the Java class `net.davidashen.text.Hyphenator`. What am I doing wrong or also need to do to get this add-on package to work? (The package provides a functions that hyphenate a given string and list the syllables of a string.) P.S. Yes, `WordData[word, "Hyphenation"]`will give a list of syllables for `word`, but I would expect using Java for this may be quicker, since no delay is involved in going out to the WRI server to import the needed word data paclets.


title: Efficiently evaluating a held expression directly from a list

text: I am able to evaluate a held expression that I have put on a list by:               ReleaseHold[expressionList[[1]]]      and               expression1 := ReleaseHold[expressionList[[1]]];     expression1      Using `expression1` is more efficient than `ReleaseHold[expressionList[[1]]]`, but I loose the ability to use it in `Map` (or so I think). I would like to be able to use the held expression directly from a list, i.e. `expressionList[[1]]` . Any suggestions? A test harness follows. You can change the expressions being tested see `AddExpression[1];`, which is currently `1` to `Pause[$TimeUnit]`, `Range[1, 1000]`, ... . * * *               SetAttributes[AddExpression, HoldAll];     AddExpression[expression_] := AppendTo[expressionList, Hold[expression]];          EvaluateExpressions[] :=      (       expression1 := ReleaseHold[expressionList[[1]]];       expression2 := ReleaseHold[expressionList[[2]]];            totalRunTimeDo = AbsoluteTiming[          Do[(expression1; expression2;), {iterations}];          ][[1]];            Print["Do      total: ", totalRunTimeDo, "   per iteration: ",         totalRunTimeDo/ iterations];            (* -------------------------------------------------*)            totalRunTimeDoMap = AbsoluteTiming[          Do[Map[ReleaseHold[#] &, expressionList], {iterations}];          ][[1]];            Print["DoMap   total: ", totalRunTimeDoMap, "   per iteration: ",         totalRunTimeDoMap/ iterations];       )          iterations = 10000000;     expressionList = {};     AddExpression[1];     AddExpression[1];     EvaluateExpressions[];      Results:               Do      total: 12.526729   per iteration: 1.2526729*10^-6     DoMap   total: 19.018290   per iteration: 1.9018290*10^-6      Obviously, you can see why I want to pull it directly from the list. ## Background The above test harness was boiled down from something I was using to benchmark code.               iterations = 10000000;     expressionList = {Hold[1], Hold[1]};      I started here:               expressionTimingsByIteration =       Map[Map[AbsoluteTiming[ReleaseHold[#]][[1]] &, expressionList] &,        Range[1, iterations]];     iterationsTimingsByExpression = Transpose[expressionTimingsByIteration];      Refactored to this:               iterationsTimingsByExpression =       Map[        (          expression := ReleaseHold[#];          Map[AbsoluteTiming[expression][[1]] &, Range[1, iterations]]           ) &        , expressionList];      However evaluating code whose `AbsoluteTiming < $TimeUnit` is prone to error. Which I refactored for those cases to:               totalTimingByExpression =       Map[        (          expression := ReleaseHold[#];          AbsoluteTiming[Do[expression, {iterations}]][[1]]          ) &, expressionList];     totalTimingByExpression


title: Find exact limit of recurrence relation $x_{n+1}=\cos(x_n)+1, x_0=1$

text: I did this:               b[x_] := Cos[b[x - 1]] + 1; b[0] = 1;     num = SequenceLimit[N[Table[b[n], {n, 1, 100}], 50]]      I also did the listplot which shows a convergent value. ![the recurrence relation](http://i.stack.imgur.com/4IOtd.jpg) Both results suggests that SequenceLimit did the right thing. The limit is 1.2834287895560837995226068447. Is there a way to find the exact value of convergent recurrence relation? Or find the limit without repeated calculation ?


title: Find set of subgraphs of g1 isomorphic to g2

text: I would like to find all the subgraphs of a given graph g that are isomorphic to the graph h. My current code doesn't work how it should. Many solutions are missed and I think something is fundamentally wrong with my approach.   * I generate g and h.    * Extract the subsets from g with the same length as h.    * Select the subsets that are isomorphic to h    * Generate subgraphs and highlight them in g .               {g, h} = {Graph[RandomInteger[#] \[UndirectedEdge] # + 1 & /@ Range[1, 4]],      Graph[{{1, 2}, {2, 3}, {3, 4}}]}     s = Subsets[Range[VertexCount[g]], {VertexCount[h]}];     Select[Subgraph[g, #] & /@ s, IsomorphicGraphQ[#, h] &];     HighlightGraph[g, #] & /@ %


title: Simplifying already defined symbols

text: Consider the following code:               ClearAll[x, y]     x = y;     y = 2;     ?x     ?y      This will store $x$ being equal to _the variable $y$_ , and $y$ having _the value of $2$_. Now switch the assignment lines:               ClearAll[x, y]     y = 2;     x = y;     ?x     ?y      the internal representation will be $x=2$, $y=2$, since at the time of the assignment $x=y$, _the value of $y$_ is known and used for the assignment, not the variable $y$ itself, as it has been in the first case. Now consider the case where I've built up a long code with complicated expressions being substituted into each other, and at some final point I would like to boil this down as much as possible. Stated differently: _How would I make sure $x$ is updated to the value of $y$ in the first example instead of still referring to $y$?_


title: Efficient method for Inserting arrays into arrays

text: This is strongly related to the following Questions:   * Looking for a way to insert multiple elements into multiple positions simultaneously in a list   * Building matrices by attaching vectors (columns) and matrices   * What is the most efficient way to add rows and columns to a matrix? I am looking for an efficient method to insert an array into an array. Let’s assume that both arrays have similar number of rows. Let’s further assume insertion is by column.               a = {{a1, b1, c1, d1, e1}, {a2, b2, c2, d2, e2}, {a3, b3, c3, d3, e3}}; (*example may be larger*)     b = {{x1, y1, z1}, {x2, y2, z2}, {x3, y3, z3}}; (*example may be larger*)      **Q1:** What is the fastest method to insert **b** into **a** at a position _p_. Let’s assume that both arrays have similar number of rows. Let’s further assume insertion is by column. My current method is as follows:               insertarray[a_, b_, pos_] :=     FlattenAt[     Transpose@Insert[Transpose@a, b[[##]], pos ] & [Range[Length@a]],      Table[{i, pos}, {i, 1, Length@a}]];      which allows me to do ![insert array](http://i.stack.imgur.com/P2gWj.png) **Q2** : Some times I have to intersperse columns of **b** into **a** at multiple positions. How do I best extend **insertarray** so that:               insertarray[a,b,{1,2,5}]//MatrixForm      ![enter image description here](http://i.stack.imgur.com/7YjEQ.png)


title: Pasting $\LaTeX$ into a Mathematica notebook

text: I have read that $\LaTeX$ source can be directly pasted into a Mathematica notebook. However, I have been unsuccessful in this regard. An example of the errors received are:               $\frac{1}{2}$     Syntax::sntxb: Expression cannot begin with "$ frac{1}{2}$".     Syntax::tsntxi: "$ frac" is incomplete; more input is needed.     Syntax::sntxi: Incomplete expression; more input is needed .      This is not remediated by removal of the `$` signs, placement of two `$` signs (`$$`), or use of other $\LaTeX$ math mode delimiters (e.g., `\\[ \\]`, `\begin{displaymath}\end{displaymath}`, `\begin{equation}\end{equation}`, etc). I do not wish to import an entire `.tex` file as I merely want to pass a few select equations. Please advise as to my error. Thank you. **Edit:** I am using Mathematica 8.0.1.0.


title: MapThread with List Manupulation

text: I have the following three lists:               kr = {{8, 8, 19, 3, 3}, {8, 8, 21, 3, 3}, {8, 8, 23, 3, 3}};     Rk = {{8., 3, 4, 5, 6}, {8., 4, 5, 6, 7}, {8., 5, 6, 7, 8}};     qsum = {{320, 270, 120, 140, 170}, {320, 280, 120, 150, 190}, {320, 290, 120, 160, 210}};       When I use               MapThread[#1 + #2 + #3 &, {Take[#, {3, -2}] & /@ kr, Take[#, {4, -1}] & /@ Rk, Take[#, {3, -2}] & /@ qsum}]      It shows the output {{144., 149.}, {147., 160.}, {150., 171.}} which is perfectly fine, but using the function `floExct` in the `MapThread` as               floExct[n_, ku_, qr_] := Min[100*ku, (2500*n) - qr];     MapThread[ floExct[#1, #2, #3] &, {Take[#, {3, -2}] & /@ kr, Take[#, {4, -1}] & /@ Rk, Take[#, {3, -2}] & /@ qsum}]      gives me               {500., 600., 700.}      instead of the format               {{a,b},{c,d},{e,f}};      What am I missing?


title: How do I use wildcard characters with StringTake?

text: Say I'd like to pick substrings from some string such that these substrings have the pattern `@@@q@@@`, where `@` is used here as a stand-in for a 'wildcard' character (i.e. any character) and `q` is just an example of a specific character that can be specified as desired. The kind of lame solution might be as follows:               substringList = StringTake[testString, # + {-3, 3} & /@ StringPosition[testString, "q"]];      This, of course, runs into trouble when `q` appears near one of the two ends of `testString`. What's the correct way to do this?


title: Find eigenvalues without filling the matrix

text: Is it possible to find eigenvalues of a matrix without filling it? The matrix elements are given by a known function `f[p1,p2]`. This is relevant for a matrix too large to fit in a memory. Of course, a custom implementation of the Arnoldi algorithm would allow one to do so. I wonder whether it is possible with built-in functions like `Eigenvalues[]` and some clever rules.


title: Dual complex integral over implicit path using contour plot

text: **Context** I am interested in doing double contour integral over paths which are defined implicitely. For the sake of debugging, let's assume its $$\oint_{\cal C}\oint_{\cal C} \frac{1}{u\, x} d u d x$$ where $\cal C$ is defined implicitly as the zero of a function (here for instance $x^4+y^4- x y/2=0$). I would like to make use of the `Contour` function of mathematica to extract the contour path for me.   (The motivation is to implement the so called "saddle point method" in the complex plane while integrating over contours of null imaginary part of some given function) **Question** > How to extract smooth enough contours to not mess up the double complex > integral? **Attempt** I first extract the path               pl = ContourPlot[x^4 + y^4 - 1/2 x y == 1, {x, -2, 2}, {y, -2, 2}, PlotPoints -> 25];     dat = Cases[pl // Normal, Line[a_] :> a, Infinity][[1]] // Chop // Rest // Transpose;     dat = GaussianFilter[#, 0] & /@ dat;nn = Length[dat[[1]]];rg = (Range[nn] - 1.)/(nn - 1);     dat = Transpose /@ Partition[Riffle[{rg, rg}, dat], 2];     path = Interpolation[#, InterpolationOrder -> 1] & /@ dat;     path = Function[t, path[[1]][t] + I path[[2]][t] // Release];      (ignore the `GaussianFilter` for now) which looks like this               {ParametricPlot[path[t] // {Re[#], Im[#]} & // Release, {t, 0, 1},ImageSize -> 200],     Plot[path[t] // {Re[#], Im[#]} & // Release, {t, 0, 1}, ImageSize -> 200]} // Row      ![Mathematica graphics](http://i.stack.imgur.com/JBrT1.png) For reference let us also define an explicit (circular) path               path0[t_] = Exp[2 Pi I t];      Let's now start with a simple contour integration in the complex plane, using `NContourIntegrate` defined by                  NContourIntegrate[f_, par : (z_ -> g_), {t_, a_, b_}, opts : OptionsPattern[]] :=         NIntegrate[Evaluate[D[g, t] (f /. par) /. t -> t1], {t1, a, b},opts]      :               NContourIntegrate[1/x, x -> path0[t], {t, 0, 1}, PrecisionGoal -> 3] // Chop     NContourIntegrate[1/x, x -> path[t], {t, 0, 1}, PrecisionGoal -> 3] // Chop          (* 0. +6.28319 I -0.00291648-6.27423 I *)      (the negative $2\pi\imath$ reflects a wrong orientation of the implicit path which is not relevant to my problem). Now moving on to double integration, first with the explicit path (where I divide the answer by the expected answer $(2 \imath \pi)^2$)                Clear[h]; h[u_?NumberQ] := NContourIntegrate[1/x/u, x -> path0[t], {t, 0, 1}, PrecisionGoal -> 3];      NContourIntegrate[h[u], u -> path0[t], {t, 0, 1},PrecisionGoal -> 3]/(2 I Pi)^2 // Chop           (* 1.*)      and finally for the implicit path               Clear[h]; h[u_?NumberQ] := NContourIntegrate[1/x/u, x -> path[t], {t, 0, 1}, PrecisionGoal -> 3];     NContourIntegrate[h[u], u -> path[t], {t, 0, 1}, PrecisionGoal -> 3]/(2 I Pi)^2 // Chop           (* 1.53254 +0.00796458 I *)      which is a terrible answer! Now in the code above I replace the useless command `dat = GaussianFilter[#, 0] & /@ dat;` by               dat = GaussianFilter[#, 4] & /@ dat;      I get                (* 1.00097 +0.00168785 I *)      which is better. I strongly suspect that the problem lies with the contour extraction which produces dat containing duplicates such as {{-1., 0} {-1., 0} {-1., 0} {-1., 0} {-0.990251, 0.0735841} {-0.988311, 0.0833333} {-0.987415, 0.0959183}} which in turn as suppressed by the Gaussian filtering. Indeed, while the contour itself seems unaffected, its components in red and pink are less jaggy: ![Mathematica graphics](http://i.stack.imgur.com/0orp5.png) and this apparently small amount of noise (and/or duplicates) mess up completely the integral. > Is it possible to tweak the `ContourPlot` routine or its output to avoid > duplicates and get good accuracy on this type of integrals? **EDIT** The improvement involved with the `GaussianFilter` is actually critical because if I extend this problem to a triple integral, $$\oint_{\cal C}\oint_{\cal C}\oint_{\cal C} \frac{1}{u \,v\, x } d u d v d x$$ via               Clear[h1]; h1[u_?NumberQ, v_?NumberQ] := NContourIntegrate[1/(x u v), x -> path[t], {t, 0, 1}];     Clear[h2]; h2[v_?NumberQ] := NContourIntegrate[h1[u, v], u -> path[t], {t, 0, 1}]     NContourIntegrate[h2[v], v -> path[t], {t, 0, 1}]/( 2I Pi)^3      I get               (* -0.975052-0.00767858 I *)       compared to               (* -2.91536 -0.040382 I *)      without! **EDIT 2** To be more specific about the core of the problem, this curve is too jaggy:               pl = ContourPlot[x^4 + y^4 - 1/2 x y == 1, {x, -2, 2}, {y, -2, 2}, PlotPoints -> 25];     dat = Cases[pl // Normal, Line[a_] :> a, Infinity][[1]] // Chop // Rest // Transpose;     dat = GaussianFilter[#, 0.] & /@ dat;nn = Length[dat[[1]]];rg = (Range[nn] - 1.)/(nn - 1);     dat = Transpose /@ Partition[Riffle[{rg, rg}, dat], 2];dat[[1]] // ListLinePlot      ![Mathematica graphics](http://i.stack.imgur.com/ikJhA.png) I can make it less jaggy by changing the option to `PlotPoints -> 125` but it actually makes the contour integration worse!


title: Mathematica style (drawing cubes)

text: I wanted to draw (lattice-aligned) unit cubes inside a sphere with a given radius centered on the origin, so I wrote this program:               Cube[x_, y_, z_] := Cuboid[{x - 1, y - 1, z - 1}, {x, y, z}];     Coords[r_] := {#1, #2, Floor[Sqrt[r^2 - #1^2 - #2^2]]} & @@ # & /@         With[{t = Sqrt[r^2 - 1]},          Select[Flatten[Table[{x, y}, {x, 1, t}, {y, 1, x}], 1],           Norm[#] <= t &]];     Cubes[r_] :=        Cube @@ # & /@         Union[Flatten[Permute[#, SymmetricGroup[3]] & /@ Coords[r], 1]];     Draw[r_] :=        Graphics3D[        Union[Cubes[r], {{Green, Opacity[0.1], Sphere[{0, 0, 0}, r]}}],         PlotRange -> {{0, r}, {0, r}, {0, r}},         ViewPoint -> {r, 3 r/4, 3 r/5}];     Draw /@ Sqrt /@ {50, 100, 250, 500, 1000, 2500, 6054}      (Note that it shows only the cubes on the outside -- drawing the inner ones takes too long and usually Mathematica runs out of memory.) It gets the job done, but it's pretty ugly. I'm not a regular Mathematica user, and tips for improving my code? That is, how can I write idiomatically-better Mathematica code? * * * Improved code:               Coords[r_] := {#1, #2, Floor[Sqrt[r^2 - #1^2 - #2^2]]} & @@@         With[{t = Sqrt[r^2 - 1]},          Select[Join @@ Table[{x, y}, {x, t}, {y, 1, x}], Norm[#] <= t &]];     Cubes[r_] := (Cuboid /@ (Union @@ (Permute[#, SymmetricGroup[3]] & /@               Coords[r]) - 1));     Draw[r_] :=        Graphics3D[        Union[Cubes[r], {{Green, Opacity[0.1], Sphere[{0, 0, 0}, r]}}],         PlotRange -> {{0, r}, {0, r}, {0, r}},         ViewPoint -> {r, 3 r/4, 3 r/5}];     Draw /@ Sqrt /@ {50, 100, 250}


title: Fourier transformation of HeavisideTheta functions

text: I want to find 2D-Fourier transformation of the function given below               f = HeavisideTheta[y1]*HeavisideTheta[y2 - y1]      For the purpose, I use built-in function in two ways as below,               FourierTransform[f, {y2, y1}, {q2, q1}]      FourierTransform[f, {y1, y2}, {q1, q2}]       The outputs are different depending on the order of variables. Please, See below. > >     -(1/(2 π q1 q2 + 2 π q2^2)) + (I DiracDelta[q2])/(2 q1) + >     (I DiracDelta[q1 + q2])/(2 q2) + 1/2 π DiracDelta[q2] DiracDelta[q1 + > q2] >   >     -(1/(2 π q1 q2 + 2 π q2^2)) + (I DiracDelta[q2])/(2 q1) - (I > DiracDelta[q1 + q2])/(2 q1) >   I thought they should be same. I don't know why they are different. Please help me to figure out which one is correct.


title: My plot is cut off if a frametick is "0" but resized if a frametick is "0." Why?

text: I have been trying to customize the frame ticks and frame label around a certain contour plot and am running into very strange behavior where the graphics will get cut off by `ImageSize` rather than being resized. In the following example code (more or less minimal), note that all I have changed is a `0` to `0.` in the frametick specification. What's going on here? Minimal example:               ContourPlot[θ1 + θ2 == 0, {θ1, -3 π/2, π/2}, {θ2, -π/2, 3 π/2},      FrameTicks -> {{{0, π}, None}, {{-π, 0.}, None}},       FrameLabel -> {"\!\(\*SubscriptBox[\(θ\), \(1\)]\)", "\!\(\*SubscriptBox[\(θ\), \(2\)]\)"},       BaseStyle -> {FontSize -> 20}, ImageSize -> 200]          ContourPlot[θ1 + θ2 == 0, {θ1, -3 π/2, π/2}, {θ2, -π/2, 3 π/2},      FrameTicks -> {{{0, π}, None}, {{-π, 0}, None}},       FrameLabel -> {"\!\(\*SubscriptBox[\(θ\), \(1\)]\)", "\!\(\*SubscriptBox[\(θ\), \(2\)]\)"},       BaseStyle -> {FontSize -> 20}, ImageSize -> 200]      ![input and output](http://i.stack.imgur.com/gue4h.png)


title: List of dangerous functions

text: _I no longer believe it is a good idea to work with a list of dangerous functions. I have tried to edit the question is such a way that it respects my earlier perspective, but also so that it does not give users the impression that certain things are safe whereas they are not._ **Introduction** Running _Mathematica_ code from an untrusted source is very dangerous. Luckily, _Mathematica_ warns you about dynamic content, so that it is probably safe to open any notebook, as long as you don't run it. I feel it would be very nice to have a list of functions that can harm a system. Using this, we may be able to make a function that checks if a notebook is safe. **A function to find dangerous functions** A naive function to see if dangerous expressions are present in a `NotebookObject`, could be the following.               Through[{Unprotect, ClearAll}[dangerousFunctionsQ]]          dangerousFunctionsQ[nb_] := !         FreeQ[ToExpression[Unevaluated[#], StandardForm,             HoldComplete] & /@ (NotebookRead@Cells[nb])[[All, 1]],          Alternatives @@ listOfDangerousFunctions];          Protect[dangerousFunctionsQ];      Where `listOfDangerousFunctions` is given. Unfortunately, this code does not guarantee safety, even we know the full list of dangerous functions. Furthermore, getting the `NotebookObject` is a bit tricky. We could simply open the notebook and use `Notebooks`, but opening the notebook doesn't sound too safe. Also making an automated approach based on this is inelegant. Note however, that using the obvious alternative, which is to use `Import` (with one argument) on the notebook file turns out not to be safe. **The question is** : Which built-in functions are dangerous (especially just by themselves)? **Related** In a CDF can I suppress or avoid “This file contains potentially unsafe dynamic content…”


title: Multiplayer game in Mathematica: how to communicate between kernels?

text: This may have been asked already, but I am considering making a game in Mathematica that two people can play. However, the issue with my idea is that the other player can't view the cards of the first player. Does anyone have any suggestions as to how I would tackle this problem? I would use two different computers, both with Mathematica installed.


title: Plotting power spectral density from transfer function

text: I am new to signal processing. The equations below are given in $LaTeX$. I have the following transfer function (from the Dryden Model) for the two- sided Power Spectral Density: $$S(w) = \frac{\sigma_u ^2 \tau_u}{\pi} \frac{1}{1+(\tau_u w)^2}$$ I would like to plot the above as: Power Spectral Density, dB vs. w Any help on this would be appreciated. (please use any numerical values for $\sigma_u, \tau_u$) I also need to calculate the auto-correlation function by taking the inverse Fourier transform (call it `R(s)` ) of `S(w)`. Finally, I want to compute $$S1(w) = \int_{0}^{\infty} R(s) \cos (ws) ds$$ I would really appreciate someone's kindest help and advice in this regard. Thank you! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%               L := 50     Umc := 4.31     Su[\[Omega]_, \[Sigma]_, \[Tau]_] := (\[Sigma]^2 *\[Tau]/\[Pi] )*1/(1 \     + (\[Tau] *\[Omega])^2)     Sw[\[Omega]_, \[Sigma]_, \[Tau]_] := (\[Sigma]^2 *\[Tau]/(2*\[Pi] \     ))*(1 + 3*(\[Tau]* \[Omega])^2)/(1 + (\[Tau]*\[Omega])^2)^2          Ru[s_] := InverseFourierTransform[Su[\[Omega], 1, L/Umc], \[Omega], s]          S2 [\[Omega]_] := Integrate[Ru[s]*Cos[2*\[Omega]*s], {s, 0, Infinity}]          Plot[S2[\[Omega]] , {\[Omega], 0, 1}]


title: Color of first and last point in a graphic

text: I'm trying to make a graphic of a random walk in 1D, but i want that the first and the last point have a color (in this case the first one red and the last blue), but i dont know what i'm doing wrong.. This is my code:               RandomWalk[n_, d_] :=      NestList[(# + Table[Random[Real, {-1, 1}], {d}]) &, Table[0, {d}],      n];          OneDim = RandomWalk[5000, 1];          firstpoint = OneDim[[1]]          lastpoint = OneDim[[5001]]          ListPlot[{{Hue[0], PointSize[.02],      Point[firstpoint]}, {Hue[.7], PointSize[.02], Point[lastpoint]},      Line[OneDim]}]


title: How to replace While construct to NestWhile(functional-style) correctly?

text: Recently,I find the program of _@J.M._ about Get a "step by step" evaluation in Mathematica is a very useful example for learning _Mathematica_ programming. In the function **`WalkD`** ,I see the construct of **`While`** (it is common in procedural programming paradigm).I know _Mathematica_ 's functional programming paradigm is very elegent,so I'd like to use the function **`NestWhile`** to rewrite the the construct of **`While`**. ### Origin program:               WalkD[f_, x_] := Module[{derivative, oldderivative, k},          derivative = d[f, x]; displayStart[derivative];             (*First While construct*)         While[! FreeQ[derivative, d],             oldderivative = derivative; k = 0;                  (*Second while construct*)             While[oldderivative == derivative,                       k++;                       derivative = derivative /.                                ToExpression[StringReplace[$RuleNames[[k]], " " -> ""]]];             displayDerivative[derivative, k]];         D[f, x]]      ### My trial to rewrite the inner `While` construct               WalkDRewrite[f_, x_] :=      Module[       {derivative, oldderivative, k},        derivative = d[f, x];        displayStart[derivative];           While[! FreeQ[derivative, d],       oldderivative = derivative;       k = 0;           (*begin to rewrite*)      NestWhile[        CompoundExpression[#2++,          #1 = #1 /. ToExpression[StringReplace[$RuleNames[[k]], " " -> ""]]] &,        Sequence[derivative, k],        oldderivative != derivative      ]      (*end *)            displayDerivative[derivative, k]      ];      D[f, x]     ]      However,I failed after debugging all morning. ## Question: Is it possible to use `NestWhile` to replace `While`?Thanks sincerely!


title: Mapping multiple parameters of a function to specific values

text: I am a little bit confused by the documentation for `Apply` (`@@`). I want to define a list of parameters, for instance:               parameters = {{1/2, 1/2}, {1, 1/3}, {2, 1/4}, {0.5, 1/5}};      Then I have a function:               (b/a)*((a/x)^(b+1))      Now I want to map the pair (a,b) to the values defined in `parameters` and generate a plot for each pair of parameters in the same graph. Now the plot syntax would look something like this:               p = Plot[Evaluate[myfunction /@ parameters], {x, 0, 3},              AxesOrigin -> {0, 0}, AxesLabel -> {x, f}, PlotStyle -> styles]      What I struggle with, is getting the syntax right in the following part:               myfunction /@ parameters      How do I need to define this so I get a proper map of (a,b) to my list of parameters? To be honest, I am not very satisfied with the documentation for `Map`. Are there better tutorials?


title: How can I change InputField value dynamically

text: I am storing the values from xlData to the result in a `Grid` form. I want when I change any of the value in any of the `InputFields`, it should show the change dynamically when I evaluate result again. I have to use this result variable again in my code. How can I do this?                  result = {};           xlData = {{1, "a", "b", "c"}, {2, "d", "e", "f"}};        For[i = 1, i <= Length[xlData], i++,         (iniRow = {};          For[j = 1, j <= Length[xlData[[i]]], j++,           If[xlData[[i, j]] != "",                (iniRow =Append[iniRow,InputField[xlData[[i, j]], FieldSize -> {4, 1}]];           )]];                                 result = Append[result, iniRow];)]            Grid[result]


title: Automating Esc [[ Esc formatting?

text: Is it possible to program the Front End to automatically format double square brackets without having to type `Esc``[[``Esc` each time? It's awful to have to type `Esc` four times for each `Part` expression, and even more annoying to visually parse the unformatted double brackets. See also this entry in MathGroup archive: adding a keyboard shortcut for double brackets


title: Is it possible to make a variable wrapped in Dynamic non-dynamic?

text: If I have a function call wrapped in `Dynamic` can I make one or more of the parameters in the call non-dynamic? i.e. I would like to make `diskcx` and `diskcy` in the following snippet be unaffected by changes in their values after the call while making the output of `colorer` and the value of `rectangleCoordinates` dynamic: `...Graphics[ {Dynamic[colorer[ rectangleCoordinates, {radius + diskcx, diskcy}, .4 radius]], Disk[{radius + diskcx, diskcy}, .4 radius]....` Edit: As requested, here is the relatively large block of code the problem is concerned with. Of note is that: `rectangleCoordinates` refers to a set of rectangles that can pass over a disk to change its color;`colorer[rectangles_,center_,radius_]` is a function whose output is a color that depends on whether a rectangle passes over the disk defined by the center and radius that are given as parameters; the `radius` variable is defined outside the module; and of course as a precondition `amount_` is never greater than 5.                   diskGenerator[amount_, space_] :=          Module[{z = 1, listx, listy, positionx, positiony, diskcx, diskcy,          intervals = space/11, disks = {}},         listx = {1, 3, 5, 7, 9};         listy = {1, 2, 3, 7, 8, 9, 10};         For[z = 1, z <= amount, z++,           positionx = RandomChoice[listx];           positiony = RandomChoice[listy];           listx = DeleteCases[listx, positionx];           (*listy=DeleteCases[listy,positiony];*)           diskcx = positionx*intervals;           diskcy = positiony*intervals;           disks =            AppendTo[disks,                Graphics[{             Dynamic[colorer[rectangleCoordinates, {radius + diskcx, diskcy}, .4 radius]],              Disk[{radius + diskcx, diskcy}, .4 radius],                  Dynamic[colorer[rectangleCoordinates, {.5 radius + diskcx, Sqrt[3]/2 radius + diskcy}, .4 radius]],              Disk[{.5 radius + diskcx, Sqrt[3]/2 radius + diskcy}, .4 radius],                  Dynamic[colorer[rectangleCoordinates, {-.5 radius + diskcx, Sqrt[3]/2 radius + diskcy}, .4 radius]],              Disk[{-.5 radius + diskcx, Sqrt[3]/2 radius + diskcy}, .4 radius],                  Dynamic[colorer[rectangleCoordinates, {-radius + diskcx, diskcy}, .4 radius]],              Disk[{-radius + diskcx, diskcy}, .4 radius],                  Dynamic[colorer[rectangleCoordinates, {-.5 radius + diskcx, -(Sqrt[3]/2) radius + diskcy}, .4 radius]],              Disk[{-.5 radius + diskcx, -(Sqrt[3]/2) radius + diskcy}, .4 radius],                  Dynamic[colorer[rectangleCoordinates, {.5 radius + diskcx, -(Sqrt[3]/2) radius + diskcy}, .4 radius]],             Disk[{.5 radius + diskcx, -(Sqrt[3]/2) radius + diskcy}, .4 radius],                  Dynamic[colorer[rectangleCoordinates, {diskcx, diskcy}, .5 radius]],              Disk[{diskcx, diskcy}, .5 radius]           }]           ]         ];         Return[disks]         ];      I'm thinking I should just create a List of `diskcx` and `diskcy` values that the function would refer to just to avert the problem, but if this solution seems unsound I would be happy to read others. Thanks for your time, in any case.


title: Using Mathematica or WebMathematica to develop interactive, crowdsourced timeline visualizations

text: I aim to develop a series of timeline ZUI visualizations which will display a set of events similar to Wolfram's own Timeline of Computable Knowledge, but that can also handle crowdsourced uploading of events (and hyperlink to, say Wikipedia articles). In addition, I would like the layout to look more like the printed poster version of the Wolfram timeline (shown at the bottom of the page), which means developing a layout engine so that labels don't overlap. Could this project be developed as a CDF? With WebMathematica? Any pointers to documentation, tutorials or identification of other technologies (such as databases) to this end are appreciated.


title: Interpolating a function of two variables

text: I am trying to create the interpolating function for a function of two variables, over a finite area. Just for consistency we can think of a function:               MyFunc[a_,b_]:=Sin[a*b]/Sqrt[1+a^2+b^2]      I've read the documentation and, in order to get the interpolating function I use:               MyTable=Table[MyFunc[a,b],{a, -5, 5, 0.1}, {b, -5, 5, 0.1}]     MyApproximateFunc = ListInterpolation[MyTable]      this seem to work, but when I try to plot MyFunc and MyApproximateFunc they look very different: I must have missed some detail...               Plot3D[MyFunc[a, b], {a, -5, 5}, {b, -5, 5}]     Plot3D[MyApproximateFunc[a, b], {a, -5, 5}, {b, -5, 5}]      Thanks in advance for your kind help!


title: Is there a bug in the Part function of Mathematica 10?

text: I am using Mathematica 10 now. I typed code below               {{1, 2}, {2, 4}, {3, 6}, {4, 8}}[[;; , 1]][[1]]      and this gives result               1      But code               {{1, 2}, {2, 4}, {3, 6}, {4, 8}}[[;; , 1, 1]]      gives error > Part::partd: Part specification {{1,2},{2,4},{3,6},{4,8}}[[1;;All,1,1]] is > longer than depth of object. >> But according to help doc > expr[[i,j,...]]] or Part[expr,i,j,...]] is equivalent to expr[[i]][[j]]... What is wrong?!! I remember I always coded it like this in Mathematica 9, no error occurs. Is it a bug??


title: Difference between AbsoluteTiming and Timing

text: I need to evaluate the efficiency of my code. Therefore I would like to evaluate the time the code need for some calculations. Mathematica gives me two possibilities for this kind of evaluation: `AbsoluteTiming[expr]` > evaluates expr, returning a list of the absolute number of seconds in real > time that have elapsed, together with the result obtained. `Timing[expr]` > evaluates expr, and returns a list of the time in seconds used, together > with the result obtained. For both functions the Mathematica Documentation does not provide the section "Properties & Relations" which normally helps to find out the differences between two or more functions. Does anyone have an idea?


title: Flying to Australia

text: I want to compare different flight routes to Australia and their lengths. So far I have written:               departure =      Entity["City", {"BuenosAires", "BuenosAires", "Argentina"}];          destination =      Entity["City", {"Perth", "WesternAustralia", "Australia"}];          km =      ToString@QuantityMagnitude@Round@(GeoDistance[departure, destination]) <> " km";          GeoGraphics[      {       {Thick, Red, GeoPath[{departure, destination}]},       Style[Text[km, GeoPosition[destination]], Blue, 14, Bold]       },      GeoCenter -> destination,      GeoProjection -> "Mercator",      GeoRange -> "World",      ImageSize -> 400,      Frame -> True]      ![enter image description here](http://i.stack.imgur.com/g1ONM.jpg) My problem: To specify a city with Mathematica I have to include its federal state / administrative division, which, in many cases, I don' t know. So I have to google and manually input it. Since I want to automate the program for other cities the question is: How can I persuade Mathematica to tell me that Perth, Australia, is part of Western Australia and use this answer as automated input?


title: Why does Mathematice dislike my boundary condition in NDSolve?

text: im trying to solve a PDE-System, with the "periodic boundary condition"               c[t,0]==4*c[t,2pi]      But mathenmatica says: NDSolve::bcedge: "Boundary condition c[t,0]==4\ c[t,2\ [Pi]] is not specified on a single edge of the boundary of the computational domain." If i replace the 4 by 1 everything is fine. Anyone can explain this to me? And/or can tell me how/if mathematica can solve this? Thanks for reading!


title: How to enter a LaTeX integral?

text: How can I enter a LaTeX integral into _Mathematica_? For example, I evaluated the expression               ToExpression["\int 2*x\[DifferentialD]x ", TeXForm]      but _Mathematica_ told me that this is wrong.


title: Projecting Reference Lines in a SmoothHistogram3d Surface

text: What is the best way to draw a path (red color, dashed) along the surface of the smoothHistogram3D. Assume the paths desired to be the X=0 and Y=0 Axes.               data = {{0.798333, 1.21167}, {-0.415, 0.915}, {-0.675, 0.715}, {0.785,      0.675}, {-0.55, 0.645}, {-0.125, 0.57}, {0.15, 0.27}, {-0.3,      0.115}, {0.925, -0.685}, {0.748333, 1.27167}, {-0.465,     0.975}, {-0.725, 0.775}, {0.735, 0.735}, {-0.6, 0.705}, {-0.175,      0.63}, {0.1, 0.33}, {-0.35, 0.175}, {0.875, -0.625}, {0.628333,      1.18167}, {-0.585, 0.885}, {-0.845, 0.685}, {0.615, 0.645}, {-0.72,       0.615}, {-0.295, 0.54}, {-0.02, 0.24}, {-0.47,      0.085}, {0.755, -0.715}, {0.718333, 1.23167}, {-0.495,      0.935}, {-0.755, 0.735}, {0.705, 0.695}, {-0.63, 0.665}, {-0.205,     0.59}, {0.07, 0.29}, {-0.38, 0.135}, {0.845, -0.665}, {0.738333,      1.23167}, {-0.475, 0.935}, {-0.735, 0.735}, {0.725, 0.695}, {-0.61,      0.665}, {-0.185, 0.59}, {0.09, 0.29}, {-0.36,      0.135}, {0.865, -0.665}, {1.07833, 1.43167}, {-0.135,      1.135}, {-0.395, 0.935}, {1.065, 0.895}, {-0.27, 0.865}, {0.155,      0.79}, {0.43, 0.49}, {-0.02, 0.335}, {1.205, -0.465}};     SmoothHistogram3D[data]      ![enter image description here](http://i.stack.imgur.com/A4pdw.png)


title: How do I make data retrieved from Wolfram|Alpha persist in a notebook?

text: I want to store hourly temperature readings retrieved from Wolfram|Alpha in an array in my notebook. If this is not possible, then tell me how to preserve the retrieved data in my notebook, so when it is reopened, the previously retrieved data need not be reentered. Additional data entry should be limited to just the data required from the user. Thanks in advance.


title: Trying to plot ugly expression, not working

text: I have this ugly function :               A[x_]:=((2 x^3 + 9 x^2 + 27 x + 3 Sqrt[3] (3 x^4 + 14 x^3 + 27 x^2)^(1/2))/2)^(1/3)      (notice the fractional exponents at the end, it is indeed ugly) and it so happens that I want to plot the complex solutions               Abs[A[x] + (3x + x^2)/A[x] + x] == Abs[rho A[x] + rho^2 (3 z + z^2)/A[x] + x]      where rho is a cube root of unity (so we can just set it to `(-1 - I Sqrt[3])/2)`. This displays beautifully with ContourPlot and gives a picture of a curve (I actually have to replace x above by x+Iy and both x and y are in a [-3,3] range to see the picture). In theory, I am supposed to be able to simplify this equation to something a little simpler, i.e. giving something like this :               A[x] Conjugate[x] + Conjugate[(3x+x^2)/A[x]] x + Conjugate[A[x]] (3x + x^2)/A[x] ==      rho^2 Conjugate[A[x] Conjugate[x] + Conjugate[(3x+x^2)/A[x]] x + Conjugate[A[x]] (3x + x^2)/A[x]]      I have checked the details a thousand times ; getting from the above equation to the latter is just squaring the absolute values, using `|z|^2 = z Conjugate[z]` and expanding, it's really trivial math. But when I use ContourPlot to find the solutions to the latter equation, the curve doesn't show up. Any explanations on this?... Anything would be appreciated! From a wild guess to a very detailed attempt or even a suggestion/question.


title: Solving equations with QuantityVariable

text: I'm trying to understand how to easily solve equations that use `QuantityVariable`. Why does this fail?               Quantity["Speed of Light"] ==         QuantityVariable[ν, "Frequency"] (2 π)/QuantityVariable[k, "wavenumber"] /.           QuantityVariable[ν, "Frequency"] -> Quantity[2, "THz"]     // Solve      > Solve::units: Solve was unable to determine the units of quantities that > appear in the input. >> while this doesn't?               Solve[      QuantityVariable[k, "wavenumber"] == (2 π)/QuantityVariable[λ, "Wavelength"],       QuantityVariable[λ, "Wavelength"]]      > >     {{QuantityVariable[λ,"Wavelength"] -> (2 > π)/QuantityVariable[k,"wavenumber"]}} >   Nor does this,               Solve[ 3 10^8 == 2 10^12 (2 π)/k]      > >     {{k -> (40000 π)/3}} >   Notice that its not necessary to explicitly say which variable to solve in the last example as there is only one possibility, yet that fails if using `QuantityVariable`. The question is: Why does my first code fails?


title: Highlighting a single Period of a Trig Plot

text: How do I highlight a single period of a trig function say by using color and/or thickness when the graph itself extends further than just a single period? Thanks...Gregory Lane


title: How to rotate the z label in 3D plots

text: Let's take the following simple and funny case               S0 = ParametricPlot3D[{t*Sin[t], t*Cos[t], t}, {t, -100, 100},           BoxRatios -> {1, 1, 1}, AxesLabel -> {"x", "y", "a very long label"}, ImageSize -> 550]      which gives this ![plot](http://i.stack.imgur.com/O2rYB.jpg) We see, that the label of the z axes is printed horizontally by default, thus wasting a lot of space. In two-dimensional plots however, this can be easily fixed with the option `RotateLabel -> False`. Is there something similar for three-dimensional plots for rotating and printing vertically the z label? Many thanks in advance.


title: Finding Values of All Nine Constants in q-hypergeometric Equation

text: I suspect that an identity of the form $$\sum_{j=-n}^{j=n}(-1)^jq^{j(5j+1)/2}=\sum_{r=0}^{n}f_{ar+bn+c}(-1)^{n-r}q^{(n-r)(dr+en+f)/2}\frac{(q;q)_{gr+hn+j}}{(q;q)_{n-r}}$$ for $a, \dots , j$ integer constants, where $$f_N=\sum_{j=0}^{N}{N \brack j}q^{j^2}.$$ Here $(a;q)_n$ and $a \brack b$ denote the standard q-pochammer symbol and q binomial coefficient, resp. I turned to Mathematica for help in determining exactly what these integer constants must be. The bulk of my code is as follows:               f[n_] := Expand[Sum[FunctionExpand[QBinomial[n, j, q]]*q^(j^2), {j, 0, n}]]          lhs[n_] := Sum[(-1)^j*q^(j (5 j + 1)/2), {j, -n, n}]      The following implementation worked for 3 variables, but not for 6 variables:               rhs[n_, a_, b_, c_, d_, e_, f_] :=        Expand[Sum[f[r]*(-1)^{n - r}*q^{(n - r) (a*n + b*r + c)/2}*         FunctionExpand[QPochhammer[q, q, d*n + e*r + f]/QPochhammer[q, q, n - r]], {r,          0, n}]]          L[n_] :=        Do[         If[CoefficientList[lhs[n], q] == CoefficientList[rhs[n, a_, b_, c_, d_, e_, f_], q],          Print[{a, b, c}]], {a, t, -t + 1}, {b, t, -t + 1}, {c, t, -t + 1}, {d, 1, 3},          {e, 0, 3}, {f, 0, 3}]       It's also fairly sluggish in 3 variables. ### A New Approach Following George2079's suggestion, I now seek polynomials $g(r,n), h(r,n)$ in $q$ of fixed degree for which $$\sum_{j=-n}^{j=n}(-1)^jq^{j(5j+1)/2}=\sum_{r=0}^{n}f_{g(r,n)}\cdot h(r,n).$$ I am almost certain that such an $h(r,n)$ exists for all $n$ when $g(r,n)=ar+bn$. Then the following is a preliminary function on the assumption that $g(r,n)=r$, and finds something for $n\le8$:               Guess[n_] :=       Module[{maxr = Floor[Sqrt[n (5 n + 1)/2]], maxk = 20, mat, ns},        mat = Transpose[          PadRight[CoefficientList[#, q] & /@             Append[Flatten[Table[q^k*f[r], {r, 0, maxr}, {k, 0, maxk}]], lhs[n]]]];       ns = Select[NullSpace[mat], Last[#] =!= 0 &];       If[Length[ns] =!= 1, Throw["Error"]];       Return[((#.q^(Range[Length[#]] - 1)) & /@ Partition[Most[First[ns]], maxk + 1]).         Table[F[r], {r, 0, maxr}]];     ];          Guess[5]     (-1 + q^2 + q^3 + q^8 + q^9 - 3 q^10 - 8 q^11 + q^12 + 12 q^13 +      7 q^14 - 5 q^15 - 12 q^16 + 10 q^17 + 16 q^18 + 3 q^19 -      5 q^20) F[0] -      13 q^20 F[1] + (19 q^19 + 11 q^20) F[     2] + (-8 q^16 - 17 q^17 - 17 q^18 - 9 q^19 + 5 q^20) F[     3] + (9 q^14 + 18 q^15 + 18 q^16 + 8 q^17 + 5 q^18 - 2 q^19 -      10 q^20) F[     4] + (-9 q^12 - 11 q^13 - 9 q^14 - 8 q^15 + q^17 + 3 q^18 +      4 q^19 + 6 q^20) F[     5] + (5 q^10 + 3 q^11 + 2 q^12 + q^13 + q^14 - q^15 - 2 q^16 -      2 q^17 - q^18 - q^19 - q^20) F[6] + (-q^8 - q^9 + q^11 + q^16) F[     7]              Expand[% /. F -> f]     -1 + q^2 + q^3 - q^9 - q^11 + q^21 + q^24 - q^38 - q^42 + q^60 + q^65          tab = {}; ii = 1;     While[True, AppendTo[tab, Guess[ii]]; ii++; Print[ii]]     2     3     4     5     6     7     8      And one gets `Hold[Throw[Error]]`. Can someone produce an implementation that caters well to guessing what the general $h(r,n)$ might look like/be?


title: Unsatisfactory view of Panel, when transformed to pdf

text: I like very much to wrap Mathematica images by `Panel`, which gives many of them a much better view. To be precise, if image is some illustration, plot etc. I would like to put it in Mathematica document as `Panel@image` Then I typically mark the output as Figure in the JournalArticle StyleSheet. However, most of my documents should be later transformed into PDF for further use. This is unavoidable, since in my company nobody else uses Mathematica. In the PDF document version the panel loses most of its attractiveness. The gray color becomes almost white, and the fine rim details (which made the panel looking in Mathematica like a 3D-relief) disappear. In this form Panel makes the view worse, rather than improve it. To be more precise, here is an image wrapped by a panel: please execute the following in Mathematica notebook:               Panel[Import["ExampleData/rose.gif"]]      ![Mathematica graphics](http://i.stack.imgur.com/01qNy.png) As you see the panel looks a 3D relief. It does not exist any more in the PDF version of the file that you can see below. Besides, the panel color is much worse now. Have you any idea of what could be done to improve the `Panel` view after the document is transformed into PDF?


title: Alternatives to While Loops?

text: I am using Mathematica to run a probabilistic simulation. Essentially, I have a list of members of a population (they only have one, numerical, attribute, so it's just implemented as a list of numbers), and a function to move from one generation to the next, in a random manner. I need to iterate this function on my list until the list exceeds a given length, and then I want the number of iterations/generations is took to reach that length. My first instinct would be to use a While loop, but I know that using explicit loops in Mathematica is usually bad practice. Unfortunately, I haven't been able to find a better or more functional construction, and that's where I'm asking for help.


title: Axes/Frame Label as Log base 10

text: I am trying to label one of the frames on a ListPlot as log_10(x). When I try `ListPlot[twodimndata,Frame -> True, FrameLabel -> {Style[Log10[r], 20], Style[d, 20]}}` the output on the x-axis is `Log[r]/Log[10]`, rather than Log_10[r] as I expected How can I get Mathematica to plot Log_10[r] on the x-axis?


title: Switching the axis of a plot

text: I have a plot but the x and y axis need to be switched. The problem is that I can't explicitly solve for the other so I can change the axis.               e = .65;          Ec[M_] = M +        Sum[(1/2^(n - 1)*           Sum[((-1)^k*(n - 2*k)^(n - 1))/((n - k)!*k!)*             Sin[(n - 2*k)*M], {k, 0, Floor[n/2]}])*e^n, {n, 1, 3}]     Plot[Ec[M], {M, 0, 2 \[Pi]},       PlotRange -> {{0, 2 \[Pi]}, {0, 2 \[Pi]}}]      Basically, I want Ec to be on the x axis and M the y axis. As of right now, they are swapped.


title: Extracting Imported Information

text: What I want to do is to compare the relationship between the consumption of say beer and wine using scatter plots where each point designates the particular country (preferably named). I have tried to part the information - so that each particular column becomes a vector - using the function Part without any success. I find this bewildering given that `Dimension[data]` yields the result `{19,4}`. For those of you that are familiar with R: What I would like to do to is to part the information, like this                   > Country <-data$Country         > Beer <-data$Beer         > Wine <-data$Wine         > HardLiquid <-data$HardLiquid      and then produce scatter plots which names every country.               > plot(Beer,Wine,type="n")     > text(Beer,Wine,Country)      **Extra** This is the data that I am working on in _Mathematica_ :               data = {{"Country", "Beer", "Wine", "Hard Liquid"},       {"Sweden", 56., 16., 2.9},       {"Danmark", 98., 32., 2.7},       {"Finland", 79., 10., 5.7},       {"Norway", 56., 11., 2.4},       {"Belgium", 98., 30., 2.6},      {"France", 47., 41., 7.2},       {"Irland", 155., 13., 5.3},       {"Italy", 29., 54., 2.7},       {"Netherlands", 80., 20., 4.7},       {"Switzerland", 57., 42., 2.4},       {"Kingdom United", 20., 97., 3.9},       {"Germany", 26., 119., 5.3},       {"Austria", 36., 106., 3.2},       {"USA", 85., 7., 4.8},       {"Canada", 70., 10., 4.3},       {"Australia", 21., 89., 2.6},       {"Nya Zeeland", 19., 78., 2.3},       {"Japan", 55., 10., 8.2}}


title: DeleteDuplicates not deleting duplicates

text: It is not surprising that `DeleteDuplicates[{5,5.}]` returns `{5,5.}` because `DeleteDuplicates` uses `SameQ` by default, and `SameQ[5,5.]` is `False`. However, `Equal[5,5.]` is `True`, but `DeleteDuplicates[{5,5.},Equal]` still returns `{5,5.}`. It is interesting to note that `Union` works properly, in that `Union[{5,5.},SameTest->Equal]` returns `{5}`, as expected. Is this a bug, or am I missing something? I'm using version 9. **Update:** I realize that using the function `#1==#2&` will get it working, thanks for pointing this out. However, my question really is "Is this a bug, or am I missing something?". To illustrate this further, consider the following:               f[x__]:=Equal[x]     DeleteDuplicates[{5,5.},f]     (* {5} *)      In what capacity are `f` and `Equal` different? Or what is leading `DeleteDuplicates` to treat them differently? They both take an arbitrary number of inputs, which is what I originally thought was the problem.


title: Clojuratica setup in Windows

text: I have been trying to setup Clojuratica on Windows using instructions from Clojure Data Analysis Cookbook and http://drcabana.org/2012/10/23/installation-and-configuration-of-clojuratica/ Each time I run this code               java -cp ".\clojure-1.6.0\clojure-1.6.0.jar;.\Clojuratica-master\clojuratica.jar;     C:\Program Files\Wolfram Research\Mathematica\9.0\SystemFiles\Links\JLink\JLink.jar;."          clojure.main Clojure 1.6.0      I get the error > Exception in thread "main" java.io.FileNotFoundException: Clojure (The > system cannot find the file specified) What am I doing wrong?


title: writing a function using multiple variables

text: I am fairly new to _Mathematica_ and am trying to write a function for the equation:               xx = [x/(Sqrt[h^2 + d^2 + y^2]))*(Sqrt[h^2 + (d + yy)^2])      where h, d are known and x, y and yy are functions that give lists of numbers of equal list length. Is there a way to write a function that encompasses all the variables x, y, yy? I'm assuming it would start with               xx[x_, y_, yy_] := .........      or is the best method to create a loop?


title: How to find a fit for a function?

text: I have the following function:               F[t_] := V1 (Cos[w1 t - ph1] Exp[-alpha1 t] -           Cos[ph1] Exp[-beta t]) +        V2 (Sin[w2 t + ph2] Exp[-alpha2 t] - Sin[ph2] Exp[-beta t])      where all the variables are constants. I want to express it in terms of Spherical Bessel Functions of any type or any linear superposition of them. My first idea was to extract the data from the function making a list and then use               FindFit[data, p SphericalBesselJ[q, t], {p, q} t];      But I am struggling to export the data so that it matches the form of a function. I tried:               data = Table[F[t], {t, 0, 0.1, 0.0001}]      But the label of the x axis is 1,2,3.... where I need 0.0001, 0.0002 and so on. Any ideas of how to get around it or maybe another way of finding the correct expression of `F[t]` in terms of Bessel Functions?


title: NDSolve Differential Equation Error

text: I am trying to solve the following differential equation-               k = NDSolve[{y'''[x] == -76*Sin[y[x]], y[0] == Pi/4, y'[0] == 0,         y[1.85] == 0}, y, {x, 0, 2}, AccuracyGoal -> 10,        PrecisionGoal -> 30]      I am getting a solution but when I plot a graph, it does not satisfy the boundary conditions. I am getting the following two errors- FindRoot::sszero: The step size in the search has become less than the tolerance prescribed by the PrecisionGoal option, but the function value is still greater than the tolerance prescribed by the AccuracyGoal option. >> **NDSolve::berr: There are significant errors {-0.239832,-0.0591905,-0.0015434} in the boundary value residuals. Returning the best solution found. >>** The funny thing is when I reduce the coefficient of `Sin[y[x]]` it works fine. Can anyone help me with this? Thanks,


title: How can I make the output from Solve look nice?

text: I have a problem with presenting solutions. Roots of 4th order polynomials are big expressions. Is there a way to present the roots, s2 and s3, in normal form with some substitutions? Maybe a way to force _Mathematica_ to find some similar terms under the radicals and replace them with substitutions (to factorize or simplify that way), so s2 and s3 are presented in a way that looks nice?               a1 = Roots[x^4 + r1 x^3 + r2 x^2 + r3 x + r4 == 0, x][[1]][[2]];     a2 = Roots[x^4 + r1 x^3 + r2 x^2 + r3 x + r4 == 0, x][[2]][[2]];     a3 = (-s2 - Sqrt[s2^2 - 4  s3])/2 ;     a4 = (-s2 + Sqrt[s2^2 - 4  s3])/2 ;          Solve[{a1 - a3 == 0, a2 - a4 == 0}, {s2, s3}]


title: Is it possible to assign different colors to parts of an .obj file?

text: There are four different cubes in an .obj file. After loaded into Mathematica, is it possible to assign four random colors to the cubes?                (* assuming the .obj file was loaded in the c: root *)      cubes = Import["c:\\4cubes.obj"] ;      Graphics3D[  First[cubes]  ]      ![enter image description here](http://i.stack.imgur.com/GaVST.gif)


title: Selecting expressions from a sequence that are not subexpressions of earlier elements

text: I have a `While` loop that generates and prints an expression on each iteration (there can be thousands of iterations). _UPDATE:_ Some expressions are generated in unevaluated form (e.g. `1 + 1`) and printed in this form. This behavior should be kept in the modification explained below. I want to modify it to print only _new_ expressions -- that do not appear as sub-expressions of any expression that has been generated at an earlier step. We assume that any expression is a sub-expression of itself, so no expression should be printed twice. Generated expressions may contain patterns, and they should be handled verbatim (each symbol represents only itself). For example:               (* Iteration 1 *)     f[_] (* PRINTED *)          (* Iteration 2 *)     f (* Skipped *)          (* Iteration 3 *)     _ (* Skipped *)          (* Iteration 4 *)     Blank (* Skipped *)          (* Iteration 5 *)     f[0] (* PRINTED *)          (* Iteration 6 *)     f[_] (* Skipped *)          (* Iteration 7 *)     g[f[0]] (* PRINTED *)      What is the most efficient way to maintain a set of expressions that have been already printed and validate newly generated expressions against this set?


title: Workflow in the Mathematica and Workbench IDE

text: After visiting one of the Wolfram presentations, I started writing code for my number theory research project in Mathematica because I found it to be faster than Sage. I downloaded Workbench and Mathematica, watched the video tutorials on the Wolfram website and read the tutorials in the manual. Then I started coding. After being at it for a week, I find the whole experience to be extremely clumsy as I can not figure out any reasonable workflow. What I do now is this: I open Workbench which in turn starts Mathematica notebook. I write a procedure spread over multiple cells in the notebook. When I am happy with the result, I copy the code into the workbench .m file where I make it into a function. Afterwards, I start using the function in the notebook to do my calculations or to use it in other procedures. I am very happy with the control I have over each step in the notebook and coding in workbench feels quite smooth. What really bugs me is the transition between the two. I just can not figure out how to achieve the smooth workflow I am used from IDEs like IntelijIdea in Workbench. Truth is, when I was downloading Workbench, I was expecting it to replace the notebook environment of Mathematica with more serious IDE. Yet it just launches Mathematica and the notebook each time I run the project anyway. So my question is this: What is the proper way to use Workbench to write code? Or is it just my inexperience that makes me think I am doing something wrong? The closest question I found was this: Working in a team in Workbench which talks mainly about version control (which I wanna look at in the next step as git does not seem to cut it). Links to articles or tutorials describing proper workflow in Workbench would be much appreciated as well.


title: How can I get Mathematica to simplify my expression?

text: 4.`*^-12 Sqrt[3.0254210421890627`*^22 - 6.25`*^22 T6^2]      The above expression is equal to               Sqrt[0.48406736675024997` - T6^2]      How can I tell _Mathematica_ to simplify the first form into the second form?


title: How to embed a Mathematica demonstration in Google sites?

text: I want to have students submit articles that include Mathematica demonstration projects in a document that is on Google sites. I am having problems with embedding the JS code. Could you provide step-by-step instructions. Not sure of the tag for this question.


title: How to specify default style in Mathematica 9

text: In _Mathematica_ 8, I can use `GraphicsBoxOptions->{DefaultBaseStyle->{"Graphics", FontFamily -> "Helvetica", FontSize -> 14}}` to specify the default font for graphics. But this does not work for _Mathematica_ 9. How to specify the default style in _Mathematica_ 9 then? Using `BaseStyle` may be a solution. But it is not generalizable to other default styles like `DefaultAxesStyle`, `DefaultFrameStyle` etc. Originally `DefaultAxesStyle->{"GraphicsAxes", FontSize -> 12}` works in _Mathematica_ 8, but it runs into error in _Mathematica_ 9 (message: `The specified setting for the option GraphicsBoxOptions, DefaultAxesStyle cannot be used`). Does anyone know about the style specification grammar in _Mathematica_ 9?


title: Why can't an `Import[]` change $Path?

text: Does anyone know why `Import["http://**server**/file.m"]` can't make a change to `$Path`? It seems like `file.m` can set pretty much any other variable, but not `$Path`. I suspect `Get[]` would work, but I can't seem to get `Get[]` to fetch files over the web.


title: How to use Map inside MapThread?

text: Given this input               lst1 = {{a, b, c}, {d, e, f}};     lst2 = {1, 2};      and the goal is to generate this output               {  {{1, a}, {1, b}, {1, c}},         {{2, d}, {2, e}, {2, f}}     }      Perfect candidate for MapThread So I made this diagram first to figure what the function I want to map should be ![enter image description here](http://i.stack.imgur.com/IsGuG.png) So the function to use inside `MapThread`, needs to also use `Map` itself (in order to map each item into the other list). So I came up with this:               lst1 = {{a, b, c}, {d, e, f}};     lst2 = {1, 2};     foo[i_, lst_List] := List[i, #] & /@ lst     MapThread[foo[#1, #2] &, {Range[Length@lst2], lst1}]     (*  {  {{1,a}, {1,b}, {1,c}},       {{2,d}, {2,e}, {2,f}}   }  *)      _Now here is the question_ : Is there a way to do the above without having to define an explicit function but using pure function inside `MapThread`? I was getting conflict with `#` mapping. This is sort of the thing I was trying to do, but can't get the syntax right               (*invalid, for illustration only *)     MapThread[       Function[{idx, lst},List[idx, #] & /@ lst] &  ?? ??    ,{Range[Length@lst2],lst1}]      Or if you know of a better approach to do this, that will be fine as well.


title: Problem overloading D[] using UpValues

text: First I define an entry of `UpValues` overloading `D[]` for expressions with head `ftest`:               ftest /: D[ftest[aaa_, bbb_], r] := ftest[D[aaa, r], D[bbb, r]]      When I try:               D[ftest[r, r^2], r]      the result is as I expect it to be: > ftest[1, 2 r] However, when I try:               D[(r + ftest[r, r^2]), r]      Mathematica gives not the result I expect: > 1 + 2*r*Derivative[0, 1][ftest][r, r^2] + Derivative[1, 0][ftest][r, r^2] **edit** The result I expect is: > 1 + ftest[1, 2 r] (this clarification was suggested by Mr.Wizard, thanks!) **end edit** **How should I understand this?** **How can this be fixed?** * * * I tried               TreeForm@Unevaluated@Unevaluated@D[(r + ftest[r, r^2]), r]      and understand the result: ![img_1 for question on overloading D\[\] ](http://i.stack.imgur.com/SVA0m.jpg) I also tried               TreeForm@Unevaluated@Unevaluated@D[(r + ftest[r, r^2]), r]      and I don't understand what does Mathematica do in the meantime to produce this result: ![img_2 for question on overloading D\[\] ](http://i.stack.imgur.com/tiXSX.jpg)


title: Graph two interpolations together

text: I have created two functions, `inter1=Interpolation[points1]` and `inter2=Interpolation[points2]`. This creates two functions, I then created a graph `Manipulate[ListLinePlot[inter1, InterpolationOrder -> n],{n, 0, 6, 1}]`. However I need to combine these functions together. I want to be able to graph each function together and manipulate each function separately based on `InterpolationOrder`. Can someone please help? This is how far I've come               points = {{1,79},{2,181},{3,181},{4,52},{5,49},{6,8},{7,137},{8,79},{9,112},{10,164}};     inter1 = Interpolation[points];     inter2 = Interpolation[points];     Manipulate[ListLinePlot[inter1, InterpolationOrder -> n], {n,0,6,1}]      Regards New to Mathematica


title: Grain(Particle) Size Distribution (PSD) Analysis with Mathematica

text: I would like to do an analysis of the grain size distribution of a Monte Carlo Grain Growth simulation I implemented based on the nice example by Rituraj Nandan (see Link). The result of this calculation is a 2D integer matrix, where every point represents a certain grain orientation. Thus a cluster of similiar values represents a grain. Converting this information into a graphical representation by assigning a similiar color to every similiar integer gives an image which shows the grain distribution of the simulation clearly. Here is an example of such an simulation result (I converted the initial implementation in Java into Mathematica syntax): ![enter image description here](http://i.stack.imgur.com/USIZQ.png) The code used for generating this image is as follows (see above link to the java implementation for the details of the physics behind it):               meshgen[xmax_:0.01,ymax:0.01,nx_:60,ny_:60]:=Module[{hx,hy},     hx=xmax/nx;     hy=ymax/ny;     Return[{{xmax,ymax},{nx,ny},{hx,hy},{Table[i hx,{i,0,nx-1}],Table[j hy,{j,0,ny-1}]}}];     ];          temperature[mesh_,torch_,vel_]:=Module[{x,y,xc,yc,nx,ny,rad,al,t,     q0=500(*net power*),     d=0.002(*thickness of plate*),     \[Rho]=7800(*density*),     cp=600(*specifc heat capacity*),     k=45(*thermal conductivity*),     t0=298.0(*Initial temperature*)},(*quasi-steady thermal profile*)     al=k/(\[Rho] cp);(*thermal diffusivity*)      {nx,ny}=mesh[[2]];     {x,y}=mesh[[-1]];     {xc,yc}=torch;     rad=Outer[Norm[{#1,#2}]&,x-xc,y-yc];     t=Table[t0+q0/(d 2 \[Pi] k) E^(-(1/2)vel (x[[i]]-xc)/al) BesselK[0,1/2 vel rad[[i,j]]/al],{j,1,ny},{i,1,nx}];     Return[t];     ];          tmc[mesh_,t_,vel_]:=Module[     {K1=1.01,(*Model constant*)     n1=0.42,(*Model constant*)     A=1,(*Accommodation probability*)     \[CapitalNu]=1.53 10^19,(*Average number of atoms per unit area at the grain boundary in #/m\.b2*)     Na=6.022 10^23,(*Avogadro's number*)     Vm=7.11 10^-6, (* ??? *)     h=6.62 10^-34(*Planck's constant m\.b2kg/s*),     R=8.314, (*Gas Constant J/molK*)     \[CapitalDelta]Sf=9.48, (*Activation entropy of grain boundary migration J/molK*)     Q=93400, (*Activation enthalpy for grain boundary migration in J/mol*)     \[Gamma]=1.77, (*Grain boundary energy J/m\.b2*)     \[Lambda], (*Grid Size*)     L0,  (*Initial Grain Size*)     dt,time,expt,C1,x,nx},(*monte-carlo time at each location (i,j)*)     x=mesh[[-1,1]];     nx=mesh[[2,1]];     \[Lambda]=mesh[[3,1]];     L0=mesh[[3,1]];     C1=(4 \[Gamma] A \[CapitalNu] Vm^2)/(Na^2 h) E^(\[CapitalDelta]Sf/R);     time=x/vel;     dt=Append[Differences[time],time[[-1]]];     expt=Table[Exp[-Q/(R*t[[;;,i]])]*dt[[i]],{i,1,nx}];     expt=Reverse[Accumulate[Reverse[expt]]];     Return[(Sqrt[C1 expt+L0^2]/(K1 \[Lambda])-1/K1)^(1/n1)];     ];          energypart[indx_,{nx_,ny_},reflect_:True]:=     Module[{ii,jj,it,ib,jl,jr},(*get part specification of nearest neighbours of location (ii,jj). If reflect is set True then at the array boundary reflecting boundary conditions are assumed. Otherwise periodic boundary conditions are used*)     ii=indx[[1]];jj=indx[[2]];     (*rows of top and bottom neighbours*)     it=If[reflect,If[ii==1,1,ii-1],If[ii==1,ny,ii-1]];     ib=If[reflect,If[ii==ny,ny,ii+1],If[ii==ny,1,ii+1]];     (*rows of left and right neighbours*)     (*rows of top and bottom neighbours*)     jl=If[reflect,If[jj==1,1,jj-1],If[jj==1,nx,jj-1]];     jr=If[reflect,If[jj==nx,nx,jj+1],If[jj==nx,1,jj+1]];     {it;;ib,jl;;jr}     ];          pottsenergy[osub_]:=Total[Map[1-KroneckerDelta[#,osub[[2,2]]]&,osub,{2}],2];(*Potts-Function of 3x3 Array with relevant grain in the center at {2,2}. The total of this array gives the Energy of the grain at {2,2}*)          energy[o_,indx_,nmax_,reflect_:True]:=pottsenergy[o[[Sequence@@energypart[indx,nmax,reflect]]]];(*Select relevant block with center element and all neighbours and apply Potts-Function to it. The result of this function gives the Energy of the grain at position indx*)          RemoveNoise[frame_,limit_:2]:=Module[{emap,nx,ny,result,i},     {nx,ny}=Dimensions[frame];(*Set all grain size orientations for grains which just consist of one or two pixels (set by limit) (E=8) equal to -1 (with the color function defined below they will be set to black*)     emap=MapIndexed[energy[frame,#2,{nx,ny}]&,frame,{2}];     i=5;     emap[[1,;;]]=Nest[ReplacePart[#,Position[#,i--]->8]&,emap[[1,;;]],limit];(*Correct for lower number of neighbours at boundaries*)     i=5;     emap[[nx,;;]]=Nest[ReplacePart[#,Position[#,i--]->8]&,emap[[nx,;;]],limit];     i=5;     emap[[;;,ny]]=Nest[ReplacePart[#,Position[#,i--]->8]&,emap[[;;,ny]],limit];     i=5;     emap[[;;,1]]=Nest[ReplacePart[#,Position[#,i--]->8]&,emap[[;;,1]],limit];     i=8;     result=Nest[ReplacePart[#,Position[emap,i--]->-1]&,frame,limit];     Return[result];     ];          grainsize[mesh_,o_]:=Module[{dist=Table[0,{10}],avg,size,sum=0,num=0,nx,ny,hx,hy,i,j,k,xmax,ymax},(*measurement of grain size distribution and average grain size*)     {xmax,ymax}=mesh[[1]];     {nx,ny}=mesh[[2]];     {hx,hy}=mesh[[3]];     For[i=1,i<=nx,i+=5,(*measurement of average grain size using mean lineal intercept method*)     For[j=1,j<=ny,j++,     If[o[[i,j]]!=o[[i,Mod[j+ny-1,ny,1]]],(*periodic boundary*)     num+=1     ];     ]     ];     avg=nx ymax/num;(*average grain size*)     For[i=1,i<=nx,i++,(*grain size distribution*)     For[j=1,j<=ny,j++,     If[o[[i,j]]==o[[i,Mod[j+ny-1,ny,1]]],     sum+=1     ,     size=sum hy/avg;     sum=0;     For[k=0,k<10,k++,     If[(size<If[k<9,k+1,1000]/2)&&size>=k/2,dist[[k+1]]+=1];     ];     ];     ];      ];     Print["Grain size distribution : "];     For[i=0,i<10,i++,Print[i/2//N," - ",If[i<9,i+1,1000]/2//N,"    ",dist[[i+1]]]];     Print["Average grain size : ",avg];     Return[avg];     ];      The above routine grainsize is the one still to be optimized since there I did not do much conversion so far. Finally with the following statements the Graph above can be generated:               mesh = meshgen[0.01, 0.01, 500, 500];     temp = temperature[mesh, {0.0070001, yc = 0.0050001}, 0.005];     tmcs = tmc[mesh, temp, 0.005];     o = Table[RandomInteger[{0, 31}], {mesh[[2, 1]]}, {mesh[[2, 2]]}];     frames = {};     If [! FileExistsQ [NotebookDirectory [] <> "Graingrowth.dmp"],       For[i = 1, i < 250, i++,        tempc = PrintTemporary["Frame " <> ToString[i] <> "/250"];        If[i > 1,          tempp = PrintTemporary[           ArrayPlot[RemoveNoise[frames[[-1]]], PlotRange -> {-1, 31},             ColorFunction -> Function[v, If[v == 0, Black, Hue[v]]]]]];        on = potts[mesh, o, tmcs, 5000000];        AppendTo[frames, on\[Transpose]];        o = on;        If[i > 1, NotebookDelete[tempp]];        NotebookDelete[tempc];        ];       AppendTo[frames, o\[Transpose]];       DumpSave[NotebookDirectory[] <> "Graingrowth.dmp", frames];       ,       Get [NotebookDirectory[] <> "Graingrowth.dmp"];       ];     ArrayPlot[RemoveNoise[frames[[-1]]], PlotRange -> {-1, 31}, ColorFunction -> Function[v, If[v == 0, Black, Hue[v]]]]     Export[NotebookDirectory[] <> "FinalGrainStructure.png", %];ColorFunction -> Function[v, If[v == 0, Black, Hue[v]]]]      Of course there are multiple sources on the web of how to do PSD analysis, however I did not find any details about the potential of using Mathematica for this application. There is a very interesting Reference in the Wolfram Library, but it could not manage to get a hard or soft copy of this work. I guess the statistical routines within Mathematica would make it perfectly suitable for such an analysis. Any ideas/help/advice?


title: How do you express a function of x,y,and z as a function of the parameter t in a vector?

text: If I have a vector say for example $\vec{r}(t)=<t,t^2,3t^2>$ and a function $f(x,y,z)=\sqrt{1+30x^2+10y}$ whats the best way to express $f(x,y,z)$ as a function of the parameter $t$?


title: Simple ways to evaluate a derivative at a point?

text: The contrast in behavior between, say,               f[x_] = Sin[x^2];     f'[2]      vs.               u[x_, y_] = Cos[x + y^2];      ![enter image description here](http://i.stack.imgur.com/1uqai.png) has always bothered my students---and me! (Why _does_ it do it this way?) Anyway, I tell them to handle ${\partial u\over \partial x}\Big|_{x=2}$ via ![enter image description here](http://i.stack.imgur.com/V1BAQ.png) Is this the "simplest" way? How else might we accomplish this? I realize that this is a subjective question, but our context is this is a class where we use _Mathematica_ as a tool rather than a class centered on _Mathematica_ itself. Thus, I want to keep the commands and code required as reasonably elementary as possible (and preferably resembling their paper-and- pencil mathematical work).


title: How to perform fuzzy lookup between lists?

text: I have two big lists with 10,000 lines each, with product names from different databases. They have a lot of common products (50%), but they are not typed in the same way. For example there is one sample of 20 items that match: List One               Refresco em Pó TANG de Pêssego 30g     Refresco em Pó CLIGHT de Maracujá 9g     Refrigerante ANTARCTICA Soda Limão Garrafa 600ml     Refresco em Pó CLIGHT de Abacaxi com Hortelã 8g     Refrigerante ANTARCTICA Guaraná Lata 350ml     Refresco em Pó CLIGHT de Lima Limão 9g     Refrigerante ANTARCTICA Zero Guaraná Garrafa 600ml     Ração para Gatos Sabor Peixe e Frutos do Mar WHISKAS 500g     Refresco em pó TANG de Tangerina 30g     Refresco em Pó CLIGHT de Uva 9g      List Two               SUCO PO PESSEGO TANG 30G     SUCO PO DIET MARACUJA CLIGHT 8G     REFRIGERANTE SODA LIMONADA ANT 600ML     SUCO PO DIET ABACAXI C/HORTELA CLIGHT 8G     REFRIGERANTE GUARANA ANT LT 350ML     SUCO PO DIET LIMAO LIMAO CLIGHT 8G     REFRIGERANTE GUARANA ZERO ANT PET 600ML     RACAO PEIXE E FRUTOS DO MAR WHISKAS 500G     SUCO PO TANGERINA TANG 30G     SUCO PO DIET UVA CLIGHT 8G      In the original list they are out of order. In SQL Server Integration Services (SSIS) they have Fuzzy Lookup Transformations to do things like that. Question: What is the best way to make the match as automatically as possible in Mathematica? I tried something very incipient with `EditDistance`, but it's not enough. I know that some human intervention will be needed in the end, but currently the whole process is done manually. You can import a bigger list version with 400 lines each, direct in Mathematica using:               list1=StringSplit[Import["http://arquivo.rodrigomurta.com/Fuzzy_list1.txt"],"\n"]     list2=StringSplit[Import["http://arquivo.rodrigomurta.com/Fuzzy_list2.txt"],"\n"]      The lines 001 to 200 have the elements that are not equivalent, and don't match. The lines 201 to 400 have the elements that are equivalent, and are in the same order. So 201 in list 1 is equivalent in 201 in list 2. Thanks in advance


title: Both Sin[x]==0 && Cos[x]==0 as a solution

text: If I do               FullSimplify[Reduce[Sin[p1] == 0 && Cos[p1] == 0, Reals]]      I get                Cos[p1] == 0 && Sin[p1] == 0      while I would expect False. why? is there a way to have mathematica compute that both sin and cos cannot be 0?


title: Limit won't compute

text: Does anyone know why the limit:               Limit[(α*(E^((t*ϵ)/(λ*τ))*t*ϵ*(-1 + 2*λ) - E^((t*ϵ)/(λ*τ))*ϵ*(-1 +          2*λ)*τ + E^((t*ϵ*(-1 + 2*λ))/((-1 + λ)*λ*τ))*ϵ*(-1 + λ)*(1 + (-2 + ϵ)*λ)*τ +          ϵ*λ*(-1 + ϵ + 2*λ - ϵ*λ)*τ))/(E^((t*ϵ)/(λ*τ))*ϵ*(-1 + 2*λ)),        λ -> 0     ]      won't compute? Sorry about the weird formatting.


title: My mistake or error in NDSolve?

text: I try to solve the following equation $$y'=y-2ye^{-0.8y}, \quad y(0)=0.7.$$ By some aruments I expect to have a positive solution $y(t)\geq0$, for all $t>0$, however, NDSolve shows that starting from $t\approx 25$ there are some oscilations arround $0$. Their amplitude is quite small, less than $10^{-7}$. A similar result I can obtain using Maple. Is it surely means that my theoretical arguments are wrong or it may be an error in NDSolve algorithm due to some bad properties of this equation?


title: Random walk on a sphere

text: I'm trying to programme a random walk on a sphere with _Mathematica_. I found this code while I was searching, but I'm not getting results from it. I waited an entire day, but my pc didn't finish evaluating `rw`. I would like some help please (:               rotateWithAxis[p_, a_, theta_] :=        #/Norm[#] & @ ((1 – Cos[theta]) (a.p) a + p Cos[theta] + Cross[a, p] Sin[theta]);      Using the function, the random walk on a unit sphere is written as follows:               rw =        With[{stepLength = 0.03, num = 10000},         Module[{rotateWithAxis, p, a, q},           rotateWithAxis[p_, a_, theta_] :=              #/Norm[#] &@((1 – Cos[theta]) (a.p) a + p Cos[theta] + Cross[a, p] Sin[theta]);           a = {1., 0, 0};           q = {Cos[stepLength], Sin[stepLength], 0};           Table[p = a; a = q; q = rotateWithAxis[p, a, RandomReal[{0, 2 Pi}]], {num}]]];


title: Definite Integral over a path

text: What does               Integrate[f[z], {z, a, b, c, d}]      exactly calculate? Is it $$\int_a^b f(z)\, \mathrm{d}z +\int_b^c f(z)\, \mathrm{d}z +\int_{c}^d f(z)\, \mathrm{d}z ?$$ That was my first idea but               Integrate[f[z], {z, a, b, a}]      isn't simplified to 0 (even with a `FullSimplify`). For example                  Integrate[1/z, {z, 1, I, -1, -I, 1}]      gives as result $2\cdot \pi \cdot i$, which is the value of any closed path around zero. Which path does it take in the complex plane? Because there has been an Integral, where I thought it would converge, but I got an error with this one.


title: Select record when third column matches certain criterion

text: I've a table with 3 columns. The table looks like this:               test = {       {"john", {"suzan", "jan"}, {"new", "job", "policies"}},        {"carla", {"john", "piet"}, {"route", "suggestion"}},        {"jan", {"john", "suzan"}, {"re", "new", "job", "policies"}},        {"john", {"piet", "carla"}, {"re", "route", "suggestion"}}}      I would like to select the records with has no `re` in the third column. When I select the third column like this:               test1 = Select[test[[All, 3]], #[[1]] != "re" &]      The result is: > >     {{"new", "job", "policies"}, {"route", "suggestion"}} >   But I want to select also the columns one and two. When I write:               Select[test[[All, {1, 2, 3}]], #[[3]] != "re" &]      The result is empty > >     {} >   Who has a suggestion to solve this?


title: GPU user experiences

text: **Edit** Thanks to all who have responded! I now have plenty of information on the GeForce 650M GPU as found in most new, mid-range Mac laptops; the Mandelbrot code below runs in comfortably under a tenth of a second. I'm still quite curious how that compares to the GeForce 675MX GPU, which comes in new, high end iMacs. If someone provides that information as an answer, I'll happily accept! * * * **Original** When V8 came out, I was very excited about the introduction of GPU support. So far, however, I've not really been able to take advantage of it the way I would like to, simply because I haven't had a computer with an adequate GPU. Even when CUDA and/or OpenCL are supported, one might not see significant gains when using the GPU due (I think) to limited block size. Well, now it appears that I'll be getting a new computer in the not so distant future and I'd like to make sure that I'm happy with the GPU. To that end, I wonder if I could receive some feedback on actual user experiences. I am specifically interested in how CUDA and OpenGL work with midline Mac Laptops and Desktops. Laptops seem to run NVIDIA GeForce 640M or 650M GPUs, while desktops are more flexible going up to the 675 or higher in iMacs. So, does CUDA run on these machines? Specifically, does at least the following return True:               (* Warning - a large package is loaded from Wolfram Research *)     Needs["CUDALink`"];     CUDAQ[]          (* Out: False *)      I am aware, of course, of the systems requirements documentation here: http://reference.wolfram.com/mathematica/CUDALink/tutorial/Reference.html#1803279895 That page indicates that CUDA does _not_ run on 600 level GeForce GPUs, but I have a hard time believing that CUDA still is not running on main-line Macs at this point. Furthermore, NVIDIA's information seems to conflict with this here: https://developer.nvidia.com/cuda-gpus Hence, the question. * * * Also, I wonder if folks wouldn't mind trying a little test - say, generate a Mandelbrot set, since I'm quite curious about the relative speed of GPUs as accessed through Mathematica. To that end, here's a simple OpenCL program that generates escape times counts to generate a Mandelbrot image. Note that the `blockSize` parameter can be changed. I'm not an expert on GPU programming, but I believe that higher end GPUs generally allow higher block sizes and that larger block sizes permit more parallelization. My computer allows a `blockSize` of 16 or lower; lowering the `blockSize` generally slows down the computation.               Needs["OpenCLLink`"];     blockSize = 16;     code = "       __kernel void mandel_kernel(__global Real_t *mSet, int xRes, int yRes,           Real_t xMin, Real_t xMax, Real_t yMin, Real_t yMax) {          int xIndex = get_global_id(0);          int yIndex = get_global_id(1);          int i;               Real_t cx = xMin + xIndex*(xMax-xMin)/xRes;          Real_t cy = yMin + yIndex*(yMax-yMin)/yRes;          Real_t x = cx;          Real_t y = cy;          Real_t tmp;               if (xIndex < xRes && yIndex < yRes) {              for (i = 0; i < MAX_ITERATIONS && x*x + y*y <= BOUND_SQUARED; i++) {                 tmp = x*x - y*y + cx;                 y = 2*x*y + cy;                 x = tmp;             }             mSet[xIndex + yIndex*yRes] = i;           }       }       ";     If[OpenCLQ[] === True,       mandelCalculate = OpenCLFunctionLoad[code, "mandel_kernel", {{_Real, _, "Output"},          _Integer, _Integer, _Real, _Real, _Real, _Real}, {blockSize, blockSize},          "Defines" -> {"MAX_ITERATIONS" -> 100, "BOUND_SQUARED" -> "4.0"}],       Print["I'm sorry, your computer is even lamer than Mark's!"]     ];      Assuming your computer actually passes the test, the following will actually run the program for an `xRes` by `yRes` square.               xRes = 1500; yRes = 1500;     (mSet = OpenCLMemoryAllocate[Real, {xRes, yRes}];      mandelCalculate[mSet, xRes, yRes, -2.0, 0.6, -1.3, 1.3];      data = OpenCLMemoryGet[mSet]); // AbsoluteTiming          (* Out: {0.065236, Null} *)      Yeah, that's pretty fast. The computation was performed on the following GPU.               "Renderer" /. ("OnScreen" /. ("OpenGL" /.       SystemInformation["Devices", "GraphicsDevices"]))          (* Out: "ATI Radeon HD 6750M OpenGL Engine" *)      Again, the point is to compare GPUs but, if you want to generate an image, here's one way to do so:               colors = Map[{(100 - #)^2/10000, (100 - #)^3/1000000, (100 - #)/100} &, data, {2}];     Image[colors]          (* Out: Groovy picture *)


title: How to partition a list according to a nested table structure?

text: This question is related to this quesion. The goal is to use `ParallelMap` to map a function to a nested `Table` to get the FinestGrained distribution of calculation. But after that, I want to recover the original nested data structure instead of a flat one. For example, say I have a nested `Table` like this               Table[      Table[{line, honeycombnum, distance}, {line, 1,         honeycombnum + 1}, {distance, 1, 4}], {honeycombnum, 2, 5}]      as you can see, this nested table structure is **not of equal length** . Then **what is the general way** to recover the data structure after using               ParallelMap[f[#[[1]], #[[2]], #[[3]]] &, Flatten[Table[        Table[{line, honeycombnum, distance}, {line, 1,           honeycombnum + 1}, {distance, 1, 4}], {honeycombnum, 2, 5}], 2], Method -> "FinestGrained"]      **By the word "general ", I mean the method should be suitable for arbitrary complex`Table` structure.**


title: Problem with adding vector to symbolic function (for NDSolve)

text: I'm trying to set up a system of differential equations for passing to NDSolve. Note that my initial conditions are vector valued so Mathematica _should_ know that `raptor[[i]]` is a vector valued function. However, Mathematica seems to think that that `raptor[[i]]` is a scalar valued function (this is indicated by my output, which is included below). Input:               human[\[Theta]_, t_] := 0 t*{Cos[\[Theta]], Sin[\[Theta]]} + {0, 10 Sin[\[Pi]/3]}          V = {25, 10, 25};     P = {{-10, 0}, {0, 20 Sin[\[Pi]/3]}, {10, 0}};     \[Theta] = 0;           Flatten[       Table[       {        raptor[[i]]'[t] == Normalize[human[\[Theta], t] - raptor[[i]][t]]        raptor[[i]][0] == P[[i]]       }, {i, 3}]      ]      Output:               { Raptor[[1]]'[t]=={ first component of human - raptor[[i]][t],                          second component of human - raptor[[i]][t]},       Raptor[[1]][0] =={-10,0},        Raptor[[2]]'[t]== ...      }      Furthermore, changing the raptor indexes into subscripts does not change anything. When I try to use this system in NDSolve I get the error "Computed derivatives do not have dimensionality consistent with the initial conditions." After talking to my TA for the course, we got this to work by defining `human[theta, t]` as one of the differential equations. However, my TA didn't know why my code failed (it seemed very reasonable to both of us) and said I could ask the Mathematica stack exchange. So, could anyone explain why my code fails? Namely, why does Mathematica think that `raptor[[i]]` is a scalar valued function even though its initial condition is clearly vector valued? Is there a better way to do this then putting `human[theta, t]` into the list of equations for NDSolve? PS: for those wondering, this is solving a variant of problem #2 from http://xkcd.com/135/