title: Getting mesage: Set::setps assignment is not a symbol

text: Please, tell me what is the issue with the following code?               Dimensions[Subscript[R, 2]]      > >     {201, 161, 53} >                 Table[       If[Subscript[R, 2][[x, y, z]] != 2, Subscript[R, 2 ][[x, y, z]] = 0],        {x, 1, 201}, {y, 1, 161}, {z, 1, 53}];      I am getting this error: > Set::setps: Subscript[R, 2] in the part assignment is not a symbol. >>


title: Save a sequence of images using table with 2D variables

text: How can I save a sequence of images with 2D variables using `Table`. I get a > Iterator {r,{-1,-1},{1,1},{0.1,0.1}} does not have appropriate bounds. >> error when I evaluate the following piece of code.               pgrid =        Graphics[Flatten[Table[Point[{i,j}], {i, -2, 2, 0.1}, {j, -2,2, 0.1}]],          Axes-> True, AxesOrigin -> {-2, -2}, PlotRange -> {{-2, 2}, {-2, 2}}] ;          dat1 =       Table[         Show[          pgrid,           Graphics[{            {Yellow, Opacity[0.5], Disk[{r[[1]] + q[[1]], r[[2]]+ q[[2]]}, 0.85]},             Circle[{0, 0}, 0.85],             {Dashed, Circle[{0, 0}, 1.7]},             {Blue, Thick, Arrow[{{0, 0}, {r[[1]], r[[2]]}}]},            {Red, Thick, Arrow[{{0, 0}, {q[[1]], q[[2]]}}]},             {Blue,Thick, Arrow[{{q[[1]], q[[2]]}, {r[[1]] + q[[1]], r[[2]] + q[[2]]}}],              Green, Arrow[{{0, 0}, {r[[1]] + q[[1]], r[[2]] + q[[2]]}}]},            {Purple, Thick, Circle[{q[[1]], q[[2]]}, 0.85]}}]],       {r, {-1, -1}, {1, 1}, {0.1, 0.1}}, {q, {-2, -2}, {2, 2}, {0.1, 0.1}}];          SetDirectory @ NotebookDirectory[]     Export["gif.gif", dat1]


title: What is the correct syntax for setting up a simulation using a system of ODEs?

text: sys = {m x''[t] == s ω y'[t] - h (x'[t])^2,             m y''[t] == s ω y'[t] - h (y'[t])^2 - m g,             x'[0] == xdo, x[0] == 0,             y'[0] == ydo, y[0] == 0 };          parms = {m = .0459, s = .1, ω = 100 π, g = 9.8};     ics = {xdo = V Cos[θ], ydo = V Sin[θ], V == 61.69, θ = 12 °};     sol = NDSolve[sys /. parms //. ics, {x[t], y[t]}, {t, 0, 4}];     ParametricPlot[{x[t], y[t]} /. sol, {t, 0, 4}, PlotRange -> All]      I am brand new to _Mathematica_ and have been watching numerous tutorials and still cannot get anywhere. My code simulates a golf ball flight in 2 dimensions. I am not interested in the algebraic solution at all, but rather with the parametric plot. When I enter this code I get numerous errors. I have multiple other variations of these equations that I also need to plot, but I am starting with the simplest of these with no luck at all. I am sure this is not even close to what I need, so I am hoping someone with more experience in _Mathematica_ will lend me some guidance in how to approach this.


title: Parallel computation of a system of differential equation

text: I need to solve a system of differential equations which contains, at minimum, ten thousands of differential equations. Actually, I am trying to solve density matrix equation. It's like something $ \frac{\partial}{\partial t}\rho(t) = \frac{-I}{\hbar}(H(t)\rho(t) -\rho(t)H(t)) $. If the dimension of Hilbert space is $N$, then there is $N^2$ coupled differential equations. I want to know if it is possible to solve this system of differential equations in parallel in Mathematica? My cpu has six cores, so I guess I can get a six times speed up, if I solve the equations in parallel.


title: How to solve this equation with integers as a solution?

text: I want to solve the equation $$x^y + y = y^x + x$$ with $x$, $y$ are integer numbers. I tried               Solve[x^y + y == y^x + x, {x, y}, Integers]      How to solve the above equation?


title: Is there something akin to "SubgraphIsomorphismQ" in Mathematica 9?

text: Provided two _unlabeled_ graphs, $G$ and $H$, I would like to test where $H$ is a subgraph of $G$. In other words, I'd like to test whether we can prune some fixed number of vertices or edges from $G$ to transform it into the graph $H$. Is there an implementation for something like this in _Mathematica_ 9, or perhaps available elsewhere? Efficiency, within reason, doesn't matter too much to me. NOTE - I can somewhat tolerate false-positives, but no false negatives.


title: Sqrt -- how to get negative branch?

text: One of the many attractions of Mathematica is that integers are generally treated as exact symbolic entities, and not just as numbers. I was just playing with Sqrt, and was puzzled by what appeared to me to be an inconsistency that must have been there since day 1, and yet which I have somehow not noticed before. This works as expected:               Sqrt[x^2]     Sqrt[x^2]      so that this evaluates correctly:               Solve[y == Sqrt[x^2], x]     {{x -> -y}, {x -> y}}      But, if I enter exact integers, only the positive branch solution is returned:               Sqrt[9]     3      and so:               Sqrt[(-3)^2]     3      * * * In Summary: The various comments below make it clear that the Sqrt function:   * only ever returns the positive branch, by design.    * Sqrt[x^2] is left unevaluated, so that the positive branch can be selected with appropriate assumptions, as per: Simplify[ Sqrt[x^2], x<0] -> -x This leaves the prevailing issue: Is there perhaps a variant of Sqrt (or option) that gives both solutions that I have missed? Why does there not seem to be a function in Mathematica that returns the mathematically rigorous solution set {negative branch, positive branch} ... rather than just returning the positive branch that seems to operate more like a 20thC pocket calculator? For example:               Sqrt[  Interval[{-2, 0}]^2 ]     -> Interval[{0, 2}]      ... is correct given how the Sqrt function is defined (to always return the positive branch), but most confusing given that we actually seek the set of possible solutions. Many thanks for the suggestions below! It would be nice to see something like this added to the Sqrt functionality in mma.


title: Is there a built in function to obtain the back diagonal of a matrix?

text: Given the following matrix:               m = Array[Subscript[a, #, #2] &, {4, 4}]      ![enter image description here](http://i.stack.imgur.com/AXtLK.png) how can I find the skew diagonal or anti-diagonal or back diagonal of the matrix (shown in red) ![enter image description here](http://i.stack.imgur.com/S3fUV.png)


title: Graphing time-series

text: I'm currently trying to use data gathered as a function of time (here, the fluorescence of a biological sample), but am new to _Mathematica_ and don't know how to properly specify axis relations (and units, etc.). Using ExcelLink 3.5, I've imported the data for one of many drugs whose effect on the fluorescence function I want to analyze. Because of how the information was imported, the listed data I've collected for $f(t)$ is in a list, with no reference to what the independent variable (x-axis) values should be. I made my plot with               ListPlot[{28,32,37,66}]      producing x-axis values of `{1, 2, 3, 4}` by default, and not t in minutes, which would be `{300, 600, 1200, 1440}` in my case). How can I make a plot with the proper x-axis values?


title: DSolve::overdet for system of linear PDEs

text: I would like to resolve symbolically the following equation:               DSolve[{c1[x, y] + c2[x, y] == 0,        D[c1[x, y], {x, 1}] == a*Sin[Pi*(y - 1/2)]*Cos[Pi*(y - 1/2)]^3,        D[c2[x, y], {y, 1}] ==        b*Sin[Pi*(x - 1/2)]*Cos[Pi*(x - 1/2)]^3}, {c1[x, y], c2[x, y]}, {x,       y}]      which should correspond to a system: $$ \begin{align} c_1\left(x,y\right)+c_2\left(x,y\right) & = 0\\\ \frac{\partial c_2}{\partial y} & = a\sin x\cdot\left(\cos x\right)^3 ,\\\ \frac{\partial c_1}{\partial x} & = b\sin y\cdot\left(\cos y\right)^3 \end{align} $$ but Mathematica gives me an error:               DSolve::overdet: There are fewer dependent variables than equations, so the system is overdetermined.      What is it so?


title: How can I eliminate a function in a system of PDEs, Maple-style?

text: Maple can separate and eliminate a function in a system of PDE equations, with `casesplit` in the `PDEtools` package. How to do that in Mathematica? Starting PDEs are: $$ -A\frac{\partial ^2Q(x,y)}{\partial x^2}+B\frac{\partial ^3P(x,y)}{\partial x^3}+C Q(x,y)-C\frac{\partial P(x,y)}{\partial x}+D\frac{\partial ^2Q(x,y)}{\partial y^2}=0 $$ $$ -B\frac{\partial ^3Q(x,y)}{\partial x^3}+E\frac{\partial ^4P(x,y)}{\partial x^4}-C \frac{\partial Q(x,y)}{\partial x}+C\frac{\partial ^2P(x,y)}{\partial x^2}-F\frac{\partial ^2P(x,y)}{\partial y^2}=0 $$ Maple code               des:= {-A*diff(Q(x,y),x,x)+B*diff(P(x,y),x,x,x)+C*Q(x,y)       -C*diff(P(x,y),x)+D*diff(Q(x,y),y,y)=0,       -B*diff(Q(x,y),x,x,x)+E*diff(P(x,y),x,x,x,x)-C*diff(Q(x,y),x) +       C*diff(P(x,y),x,x)-F*diff(P(x,y),y,y)=0};          PDEtools:-casesplit(des,[Q,P]);      Maple output is $$\left( -{B}^{2}+EA \right) {\frac {\partial ^{6}}{\partial {x}^{6}}}P \left( x,y \right) + \left( - D C-AF \right) {\frac { \partial ^{4}}{\partial {y}^{2}\partial {x}^{2}}}P \left( x,y \right) \+ \left( AC-CE \right) {\frac {\partial ^{4}}{\partial {x}^{4}}}P \left( x,y \right) + D F{\frac {\partial ^{4}}{ \partial {y}^{4}}}P \left( x,y \right) - D E { \frac {\partial ^{6}}{\partial {y}^{2}\partial {x}^{4}}}P \left( x,y \right) +CF{\frac {\partial ^{2}}{\partial {y}^{2}}}P \left( x,y \right) = 0 $$


title: Speed up MinimalPolynomial

text: My _Mathematica_ code runs slowly               MinimalPolynomial[Sqrt[2] + Sqrt[3]+ Sqrt[5]+ Sqrt[7]+ Sqrt[11]+ Sqrt[13], x]      runs slowly, but the Maple version               evala(Norm(convert(x-(sqrt(2)+sqrt(3)+sqrt(5)+sqrt(7)+sqrt(11)+sqrt(13)), RootOf)));      runs quite fast Is there a faster way do this in _Mathematica_?


title: How can I set up a versioning system within a notebook?

text: Since the Frontend crashes a lot, for important work it would be nice to have the notebook automatically branch and save itself every so many minutes. For instance, commands like StartSavingCopies[5] would save a copy with a new name "BackupFileNumberX.nb" every 5 minutes. How can we do this behind the scenes dynamically?


title: How can I highlight one function in the Plot of a list?

text: I've got a Plot of a list of functions from this previous question of mine.               rp[x_, r_] := 1000 x (r + 1)/(r + x)     ratios = Table[10^n, {n, -2, 2, 4/10}]     Plot[Map[rp[x, #] &, ratios], {x, 0, 1}, Evaluated -> True]        ![enter image description here](http://i.stack.imgur.com/S3qyq.png) Now I want the sixth function, where ratio = 1, to be plotted with a `PlotStyle -> AbsoluteThickness` parameter. How can I do this?


title: Importing CSV financial data in Mathematica

text: I am trying to import a CSV file in Mathematica 8 with the aim of charting it with the `TradingChart` command. This is what I have done :               Take[Import["EURUSD_2004.csv"] ] // TableForm     (*     {      {"DATE", "LOW", "MAX", "VOLUME", "OPEN", "CLOSE"},      {"1998.01.05", 1.0815, 1.0985, 0, 1.0834, 1.0834},      {"1998.01.06", 1.0795, 1.0875, 0, 1.08, 1.08},      {"1998.01.07", 1.0778, 1.0865, 0, 1.0842, 1.0842},      {"1998.01.08", 1.0792, 1.088, 0, 1.0844, 1.0844},      {"1998.01.09", 1.0823, 1.0926, 0, 1.0829, 1.0829},      {"1998.01.12", 1.0808, 1.09, 0, 1.0835, 1.0835},      {"1998.01.13", 1.083, 1.09, 0, 1.0858, 1.0858},      {"1998.01.14", 1.0812, 1.0859, 0, 1.0848, 1.0848},      {"1998.01.15", 1.0785, 1.0872, 0, 1.0789, 1.0789},      {"1998.01.16", 1.0787, 1.0838, 0, 1.0788, 1.0788},      {"1998.01.19", 1.0739, 1.0812, 0, 1.0772, 1.0772},      {"1998.01.20", 1.0733, 1.0779, 0, 1.075, 1.075},      {"1998.01.21", 1.0755, 1.0852, 0, 1.0849, 1.0849},      {"1998.01.22", 1.0849, 1.0962, 0, 1.0921, 1.0921},      {"1998.01.23", 1.0919, 1.1105, 0, 1.1088, 1.1088},      {"1998.01.26", 1.0919, 1.1203, 0, 1.0983, 1.0983}     } *)          TradingChart[EURUSD]     TradingChart::ldata: <<original data>> is not a valid dataset or list of datasets. >>      So the dataset is not in a valid form. Any hint on how to fix this ?


title: Non Linear Optimization

text: I want to `NMaximize` an expression for example, say $f(x_0,x_1,\dots)=x_0+x_1+2 x_2+...$ subject to the constraints $(x_1+x_1^2+x_2+x_3 x_1+...)/(x_0+x_0^2+x_1x_2+...)$ and there are a certain number of these constraints such that the constraints are $ \geq 0$ and also we know that $f(x_0,x_1,\dots)\geq0$. How do I do this??? Is there is literature available for these kinds of problems and even problems that are more complicated than this??. I have tried `NMaximize` and `NMinimize` for this problem and these do not give me the correct results that I expect. Further the `NMaximize`/`NMinimize` even says that no solution is found. How do I tackle such problems???


title: Select and Blank

text: I try to filter sublists of a list which match a pattern.               test = {{"String1", "a"}, {"String2", "b"}, {"String3",      "a"}, {"String4", "a"}};      The result should be:               result = {{"String1", "a"}, {"String3", "a"}, {"String4", "a"}}      That means the first entry should be any String and the second should be "a". I tried:               Select[test, (# == {_, "a"}) &]      Which evaluates to {}.


title: Reasoning about Degree of Polynomial

text: Apologies if this is outside of the realm of Mathematica -- I'm still trying to figure out the limits of how expressive Mathematica is (and how much of my work can be automated). Suppose I define the following:               f[1] = x     f[n_] = x * f[n-1]      Then, I want to ask:               for integral k>1, what is the degree of f[k] ?      so for example, I want to write a function:               degreeOf[f, k] = k      Now, I know that in this above example, given that we know how f is defined, it's trivial that degreeOf[f, k] = k. However, is it possible to write generic degreeOf ? In a sense, I'm curious if the "computational" part of mathematica -- it's ability to handle symbols and do substitutions + simplifications -- or if it can reason about them at a deeper level. Thanks!


title: Importing Data with Line feeds

text: I am trying to import data from a CSV file into Mathematica that contains _line feeds_ in certain elements that I wish to be properly rendered in Mathematica. I suppose this has something to do with the type of form (InputForm, StandardForm, etc.) that Mathematica uses on and after import. I know I am missing something fundamental but have not found it yet. I do not want the solution to this problem to contain any Mathematica code in the CSV file. Lets take graph labels as an example. ![enter image description here](http://i.stack.imgur.com/pzGL6.png) I would like one vertex label to have _two_ on the first line and _deux_ on the second line. I have tried entering the data in various ways with no success. Here is what I have tried.   1. two[LineFeed]deux **Result** : is shown above. There IS a linefeed but the control code name is also rendered.   1. two\ndeux **Result** : No line feed at all. ![enter image description here](http://i.stack.imgur.com/kh4nw.png)   1. two.0Adeux (i.e. using hexadecimal code) Result: Same as [NewLine], get the line feed but the hex code is printed too. Thanks in advance for your help. Jeff Lapides


title: Find radii of concentric circles in image

text: I have an image of concentric circles, I would like to find the radii of the circles (only the innermost few are important). I've had a go using what I could find in previous posts, but am a bit confused about which method I should be using - if I need MorphologicalComponents, or whether to use SelectComponents "count" or "equivalentradius", or colornegate etc. Sometimes the circles are broken (especially when I binarize), so I need to look for incomplete circles too.. So far I have:               i = Import["http://i.imgur.com/oTTM9MG.jpg"];     b = Binarize[i, {0.3, 1}];     m = MorphologicalComponents[b];     c = SelectComponents[m, {"Count", "Holes"},         1000 < #1 < 20000 && #2 > 0 &] // Colorize     ComponentMeasurements[c, {"Centroid", "EquivalentDiskRadius"}]      or, using :               i = Import["http://i.imgur.com/oTTM9MG.jpg"];     disk = ColorNegate[Binarize[i, {0.3, 1}]];     rings = ComponentMeasurements[        disk, {"Centroid", "EquivalentDiskRadius"},         450 <= #1[[1]] <= 550 && 325 <= #1[[2]] <= 375 &&           10 <= #2 <= 500 &];     Show[{disk,        Graphics[{{Red, Circle[rings[[1, 2]][[1]], rings[[1, 2]][[2]]]}}]}]      Am I making it harder than it is? Could someone bump in the right direction? both this, How to find circular objects in an image? and this, Finding the centroid of a disk in an image were helpful (but I need to expand it to multiple circles and fit partial circles). Any help would be appreciated. Thanks! ![enter image description here](http://i.stack.imgur.com/wAPnJ.png)


title: Importing array with complex numbers

text: This is probably an easy question: I am exporting the results from a longer calculation into a dat-File, then I set the cell to non-evaluatable and put an Import in front, so I can later work with the results, even after closing and reopening the notebook:               results = Import["results.dat"]          (non-evaluatable) results = makeLongCalculation[parameters]     (non-evaluatable) Export["results.dat",results]          doSomethingwithResults[results]      (Is there a more elegant way?) Now, I have the problem that complex numbers are imported as strings. My results are typically of the form {{0.01,3*10^-6+5*10^-4*I},...}. Is there any more straightforward way than to apply something like ToExpression to the Import? I feel that native Mathemat


title: Proper way to Plot a single function in two different styles?

text: I've got this code               Plot[{(V^2/360)/0.4,  ConditionalExpression[(V^2/860)/0.4, V < 12],        ConditionalExpression[(V^2/860)/0.4, V > 12]}, {V, 8, 18},        PlotRange -> {0, 1.5},       PlotStyle -> {{AbsoluteThickness[3]}, {AbsoluteThickness[3],          Dashed}, { AbsoluteThickness[3], ColorData[1, 2]}},       GridLines -> Automatic,       Epilog -> {{Thick, Dashed, Black, Line[{{12, 0}, {12, 2}}]}, {Thick,          Dashed, Black, Line[{{8, 1}, {18, 1}}]}}]       to plot a function in two pieces, each in a different style: ![enter image description here](http://i.stack.imgur.com/Gaezk.png) This works OK for me, though I didn't like it that I had to use `ColorData[1, 2]` to get the second part in the same color. Are there better ways to do this (possibly something with `Piecewise`)?


title: Effect of Block[] on iterators in Manipulate[]

text: The following is a toy example that hopefully shows the problem clearly enough. Why does the following code create a nice, manipulable output:               simulationOutput = {1337, 2337, 30, 3337};     Clear[tmax]     {irrelevantOutput1, irrelevantOutput2, tmax, irrelevantOutput3} = simulationOutput;     Manipulate[      Plot[t^2, {t, startTime, endTime}],      {startTime, Manipulator[Dynamic[startTime, (startTime = Min[tmax - 1, #];             endTime = Max[endTime, Min[# + 1, tmax]]) &], {0, tmax}] &},      {endTime, Manipulator[Dynamic[endTime, (endTime = Max[1, #];             startTime = Min[startTime, Max[0, # - 1]]) &], {0, tmax}] &},       Initialization :> ({startTime, endTime} = {0, 1})]      ![enter image description here](http://i.stack.imgur.com/rcqHE.png) But this (almost identical) code, with the additional Block[],               simulationOutput = {1337, 2337, 30, 3337};     Clear[tmax]     Block[{irrelevantOutput1, irrelevantOutput2, tmax, irrelevantOutput3},       {irrelevantOutput1, irrelevantOutput2, tmax, irrelevantOutput3} = simulationOutput;     Manipulate[      Plot[t^2, {t, startTime, endTime}],      {startTime, Manipulator[Dynamic[startTime, (startTime = Min[tmax - 1, #];             endTime = Max[endTime, Min[# + 1, tmax]]) &], {0, tmax}] &},      {endTime, Manipulator[Dynamic[endTime, (endTime = Max[1, #];             startTime = Min[startTime, Max[0, # - 1]]) &], {0, tmax}] &},       Initialization :> ({startTime, endTime} = {0, 1})]]      result in this, un-manipulate-able output? ![enter image description here](http://i.stack.imgur.com/aBZ6a.png) If you're interested, the background behind my question is as follows. I have a simulation of a system of oscillators. The behavior of this system is then studied by providing initial conditions, then using NDSolve to find the behavior from `t=0` to `t=tmax`. The output of the simulation (as `simulationOutput`) is then fed into a function (of which the following is a simplified example) so that I can see the results - this is the reason why I'm limiting the range of times in which the `startTime` and `endTime` can vary in to keep the values in the range of the `InterpolatingFunction`.


title: Solution for equation system with piece-wise defined functions

text: As I could swear this worked just yesterday, I am probably just doing something stupid here and I am sorry to bother you :) I am trying to find the point where a curve crosses a line. In this case, the curve is a box, but it should work for other things, too, so I need to find the problem here, not better ways for a solution for boxes.               boxCurve[boundaries_List] := Module[{b = boundaries, bH, bW, cf},       bH = b[[2, 2]] - b[[2, 1]];       bW = b[[1, 2]] - b[[1, 1]];       cf = 2 bH + 2 bW;       Function[t, Piecewise[{          {{b[[1, 1]] + cf t, b[[2, 1]]}, 0 <= cf t < bW},          {{b[[1, 2]], b[[2, 1]] + (cf t - bW)}, bW <= cf t < bW + bH},          {{b[[1, 2]] - (cf t - bW - bH), b[[2, 2]]},            bW + bH <= cf t < 2 bW + bH},          {{b[[1, 1]], b[[2, 2]] - (cf t - 2 bW - bH)},            2 bW + bH <= cf t < 2 bW + 2 bH}          }, {b[[1, 1]], b[[2, 1]] + bH/4}]]       ]      The box does work `ParametricPlot[boxCurve[{{-1, 1}, {-1, 1}}][s], {s, 0, 1}]` But, when I am trying to calculate the crossing point               Solve[boxCurve[{{-1, 1}, {-1, 1}}][s] == {-1, 1} + {1, -1} t, {s, t}]     Solve[boxCurve[{{-1, 1}, {-1, 1}}][s] == {-0.9, 1} + {1, -1} t, {s, t}]     Solve[boxCurve[{{-1, 1}, {-1, 1}}][s] == {0, 0} + {1, 0} t, {s, t}]      I get no result, although two of the base points of the lines are already on the box. This is true for both `NSolve` and `Solve`. As said I could swear that something like this worked yesterday, because I got conditional expressions depending on s, when I only solved for t.


title: speed up iteration with conditionals plus optimize memory usage

text: Given `list1` and `list2` whose elements are vectors of a certain (fixed) dimension, I am interested in the behaviour of a scalar function `cfn[list1[[i]],list2[[j]]]`. As I defined it this function outputs for me a list of entries formatted as `{list1[[i]], list2[[j]], scalar}` since I would also like to keep track of which vectors the scalar number came from. The fastest way to generate such a list is of course to use Outer to map my function over the two lists               Outer[cfn[#1 ,#2]&, list1 ,list2,1]       However this will produce for me a complete list of values for the function after scanning through my lists and since my lists are very long the process is long and I run out of memory if I increase the dimension (typically `list1*list2` is a function also of the fixed dimension and I seem to be fine doing order of 10 million computations). If I am uninterested in all the function values, but say only those in a certain range `cmin < cfn[list1,list2] < cmax` is there an efficient way to scan the lists and pick out just these?   I tried the obvious nested For loops and as expected ended up slowing down the computation significantly. Thanks! Edit: As requested in the comments I am attaching a simplified version of my code which only computes the inner product of the two vectors after some redefinitions. `n` is a number that we specify and `list1` and `list2` are lists whose entries are integer valued vectors of length `(n-1)` e.g., `list1[[1]] = {0, 0, 0, 4}` etc.               cfn[list1_List, list2_List, n_] := Module[{rhow},          rhow = Table[1, {i, 1, n - 1}];              Lambda = list1 - list2 + rhow;      hdim = Lambda.Lambda;          Return[{list1, list2, hdim}]];           Timing[data = Flatten[Outer[cfn[#1 , #2, n] &, list1 , list2, 1], 1];            selectdata = Select[data, cmin < #[[3]] < cmax &];]      The second code which nests the For loops:               rhow = Table[1, {i, 1, n - 1}];     sampledataAlt[list1_List, list2_List, n_] := Module[{},                 sampledata2 = {};                 For[i = 1, i <= Length[list1], i++,                 For[j = 1, j <= Length[list2], j++,                     Lambda = list1[[i]] - list2[[j]] + rhow;                     hdim  = Lambda.Lambda;                     If[cmin < hdim < cmax,       dataNEW = {list1[[i]], list2[[j]], hdim}, dataNEW = {}];                     sampledata2 = Join[sampledata2, dataNEW];]];                     Return[sampledata2];]      Timing[test = Partition[sampledataAlt[list1, list2, 5], 3];]      where I have made some list manipulations to split things up. For my trial with `Length[list1] = 126` and `Length[list2] = 210` the second code is marginally faster, but it slows down when I increase the list sizes.


title: Error message concerning Graphics`Colors`

text: f[x_] = Sin[x];     x0 = 0;     a = -3 π;     b = 3 π;     c = -1.3;     d = 1.3;     a0 = -10;     b0 = 10;     Needs["Graphics`Colors`"];     Cdot = Graphics[{{Red, PointSize[0.02], Point[{x0, f[x0]}]}}];     Rends = Graphics[{{Green, Line[{{a0, c}, {a0, d}}]}, {Red,           Line[{{x0, c}, {x0, d}}]}, {Green, Line[{{b0, c}, {b0, d}}]}}];     For[n = 2, n <= 5, n++,      P[x_] = Normal[Series[f[x], {x, x0, 2 n + 1}]];      graph = Plot[{f[x], P[x]}, {x, a, b}, PlotStyle -> {Magenta, Blue},         PlotRange -> {{a, b}, {c, d}},         Ticks -> {Range[-3 π, 3 π, π], Range[-0.5, 1, 0.5]},        DisplayFunction -> Identity];      Show[graph, Cdot, Rends,        DisplayFunction -> $DisplayFunction];      Print["f[x] = ", f[x], "\n", "P[x] = ", P[x]];]      When I evaluate the above code, I get the following message. > Get::noopen: Cannot open Graphics`Colors`. >> What is wrong with this code? Please help me.


title: Solve[] unexpectedly giving empty solution sets for extremely large problems

text: I was calculating the set of lattice vectors in $\mathbb{Z}^4$ which have taxicab norm $r$. For example, executing               Solve[Abs[c1] + Abs[c2] + Abs[c3] + Abs[c4] <= 2, {c1, c2, c3, c4}, Integers]      yields the 41 lattice vectors of taxicab norm 2 or less. This works fine up through $r=19$, at which point there are 97,281 solutions. However, at $r=20$,               Solve[Abs[c1] + Abs[c2] + Abs[c3] + Abs[c4] <= 20, {c1, c2, c3, c4}, Integers]      simply returns {{}}. According to the documentation, Solve[] yields {{}} "if the set of solutions is full-dimensional", which is clearly not the case for the above, which has a finite, though large, number of solutions. Also, as far as I could tell, nowhere in the documentation does it specify that there is a cap on the number of possible solutions. Question: _Is there are a reason for this? And is there a way to coax Solve[] into returning the correct answer?_ I know of the obvious though tedious mathematical tricks for reducing the problem into several lower-dimensional problems, but I'd like to solve it directly if possible.


title: Memory leak issues

text: I am working with noncommuting objects and basically I am using Mathematica to sort large expressions by normal ordering and simplifying them. To this end, I first create an object called `Boson` (These satisfy $[a,a^\dagger]=1$):               Clear[Boson, BosonC, BosonA]     Boson /: MakeBoxes[Boson[cr : (True | False), sym_], fmt_] :=      With[{sbox = If[StringQ[sym], sym, ToBoxes[sym]]},      With[{abox =       If[cr, SuperscriptBox[#, FormBox["\[Dagger]", Bold]], #] &@sbox},     InterpretationBox[abox, Boson[cr, sym]]]]     BosonA[sym_: String "a"] := Boson[False, sym]     BosonC[sym_: String "a"] := Boson[True, sym]      Next I alias the noncommutative product with `CenterDot` as follows:               Unprotect[NonCommutativeMultiply];     Clear[NonCommutativeMultiply, CenterDot];     CenterDot[a__] := NonCommutativeMultiply[a];     NonCommutativeMultiply /:      MakeBoxes[NonCommutativeMultiply[a__], fmt_] :=      With[{cbox = ToBoxes[HoldForm[CenterDot[a]]]},      InterpretationBox[cbox, NonCommutativeMultiply[a]]]     Protect[NonCommutativeMultiply];     Clear[CRule]     CRule = {NonCommutativeMultiply[a_] :> a};      Then I define the `Function` `clean` which does the normal ordering. It is defined in terms of `expand`. The main definition for `expand` is               ClearAll@expand     SetAttributes[expand, HoldAll]          Unevaluated[       expand[expr_] :=        Block[         {NonCommutativeMultiply (*or times*)},              expr //. (*ReplaceRepeated instead of ReplaceAll*)          {times[left___, cnum_ /; FreeQ[cnum, (_Boson)],              right___] :> cnum*times[left, right],            times[left___,              cnum_ /; (! FreeQ[cnum, Times[n___?NumericQ, ___Boson]]),              right___] :>             Times @@ Apply[Power, Drop[FactorList[cnum], -1], 2]*             times[left, First[Last[FactorList[cnum]]], right],            times[left___, Boson[False, s_], Boson[True, s_], right___] :>             times[left, right] +              times[left, Boson[True, s], Boson[False, s], right],            times[left___, fst : Boson[_, s_], sec : Boson[_, t_],              right___] :>             times[left, sec, fst, right] /;              FreeQ[Ordering[{s, t}], {1, 2}], times[b_Boson] :> b,           times[] -> 1           }         ]       ] /. {HoldPattern[times] -> NonCommutativeMultiply }      More definitions for expand are               expand[Alternatives[NonCommutativeMultiply, CenterDot][     a1_, (a2_ + a3_)]] := expand[a1 ** a2] + expand[a1 ** a3]     expand[Alternatives[NonCommutativeMultiply, CenterDot][(a1_ + a2_),      a3_]] := expand[a1 ** a3] + expand[a2 ** a3]      Finally, the definition of `clean` is               Clear[clean]     clean = Simplify[FixedPoint[expand, Distribute //@ #] //. CRule] &;      This has been working very well for computing quartic terms but now the problem is that I am computing higher order terms which can involve products of up to 16 oscillators. When I use the `clean[]` function on those terms, the computation goes okay for a while but then the kernel starts using pretty much all the memory and it just stops doing anything else and I have quit the kernel. I am assuming that the `Module[]` function is not deleting the temporary variables and is leaking memory. I tried setting `$HistoryLength=0` but that didn't help either. What else can I do prevent this? **Update:** I think the problem is in the implementation of `FixedPoint` in `clean`. If I manually apply `expand` and `Distribute` and then clear the cache and keep doing it till the computation doesn't take long (I take that as an indication that not much is changing), then I can finish the computation. This is a "dirty" fix but it would be nice to know if there is a way I can implement clearing the cache in `clean` along with `FixedPoint`. **Update:** The data in one of the computations became so large that I kept running out of memory for everything and I had to keep dividing the expression into smaller and smaller parts to the point where it became hard to manage. Could be just that expressions are too big and I just don't have enough memory? Also edited the last block of code to remove a stray piece of code. **Update:** Here is the full working notebook in pastebin.


title: What algorithm and tools should I use to search a data set for the point nearest to a given point?

text: I have about 1,000,000,000 points, which are the longitudes and latitudes of some places in a city, formatted like this: $(106.1231233,41.43234234)$. I also have about 20,000 points which are the longitudes and latitudes of some special places in this city. For every item in the 1,000,000,000 point data set, I have to compute which point in the 20,000 point data set is the nearest. If I were to compute on a brute-force, one by one basis, it might not complete during my lifetime. Is there an algorithm which can make this job less time-consuming? Can anyone help me?


title: Reduce[] giving incorrect result for equation over $\mathbb{Z}^4$

text: This is partially in response to a question I posted earlier, although the problem in this case appears to be distinct from the problem there, so I am temporarily filing this as a separate question. Executing               Length[Reduce[Abs[c1] + Abs[c2] + Abs[c3] + Abs[c4] <= 19, {c1, c2, c3, c4}, Integers]]      yields 97281, which is in full agreement with the result obtained when `Reduce` is replaced by `Solve`. However, executing               Length[Reduce[Abs[c1] + Abs[c2] + Abs[c3] + Abs[c4] <= 22, {c1, c2, c3, c4}, Integers]]      yields 42736. This is obviously impossible, since the number of $\mathbb{Z}^4$ lattice points within a taxicab ball is a strictly increasing function of radius. Does anyone know what is going wrong here? I am going to temporarily solve the problem via alternate, more delicate approaches seeing as both `Solve[]` and `Reduce[]` have failed to give correct answers for $r\geq20$, but any insight as to this sudden behavioral discontinuity would be appreciated. EDIT: It may be possible that the lower than expected result from `Length` may be due to `Reduce` outputting a solution set whose expression depth was not just that of the simple `Or[...]` structure that it normally gives for smaller values of $r$. If anyone can confirm this, I'll close this question.


title: Difference (or intersection) of two convex polyhedra

text: I have two convex polyhedra stored in the following form: a set of vertices `vertices = {{x1,y1,z1},...}`, a set of faces, where each face is a convex polygon specified by the ordered list of the numbers of its vertices. For example,               vertices1 = {{-1, -1, -1}, {-1, -1, 1}, {-1, 1, -1}, {-1, 1, 1}, {1, -1, -1}, {1, -1, 1},                   {1, 1, -1}, {1, 1, 1}};     vertices2 = {{-(1/2), -(1/2), -(1/2)}, {5/6, -(7/6), 5/6}, {-(7/6), 5/6, 5/6},                   {1/6, 1/6, 13/6}, {5/6, 5/6, -(7/6)}, {13/6, 1/6, 1/6}, {1/6, 13/6, 1/6},                   {3/2, 3/2, 3/2}};     faces = {{5, 6, 8, 7}, {1, 2, 4, 3}, {3, 4, 8, 7}, {1, 2, 6, 5},               {2, 4, 8, 6}, {1, 3, 7, 5}};      These are just two cubes, one of them rotated and translated. They can be visualized by `GraphicsComplex`:               Show[{Graphics3D@GraphicsComplex[vertices1, Polygon /@ faces], Graphics3D@GraphicsComplex[vertices2, Polygon /@ faces]}]      ![Mathematica graphics](http://i.stack.imgur.com/gghW2.png) I need to find a way to calculate the exact coordinates of the vertices for the concave polyhedron that is the difference of these two ($P_1\setminus P_2$ or $P_2\setminus P_1$), which, I guess, is almost equivalent to finding their intersection. Obviously, in my example the difference consists of several polyhedra, not one, but the idea is still the same -- this is just a set of faces stored as lists of numbers of vertices. The output has to have the same form as the input. The algorithm has to be applicable to any pair of convex polyhedra. Edit: one interesting case is when the polyhedra do not even contain any of each other's vertices:               `vertices1 = {{-1, -1, -1}, {-1, -1, 1}, {-1, 1, -1}, {-1, 1, 1}, {1, -1, -1}, {1, -1, 1}, {1, 1, -1}, {1, 1, 1}};`     `vertices2 = {{-(1/2) - 1/Sqrt[2], -(1/2) + 1/Sqrt[2],0}, {-(1/2) + 1/Sqrt[2], -(1/2) - 1/Sqrt[2], 0}, {1/2 - 1/Sqrt[2], 1/2 + 1/Sqrt[2], Sqrt[2]}, {1/2 + 1/Sqrt[2], 1/2 - 1/Sqrt[2], Sqrt[2]}, {1/2 - 1/Sqrt[2], 1/2 + 1/Sqrt[2], -Sqrt[2]}, {1/2 + 1/Sqrt[2], 1/2 - 1/Sqrt[2], -Sqrt[2]}, {3/2 - 1/Sqrt[2], 3/2 + 1/Sqrt[2], 0}, {3/2 + 1/Sqrt[2], 3/2 - 1/Sqrt[2], 0}};`     `Show[{Graphics3D@GraphicsComplex[vertices1, Polygon /@ faces], Graphics3D@GraphicsComplex[vertices3, Polygon /@ faces]}]`      ![enter image description here](http://i.stack.imgur.com/BcQ9M.png)


title: Slow work of SQLInsert with SQLite

text: I want to store my data in `SQLite` database, but writing large numbers of data its too slow. For example:               db = JDBC["SQLite", "f:\\test1.db"];     conn = OpenSQLConnection[db];     SQLCreateTable[conn,        SQLTable["TEST"], {SQLColumn["COL1", "DataTypeName" -> "INTEGER"],         SQLColumn["COL2", "DataTypeName" -> "DOUBLE"]}];     SQLInsert[conn, "TEST", {"COL1", "COL2"},         RandomReal[{-10, 10}, {100, 2}]]; // AbsoluteTiming     (*{11.814676, Null}*)      Inserting 100 lines of data take more than 10s on my PC, but when I use `SQLite Database Browser` (external software) for creating table with more than `80000` lines its take less than 1 minute. Why inserting from `Mathematica` so slow? **EDIT** But `HSQL` much more faster 3.5s for `80000` lines


title: When to use GenerateConditions -> True

text: Many functions, usuallly those involving integration, take a `GenerateConditions` option which often defaults to `False`, or at least it does for `Expectation` and and the Fourier transform related functions.   In what situations should the default be changed? What are the pros and cons?


title: Using the mouse coordinates to index a matrix

text: I would like to "write" on to a matrix using the mouse. That is, I would like to use the integer value of Locator coordinates (p) to index a matrix. Then, if the mouse button is down, write a 1 in that location. That approach doesn't seem to work since, when attempting to do something like M[[Sequence @@ Round [p]]], the coordinate p is actually a dynamic quantity, which can't be converted to two integer indices by Sequence @@ Round. Is there any way to do this? or, Is there an equivalent workaround that gets the same result. The simplest example would be using the mouse to input a freehand black and white drawing as pixels on a matrix, which could later be subject to image processing algorithms.


title: Some question on "Reduce"

text: Is this my mistake? I am trying to solve                  Assuming[0 < a < 1 && 0 < b < 1 && 0 < c < 1 && 0 < n < 2 && Q > 0 &&        0 < p <= 1 && Element[a | b | c | n | p | Q, Reals],       Reduce[2*a*b*n*c*Q - 3*a*b*n*p*c*Q + a*b*n*p^2*c*Q -          4*a^2*b*n*p*Q^2 - 4*a*b^2*n*p*Q^2 + 6*a^2*b*n*p^2*Q^2 +          6*a*b^2*n*p^2*Q^2 - 2*a^2*b*n*p^3*Q^2 - 2*a*b^2*n*p^3*Q^2 +          a^2*b*c*Q^2 + a*b^2*c*Q^2 - 2*a^2*b*p*c*Q^2 - 2*a*b^2*p*c*Q^2 ==         0]]      However, the answer provided doesn't seem to be fit with my assumption. For instance, I clearly state that $0<p<=1$. But in the answer, it give me $p=2$, and also $p=0$. How do I filter out these unwanted values? The program returns,                    (Q == 0 && (p == 1 ||           p == 2)) || ((-c + 2 c p + 4 n p - 6 n p^2 + 2 n p^3) Q != 0 &&         a == (2 c n - 3 c n p + c n p^2 + b c Q - 2 b c p Q - 4 b n p Q +           6 b n p^2 Q -           2 b n p^3 Q)/((-c + 2 c p + 4 n p - 6 n p^2 +             2 n p^3) Q)) || (p == 1/2 && n == 0 && Q != 0) || (Q == 0 &&         2 - 3 p + p^2 != 0 && n == 0) || (Q == 0 &&         n (2 - 3 p + p^2) != 0 && c == 0) || ((p == 1 || p == 2) &&         c == 0 && Q != 0) || (n == 0 && -1 + 2 p != 0 && c == 0 &&         2 p Q - 3 p^2 Q + p^3 Q != 0) || (p == 0 && n == 0 && c == 0 &&         Q != 0) || (Q != 0 && p == 0 && 2 n != 0 && c == 0) || a == 0 ||       b == 0 || Q == 0


title: Kinetic Friction in Mathematica, weird behaviour

text: I found the behavoiur of Sign function weird in the code below. when $T=10$               T = 10;     A = 1;     Fk0 = 2;     m1 = 1;     x0[t_] = A Sin[2 Pi t];     Fk[t_] = -Fk0  Sign[x1'[t]];     sol = NDSolve[{       m1 x1''[t] == -m1 x0''[t] + Fk[t], x1'[0] == 10, x1[0] == 0},       {x0, x1}, {t, 0, T}, MaxSteps -> Infinity]     Plot[{x0''[t], x1'[t] /. sol // Evaluate}, {t, 0, T}, Frame -> True]      ![](http://i.stack.imgur.com/yEy9J.jpg) but when $T=40$ , I got   ![](http://i.stack.imgur.com/h5eeB.jpg)   which is how it is supposed to be. I wonder what I did wrong here.


title: Can tab just mean "insert tab character"?

text: Is there a way to set the tab key to simply insert the tab character in a notebook? I often find the sometimes mysterious "features" bound to that key detrimental.


title: Set min and max ranges for axes in ParametricPlot

text: I'm having trouble with this one plot I'm trying to make. I'm using NDSolve on a system of differential equations and when I plot it with ParametricPlot, the scales or lengths of the graphs axes come out in an unsatisfactory way. How can I set the minimum and maximum ranges for the axes when I'm using ParametricPlot?


title: Skewness of distribution vs. skewness of distribution's PDF

text: I'm having trouble understanding why the skewness of built-in distributions is not the same as the skewness of their probability density functions. For example, the following are different (the first being correct):               Skewness[NormalDistribution[0, 1]]     Skewness[PDF[NormalDistribution[0, 1], Table[x, {x, -4, 4, 0.1}]]]      ..despite them both being (looking?) the same:               Plot[PDF[NormalDistribution[0, 1], x], {x, -4, 4}]     ListPlot[PDF[NormalDistribution[0, 1], Table[x, {x, -4, 4, 0.1}]]]      What I'm trying to do is estimate the skewness of a distribution resulting from a numerically solved PDE model (i.e. a distribution for which I have no analytical solution). Mathematica's skewness function is giving me positive skewness estimates even when the distribution is clearly negatively-skewed. Thanks. * * * @Szabolcs The PDE itself is rather "complicated" (boundary conditions, etc.), so I’ll try illustrate with a simpler version (which, unfortunately, doesn’t exhibit the negative skew of the complete model):               deqn = D[u[x, t], t] == d D[u[x, t], x, x] - a  D[u[x, t], x] - \[Lambda] u[x, t]          g[x_, \[Epsilon]_]:=Piecewise[{{0,x<0}, {1,0<=x<=\[Epsilon]}, {0,x>\[Epsilon]}}]          d=0.02; \[Lambda]=0.001; a=0.05;          sol=NDSolve[{deqn, u[x,0]==g[x,0.1], u[-10,t]==0, u[10,t]==0}, u, {x,-10,10}, {t,0,300}]          Plot3D[Evaluate[u[x,t]/.sol[[1]]], {x,-10,10}, {t,0,300}, PlotPoints->40, Mesh->False, PlotRange->All, AxesLabel->{length, time, density}]          Plot[Evaluate[{u[1, t]/.sol[[1]], u[5,t]/.sol[[1]]}], {t,0,300}, AxesLabel->{time, density}, PlotRange->All]      It is the skewness of the two distributions in the second plot that I'm after. Thanks.


title: Make dynamic controls from existing list

text: I have a list of variables (`c1`,`c2`,`c3`,`c4`), each with its own range of possible values and each being a possible control. I need to pick two of them and make the remaining ones controls in a `DynamicModule`. I tried to use suggestions from here but I didn't mange to make the last step work.               DynamicModule[{allC, lC, fC, sC},       allC = {{{c1, 1, "c1"}, {1, 2}}, {{c2, 10, "c2"}, {10, 20}},                {{c3, 100, "c3"}, {100, 200}}, {{c4, 1000, "c4"}, {1000, 2000}}};       lC = Range[Length[allC]];       With[{controlGenerate = Function[{var, initialValue, str, range},                                          Control[{{var, initialValue, str}, range}], HoldAll]},         Column[{controlGenerate[fC, 1, "First", lC],                 controlGenerate[sC, 2, "Second", DeleteCases[lC, _?(MemberQ[{fC}, #] &)]],                 (* The line below works as I expected *)                 Dynamic@allC[[DeleteCases[lC,_?(MemberQ[{fC,sC},#] &)]]],                 (* The line below doesn't work as I intended *)                 (controlGenerate[#[[1, 1]], #[[1, 2]], #[[1, 3]], #[[2]]] & /@                                      (allC[[DeleteCases[lC, _?(MemberQ[{fC, sC}, #] &)]]]))                 }                ]       ]     ]


title: Implementation of the Polynomial Chinese Remainder Theorem

text: I would like an implementation of the Chinese Remainder Theorem for polynomials in $\mathbb{Z}[x]$, that is, a function               PolynomialCRT[{f_1,...,f_n},{m_1,...,m_n},x]      thet returns the polynomial $f\in\mathbb{Z}[x]$ of smallest degree such that $$ f(x)\equiv f_i(x)\mod m_i(x), $$ where $f_i,m_i\in\mathbb{Z}[x]$ and the $m_i$ are pairwise coprime. Any ideas? Thanks in advance.


title: PDF for Normal-Gamma Mixture

text: The normal-gamma mixture is:               NIntegrate[      Evaluate[(Sqrt[a]*sd)^(-1)*        PDF[NormalDistribution[0, 1], (x - mu)/(Sqrt[a]*sd)]*        PDF[GammaDistribution[kr, kr^(-1)], a]], {a, 0, \[Infinity]}]      where the three variables are: mu - mean; sd - standard deviation; and kr - kurtosis. The mixture allows defining a "normal" distribution with kurtosis value greater than 3. Instead of the clunky approach of defining the pdf as `func[mu_, sd_, kr_, x_]`, what is the correct syntax to use `ProbabilityDistribution`? The application in mind is to generate pdf tables for different kurtosis values.


title: Subscripts in programatically generated section headers

text: Consider the following command:               TextCell["\!\(\*SubscriptBox[\(H\), \(2\)]\)", "Section"]      How can I display the string as section header and get the DisplayForm? Right now it writes `\!\(\*SubscriptBox[\(H\), \(2\)]\)` as section header which hurts my eyes. **Edit:** To give a little more background. I have a long list of Strings with sub- and superscripts (typed in using keyboard shortcuts), i.e. explicitely not using Superscript[..] etc.. Now I want to create a notebook with one section per list entry and the string should go into the section title with proper display of super/subscripts. Here is a hopefully better example: I create a list of section headers. For A_1 I type `A <Ctrl>+_ 1`, etc. Then I want to create sections from the list. The code copied as input text:               headers = {"\!\(\*SubscriptBox[\(A\), \(1\)]\)",         "\!\(\*SubscriptBox[\(A\), \(2\)]\)",         "\!\(\*SubscriptBox[\(A\), \(3\)]\)"};     FullForm[headers]     CellPrint[TextCell[#, "Section"]] & /@ headers      Edit 2: Using ToExpression almost does the job. I am using the following code. Note that ToExpression scrambles the order of the characters in the header strings. Any idea on how to improve?               headers = {"\!\(\*SubscriptBox[\(B\), \         \(1\)]\)\!\(\*SuperscriptBox[\(A\), \(2\)]\)",            "\!\(\*SubscriptBox[\(B\), \(1\)]\)\!\(\*SuperscriptBox[\(A\), \(3\         \)]\)", "\!\(\*SubscriptBox[\(B\), \         \(1\)]\)\!\(\*SuperscriptBox[\(A\), \(5\)]\)"};     CreateDocument[      Flatten[       Prepend[         Table[          CellGroup[           {            TextCell[ToExpression[i], "Section"],            ExpressionCell[Plot[Sin[x], {x, 0, 6}]]            }]           , {i, headers}]         ,{TextCell["Title", "Title"],           TextCell["created:" <> ToString[DateString[]], "Subtitle"]}]      ,1],     Visible -> True];


title: optimization problem with NDSolve

text: I want to minimize the function `fcc`. When `fcc` is calculated for a specified point the answer is correct:               In[70]:= fcc[0.5, 0.5, 0.004, 0.006, 0.0025, 0.5]     Out[70]= 2.96667*10^6      but when I want to optimize `fcc` with `NMinimize` there is a problem below:               NMinimize[{fcc[q1, q2, q3, q4, q5, q6], 0.5 <= q1 <= 1.5,        0.5 <= q2 <= 1.5, 0.003 <= q3 <= 0.01, 0.003 <= q4 <= 0.01,        0.002 <= q5 <= 0.005, 0.5 <= q6 <= 1}, {q1, q2, q3, q4, q5, q6}]      > NDSolve::ndsv: Cannot find starting value for the variable ws. >> > > ReplaceAll::reps: {NDSolve[{-((0.00011318 (q2+q3) > (-0.0174073+ws[<<1>>]))/(q3 q4 > q6))+(ws^[Prime])[x]==0,ws[q1]==0.012529},{ws},{x,0,q1}]} is neither a list > of replacement rules nor a valid dispatch table, and so cannot be used for > replacing. >> > > ReplaceAll::reps: {NDSolve[{-((0.00011318 (q2+q3) > (-0.0174073+ws[<<1>>]))/(q3 q4 > q6))+(ws^[Prime])[x]==0,ws[q1]==0.012529},{ws},{x,0,q1}]} is neither a list > of replacement rules nor a valid dispatch table, and so cannot be used for > replacing. >> > > ReplaceAll::reps: {NDSolve[{-((0.00011318 (q2+q3) > (-0.0174073+ws[<<1>>]))/(q3 q4 > q6))+(ws^[Prime])[x]==0,ws[q1]==0.012529},{ws},{x,0,q1}]} is neither a list > of replacement rules nor a valid dispatch table, and so cannot be used for > replacing. >> > > General::stop: Further output of ReplaceAll::reps will be suppressed during > this calculation. >> > > NDSolve::ndsv: Cannot find starting value for the variable ts. >> > > NMinimize::nnum: The function value 2.18625*10^6+6618.38 (-0.012529+ws[0]) > is not a number at {q1,q2,q3,q4,q5,q6} = > {1.4748,1.12029,0.0074076,0.00951558,0.00291973,0.810076}. >> and this is the `fcc` function:               ta = 30; rha = 0.4; altitude = 1361; p =       101325*(1 - altitude*2.25577*10^-5)^5.2559; tka =       273.15 + ta; c1 = -5.8002206*10^3; c2 = 1.3914993; c3 = \     -4.8640239*10^-2; c4 =       4.1764768*10^-5; c5 = -1.4452093*10^-8; c6 = 6.5459673; psata =       Exp[c1/tka + c2 + c3*tka + c4*tka^2 + c5*tka^3 + c6*Log[tka]]; pva =       rha*psata; wa =       0.621945*pva/(p -           pva); tr = 26; rsh = 1500; nu = 7.54; lef = 0.894; tsin = ta; \     tpin = ta; twin = 20; wsin = wa; wpin = wa; tkw =       273.17 + twin; psatw =       Exp[c1/tkw + c2 + c3*tkw + c4*tkw^2 + c5*tkw^3 +         c6*Log[tkw]]; pvw = psatw; wsat =       0.621945*pvw/(p -           pvw); cps = 1006; cpp = 1006; cpv = 1873; cpw = 4183; ks = \     0.027; kp = 0.027; kwater = 0.6; kwall = 237; hfg = 2501000; lwall = \     0.0005; lwater = 0.001;     fcc[lx_, ly_, lp_, mp_, mw_, ratio_] := Module[{},        ms = ratio*mp;        ls = lp;        dhs = 2*ly*ls/(ly + ls);        dhp = 2*ly*lp/(ly + lp);        hs = nu*ks/dhs;        hp = nu*kp/dhp;        hm = hs/(lef*cps);        u = 1/(1/hp + lwall/kwall + lwater/kwater);        dels = -1; delp = -1;        wss = NDSolve[{(dels hm ly (ws[x] - wsat))/ms +              Derivative[1][ws][x] == 0, ws[lx] == wsin}, {ws}, {x, 0, lx}];        tstptw =          NDSolve[{(dels ly (ts[x] - tw[x]) (hs +                   cpv hm (-Evaluate[{ws[x]} /. wss] + wsat)))/(ms (cps +                   cpv Evaluate[{ws[x]} /. wss])) + Derivative[1][ts][x] ==             0, (delp ly (tp[x] - tw[x]) u)/(mp (cpp + cpv wpin)) +              Derivative[1][tp][x] == 0,            1/(cpw mw)               ly (delp (-tp[x] + tw[x]) u +                 dels (hs (-ts[x] + tw[x]) -                    hm (hfg + cpv tw[x] -                       cpw tw[x]) (Evaluate[{ws[x]} /. wss] - wsat))) +              Derivative[1][tw][x] == 0, ts[lx] == tsin, tp[lx] == tpin,            tw[0] == twin}, {ts, tp, tw}, {x, 0, lx}];        (*Plot[Evaluate[{{ts[x],tp[x],tw[x]}/.tstptw}],{x,0,lx}]*)        tpout = Evaluate[tp[0] /. tstptw]; tpout = tpout[[1]];        tsout = Evaluate[ts[0] /. tstptw]; tsout = tsout[[1]];        wsout = Evaluate[ws[0] /. wss]; wsout = wsout[[1]];        cp = 1006;        If[(tr - tpout) < 0.5, mt = 20, mt = rsh/(cp*(tr - tpout))];        np = Round[mt/mp];        ca = 100;        at = lx*((np + 1)*(ly + 4*lp) + ly);        n = 0.6;        cinv = ca*at^n;        kel = 120;        kw = 1.5;        \[Tau] = 3000;        \[Eta] = 0.5;        ro1 = 1.17;        v1 = ms/(ro1*ls*ly);        miu1 = 10^-5;        re1 = ro1*v1*dhs/miu1;        \[Alpha]1 = ls/ly;        f1 = 24*(1 - 1.355*\[Alpha]1 + 1.9467*\[Alpha]1^2 -              1.7012*\[Alpha]1^3 + 0.9564*\[Alpha]1^4 - 0.2537*\[Alpha]1^5)/           re1;        dps = 2*f1*ro1*(v1^2)*lx/dhs;        smd = 1.17;        mst = ms*np/smd;        cos = kel*\[Tau]*((dps*mst)/(\[Eta]*10^6));        ro2 = 1.17;        v2 = ms/(ro2*lp*ly);        miu2 = 10^-5;        re2 = ro2*v2*dhp/miu2;        \[Alpha]2 = lp/ly;        f2 = 24*(1 - 1.355*\[Alpha]2 + 1.9467*\[Alpha]2^2 -              1.7012*\[Alpha]2^3 + 0.9564*\[Alpha]2^4 - 0.2537*\[Alpha]2^5)/           re2;        dpp = 2*f2*ro2*(v2^2)*lx/dhp;        pmd = 1.17;        mpt = mp*np/pmd;        cop = kel*\[Tau]*((dpp*mpt)/(\[Eta]*10^6));        h = 2;        g = 9.81;        copump = kel*\[Tau]*h*g*mw*np/\[Eta];        ew = ms*np*(wsout - wsin);        cow = kw*\[Tau]*3.6*ew;        r = 0.1;        y = 10;        a = r/(1 - (1 + r)^(-y));        a*cinv + cos + cop + copump + cow];


title: Getting vertical bar of equal length for | a || b | in a notebook

text: How can I make |a|*|b| show well in a notebook? I typed `|` from keyboard to denote absolute value. General cleanupIt will auto adjust by matching in my notebook so that sometimes it will not show as expected. Maybe I can close the auto-matching feature? ![enter image description here](http://i.stack.imgur.com/GnuwU.png)


title: Changing Default Color for Titles, Sections, Subsections, etc., and Items (bullet color)

text: I'm new to Mathematica 9, and I assume there must be an easy fix for my problem, but I have not been able to find any yet. Essentially, I want the default color for the text of all of my titles, subtitles, sections, etc., to be colored in black and not have alternate colors (red, gray, etc.). I figured out a short fix (is it really a fix?) by trying to edit a stylesheet, but now when I make an item underneath a title or section the bullet is a different color than black. I can make the text black, but the symbols that indicate an item of some sort is always a color different than black, and the colors for the symbols changed based on how nested the itemizing list is. Basically, I want everything (titles and so forth) to be in black. Text. Bullets. Titles. Etc. How can I fix this and make the changes effective for any new notebooks I create? UPDATE: The following link seems to address what I wanted: How to use version 8 default.nb style sheet in place of version 9 default.nb Of course, this just uses the Mathematica 8 nb as the default (which I think looks much better and professional). For those very new to Mathematica 9, I found the above length to be extremely helpful.


title: Sharing styles between notebooks (Mathematica v9)

text: It appears from the documentation that we share styles via stylesheets. I am trying to set up a customised default stylesheet for my notebooks. I have tried simple ideas, and more complex ones, without success.   1. If I edit the provided default.nb, my changes to it are not saving.    2. If I make model notebook of my own, say aModel.nb, and customise that notebook's styles, a copy of that model does not have those styles.   3. If I "install" the stylesheet of aModel.nb, and apply that to some other notebook, it has no effect.


title: How to use version 8 default.nb style sheet in place of version 9 default.nb

text: I do not like the new default.nb style sheet in version 9, and would like to use the older one that was used in version 8 for any new notebook and for any notebook created since I started using V9. I saw in the `StyleSheets` folder that V8 default.nb is still there ![enter image description here](http://i.stack.imgur.com/Eq7pT.png) So I went to preferences and changed the following to say `Default_8.0.nb` ![enter image description here](http://i.stack.imgur.com/7i3GA.png) And restarted Mathematica. Now when I open a new notebook, it seems to be Default_8.0.nb since `Section` headers are in black and text font is times new Roman. So I thought that is good. Problem fixed. (even thought the Style sheet Default does not have the _check_ mark on next to the it, so I am worried I need to do something more) ![enter image description here](http://i.stack.imgur.com/vY5LQ.png) However, when I opened an existing notebook that I made some changes in since V9 was installed, I noticed that it still using V9 default.nb. Even though the Style sheet says `Default`. ![enter image description here](http://i.stack.imgur.com/G3cLx.png) _Question is_ What is the correct and recommended steps to use Version 8 default.nb in version 9, so that any notebook that was used version 9 default.nb will now automatically use `Default.8.0.nb` (I really do not understand how can WRI make this change for users without asking them. I do not want someone changing the style sheet of my documents without at least asking me. This should have an option for the user to decide on) thanks


title: How can I replace UndirectedEdges to pairs of bi-directional DirectedEdge in a Graph?

text: How can I have pair of edges between nodes in this kind of graphs?               cities = CityData[{All, #}] & /@ {"Germany"}; bigcities =      Select[Select[Join @@ cities, FreeQ[#, ""] &],      CityData[#, "Population"] > 100000 &];     cityCoords =      Select[CityData[#, "Coordinates"] & /@ bigcities, FreeQ[#, ""] &];     Needs["ComputationalGeometry`"];     pts = Reverse[cityCoords, 2];     dt = DelaunayTriangulation[pts];     toPairs[{m_, ns_List}] := Map[{m, #} &, ns];     edges = Union[Sort /@ Flatten[toPairs /@ dt, 1]];     Graph[edges, ImagePadding -> 20,      VertexCoordinates -> pts, VertexStyle -> LightBlue,      VertexLabels -> bigcities[[All, 1]],      Prolog -> {LightBrown, EdgeForm[{Thick, Black}],      CountryData["Germany", "FullPolygon"]}, ImageSize -> 800]


title: Minimizing a function with some restrictions

text: I need help in finding a way to minimize a function with some complex constraints. I'm not an expert in this field, but I'm still trying to understand if I can do something with my problem. So, here's the functions: \begin{equation} \min z = \\{ds_1*[(cp_{11}*qp_1*pp_{11}+...+(cp_{n1}*qp_n*pp_{n1})]+...+ds_m*[(cp_{1m}*qp_1*pp_{1m}+...+(cp_{nm}*qp_n*pp_{nm})]\\} \end{equation} with those given **constants** \begin{equation} ds_x > 0, qp_x > 0, pp_{xy} > 0 \end{equation} and $$ cp_{yx} = \begin{cases} 1 \\\ 0 \end{cases}, \begin{equation} \sum\limits_{i=1}^m cp_{iy} = 1 \text{ (only one element can be 1 in the whole column)} \end{equation} $$ what I have to do is to find the values for those `cp` terms to minimize the function. Now, I know a little bit of optimization (simplex, branch & bound and stuff like this) but I've never went that deep and this one looks really complex to me. Being a computer scientist, I thought of making some kind of backtracking stuff, but even with a small instance (let's say `n=3` and `m=7`) I'd have to work on \begin{equation} 2^{3*7}=2097152 \end{equation} different combinations, which is really a lot. Do you have any suggestion on this? EDIT: Based on @DumpsterDoofus's answer, this is what I tried (with some real values) \begin{equation} d=[7, 5, 11], \text{vector with the } ds_j \text{ constants} \end{equation} \begin{equation} p= \begin{bmatrix} 5 & 2 & 5 & 3 & 7 & 1 & 1\\\2 & 8 & 3 & 2 & 7 & 2 & 3\\\3 & 6 & 4 & 5 & 9 & 1 & 1 \end{bmatrix} , \text{matrix with the } pp_{ij} \text{ constants} \end{equation} assuming that \begin{equation} qp_i = 1, \forall i \end{equation} we have \begin{equation} k= \begin{bmatrix} 7*5 & 7*2 & 7*5 & 7*3 & 7*7 & 7*1 & 7*1\\\5*2 & 5*8 & 5*3 & 5*2 & 5*7 & 5*2 & 5*3\\\11*3 & 11*6 & 11*4 & 11*5 & 11*9 & 11*1 & 11*1 \end{bmatrix} = \begin{bmatrix} 35 & 14 & 35 & 21 & 49 & 7 & 7\\\10 & 40 & 15 & 10 & 35 & 10 & 15\\\33 & 66 & 44 & 55 & 99 & 11 & 11 \end{bmatrix} \end{equation} which, translated to a vecotr, becomes \begin{equation} k=[35,10,33,14,40,66,35,15,44,21,10,55,49,35,99,7,10,11,7,15,11] \end{equation} (I did it manually and now I corrected it after proper explanation of the `vec()` function) Now that I've got the value of `k`, I'm ready to run this in _Mathematica_ :               n=3;     m=7;     j[k_]:=ConstantArray[1,k];     k={35,10,33,14,40,66,35,15,44,21,10,55,49,35,99,7,10,11,7,15,11};     A=ArrayFlatten[{IdentityMatrix[m]\[TensorProduct]j[n]}];     b=j[m]\[TensorProduct]{1,0};     Round@LinearProgramming[k,A,b]      > Output: {0,1,0,1,0,0,0,1,0,0,1,0,0,1,0,1,0,0,1,0,0} [Edited after changing k > to its correct value] Changing the output back to a matrix leads to this: \begin{bmatrix} 0 & 1 & 0 & 0 & 0 & 1 & 1\\\1 & 0 & 1 & 1 & 1 & 0 & 0\\\0 & 0 & 0 & 0 & 0 & 0 & 0 \end{bmatrix} which ~~is clearly wrong as we have one column full of zeroes and another one full of ones.~~ seems correct now.


title: Asymptotics of sum of binomials

text: I would like to find the asymptotics of               Sum[Binomial[n,i]*1/i^((n+1)/2),{i,1,n}]      I saw Find asymptotics of Sum[2^i*Binomial[n-i-1,2*n/3-1],{i,0,n/3}] but I can't get anything similar to work in my example. What is the right way to do this?


title: transparency in image used for texture?

text: Is there a way to set a transparancy channel in a raster image used for a texture in 3d graphics? this creates a raster image with a transparency channel:               img = SetAlphaChannel[Image@Table[0, {400}, {400}],              Graphics[{GrayLevel[0], Disk[]}]];      This works just fine in a 2D graphic:               Graphics[{Thick , Red, Line[{{0, 0}, {1, 1}}], Inset[img], Thick , Blue,             Line[{{1, 0}, {0, 1}}]}]      (Sorry.. I cant post graphics). But in 3D my transparent region is just white..               Graphics3D[{Line[{{1/2, 1/2, 1/2}, {1/2, 1/2, 3/2}}], Texture@img,          Polygon[{{0, 0, 1}, {1, 0, 1}, {1, 1, 1}, {0, 1, 1}},          VertexTextureCoordinates ->             {{0, 0, 1}, {1, 0, 1}, {1, 1, 1},{0,1, 0}}]}, Lighting -> "Neutral"]      Any ideas? Ive already treid the rendering options here with no joy: Transparent textures don't show \-- the point of this is to import real raster images and set a transparancy mask by the way.


title: Shading regions in ParametricPlot

text: I am using ParametricPlot to get an X vs Y plot. I want to shade the area enclosed by the curve falling in the region where Y<0\. For example, how to shade the area enclosed by the Sin curve where Sin[x]<0\.               ParametricPlot[{x, Sin[x]}, {x, 0, xm}]


title: Extracting rational coefficients from an irrational sum

text: I have a function that returns results that always can be represented as $p+q\,\pi^2+r\ln2+s\ln^22+t\sqrt2$ where $p,q,r,s,t\in\mathbb Q$. But the actual _Mathematica_ expression returned not always in exactly this form, e.g. it can be               1/Sqrt[2] + 1/54 (34 - 3 π^2 + (-8 + Log[8]) Log[64])      It's not difficult to extract rational coefficients from this expression manually, but I need to process hundreds of expressions, so I want to make this process automated. How can I do this?


title: Is is possible to use regular expressions in the search and replace diaglog?

text: I find myself wanting to be able to do regular expression search and replaces in the Mathematica gui over and over again. Using a regex capable editor (such as vim), I could do something like:                :,$ s/ *+ *s\>//cg      for a prompted search and replace of '+ s', ' +s', '+s', ..., but not '+ sa' (say). Is there any thing that offers similar capability in the Mathematica GUI?


title: How do i draw a hemisphere using SphericalPlot3D?

text: I want to know what ranges must be set for theta and to get a hemisphere of radius 5 from SphericalPlot3D.


title: Problem to solve an integral equation

text: I am new to Mathematica. I am trying to numerically solve for C in the following equation: $\begin{equation} \begin{array}{lcl} -\int_0^\infty (5000000+100000 x+ C)^{-1} \frac{1}{0.20x \sqrt{20 \pi}} exp(-0.5 (\frac{log(x/50)-0.10*10}{0.20\sqrt{10}})^2)dx=\\\ -\int_0^\infty (5000000+100000 x+ 10000 *Max(x-50,0))^{-1} \frac{1}{0.20x \sqrt{20 \pi}} exp(-0.5 (\frac{log(x/50)-0.10*10}{0.20\sqrt{10}})^2)dx \end{array} \end{equation}$ I know a solution is: C=152300. However, when I write the following code:               f[C_?NumericQ] := NIntegrate[(-(5000000 + 100000*x +           10000*Max[0, x - 50])^(-1) + (5000000 + 100000*x +          C)^(-1))*1/(x*0.20*(10*2 Pi )^(0.5))* Exp (-0.5*((Log[x/50] - 0.10*10)/(0.20*(10)^(0.5)))^2), {x, 0, Infinity}]                          {FindRoot[f[C] = 0, {C, 150000}]}      I have an error message and cannot find the root. In addition, there are other similar equations I want to solve for which I don't have an initial guess for the solution. Is there a good procedure for finding the root in such cases? Thank you very much for any advice!


title: How to get VertexDelete to work?

text: I'm using Mathematica 9 and want to delete a single vertex and all associated edges on a graph but can't seem to get the function VertexDelete function to work. My code is below. I declare a graph "newgraph" and GraphPlot works fine but when I call VertexDelete I get the following error: > VertexDelete::graph: A graph object is expected at position 1 in > VertexDelete[{0->1,0->3,0->6,0->11,0->12,0->14,0->30,0->56,0->75,0->76,0->78,0->86,0->94,0->112,0->120,0->222,0->232,0->248,0->504,0->960,1->7,1->12,1->14,1->15,1->31,1->57,1->62,1->75,1->76,1->78,1->79,1->86,1->94,1->95,1->112,1->116,1->120,1->121,1->124},79]. > >> My code is:               newgraph = {0 -> 1, 0 -> 3, 0 -> 6, 0 -> 11, 0 -> 12, 0 -> 14,        0 -> 30, 0 -> 56, 0 -> 75, 0 -> 76, 0 -> 78, 0 -> 86, 0 -> 94,        0 -> 112, 0 -> 120, 0 -> 222, 0 -> 232, 0 -> 248, 0 -> 504,        0 -> 960, 1 -> 7, 1 -> 12, 1 -> 14, 1 -> 15, 1 -> 31, 1 -> 57,        1 -> 62, 1 -> 75, 1 -> 76, 1 -> 78, 1 -> 79, 1 -> 86, 1 -> 94,        1 -> 95, 1 -> 112, 1 -> 116, 1 -> 120, 1 -> 121, 1 -> 124}          GraphPlot[newgraph, VertexLabeling -> True]          VertexDelete[newgraph, 79]      As far as I am aware, I am indeed passing a graph as an argument! Someone please help me! Many thanks.


title: ListVectorPlot3D invalid dataset

text: I have generated a dataset which seems to fine according to the help page of Mathematica for a ListVectorPlot3D but, it says it is not a valid set. I have given the data set below, could someone please tell me what is wrong here? In each element the first list containing three elements is the position and the next list containing three elements is the vector components.               In[170]:= FullData1          Out[170]= {{{-0.027267, -0.0278571,         0.1}, {0.710454, -0.695403, -0.108031}}, {{-0.0380811, -0.00808106,         0.1}, {0.206099, -0.971216, 0.119427}}, {{-0.0359774, 0.0154511,         0.1}, {-0.394081, -0.917603, 0.0520121}}, {{-0.020237, 0.0330941,         0.1}, {-0.844052, -0.516136, -0.145537}}, {{-0.000633865,         0.0392053, 0.1}, {-0.999843, -0.0161653, -0.00730729}}, {{0.020237,         0.0330941, 0.1}, {-0.844052, 0.516136, 0.145537}}, {{0.0342857,         0.0190214, 0.1}, {-0.485118,         0.874415, -0.0077212}}, {{0.0379892, -0.00857143, 0.1}, {0.218605,         0.968876, -0.116149}}, {{0.0228341, -0.0314056, 0.1}, {0.800943,         0.582344, 0.139165}}, {{0.00214286, -0.0391452, 0.1}, {0.998203,         0.0546429, 0.0246024}}}          In[168]:= ListVectorPlot3D[FullData1]          During evaluation of In[168]:= Visualization`Core`ListVectorPlot3D::vfldata: {{{-0.027267,-0.0278571,0.1},{0.710454,-0.695403,-0.108031}},<<8>>,{{0.00214286,-0.0391452,0.1},{0.998203,0.0546429,0.0246024}}} is not a valid vector field dataset or a valid list of datasets.


title: How could I optimize the following high-dimensional table with a lot of duplicates?

text: Union[FullSimplify[Flatten[            Table[Sum[Exp[2 \[Pi] I Subscript[n, i]/5], {i, 0, 6}],                 {Subscript[n, 0], 0, 4}, {Subscript[n, 1], 0, 4},                  {Subscript[n, 2], 0, 4}, {Subscript[n, 3], 0, 4},                  {Subscript[n, 4], 0, 4}, {Subscript[n, 5], 0, 4},                  {Subscript[n, 6], 0, 4}]]]]      This Table goes through a lot of redundant calculations, blows up unnecessarily and then throws them away. _Is there a more efficient way to just generate unique values of this kind?_ All I'm trying to do here is to generate a list of complex points that can be expressed as arbitrary sums of, in this case, six fifth roots of unity. That job still finished in a reasonable amount of time, but I'd like to do the same thing for a higher number of higher-order roots of unity.   Ideally, I'd like to be able to generate the generic limiting pattern, if it exists, for an infinite number of n-order roots. - for 2nd, 3rd, 4th and 6th order roots that generates, respectively, all integers, a triangular grid, a square grid and another triangular grid. I wonder how cases look like that can't have such regular grids - so any other Integer, essentially.


title: Plotting Chebyshev's theta function $\vartheta(x)$

text: The function I would like to plot is defined as $\sum\limits_{p\leq x}\log p.$ The following gives me I think a plot of the points of interest, but the function is defined for all $x > 0$ and so it's basically a step function between primes. Is there a way to augment the following to include the "steps?"               a8 = Table[Sum[Log[Prime[i]], {i, 1, j}], {j, 1, 10}];          a7 = Table[Prime[i], {i, 1, 10}];          a9 = Table[{a7[[i]], a8[[i]]}, {i, 1, 10}];          ListPlot[a9]      Thanks for any suggestions.


title: Parametric differentiable interpolation of a 2D data set

text: I have a set of data               table = Reverse[{        {0, -947}, {-212, -947}, {-424, -950}, {-635, -963}, {-845, -995}, {-1051, -1044},        {-1248, -1119}, {-1432, -1224}, {-1591,-1365}, {-1715, -1537}, {-1796, -1732},         {-1828, -1942}, {-1810,-2153}, {-1755, -2357}, {-1668, -2551}, {-1556, -2730},         {-1423,-2895}, {-1278, -3050}, {-1126, -3197}, {-973, -3343}, {-803,-3506}     }];      which I need to interpolate with a parametric curve. Endpoints and tangent vectors at them are critical. Trying independent polynomial fits for X and Y leads to a wavy curve which is unacceptable. `BSplineFunction` of degree around 3 leads to a very good-looking curve:               interp = BSplineFunction[table, SplineDegree -> 3];         Show[ListPlot[table], ParametricPlot[interp[t], {t, 0, 1}], AspectRatio -> 1]      ![enter image description here](http://i.stack.imgur.com/zv5og.png) but has a discontinuous derivative (btw: why? help promises that it should be a `BSplineFunction` of one lesser degree but it's a scary jump-step function if you plot it):               x1[t_?NumericQ] := Module[{val}, val = interp[t]; First@val]     y1[t_?NumericQ] := Module[{val}, val = interp[t]; Last@val]         Plot[Norm[{x1'[t], y1'[t]}], {t, 0, 1}, PlotRange -> All]      ![enter image description here](http://i.stack.imgur.com/jbm69.png) I then intend to use these functions in `NDSolve`, `NIntegrate` etc., therefore behaviour like above is too bad. What parametric interpolation is better in this case?


title: How should I make a label?

text: This is my code for making a label. I used a `Button` expression to build it. Is there a better way to make a label? My objection to doing it this way is that, when I set `Enabled -> True`, the button becomes clickable. For my application, I don't want anything clickable.               Button[StringJoin["Label", ToString[3]], Null,        Background -> Black, BaseStyle -> {White, 16, Bold}, Enabled -> False]


title: Creating a number based on given conditions

text: In the grade 7 math curriculum here in Alberta we teach divisibility. I'm trying to write a program to create questions based on the idea of a student being given say, 4 digits, and then choosing one of their own to create say, "the largest number divisible by 5". I have a few simple ideas. Get a list of 4 numbers...               RandomInteger[{0, 9}, 4]      Arrange them               Permutations[list]      Turn them into numbers...               FromDigits /@ Permutations[list]      I'm sure there must be an elegant way to use Mathematica to do this. I'd need to have the original 4 digits and the answer so I could create the question under program control. I.E. Given the digits 9, 0, 0, 2 and 1 other digit of your choice, create the largest 5 digit number you can that is divisible by 5. I'd appreciate any hints or suggestions.


title: How to remove ticks?

text: I wanted to remove the `Ticks` in my coding but i can't. Here when i try to remove the `Ticks` the number also gone. I need numbers without `Ticks`, `Ticks` and `GridLines` should be automatic and don't use`PlotRange` .               BarChart[{{1, 2, 3}, {4, 5, 6}}, ImageSize -> 400, BarOrigin -> Left,       ChartLayout -> "Stacked", ImageSize -> {500, 300},       GridLines -> {Automatic, None}, Ticks -> {{Automatic}, None},       LabelStyle ->        Directive[Bold, Opacity[1], Thick, Black,         FontFamily -> "Helvetica"],       TicksStyle -> Directive[20, Opacity[.3]], Axes -> {True, False},       AxesStyle -> Opacity[.0],       ChartStyle -> {RGBColor[.06, .29, .66], RGBColor[.01, .56, .61],         RGBColor[1, .58, 0]},      ChartBaseStyle -> EdgeForm[GrayLevel[.6]]]


title: How to use ParametricPlot Wih Conditions (or similar)

text: I´m analizyng the game "Battle of the Buddies" similar to "Prisioner´s Dilenma" All works fine, BUT... I want to draw in red the point whose coordinates are less than the coords of a strategy.               Manipulate[           ParametricPlot[{5* x*y - x - y + 1, 6*x*y - 5 x - 5 y + 5}, {x, 0,         1}, {y, 0, 1}, PerformanceGoal -> "Quality",            Epilog -> {Red, PointSize -> .036,          Point[{5* p*q - p - q + 1, 6*p*q - 5 p - 5 q + 5}]}],      (*ParametricPlot[{5* \     x*y-x-y+1,6*x*y-5x-5y+5},{x,0,1},{y,0,1},PerformanceGoal->"Quality",*)     \                Style["Representación de los pagos Norm(abscisas) y Cliff(ordenadas) \     en Battle of the Buddies", 11, Bold],      Delimiter,           Style["Norm usa la estrategia mixta(p,1-p), con el valor de p \     indicado a continuación", 10, Darker@Blue],      {{p, 0}, 0, 1, Appearance -> "Open"},      Delimiter,           Style["Cliff usa la estrategia mixta (q,1-q), con el valor de q \     indicado a continuación", 10, Darker@Orange],      {{q, 0}, 0, 1, Appearance -> "Open"},      Delimiter,           Style["Valores MAXIMIN", 11, Bold, Darker@Black],      Style["Valor Maximin para Norm: 5/6", 10, Darker@Gray],      Style["Valor Maximin para Cliff: 5/6", 10, Darker@Gray],           Delimiter,      Style["Estrategias de Equilibrio", 11, Bold, Darker@Black],      Delimiter,      Style["Creado por Mika Ike (mika2ike@gmail.com)", 10,        Darker@Black],           ControlPlacement -> Left, SaveDefinitions -> True           ]      I can view this ![enter image description here](http://i.stack.imgur.com/Jt75D.png) BUT I want to view this.... and I can´t coding that. (Highlighting the set in red) ![enter image description here](http://i.stack.imgur.com/Ye6Es.jpg)


title: Customizing the numbers used by DisplayFormulaNumbered cells

text: ![enter image description here](http://i.stack.imgur.com/RWviQ.png) I was typesetting some formulas and I encountered a formula number marked with a prime. I am using the `DisplayFormulaNumbered` cell style`. How can I add a cell with numbered with $7'$? Here is an excerpt from one of my notebooks marked to show how I want a formula numbered. ![enter image description here](http://i.stack.imgur.com/Dr1r7.png)


title: Running function - updating list - run function etc

text: I am making a larger program, so I would prefer to give a short example of my problem:                   soba={2.45649, 4.04015, 4.92679, 4.03324, 0.761532, 2.41486, 1.96081,     4.37201, 4.26696, 2.99139}          While[NumberQ[Select[soba, Function[{a}, a > 2], 1][[1]]],       soba = (soba /. Select[soba, Function[{a}, a > 2], 1][[1]] -> 1)]               Wanted output:          {1, 1, 1, 1, 0.761532, 1, 1.96081, 1, 1, 1}      The reason why I want this to happen is: First I want to find the first value in the list that matches criteria, second I want a rule to be applied in this case it is just changing the value to 1. But in the real code it is changing several values based on some other rules, it could for example change `2.45649, 4.04015, 4.92679, 4.03324` with `1`. Then I want it to run over the list again, but since it now has changed all this values `2.45649, 4.04015, 4.92679, 4.03324`to 1 my next value it would pick is `2.41486`.Then change the list based on some rules and run the code all over again on the updated list. First off all you can see that the code does not work, second THERE HAS TO BE A BETTER WAY!


title: OpenSQLConnection problem - password visible

text: **Prerequisites**   * some database (here, it's called sakila (mysql standard test db I think))   * a user (with password) that has access to that db (I'll use u:testuser/p:testpass) **Setup - minimal (?) working example** We call                Needs["DatabaseLink`"]      Next we shall use the wizard/connection tool to create a new database connection, like:               c1 = OpenSQLConnection[]      ![enter image description here](http://i.stack.imgur.com/6Jw3z.png) (after creating the new connection, we use the wizard to connect right to the new connection; and obviously, we do **not** tick the "store password in plain text"). Next, we set up another connection:               c2 = OpenSQLConnection["test"]      where `"test"` is the name we used for above connection (we get prompted for the password). Finally, a third connection:               c3 = OpenSQLConnection[         JDBC["MySQL(Connector/J)", "localhost:3306/sakila"],          "Catalog" -> Automatic, "Description" -> None, "Name" -> "test",          "Password" -> "$Prompt", "Properties" -> {}, "ReadOnly" -> False,          "RelativePath" -> False,          "TransactionIsolationLevel" -> "ReadUncommitted",          "UseConnectionPool" -> False, "Username" -> "testuser",          "Version" -> 2.]      (this is exactly copy/paste from the .m file created by the wizard, using `OpenSQLConnection` instead of `SQLConnection`. You can check the `FullForm` of `c1` or `c2` to find its location, on MacOSX, standard: "/Users/username/Library/Mathematica/DatabaseResources/test.m"). And maybe a last one (choose `"test"` in the GUI):               c4 = OpenSQLConnection[]      **The Problem** Execute:               Cases[#, HoldPattern[Rule["Password", ___]], Infinity] & /@ {c1, c2, c3, c4}      > {{"Password" -> "testpass"}, {"Password" -> "\$Prompt"}, {"Password" > ->"\$Prompt"}, {"Password" -> "testpass"}} i.e., `c1` and `c4` (the connections I **opened** with `OpenSQLConnection[]` (without argument)) are sharing my password in plain text! **My Question** Is this a known behaviour? I was using `OpenSQLConnection[]` (using the GUI) frequently, am I doing something wrong? **Edit** See @Murta's answer for an example where the password is visible without using the GUI.


title: Why doesn't my code compile?

text: Clear["`*"];     cf = Compile[{{A, _Real, 2}, {n, _Integer}},        With[{a = A[[1]], b = A[[2]], c = A[[3]]},         If[n < 1, {{a, b, c}},           Join[cf[{a, (a + b)/2, (a + c)/2}, n - 1],            cf[{(b + a)/2, b, (b + c)/2}, n - 1],            cf[{(c + a)/2, (c + b)/2, c}, n - 1]            ]          ];         ]        ];          cf[{{0, 0}, {1, 0}, {.5, .8}} // N, 3]      This code I wrote can't be compiled, _Mathematica_ returns               CompiledFunction::cfex: Could not complete external evaluation at instruction 19; proceeding with uncompiled evaluation. >>      How can I correctly compile it? The uncompiled version:               Clear["`*"];     f[{a_, b_, c_}, n_] :=       If[n < 1, {{a, b, c}},        Join[f[{a, (a + c)/2, (a + b)/2}, n - 1],         f[{(b + a)/2, b, (b + c)/2}, n - 1],         f[{(c + a)/2, (c + b)/2, c}, n - 1]]        ];          n = 3;     data = f[{{0, 0}, {1, 0}, {.5, .8}} // N, n];     ListLinePlot[data /. {a_, b_, c_} :> {a, b, c, a}]


title: Factoring terms out of a polynomial

text: I don't do much algebra in Mathematica and was surprised to discover, while attempting to answer this question, that I had no idea how to factor out an expression from a polynomial. The question was, given               τ = (1 + Sqrt[5])/2 (* golden ratio *)      and               coords = {{0,0,1},{0,1/2 (1+Sqrt[5]),-1},{1/2 (1+Sqrt[5]),1/2 (-1-Sqrt[5]),1/2 (1+Sqrt[5])},     {1/2 (-1-Sqrt[5]),0,1/2 (1+Sqrt[5])},{1/2 (1+Sqrt[5]),1,1/2 (-1-Sqrt[5])},{1/2 (-1-Sqrt[5]),     1/2 (3+Sqrt[5]),1/2 (-1-Sqrt[5])},{1/2 (3+Sqrt[5]),-1,0},{1,1/2 (-3-Sqrt[5]),     1/2 (3+Sqrt[5])},{1/2 (-3-Sqrt[5]),1/2 (1+Sqrt[5]),0},{-1,1/2 (-1-Sqrt[5]),1/2 (3+Sqrt[5])},     {1,1/2 (1+Sqrt[5]),1/2 (-3-Sqrt[5])},{-1,1/2 (3+Sqrt[5]),1/2 (-3-Sqrt[5])},{1/2 (3+Sqrt[5]),     1/2 (-1-Sqrt[5]),0},{1/2 (1+Sqrt[5]),1/2 (-3-Sqrt[5]),1/2 (1+Sqrt[5])},     {1/2 (-3-Sqrt[5]),1,0},{1/2 (-1-Sqrt[5]),-1,1/2 (1+Sqrt[5])},{1/2 (1+Sqrt[5]),     0,1/2 (-1-Sqrt[5])},{1/2 (-1-Sqrt[5]),1/2 (1+Sqrt[5]),1/2 (-1-Sqrt[5])},     {0,1/2 (-1-Sqrt[5]),1},{0,0,-1}}      how can `coords` be expressed in terms of `τ`. I came up with               Map[       If[         AtomQ@#,          #,          (Simplify[#/τ]*HoldForm@τ) /. {           τ -> HoldForm@τ,            -τ -> HoldForm@-τ}] &,         coords, {2}]      ![enter image description here](http://i.stack.imgur.com/hXAmt.png) but obviously this is not a generally robust solution, and it is ugly. I assume there must be better ways to do this. This overlaps somewhat with the original question, but I am hoping for a more comprehensive explanation than that question requires.


title: Asynchronous evaluation: Is it possible?

text: Currently we have a limited number of ways to perform asynchronous evaluation. The most common is through `Dynamic` and `Manipulate`. Using `Dynamic`, we can have part of a cell update independent of whatever we're working on:               Dynamic["x = " <> ToString@x]     For[i = 0, i < 100, i++, Pause[0.05]; x = i^2];      Similarly, we can use Manipulate to continuously evaluate an expression and output the result:               Manipulate[      {r, v} = {r + dt v, v - dt r};      Show[Graphics@Point[r], PlotRange -> {{-2, +2}, {-2, +2}}],      {{dt, 0.01}, 0.01, 1},           Initialization -> {        r = {0, 1};        v = {1, 0};        }]      We also have a way to submit jobs and have them work independently of each, however it does block any further input:               jobs = Table[        ParallelSubmit[         SingularValueList[RandomReal[1, {1000, 1000}]]],        {10}];          WaitAll[jobs]      The third option gets the closest to being an asynchronous evaluation, however it fails in that it requires any further input to be blocked. What I would love to see is some function, tentatively named `AsynchronousEvaluate`, which does exactly what it name says:               AsynchronousEvaluate[Pause[10];]     Print["Hello!"]; (* Printed immediately *)      Is there any way we can get close to achieving this? My dream is to be able to queue up a job for processing on a parallel kernel with certain constraints (Like `MemoryConstrained`) and be able to just "set and forget." When processing is finished, the result will be returned to me. But in the mean time I can still be productive by doing something else. Asynchronous evaluation is the only piece that's missing from this, and I'd like to do it if it's possible.


title: Making flash cards with Mathematica

text: I've been trying to make flash cards to help me memorize some concepts in my technical classes this semester. Since Mathematica's (mathematical) type setting is so superb, I attempted to make flash cards with it. * * * Some of my attempts: **1) Add group openers to input cells** : Go to `Format > Edit Stylesheet`. Then, if your input cell style isn't already in the stylesheet, click on the 'Choose a style' drop down menu and choose `Input`. Then, with the `Input` cell style highlighted, press `Ctrl`+`Shift`+`E`, and append `ShowGroupOpener->True` to the end of the cell editor. For example, your `Input` cell might look like this: ![Mathematica graphics](http://i.stack.imgur.com/ip5Wa.png) After that, press `Ctrl`+`Shift`+`E` again to close the cell editor, and close the stylesheet editor. Your "flash card" should now behave like this: ![enter image description here](http://i.stack.imgur.com/Mk1dx.gif) **2) Use`Button`**: For flash cards whose questions are a combination of words and formulas, I use `Button` (I also chose `Grid` for its robust customization):               Clear[show]     SetAttributes[show, HoldAll];     show[string_String, expression_] :=       Grid@{         {string,           Defer@TraditionalForm@expression}, {Button["Show",            Print@TraditionalForm@expression], SpanFromLeft}         };          show["Calculate", Integrate[1/(x^3 + 1), x]]      ![Mathematica graphics](http://i.stack.imgur.com/v54aL.png) One problem with this method is that if you hide the input cells (so that only the output cells containing the buttons are shown in the notebook) using this method, these flash cards behave weirdly: pressing the button again might reveal the input cell, or in subsequent pressing of the buttons, it will print out an answer that is hidden within a cell grouping (try evaluating the above example and pressing the button several times and you'll see). This is probably caused by the groupings of the print cells. Another issue is getting rid of these cells (or hide them), which I can't figure out how to do right now. * * * This question is supposed to **encourage everyone to show your implementations of flash cards in MMA** (or improving on my methods), especially ones that have helped you study in the past. Please feel free to post _whatever_ you'd like: small self-contained flash cards, helper functions/manipulates to display flash cards based on users' input, or systematic ways to smartly organize flash cards. Let your creativity fly! Other ideas might include: asking users to input an answer and returning `True` or `False` if the answer is right or wrong, randomizing the display of flash cards, and delaying a flash card if the user answers/guesses correctly on it. Anki is a good reference for good examples of flash card implementation.


title: Problem with Covariance Matrix Output in NonlinearModelFit

text: I am running `NonlinearModelFit` based off of some simulated data and trying to fit to a function with more than one parameter. Eventually, I would like to fit to 5 parameters (Right now I'm just trying to get it working with 2 parameters), but the output covariance matrix is almost all 0's. I believe this stems from the fact that the estimated error for some of my parameters is 0, which I know cannot be the case. I will outline as best as possible my methodology below:   1. Data creation. (This data takes the model and adds a Gaussian error for each data point.) Note that I had to set the precision higher because of some numerical accuracy issues.              AU = 149597871000;     G = 6.67428`20*^-11;     GMsun = 1.32712442099`20*^20;     GMjup = GMsun/1047.348644`20;     rJup = 5.2`20 AU;     lambda = 20 AU;          dela = 10^-11;          Data[dist_] := {        dist,         GMsun/dist^2 + (GMjup dist)/(dist^2 + rJup^2)^(3/2) +          RandomVariate[NormalDistribution[], WorkingPrecision -> 20] dela       };          Model[dist_, alpha_, jupiter_] :=        GMsun/dist^2 (1 + alpha Exp[-dist/lambda]) +        (G jupiter dist)/(dist^2 + rJup^2)^(3/2);          Dat = Table[Data[x], {x, AU, 100 AU, AU}];        2. Then for a simple case I tried to fit to my model:              NLM = NonlinearModelFit[Dat, Model[dist, alpha, jupiter], {{alpha, 10^-4}, {jupiter, 10^27}}, {dist}, WorkingPrecision -> 20];          NLM["ParameterTable"]      But what this does is output the following: ![Table of parameter values](http://i.stack.imgur.com/VQvJD.png) Similarly, when I output the covariance matrix I get:               NLM["CovarianceMatrix"]     (* -> {{2.762131253783*10^-18, 0},            {0,                     0}} *)      My question is this: Why do I get 0's in my covariance matrix? Clearly these 0's stem from the 0 standard error for the `jupiter` parameter, but shouldn't there be some associated standard error with `jupiter` just as there is with `alpha`? Thank you so much


title: Solve[Tan[theta] == (b*Sin[t])/(a*Cos[t]), theta] breaks when "Reals" is added?

text: _Mathematica_ solves this equation fine:               Solve[ Tan[theta] == (b*Sin[t])/(a*Cos[t]), theta] // InputForm                > >     {{theta -> ConditionalExpression[ArcTan[(b*Tan[t])/a] + Pi*C[1], >       Element[C[1], Integers]]}} >   The solution is real when $a$, $b$, and $t$ are real (and $t$ isn't a multiple of $\frac{\pi}{2}$). However, adding the `Reals` condition breaks things:               Solve[ Tan[theta] == (b*Sin[t])/(a*Cos[t]), theta, Reals] // InputForm         > >     Solve::nsmet: This system cannot be solved with the methods available to > Solve. >   >     Solve[Tan[theta] == (b*Tan[t])/a, theta, Reals] >   Why?


title: Is there a Mathematica barcode reader?

text: Is there a _Mathematica_ barcode image reader (much like `TextRecognize`) that allows the user to enter an image of a barcode and then read it to get an output string?


title: How can I ensure that I am constructing patterns in the most efficient way possible?

text: Inspired by this answer, I am interested to know if there are best practices or rules of thumb for constructing patterns, for example for use in function definitions (`f[x_ _Pattern_ ]` or `f[x: _Pattern_ ]`), replacement rules (`expr /. x: _Pattern_ :> y`), or functions that use patterns as arguments (e.g. `Cases`). Leonid mentions that "syntactic patterns", without `Condition` or `PatternTest` elements, are faster for things like `Cases`. Is this a general observation for all pattern-matching constructs in Mathematica, or is it specific to `Cases`? Is there a definition of a syntactic pattern as opposed to other kinds? And if the test in question requires "slower" constructs like `BlankNullSequence` (`___`), are there workarounds or optimisations that are effective, or is it not worth the time spent optimising code?


title: One ChartLegend for multiple charts in Dataset?

text: Dataset's documentation shows how to leverage GroupBy operator at multiple levels               titanic = ExampleData[{"Dataset", "Titanic"}];          titanic[GroupBy[Key["sex"]], GroupBy[Key["class"]], ratio, "survived"]      Taking a step further, can generate summary graphics in one line:               titanic[GroupBy[Key["sex"]], GroupBy[Key["class"]],       Counts /*        KeySort /* (PieChart[#, SectorOrigin -> {Automatic, 1},           ChartLegends -> Automatic] &), "survived"]      ![enter image description here](http://i.stack.imgur.com/p3Gmi.png) KeySort insures uniform color assignment to `True` and `False`; without it, some charts will have inverted colors. Since all charts share the same interpretation, the 6 ChartLegends are redundant. Is there an option for a single legend to appear, outside the frame of the Dataset? Wouldn't it be great if the various Chart functions returned associations like `<|"chart"->Graphics[...], "legend"->Graphics[...] |>` that can be more easily processed. Also, `BarChart[#, ChartLegends->Automatic]` inside Dataset doesn't work, but adding manual values, eg ChartLegends->{"T","F"} works.


title: Controlling ListPlot Line Colors

text: I am using `ListPlot` to display from 5 to 12 lines of busy data. The individual time series in my data are not easy to distinguish visually, as may be evident below, because the colors are not sufficiently different. ![enter image description here](http://i.stack.imgur.com/PiMMh.png) I have been trying to use `PlotStyle`, `ColorData`and related functions to get better colors. I would rather not have to specify a specific list of colors because the number of plot items varies from test to test. I created a toy plot to experiment with - the problem is illustrated by lines "F" and "G", which seem to be almost the same color. `PlotStyle` -> `ColorData` doesn't seem to work. Is there a simple way to do this?               ListPlot[Table[i*Range[0, 10], {i, 1, 5, 0.5}]      , Frame -> True, Joined -> True, PlotRange -> All      , PlotLegends -> SwatchLegend[Characters["ABCDEFGHIGKLMNOP"]]      , PlotStyle -> ColorData["TemperatureMap"]  ]      ![enter image description here](http://i.stack.imgur.com/Wdi0O.png) It looks like               ListLinePlot[Table[data2*i, {i, k}], PlotStyle -> Thick,      ColorFunction -> Function[{x1, x2}, ColorData[c1][x2]]]       from another question may be the answer. I didn't see that before. I'll try it out. I don't think I really understand `ColorData`. Meanwhile, if anyone has generally enlightening comments, I would appreciate them.


title: How to save the result in the Notebook (.nb) and shut down the computer when the calculation is done

text: I have a notebook(.nb) which its calculation is time-consuming and long. I can not observe it if the calculation is done or not. Therefore, I want to : (1) Save the results in the notebook(.nb) ( I do not want to save the data in a .Xls,.CSV,... file) and then (2) Use a command in that notebook(.n) to shut down the computer from _Mathematica_ when the calculation and saving the data is done. I wonder if you could possibly help me with this problem. P.S: I have already searched the documentation and found `NotebookSave[]` command, but I'm not sure if it is a proper command to save the notebook. However, I couldn't find anything relate to shuting down the computer after calculation.


title: How to create a list of pairs from 1d list(s)?

text: Say I've got two 1-dimensional lists               A = {1,2,3}     B = {a,b,c}      How do I   1. create a list of all pairs from list `A` such that the result looks like `{{1,2},{1,3},{2,3}}`?   2. create a list of all pairs from lists `A` and `B` such that the result looks like `{{1,a},{1,b},{1,c},{2,a},{2,b},{2,c},{3,a},{3,b},{3,c}}`? I would also need both options, one with no duplicates as above and one with duplicates, e.g. one where the result from case 1 also includes `{{2,1},{3,1},{3,2}}`.


title: Listing all combinations produced by picking one element from each of several sets

text: I have a problem like this, I am given the following sets `{a,b,c}, {d,e,f}, {h,i,j}`. I want to pick one element from each set, and output a list of all the possibilities. The output will be a set of sets, all which have the length `3`. I have tried many different approaches now.


title: NestList with a list inside?

text: I'm new to _Mathematica_ , and was looking for more efficient ways to implement the `Do` loop below. `a`, `b`, `c` and `d` are all constants, but I'm also using a list in the loop. Is this possible to implement with `NestList`? I haven't been able to find any examples with a list being used inside of `NestList`.               Do[     X = Tanh[a.input[[i]] + b.X + c];     Y = d.X;     YOut = Append[YOut, Y];      ,{i, Length[input]}];      Thanks! * Sorry for the confusion, I tried to simplify my code for the sake of brevity.               Do[     X = Tanh[Win.input[[i]] + Wres.X + Wbias]];     Y = WOUT.X;     YOut = Append[YOut, Y];     , {i, Length[input]}     ];      `Win`, `Wres`, `Wbias`, and `WOUT` are all appropriately sized matrices. This do loop is part of a testing routine for Reservoir Computing, a type of machine learning. With help from your answer, I'm rewriting the above as:               f = WOUT.(Tanh[Wbias + Win.#2 + WRes.#1]) &;     YOut = FoldList[f, X, input];      Will try it out now. Thanks for the help!


title: Bessel derivatives

text: I tried to expand `BesselJ[k,x]` function into a Taylor series with `Series` command. Here both `k` and `x` are some functions of the expansion variable $\lambda$, so in the expansion, derivatives with respect to both `k` and `x` occur. The problem is, whenever there is a term that is the derivative of both variables, _Mathematica_ leaves it as (e.g.) `Derivative[2, 1][BesselJ][0., 2.40483]` and doesn't give a numerical value in the end. First I thought it is because assigned values aren't exact -- since the above `2.40483` is the value of `BesselJZero[0, 1]`. However, it also doesn't give numerical or analytical result for the following easier calculation:               D[BesselJ[k, x], {k, 1}, {x, 1}] /. {k -> 1, x -> 1} // N     (* -> Derivative[1, 1][BesselJ][1., 1.] *)      But, when the order of the differentiation changes, it gives numerical results:               D[BesselJ[k, x], {x, 1}, {k, 1}] /. {k -> 0, x -> 1} // N     (* -> 1.22713 *)      It works with `x -> BesselJZero[0, 1]` as well. First question: why is this the case? Second (if it is possible): how can I handle it with `Series` command?


title: confusion about the use of MapThread and out product

text: To help distinguish the various dimensions, I have a model which outputs a vector in a series of time intervals, I then construct a list of these models. Next, I would like to compute the outer product of the vector at each time step. I think I can do something like the following               tdim = 100;     vecdim = 3;     modeldim = 2;          (*veclist is supposed to represent the output for 2 models*)     veclist = Table[v[model, t, a], {model, modeldim}, {t, tdim}, {a, vecdim}];          outerproduct[x_, y_] := Outer[Times, x, y];     MapThread[outerproduct, {veclist, veclist}, 2]      I think this does the right thing. It does not mix the models or the time steps. As far as I can tell it is taking the outer product at the appropriate level. However, I would like to be able to do this in the case where model 1 and model 2 have a different number of time steps and I can't see a neat way to do this. If I do the same as above but for 2 models with a different number of time steps, I get an error because the rank of the list has changed:               tdim1 = 3;     tdim2 = 4;     veclist1 = Table[v1[model, t, a], {model, 1, 1}, {t, tdim1}, {a, vecdim}];     veclist2 = Table[v2[model, t, a], {model, 2, 2}, {t, tdim2}, {a, vecdim}];     veclistall = Join[veclist1, veclist2];     MapThread[outerproduct, {veclistall, veclistall}, 2]      For the problem I have in mind these lists are much much larger, so finding an efficient way of doing this would be a great help. Any suggestions would be hugely appreciated