title: Multiply value if it includes a period

text: I download data from an online source, now I have a problem: the source code doesn't allow to differ between values of 10 (which actually stands for 10) and 10.000 (which is 10'000, but _Mathematica_ reads it as 10 as well). Now I'm thinkg about letting all values that include a period like `10.000` multiply with the factor 1000 and let all the values without a period remain the same. Lets say I have the following vector `a={10.350,20,20.000,10.700,30,40.522}`. What I want to do is to multiply all elements of `a` except the second (`20`) and fifth one (`30`). Is there a chance to distinguish between 20 and 20.000 ? Thanks for your help in advance!!


title: How can I get Mathematica to allow me to apply FindRoot to an expression that contains NIntegrate?

text: I am trying to run the following command in Mathematica:               FindRoot[NIntegrate[D[f[x], x] / Sqrt[1 - x^2], {x, 0, 1}] - d, {a, 245}]      As you might expect, a is buried within f[x] and 245 is a reasonable initial guess at its value. As you may also have guessed, the above integral is an expression for d in terms of a but I can't do the integral in closed form so I can't invert the expression to find a in terms of d. So, I wish to numerically integrate my integral expression for d but that just give me the d that corresponds to a given value of a. I want to go the other direction, find the a value that corresponds to a given d. That's what I'm using FindRoot for (kudos if you're staying with me so far, it's taken me days to get to this point). So here's the problem: NIntegrate gets upset if anything in the integrand is an undefined variable so every variable in the above integrand is defined except a (because I don't know it yet). However, FindRoot does know it. What I mean is, FindRoot is presumably running in an iterative loop and in every iteration it is working with a guess at a so somewhere in the bowels of the code, a always has a definite value. If I could somehow get NIntegrate to know this, I think I can get the above command to work (which would be a nice example of a powerful one line Mathematica operation). Any tips or do you think I'm trying to do something impossible? Thanks, Dessie.


title: Autorotating 3D plots

text: These days, I have to produce quite a few 3D surface plots (mostly functions of the type $\rho(\theta,\phi)$ plotted with `SphericalPlot3D`). To exchange these results colleagues who don’t use Mathematica, or to include them in presentations, I need to export these plots as movies showing the surface rotating. What I’d love to do is to be able to choose one graph, and just export it as autorotating around the current vertical axis (i.e. the axis contain in the plane of the screen, and directed upwards). This not being possible, I'm trying to do the next best thing: a procedure that takes as an argument the produced 3D graphics (say, the output of `SphericalPlot3D`) and makes it automatically rotate. Here’s what I’ve been able to do with `Animate`, but I could follow the same logic and export it directly instead.               rotateMeHarder[g_] := Module[{range},        range = Max /@ (Abs@PlotRange /. AbsoluteOptions[g, PlotRange]);        Animate[         Show[          Graphics3D[{Red, Thick, Line[{{-1.2*range[[1]], 0, 0}, {1.2*range[[1]], 0, 0}}]}],          Graphics3D[{Green, Thick, Line[{{0, -1.2*range[[2]], 0}, {0, 1.2*range[[2]], 0}}]}],          Graphics3D[{Blue, Thick, Line[{{0, 0, -1.2*range[[3]]}, {0, 0, 1.2*range[[3]]}}]}],          g,          ViewPoint -> RotationTransform[\[Theta], {0, 0, 1}][{0, 2*Max@range, 0.2*Max@range}],          SphericalRegion -> True, Boxed -> False],         {\[Theta], \[Pi]/20, 2 \[Pi] + \[Pi]/20, \[Pi]/20}]        ];          p = SphericalPlot3D[       10 + 5*Re@SphericalHarmonicY[3, -3, \[Theta], \[Phi]], \[Theta], \[Phi],       Boxed -> False, Axes -> None, PlotStyle -> Opacity[0.7]];     rotateMeHarder[p]      * * * What I like about this:   * It does generate a nicely rotating object in simple cases.   * It draws axis lines on top of my graph, but that's just because it looks great on my pictures, it's not a requirement for the question… What I don’t like, or am unsure about:   * It doesn’t start with the current orientation of the graph, but works with a fixed rotation vector (along the 3D $z$ axis) and a fixed starting position (slightly above the $xy$ plane). If I understood this answer correctly, they is not way of retrieving the current viewpoint for a given interactive 3D graph. So bad!.   * It doesn’t seem very robust. In particular, it only works for 3D plots centered around the origin, which extend about the same length in each axis direction (i.e. does not deal with very anisotropic surfaces).   * It leaves a lot of white padding around the graphics. * * * So, the question is: what do you think of this code? **How could I make it more general, more robust, or in any way closer to my initial goal of a one- size-fits-all exporting procedure for 3D graphics?**


title: How to get a more traditional-looking for protected constants

text: Is there any solution to make rule to export as a traditional form protected constants. Here is example which doesn't work.               aa = I0*I0;     rules11 = {I0 :>      \!\(\*SubsuperscriptBox[     OverscriptBox[\(I\), \(^\)], \(0\), \(0, 2\)]\)};            aa //. rules11 // TraditionalForm


title: Creating a simple interactive app with CDF

text: I would like to implement an algorithm I have created using a ( _free_ ) CDF document as interface. The idea is:   * The user has to give some input values (maybe through a sort of text box, if possible —a slider would also apply).   * When the user has finished to inform those input values, he/she _starts_ the algorithm (by pressing a sort of button, if that is possible).   * That action makes the algorithm to start computing.   * When the algorithm has finished (that would be a few seconds later), the user can see in the CDF document some numerical results and some plots (that could be interactive, but no matter if they are not). The process is supposed to be transparent and black-boxed to the user. Specifically, _I do not want the user to see the code of the algorithm_ (this is an important point), but only the input boxes and the results. I have been looking into the Internet but I have not been able to find any "getting started" CDF tutorial or something similar. My questions are: (1) Is it possible to build such an app in ( _free_ ) CDF format (provided that the algorithm is already programmed in Mathematica as a series of steps)? (2) Which are some basic places to start learning to create CDF documents, step by step??? **[EDITED 5 aug 2014]** As far as I understand, the most reliable way to create a working free CDF document is embedding all the code within a `Manipulate` interactive command. I wonder if I can sort of _embed_ a quite simple algorithm (several steps starting from some input info and finishing with a numerical and graphical output) within a `Manipulate` sentence. **[EDITED 6 aug 2014]** I've been playing around, and I found that things like this are allowed:               Manipulate[f[x_] := Sin[x]; {Plot[f[x], {x, 0, a}], f[a]}, {a, 1, 50}]      I mean, it works —I can connect several expressions with `;`, and also I can show both graphical and numerical results. I am going to continue trying things, and if I manage to get the results I want, I'll post it as an answer to this question. Of course, any suggestions, help, comments... are still welcomed.


title: Memory problem in Mathematica 10

text: I'm having a problem with memory. I'm doing nonliner fits of several data lists to a system of differential equations. When I evaluate the "Do" cycle the memory grows with the iteration step up to my RAM memory (8GB). I tried to Clear the functions "sol" and "modelSIR" in each iteration, but even so the kernel keeps everything in memory. What is event more strange is that I ran this in Mathematica 9 and everything was ok. Now I'm running it in Mathematica 10. I post here one example of the data list.               DataANotTruncadaShifted[[1]] = {{0, 0}, {1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {6,0}, {7, 1}, {8, 4}, {9, 6}, {10, 4}, {11, 5}, {12, 4}, {13, 6}, {14, 11}, {15, 6},{16, 9}, {17, 15}, {18, 18}, {19, 24}, {20, 5},{21, 9}, {22, 8}, {23, 15}, {24, 12}, {25, 12}, {26, 8}, {27, 6}, {28, 0}, {29, 0}, {30, 1}, {31, 0}, {32, 0}, {33, 8}, {34,3}, {35, 6}, {36, 1}, {37, 1}, {38, 1}, {39, 0}, {40, 0},{41, 0}, {42, 0}, {43, 0},{44, 0}, {45, 0}, {46, 0}, {47, 0}, {48, 0}, {49, 0}, {50, 0}, {51, 0}};               AList = Table[{}, {i, 1, 18}];     gamaList = Table[{}, {i, 1, 18}];     t0List = Table[{}, {i, 1, 18}];               Do[     Clear[sol, modelSIR];          sol = ParametricNDSolveValue[     {     beta[t] == (1000*gama)/(1000 - 1) + A*1/(1 + Exp[-(t - t0)/1]),     s'[t] == -((beta[t]*s[t]*i[t])/1000),     i'[t] == (beta[t]*s[t]*i[t])/1000 - gama*i[t],     r'[t] == gama*i[t],     s[0] == 1000 - 1, i[0] == 1, r[0] == 0}, {s, i, r}, {t, 0, 53}, {A, gama, t0}];     modelSIR[A_, gama_, t0_][t_] := Through[sol[A, gama, t0][[2]][t],List]/;And@@NumericQ/@{A,gama,t0,t};               fit = NonlinearModelFit[DataANotTruncadaShifted[[n]], {modelSIR[A, gama, t0][t],0.1 < A < 5, 1 < gama < 5, 0 < t0 < 40}, {A, gama, t0}, t, MaxIterations -> 200, Method -> {"NMinimize"}];               Afit = fit[[1]][[2]][[1]][[2]];     gamafit = fit[[1]][[2]][[2]][[2]];     t0fit = fit[[1]][[2]][[3]][[2]];          AList[[n]] = Afit;     gamaList[[n]] = gamafit;     t0List[[n]] = t0fit;          , {n, {1, 3, 4}}]


title: Doing arithmetic with binary numbers

text: How do I execute binary operations in Mathematica? I want to to multiply say 1010101011 (binary) to 1111101110 (binary) and getting the result 10100111101111111010? Then I want to add the result to say 10101010000111 (binary)? Assume the all binary numbers are given as lists such as {1,0,1...}. Thanks!


title: Seeking strategies to deploy a function securely without a front end

text: **Background** I have a fuction, which calculates an analytic solution to a multi-dimentional geometry problem. The function takes a list of real numbers (typically less than a dozen) and outputs a list of reals of equal length (12 reals in -> 12 reals out). The function runs fast and doesn't require a lot of computational resources. More typical solutions to the problem involve statistical sampling of something like 10^5 points and use a substantial parallel computing infrastructure or lots of time. The idea has a number of commercial applications including epidemiology and insurance. The function uses a number of "high-level" Mathematica functions including:               CholeskyDecomposition[]     IdentityMatrix[]     LinearSolve[]     Simplify[]      **What I need** I need to deploy this function into a Windows based technology environment so that the users can call the function from some of their process workflows (e.g., they may call it from a database stored procedure or another program). I need a deployment solution and have some concerns I need the solution to address, especially:   * keep the code proprietary;    * deploy reliable code; and    * make the function easy to use in the target environment. The target environment does not include Mathematica; they have no other need to run Mathematica, CDF, or Wolfram Player Pro. They have no need or interest in running a Mathematica front end. **An ideal but likely unworkable solution** Generation of a C code executable would provide an ideal solution, but the function's use of the "high-level" Mathematica functions listed above excludes this as a simple option. I'd consider developing my own versions of the high-level functions from lower-level Mathematica code that one could then compile to C code, but this just seems silly (and probably hard) If anyone has suggestions along these lines, thinks it possible, or can direct me to examples please let me know. One can readily get C implementations of the Cholesky Decomposition, but that would introduce a whole other layer of complexity. Also, I never wrote much C code and what I did I did a very long time ago. **A workable solution?** Running the kernel and the code from a script file (without the frontend) seems like a place to start: See: Mathematica Scripts It looks like I can send parameters to a script. From the documentation on `Script Parameters` > ...When running a Mathematica script, you may often want to modify the > behavior of the script by specifying parameters on the command line. It is > possible for the Mathematica code to access parameters passed to the > Mathematica script via $ScriptCommandLine. Promising, but the documentation does not provide a clear example of how I could call a `Mathematica Script` with a list as a parameter. If anyone has suggestions on how to go about this or can refer me to information that gets me part of the way to a solution, please let me know. * * * _Sidebar -- the tutorial makes no mention of running Mathematica Scripts under Windows. This has me a little worried. An answer to anearlier question I asked implies that one can do this on a Windows platform see: Chris' answer at the bottom. Does anyone know for certain? Examples appreciated._ * * * Using `Encode[]` seems like it could also help by securing the code and making it less likely that anyone could view it. This raises some questions: The documentation for `Encode[]` states: > On certain computer systems Encode["source","dest",MachineID->"ID"] can be > used to generate an encoded file that can be read only on a computer with a > particular $MachineID. This would help a great deal in securing the code, but the documentation does not list the "...computer systems..." on which this will work. Any ideas? More `Encode[]` questions. Does one use `Encode[]` to encode:   * single functions?    * notebooks including the function?   * packages (.m files)?   * something else? The example in the documentation doesn't seem clear on this. **The beginning of a solution...** It seems like the following begins to give me a workable approach if I can clear up some of the issues:   * Use `Encode["source", "dest", MachineID->"ID"]` to secure the code.   * Run the kernel(s) and the function from a `Mathematica Script`. The target environment will need a Mathematica license and processes and policies to launch and shut down the kernels, but I can work with that. Can I create a workflow wherein I:   * launch the kernel by a script at the begining of a day;    * use a script to call the function on the kernel throughout the day; and    * close the kernel at the end of the day? This would help address the reliability issue. Or should the kernel launch, run the function, then close everytime I want to use the function? So...I've got a general idea of one way to go about this. I could use some guidance take it down another level of detail. Oh, course if anyone has other ways to go about this, let me know.


title: Simulation Beta Distribution

text: Suppose a function such as: $\phi^{\alpha} (x,y) = \left\\{ \begin{array}{l l} \alpha x & \quad \text{if $x < y$}\\\ x & \quad \text{if $x = y$}\\\ \alpha x + (1 -\alpha) & \quad \text{if $x > y$}\\\ \end{array} \right.$ I wish to run a simulation for 5 random walks (each with length 100) on $\phi$ where $x$ is drawn from a beta distribution with parameters (3,1) and $\alpha = 0.5$. I don't know how to deal with $\phi$ in the random walk process, especially given its 3 conditions. EDIT: $y$ is the mean of all the previous $x$. For instance, suppose we are at time $t=3$ and observations start at $t=0$. Then, $y_3 = \frac{x_0 + x_1 + x_2}{3}$. * * *               ϕ[x_, y_] := Piecewise[{       {α*x, x < y},        {x, x == y},        {α*x + (1 - α), x > y}}]     ϕ[x, y]      ![](http://i.stack.imgur.com/8ODgj.png)


title: Eliminate 3 Variable from 4 Equations

text: I am trying to use _Mathematica_ to `Eliminate` 3 following variable from 4 equations. Any clue or link to similar solved problem is highly appreciated:               eq = {       Cos[θ] + Cos[ϕ] + Cos[ψ] == a,       Sin[θ] + Sin[ϕ] + Sin[ψ] == b,       Cos[2 θ] + Cos[2 ϕ] + Cos[2 ψ] == c,       Sin[2 θ] + Sin[2 ϕ] + Sin[2 ψ] == d};     Eliminate[eq, {θ, ϕ, ψ}]


title: Changes in Handling of Real Zeros

text: I recently upgraded from Mathematica 5 to Mathematica 8 and I have a number of notebooks that no longer work correctly. The problems relate to the use of units. I don't need complicated unit conversions so I typically just tag values with symbols for the units. Under Mathematica 5, I could write the following (I understand that this example isn't physically meaningful):               3. in + 4. in - 7. in + 5. lb      And Mathematica would return               5. lb      Now, under Mathematica 8, I get               0. + 5. lb      This breaks a large number of notebooks. Can someone explain what is happening, and what if anything I can do to get the old behavior back? Thanks!


title: Aligning two lists

text: I have two lists, L1 and L2, each with a key and some data. Let us say the key is a person's name, a string, and the data follows. (To respond to _rasher_ 's query:) Let us also assume the lists are sorted by key:               L1 = {            {"Joseph O'Rourke", data1, data2, ... },            ...          }      I would like to "align" the two lists in the following sense. If L1 has a name A that is not in L2, then L2 is padded to include a "blank" record for A. And vice versa: If L2 has a name B that is not in L1, then L1 is modified to include a "blank" record for B. Then I will have two lists that "align":               L1' = { {A,...}, {0,...}, {C,...},  {D,...}, ...}     L2' = { {A,...}, {B,...}, {0,...},  {D,...}, ...}      where maybe `0 == {}`. With the lists aligned in this fashion, I could make a two-column table (one column per list) that would directly compare one list against the other. My question is: > What is a clean method for accepting L1 and L2 as input, and returning L1' > and L2' as output, with the latter two lists aligned as above? I can accomplish this via tedious list For-loops, but I suspect the cognoscenti :-) will offer more concise and efficient methods. Thanks for your help!


title: Function Interpolation with Automatic / Algorithmic Values Mesh

text: I have an underlying function f(x,y,z) that is computationally intensive, but is smooth and continuous. I'm needing to find the function values along a line in xyz. Currently, I'm calculating f at discrete steps and I'm wondering if there is a way to get mathematica to automatically chose the step size and work out an interpolating function based on some inputs like how accurate I need it to be and what the initial step size should be. I'm thinking it would kind of work like the mesh function does in plotting by evaluating functions more often in areas of higher complexity. Does anyone have any ideas where to start?


title: Stopping Agglomerative clustering under a condition in Mathematica

text: How do I instruct Agglomerative clustering to stop/NOT merging two particular clusters if the distance between the two clusters is larger than a threshold value? I know that we can implement a custom distance measure and a custom linkage function. Distance measure says how to measure the distance between any two data points. So even if I implement a custom distance measure, it just says what is the distance between any two data points. Where in the code should/can I mention a threshold value, that if not met, should prevent thw clusters from being merged. Thus, at the end, if only two clusters are remaining, and if the threshold value is not met between these two clusters, then these two clusters should not be merged into one global cluster. Is this possible in Mathematica?


title: Computing Many Slow I/O Operations

text: In working on a custom stock screener, I often need to run mathematica code like this:               {#, FinancialData[#, "DividendYield"]} & /@ Take[FinancialData["NYSE:*"], 30]      In this example, I've limited the result set to 30, but ideally I'd like to get the dividend yield for a much larger set. This is a specific example of a more general problem I have with mathematica, which is that sometimes I need to run a large number of distinct network IO calls and this blocks further computations. Is there some workaround for writing calls like this that won't block further computations? I am a fairly competent programmer and therefore can implement a system in my Mathematica code to compute results one at a time, but I am trying to avoid reinventing the wheel. I feel this must be a very common problem for Mathematica users who use the built in data sources/Wolfram|Alpha integration.


title: Data acquisition from NI USB-6008, NI-DAQmx

text: I want to connect an interface from National Instruments to Mathematica in mac, i already download the driver Ni-DAQmx_Base_3.6 from NI page. How to tell Mathematica to dump data from the interface?


title: How to create strong types?

text: In a program I'm writing, I create a list of lists, that looks something like this:               {{100, {1,2,3,4,5}},      {105, {2,4,6,8}},      {42, {42,39,56}}}      I then pass this list of lists around to other functions. All well and good -- the problem is that this program has been developed iteratively, and this representation has changed, and so now I'd like to take more care in checking that the function is receiving the right kind of input. In another language I could make this list of lists into its own type, and the compiler would enforce things. I know Mathematica has some facility for doing type checking, at least with primitive types, such as:               myFunc[a_String, b_Integer] := ...      But are there facilities available for creating (and enforcing, or at least checking) one's own ADTs?


title: Function for Autocorrelation

text: Is there a built in function to compute the autocorrelation of a signal ?


title: TeX and TraditionalForm

text: I have a little problem, and hope, with your help, I'll be able to solve it. As you got from the title, I have some trouble with TeX in Mathematica. Imagine, I want to output a nice DisplayFormula, such that it would represent a function, which evaluates piecewise. In TeX it would look like this (Let's take a uniform distribution for example) $$\left\\{ \begin{aligned} &0,& t\leq x_{\min} \\\ &\frac{t-x_{\min}}{x_{\max}-x_{\min}},&x_{\min}<t\leq x_{\max} \\\ &1,& t>x_{\max} \end{aligned} \right.$$ So what's the best way to create that exact output in Mathematica? I've tried `TraditionalForm[CDF[UniformDistribution[{x_ {min}, x_ {max}}], t]]`, but that gives me almost the same output, but without the zero part. ![enter image description here](http://i.stack.imgur.com/D4N8f.png) I do know, it's not significant whether to write or not the 0 part in the piecewise function. So it works well for CDF, but with PDF there's an extraneous part is shown at the end               TraditionalForm[CDF[UniformDistribution[{x_ {min}, x_ {max}}], t]]      ![enter image description here](http://i.stack.imgur.com/OZUup.png) So in the CDF Mathematica's decided not to output the 0 part, but in the PDF it's shown. I've also tried to use               TraditionalForm[       Piecewise[        {{0, t <= Subscript[x, min]},         {(t - Subscript[x, min])/(Subscript[x, max] - Subscript[x, min]),           Subscript[x, min] < t <= Subscript[x, max]},         {1, t > Subscript[x, max]}},        t       ]     ]      But that variant also reveals the part that I haven't specified. ![enter image description here](http://i.stack.imgur.com/xCkPI.png) The last thing I've tried to use is `ToExpression["TeX source",TeXForm]`, but this one can't parse the simple TeX source with aligned environment (or I haven't found a way to make it work).


title: Why does Hash return different values in Version 7?

text: This function does not work correctly for me. The generated Gravatars do not match the ones actually produced by using the corresponding address. The problem was traced to differing output from the `Hash` function. VLC points out that the `Hash` documentation pages for version 7 and version 8 have common examples but show different outputs. From version 7 I get:               IntegerString[Hash["gmailuser+10511@gmail.com", "MD5"], 16, 32]      > >     "cc270b8fbfb33469629c14e358183dd7" >   Version 8 users apparently get: > >     "d9c48b644b8cc89bbcd07ec7a54dafc9" >   Why do I get a different result and how do I get the right one?


title: Operator-Input Form for Lists?

text: The documentation on Operator-Input Forms shows the following example ![enter image description here](http://i.stack.imgur.com/trzvh.png) which suggests that there is an alternative, convenient, operator-style, tidy technique for inputting lists. However, there is not enough clarity in the example to determine what that technique or operator might be. I tried `e11``Space``e12` and `e11``Tab``e12`, but they both result in `Times[e1,e2]`, somewhat predictably, since space normally denotes multiplication in Mathematica notebooks. Any ideas whether there is an operator form for inputting lists? What does the documentation mean in this case?


title: How to fit a one-dimensional dataset with respect to several bounded parameters?

text: I have this set of data               mydata={{1244,0.90237},{1289,0.83072},{1306,0.76147},{1360,0.6094},{1388,0.40952},{1428,0.29419},{1488,0.15592},{1494,0.11718},{1527,0.09192},{1537,0.07757},{1590,0.04546},{1594,0.04563},{1654,0.03229},{1737,0.01976},{1740,0.01949};      and I need it fitted into a function of the form               Exp[-(A*TT*^n*Exp[-Ea/(R*TT)])*t]      where $R$ is the gas constant $R=8.31\dots$ and $t=0.002$. This is a decay and the function in the exponent is the Arrhenius factor. I checked the help for the fitting tools, but what I found was either in one variable, or in more variables, but for a higher dimensional plot. I also have variable bounds which I need to implement. I have this simple curve with parameters               A, n, Ea      $A$ is bounded by $10^{12}$ and $10^{14}$, $Ea$ lies between $270000$ and $320000$, $n$ close to zero (single digit). The plot of the function should be with respect to temperature $TT$ is the varying variable on the x-axis.


title: Trial version 10 vs Version 10 Prerelease 13

text: When I open the new trial version (creation id 5099521; 10.0.30732.17750) I get these error messages ![enter image description here](http://i.stack.imgur.com/Ez2Ry.jpg) and only a partial view of the "About" box ![enter image description here](http://i.stack.imgur.com/dUUP1.jpg) I haven't run into any particular problem, except that color of 3D plots are different from version 10 prerelease 13 (but now using PlotTheme -> {"Classic", "ClassicLights"} thanks to this web site!) Using Windows 7 64 bit professional


title: Simpler way to fill date gaps with zero values

text: One basic problem when working with data like sales and dates is the case where you dont't have sales in all days, so you have to fill it to take information as average or to make a plot. See this toy code as example:               dateList={{{2012,1,1},1},{{2012,1,2},2},{{2012,1,5},3},{{2012,1,8},4}};      And I need to get this answer:               {{{2012,1,1},1},{{2012,1,2},3},{{2012,1,3},0},{{2012,1,4},0},{{2012,1,5},3},{{2012,1,6},0},{{2012,1,7},0},{{2012,1,8},4}}      where the missing dates are filled with value zero. They are date and sales values that I get from an SQL database. I created this functions, but I fell that it could be simplified:               getDateRange[dtIni_,dtFim_]:=NestWhileList[DatePlus[#,1]&,dtIni,(#!=dtFim)&]          fillDateGaps[list_]:=Module[{sortedOrgList,dateRange,listGaps},         sortedOrgList=SortBy[list[[All,1]],#[[1]]&];         dateRange=getDateRange[First@sortedOrgList,Last@sortedOrgList];         listGaps={#,0}&/@Complement[dateRange,sortedOrgList];         Union[list,listGaps]     ]      With this function I can do calculations and things like this:               DateListPlot[fillDateGaps[dateList], Joined -> True]      ![DateListPlot with filled zeros](http://i.stack.imgur.com/zmXQg.png) How to make it simpler and faster?


title: Scaling edge thicknesses

text: * * * **UPDATE** There may be some confusion as to the specification of the problem. kguler's answer doesn't really answer the question. I'll try to elaborate a bit at **the bottom of the post**. * * * One problem with the solutions of the custom arrow shaft question is the specification of the edge thickness. In the design of the arrows, the thickness of the edge _in relation to the overall size of the arrow_ is part of the effect one wants to achieve. ![Mathematica graphics](http://i.stack.imgur.com/ajCIw.png) Unfortunately, the two methods that can be used to specify the edge thickness, namely `Thickness` and `AbsoluteThickness` are not sufficient for this goal. As an easy illustration of the problem, I'll draw some circles here. **Thickness**               Graphics[{FaceForm[], EdgeForm[{Thickness[0.1], Blue}], Disk[{0, 0}]}, ImageSize -> 200]      ![](http://i.stack.imgur.com/tummV.png) Add some **identical (!)** copies of the same circle:               Graphics[{FaceForm[], EdgeForm[{Thickness[0.1], Blue}],               Disk[{0, 0}], Disk[{3, 0}], Disk[{6, 0}]}, ImageSize -> 600]      ![Mathematica graphics](http://i.stack.imgur.com/Z9nqd.png) The number in the `Thickness` specification is a fraction of the horizontal image extent. **AbsoluteThickness**               Graphics[{FaceForm[], EdgeForm[{AbsoluteThickness[20], Blue}], Disk[{0, 0}]}, ImageSize -> 200]      ![Mathematica graphics](http://i.stack.imgur.com/qZKuy.png) Now, let's reduce the image size:               Graphics[{FaceForm[], EdgeForm[{AbsoluteThickness[20], Blue}], Disk[{0, 0}]}, ImageSize -> 70]      ![Mathematica graphics](http://i.stack.imgur.com/niktc.png) In both cases, the ratio between the edge thickness and the object size changes. Sometimes that may be desirable, but here it isn't. What is needed is either a thickness specification that is related to object size or a status variable from which the current image extent can be read, so that with known object size the edge thickness can be scaled. The latter would be something akin to `CurrentValue` or so. Something self-referential like               pl = Graphics[{Text[Norm@PlotRange[pl][[2]] // Dynamic, {10, 10}]}]      could work, but is rather ugly and, frankly, scary. When I changed `PlotRange` to `ImageSize` I got my frontend hanging. Any ideas? * * * **UPDATE** Trying to further clarify the question. * * * First, some definitions: ![Mathematica graphics](http://i.stack.imgur.com/n0SyH.png) We have one or more objects with a given **object size**. In this case, circles with a radius of one. This size is given in Mathematica's internal, dimensionless canvas coordinate system. We want to specify the **object edge thickness** in terms of this object size. However, MMA doesn't have that capability. You have to either specify the `EdgeForm` as `Thickness` (which measures edge thickness as a fraction of the horizontal `PlotRange`) or as `AbsoluteThickness` (which measures edge thickness in terms of printer's points, 1/72 of an inch). The `PlotRange` is the dimensionless size of MMA's canvas as displayed in the figure. It is fully independent of the `ImageSize`, which determines the graphics's physical size in printer's points. This leads to the following problem :               Graphics[{FaceForm[], EdgeForm[{Thickness[0.1], Blue}], Disk[{0, 0}]}]      ![Mathematica graphics](http://i.stack.imgur.com/1xf7h.png)               Graphics[{FaceForm[], EdgeForm[{Thickness[0.1], Blue}], Disk[{0, 0}], Disk[{3, 0}], Disk[{6, 0}]}]      ![Mathematica graphics](http://i.stack.imgur.com/CoJy8.png) Both figures have the same `ImageSize`, but the `PlotRange` has increased (more of MMA's internal canvas is revealed), which means that edge thickness related to object size increases too, since the thickness in canvas terms increases whereas the object remains at the same canvas size. The circle's edge now takes up most of the circle's area, which wasn't the case before. If we specify thickness with `AbsoluteThickness` we get:               Graphics[{FaceForm[], EdgeForm[{AbsoluteThickness[10], Blue}], Disk[{0, 0}]}]      ![Mathematica graphics](http://i.stack.imgur.com/YYuA4.png)               Graphics[{FaceForm[], EdgeForm[{AbsoluteThickness[10], Blue}],                Disk[{0, 0}], Disk[{3, 0}], Disk[{6, 0}]}]      ![Mathematica graphics](http://i.stack.imgur.com/V3swe.png) In this case, the edge thickness _in points_ remains the same, but the object size in points decreases because the `ImageSize` in points is the same, but more objects have to be fitted in that same space, so they get less points allotted per object. Again, the edge thickness related to the object size changes. Introducing `ThicknessC` as the desired edge thickness and `ObjectSizeC` the object size, both in canvas terms, we have               ThicknessC = C*ObjectSizeC       with C the desired constant ratio of these two variables. C is responsible for the appearance of the object. For instance, we might want to have a circle where the edge thickness is 1/10 of its diameter, so C = 1/10. Since `Thickness` is a fraction of the horizontal `PlotRange` we have:               ThicknessC = Thickness*PlotRange (hor.)      and hence, to get the desired edge thickness `ThicknessC`, we have to specify a `Thickness` given by:               Thickness =  C * ObjectSizeC / PlotRange (hor.)      Similarly, we have:               Thickness = AbsoluteThickness / ImageSize      and hence,               AbsoluteThickness = C * ObjectSizeC * ImageSize / PlotRange (hor.)      It seems that any object related edge thickness specification minimally needs to know the final `PlotRange` of the figure, which, on its turn, is determined by all objects in the figure. If we're going to use `AbsoluteThickness` (but why would we bother?) we'd also need awareness of the `ImageSize` in addition to knowledge about `PlotRange`. > So, there you have it. The problem can be solved if we can obtain the final > `PlotRange`. The question to be asked is: How can we determine the > `PlotRange` of a figure while we are drawing it? Of course, `PlotRange` can be set manually, or be obtained after the fact, but that would mean something ugly like:               pr1 = -Subtract @@PlotRange[             Graphics[{FaceForm[], EdgeForm[{Thickness[0.3], Blue}],                      Disk[{0, 0}], Disk[{3, 0}], Disk[{6, 0}]}]][[1]];     pr2 = -Subtract @@ PlotRange[             Graphics[{FaceForm[], EdgeForm[{Thickness[0.3], Blue}], Disk[{0, 0}]}]][[1]];     Graphics[{FaceForm[], EdgeForm[{Thickness[0.3 pr2/pr1], Blue}],                Disk[{0, 0}], Disk[{3, 0}], Disk[{6, 0}]}]     Graphics[{FaceForm[], EdgeForm[{Thickness[0.3], Blue}], Disk[{0, 0}]}]      ![Mathematica graphics](http://i.stack.imgur.com/ESZGG.png) This works, but isn't elegant.


title: 1D Euler Equations

text: Is it possible to _accurately_ solve the 1D Euler equations in Mathematica using NDSolve? For example, let us consider the problem given here: http://www.csun.edu/~jb715473/examples/euler1d.htm Using the notation $(r,v,e)$ for $(\rho,v,E)$ we can formulate the problem in Mathematica as:               eqs = {         D[r[x, t], t] + D[r[x, t] v[x, t], x] == 0,         D[r[x, t] v[x, t], t] + D[r[x, t] v[x, t]^2 + p[x, t], x] == 0,         D[e[x, t], t] + D[v[x, t] (e[x, t] + p[x, t]), x] == 0     };      with $g:=\gamma$,               p[x_, t_] := (g - 1) (e[x, t] - r[x, t] v[x, t]^2/2);      and initial conditions               r0[x_] := 1.0 Boole[0 < x <= 0.5] + 0.25 Boole[0.5 < x <= 1.0];     v0[x_] := 0.0;     p0[x_] := 1.0 Boole[0 < x <= 0.5] + 0.1 Boole[0.5 < x <= 1.0];      Setting Dirichlet boundary conditions and throwing it into NDSolve:               ppR = 401;     ndsol = NDSolve[Join[eqs, {         r[x, 0] == r0[x], r[0, t] == r0[0], r[1, t] == r0[1],         v[x, 0] == v0[x], v[0, t] == v0[0], v[1, t] == v0[1],         p[x, 0] == p0[x], p[0, t] == p0[0], p[1, t] == p0[1]}],      {r, v, e}, {x, 0, 1}, {t, 0, 0.1},      MaxSteps -> 10^3, PrecisionGoal -> 4, AccuracyGoal -> 4,       Method -> {"MethodOfLines", "Method" -> "StiffnessSwitching",       "SpatialDiscretization" -> {"TensorProductGrid",        "DifferenceOrder" -> Pseudospectral, "MaxPoints" -> {ppR},        "MinPoints" -> {ppR}}}]      Taking the solution and plotting               DensityPlot[Evaluate[First[v[x, t] /. ndsol]], {x, 0, 1}, {t, 0, 0.1}, ColorFunction -> Hue]      ![Solution plot](http://i.stack.imgur.com/ZVXXy.png) We see some nasty numerical errors. Is there anyway to get an accurate solution using NDSolve? **Edit:** This paper suggests that the Method of Lines should apply: http://math.lanl.gov/~mac/papers/numerics/H79.pdf


title: silent soundnote and superimposing sound objects

text: In Mathematica 9, Soundnote[None] has zero duration if it is the last note in a Sound expression. For instance, the sound object               Sound[{SoundNote[None],SoundNote[None],SoundNote[1]}]      has a correct duration of 3 seconds, while               Sound[{SoundNote[1],SoundNote[1],SoundNote[None]}]      has a duration of 2 seconds. This means that a SoundNote[None] has a duration of 1 second if and only if it is not the last note, otherwise has zero duration. This does not make sense at all. Silent notes must have the same duration at any point of a musical composition. As an example of consequence of this non-sense behaviour, let us superimpose two sounds objets composed of the same number of notes, one of which has a silent note at its end:               s1 = Sound[{"Piano", SoundNote[1], SoundNote[5], SoundNote[8]}, {0, 3}];          s2 = Sound[{"Viola", SoundNote[3], SoundNote[1], SoundNote[None]}, {0, 3}];          Sound[{s1, s2}]        ![enter image description here](http://i.stack.imgur.com/vsMzb.png) You can see that they do not superimpose as you might expect. Each instrument should play a note every second. What happens instead, is that the Viola (green) plays every 1.5 seconds because has a silent note at the end.


title: Strange behavior of `BoundaryMeshRegion`

text: `BoundaryMeshRegion` is new function of version 10. I am not familiar with the function. I want to decide whether a point is inside or outside in the Boundary using `RegionMember`. This code is not able to work. why is it?               BoundaryMeshRegion[{{4, 4, 4}, {4, 4, 6}, {4, 6, 4}, {4, 6, 6}, {6, 4,         4}, {6, 4, 6}, {6, 6, 4}, {6, 6, 6}},       Polygon[{{2, 3, 1}, {6, 8, 7}, {2, 5, 6}, {1, 7, 5}, {4, 7, 8}, {2,          6, 4}, {2, 3, 4}, {6, 5, 7}, {1, 2, 5}, {1, 3, 7}, {3, 4, 7}, {8,          4, 6}}]]      > BoundaryMeshRegion[{{4, 4, 4}, {4, 4, 6}, {4, 6, 4}, {4, 6, 6}, {6, 4, 4}, > {6, 4, 6}, {6, 6, 4}, {6, 6, 6}}, Polygon[{{2, 3, 1}, {6, 8, 7}, {2, 5, 6}, > {1, 7, 5}, {4, 7, 8}, {2, 6, 4}, {2, 3, 4}, {6, 5, 7}, {1, 2, 5}, {1, 3, 7}, > {3, 4, 7}, {8, 4, 6}}]] But this is able to work. What is different.               BoundaryMeshRegion[{{4, 4, 4}, {4, 4, 6}, {4, 6, 4}, {4, 6, 6}, {6, 4,         4}, {6, 4, 6}, {6, 6, 4}, {6, 6, 6}},       Polygon[{(*{2,3,1},{6,8,        7},*){2, 5, 6}, {1, 7, 5}, {4, 7, 8}, {2, 6, 4}, {2, 3, 4}, {6, 5,          7}, {1, 2, 5}, {1, 3, 7}, {3, 4, 7}, {8, 4, 6}}]]      > ![Blockquote](http://i.stack.imgur.com/09jD3.png) ## Are these bugs too? **Case 1**               Graphics3D[{Opacity[0.5], tmp, Opacity[1], Red, PointSize[0.05],        Point[{2, 0, 0}]}, Boxed -> False]      > ![Blockquote](http://i.stack.imgur.com/ECyhn.png)               tmp = RevolutionPlot3D[{2 + Cos[t], Sin[t]}, {t, 0, 2 Pi},       PlotPoints -> 2]; tmp =       GraphicsComplex[tmp[[1, 1]], tmp[[1, 2, 1, 1, 5, 1]]];     r1 = BoundaryDiscretizeGraphics@tmp      > ![Blockquote](http://i.stack.imgur.com/UyCqH.png)               RegionQ[r1]      > True               RegionMember[r1, {2, 0, 0}]      > False **Case 2**               BoundaryDiscretizeGraphics[      GraphicsComplex[{{4, 4, 4}, {4, 4, 6}, {4, 6, 4}, {4, 6, 6}, {6, 4,          4}, {6, 4, 6}, {6, 6, 4}, {6, 6, 6}},        Polygon[{(*{2,3,1},{6,8,         7},*){2, 5, 6}, {1, 7, 5}, {4, 7, 8}, {2, 6, 4}, {2, 3, 4}, {6, 5,           7}, {1, 2, 5}, {1, 3, 7}, {3, 4, 7}, {8, 4, 6}}]]]      > ![Blockquote](http://i.stack.imgur.com/snusC.png)


title: Analysis of Facebook group

text: I am the admin of a Facebook group for our year at university and wanted to graph the members of the group like you can with your own friends so we can find the isolated people and get rid of them (as they are spamming). I have tried treating the page as an ID but don't really know how to proceed. Is this possible?


title: problem with Importing multiple files

text: I need to import about 100000 "dat" files to my progrom. I want to do this using the last answer to this question: Importing multiple files using a for-loop I know that I should define a list of all the names of my files, and at the end, I `Import` all of them. But I have a problem with this. The names of my files obey a special pattern, like this:               "mutomu,dms41,x1,dms51,x2,q24,x3,q25,x4.dat"      Which x1-x4 are integers in this way:               {x1, 1, 21}, {x2, x1, 21}, {x3, 1, 15}, {x4, 1, 15}      . When I am defining the names of my files, I do it as:               allprobabilityfiles = {Flatten[Table[{{x1, x2, x3, x4},"mutomu,dms41,x1,dms51,x2,q24,x3,q25,x4.dat"}, {x1, 1, 21,1}, {x2, x1, 21, 1}, {x3, 1, 15, 1}, {x4, 1, 15, 1}], 3]};      but in this way, the result is:               ....{{21, 21, 6, 5}, "mutomu,dms41,x1,dms51,x2,q24,x3,q25,x4.dat"},      {{21, 21, 6, 6}, "mutomu,dms41,x1,dms51,x2,q24,x3,q25,x4.dat"},      {{21, 21, 6, 7}, "mutomu,dms41,x1,dms51,x2,q24,x3,q25,x4.dat"}, ....      (x1-x4 don't change inside the file names in this table), but what I need is the following:               ....{{21, 21, 6, 5}, "mutomu,dms41,21,dms51,21,q24,6,q25,5.dat"},      {{21, 21, 6, 6}, "mutomu,dms41,21,dms51,21,q24,5,q25,6.dat"},      {{21, 21, 6, 7}, "mutomu,dms41,21,dms51,21,q24,5,q25,7.dat"}, ....      How can I solve this problem?


title: How to localize the symbols x,y, A, B in the following program?

text: I see a example in Paul Wellin's _Programming with Mathematica An Introduction_ , 4th edition:               TruthTable[expr_, vars_] :=       Module[{len = Length[vars], tuples, rules, table,         head},       tuples = Tuples[{True, False}, len];       rules = Thread[vars -> #1] & /@ tuples;        table = Transpose@Join[Transpose[tuples], {expr /. rules}];head=       Append[vars,TraditionalForm[expr]];       Grid[Prepend[table /. {True -> "T", False -> "F"}, head],        Dividers -> {{1 -> {Thin, Black}, -1 -> {Thin, Black}, -2 -> {Thin,              LightGray}}, {1 -> {Thin, Black},            2 -> {Thin, LightGray}, -1 -> {Thin, Black}}},        BaseStyle -> {FontFamily -> "Times"}]];     Manipulate[      Module[{eqns = {(x - .5)^2 + y^2 < 1, (.5 + x)^2 + y^2 < 1},         c1 = {-.5, 0}, c2 = {.5, 0}},        Row[{(*IPM4`Chap05Functional`*)TruthTable[f[A, B], {A, B}],          Show[RegionPlot[f @@ eqns, {x, -2, 2}, {y, -2, 2}, Frame -> None,            PlotLabel -> f[A, B], PlotRange -> {{-2, 2}, {-1.2, 1.2}},            AspectRatio -> Automatic, MaxRecursion -> 5],           Graphics[{Circle[c1], Circle[c2], Text["A", {-0.75, .5}],             Text["B", {0.75, .5}]}], ImageSize -> Small]}]], {{f, Xor,         "Logical function"}, {And, Or, Xor, Implies, Nand, Nor}},      SaveDefinitions -> True]      I try as: TruthTable[expr_, vars_] := Module[{names, showNames, len = Length[vars], tuples, rules, table, head}, tuples = Tuples[{True, False}, len]; rules = Thread[vars -> #1] & /@ tuples; table = Transpose@Join[Transpose[tuples], {expr /. rules}]; names = Map[ToString, vars]; showNames = Map[StringSplit[#, "$"][[1]] &, names]; head = Append[showNames, StringReplace[ToString@TraditionalForm[expr], MapThread[#1 -> #2 &, {names, showNames}]]]; Grid[Prepend[table /. {True -> "T", False -> "F"}, head], Dividers -> {{1 -> {Thin, Black}, -1 -> {Thin, Black}, -2 -> {Thin, LightGray}}, {1 -> {Thin, Black}, 2 -> {Thin, LightGray}, -1 -> {Thin, Black}}}, BaseStyle -> {FontFamily -> "Times"}]] Manipulate[ Module[{A, B, x, y, eqns, c1 = {-.5, 0}, c2 = {.5, 0}, lgrid}, eqns = {(x - .5)^2 + y^2 < 1, (.5 + x)^2 + y^2 < 1}; lgrid = TruthTable[f[A, B], {A, B}]; Row[{( _IPM4`Chap05Functional`_)lgrid, Show[RegionPlot[f @@ eqns, {x, -2, 2}, {y, -2, 2}, Frame -> None, PlotLabel -> lgrid[1, 1, 3], PlotRange -> {{-2, 2}, {-1.2, 1.2}}, AspectRatio -> Automatic, MaxRecursion -> 5], Graphics[{Circle[c1], Circle[c2], Text["A", {-.9, .25}], Text["B", {.9, .25}]}], ImageSize -> Small]}]], {{f, Xor, "Logical function"}, {And, Or, Xor, Implies, Nand, Nor}}, SaveDefinitions -> True] It works. But I wonder any better solution?


title: Parametric plot from two NDsolve solutions

text: I have two independent ODE systems.               A = NDsolve[..., {x, y}, {t, 0, 10}];     B = NDsolve[..., {a, b}, {t, 0, 10}];      I can draw a `ParametricPlot` from one ODE. That is,               ParametricPlot[Evaluate[{x[t], y[t]} /. A], {t, 0, 10}]      I wonder if I can draw a `ParametricPlot` from the two independent ODE systems. That is a `ParametricPlot` of `x[t]` taken from A and `a[t]` taken from B.


title: Reproducing the Integral Definition of the Modified Bessel function

text: I need to simplify some integral expressions in terms of special functions, such as the modified Bessel function of the first kind. See for example Eq. (5) on this page. Notice that the real expressions I am working with are somewhat more complex, but I thought it might be a good idea to start by reproducing some known expression with Mathematica. However, I am failing miserably. After searching on the internal help pages and the web, I thought that this expression may do exactly what I wanted:               Assuming[{m \[Element] Integers && z \[Element] Reals},       Integrate[Exp[z*Cos[x] ]*Cos[ m * x], {x, 0, Pi}]]      But it simply outputs the same integral again. What am I doing wrong? Why does it not output the result in terms of the Bessel function?


title: Directional derivative of SiegelTheta

text: I'm working on a problem where I have to integrate both the Mathematica function SiegelTheta and some of its second order directional derivatives. Using the function works well but something goes wrong when I try to differentiate it. What I want to do is to take the second order derivative with respect to the vector $s$ in SiegelTheta[$\Omega$,s] and then dot it twice with the vectors (1,0),(1,0) or (0,1),(0,1). I want $s$ to be a two- component vector and $\Omega$ to be the matrix > $$\Omega(x,y,z) = \frac{i\sqrt{1/z - 1}}{\pi}\begin{pmatrix} (1 - y) & > (-1+x+y) \\\ (-1+x+y) & (1-x) \end{pmatrix}.$$ and after differentiating I want to let $s\to0$. Since I don't know how to take the derivative with respect to a vector I've tried doing it component- wise, using               S[Omega] = D[SiegelTheta[Omega,{s1,0}],{s1,2}]/.t1->0      and similarly for the derivative with respect to the second component of $s$. My problem is that I can't get the resulting function to take numerical values, even when evaluating it in a single point such as $(0.5,0.5,0.5)$. Upon integrating it I also get an error message saying the integrand takes non-numerical values in the whole region $x\in[0,1],y\in[0,1-x],z\in[0,1]$. To be more specific regarding the integration what I've tried using is               NIntegrate[S[Omega[x,y,z]],{x,0,1},{y,0,1-x},{z,0,1}].      My question is thus this: Do I have to somehow specify before taking the derivative that I want $\Omega$ to be a $2\times 2$ matrix and $s$ a vector with two components, and in that case how do I do that? Also, is there something happening during the differentiation that I'm not aware of that stops the function from taking numerical value? And is there something wrong with my approach to the integration? I'm far from an expert on Mathematica and would appreciate any help I could get.


title: What is a good way to plot some difficult implicit equations?

text: Here are several equations, it seems that Mathematica couldn't plot them well, although I set PlotPoints>100                ContourPlot[Csc[1. - x^2] Cot[2. - y^2] - x*y == 0,         {x, -10, 10}, {y, -10, 10}, PlotPoints -> 120]      ![enter image description here](http://i.stack.imgur.com/LwOZ0.jpg) I tried               cf = Compile[{{d, _Real}},         Do[If[Abs[Csc[1. - x^2] Cot[2. - y^2] - x y] < 0.02,           Sow@{x, y}], {x, -10, 10, d}, {y, -10, 10, d}],         CompilationTarget -> "C", Parallelization -> True,         RuntimeOptions -> "Speed"];               Graphics[{AbsolutePointSize@1, Point@Reap[cf[0.002]][[2, 1]]}]      but I don't know how to join the points. Is there other better method do it? ![enter image description here](http://i.stack.imgur.com/lkORL.jpg)


title: Summation of If statements

text: The following made me curious. Suppose you want to sum the if statement `If[x[i] < 1., x[i]^2, 0.]` over `i=1,2`, i.e.               Sum[If[x[i] < 1., x[i]^2, 0.], {i, 1, 2}].       Mathematica returns               If[x[1] < 1., x[i]^2, 0.] + If[x[2] < 1., x[i]^2, 0.].      Notice the `i`'s if the statement is true. However, I thought a more "natural" representation of the sum should look like               If[x[1] < 1., x[1]^2, 0.] + If[x[2] < 1., x[2]^2, 0.].      Does anybody can enlighten me on this one? Thanks in advance.


title: Derivative of Interpolating Function

text: Let's assume that Sol is the solution of NDSolve, given as an InterpolatingFunction               f     InterpolatingFunction[{{0.,10.},{0.,100.}},<>]      If I want to plot it, for a fixed x, it is sufficient to write               Plot[f[0,t],{t,0,T},PlotRange->All,Frame->True]      Why, if I want to define the partial derivative of f, I cannot use the following code?               GradTheta[t] = D[f[x, t], x]          ReplaceAll::reps: {InterpolatingFunction[{{0.,10.},{0.,100.}},{3,10,1,{25,103},{6,4},0,0,0,0},<<1>>,{Developer`PackedArrayForm,{<<1>>},{<<1>>}},{Automatic,Automatic}]} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing. >>


title: Solving $k\log(n) - k\log(k) \leq u$

text: How can I persuade _Mathematica_ to help me find solutions to the inequality $k\ln(n) - k\ln(k) \leq u$ over the reals, assuming $u \geq n \geq k \geq 1$. When I evaluate               Reduce[{k*Log[n] - k*Log[k] <= u, u > n, k > 1, n > k}, k, Reals]      _Mathematica_ can't find a solution. However, $k=2, n=e^2, u = 8$ is a solution, for example.


title: Problem when merging cells including commentary

text: This is a more of a problem report than a question. When merging the two cells Cell1:               foo     (*foobar*)     bar      and Cell2:               foobar      the line immediately before the comment together with the comment line embark on a journey into another universe, leaving nothing behind than a vicious red box and the farewell greeting "A RowBox with an invalid first argument was encountered. The first argument to RowBox must be a list." _Mathematica_ 9


title: Adding elements to a collection of lists

text: I would like to add element `a` at the start of a series of lists. For example I have a collection of lists called               LISTS1 = {{1,2,3,4,5,},{2,3,4,5,6},{3,4,5,6,7,},{4,5,6,7,8,}}      Now I want to add a `0` to the beginning of the first list, two `0`s to the second list and so on, to get:               {{0,1,2,3,4,5,},{0,0,2,3,4,5,6},{0,0,0,3,4,5,6,7,},{0,0,0,0,4,5,6,7,8,}}.      I suspect this needs to be done using the `Prepend` command in combination with something to change the numbers of elements to add for each individual list in the collection.


title: 2D Heat equation: inconsistent boundary and initial conditions

text: I'm attempting to use NDSolve on a 2D boundary value problem with initial conditions. Upon running my code, I get the following message: _"NDSolve::ibcinc: Warning: Boundary and initial conditions are inconsistent."_ After much head-scratching, I can't seem to find my mistake. It seems to me that my initial condition is consistent with my boundary conditions:               k = 1 / (5*(Pi^2));     soln = NDSolve[       {       (* PDE *)       D[u[x, y, t], t] == k*(D[u[x, y, t], x, x] + D[u[x, y, t], y, y]),            (* initial condition *)       u[x, y, 0] == y + Cos[Pi*x] Sin[2*Pi*y],            (* boundary conditions *)       u[x, 0, t] == 0,       u[x, 1, t] == 1,       (D[u[x, y, t], x] /. x -> 0) == 0,       (D[u[x, y, t], x] /. x -> 1) == 0       },      u,      {x, 0, 1},      {y, 0, 1},      {t, 0, 1}      ]      Any advice is greatly appreciated, Rick


title: Why FieldSeparators is printing a lot of quotation marks instead of just spaces?

text: In the following code `"FieldSeparators"->" "` prints a lot of quotation marks in the output file, instead of just spaces. What's wrong with it?               SetDirectory[NotebookDirectory[]];     s = 30; sy = s;     nmin = 0; nmax = 3; xmin = 0; xmax = 3;          out = Flatten[             Table[{N[n] // ToString[PaddedForm[#, {6, 5}, NumberPadding -> {" ", " "}]] &,                    N[x] // ToString[PaddedForm[#, {6, 5}, NumberPadding -> {" ", " "}]] &,                     N[BesselJ[n, 3 x]] /. {                       Indeterminate -> "nan", ComplexInfinity -> "nan", Infinity -> "inf"} //                       ToString[ PaddedForm[#, {6, 5}, NumberPadding -> {" ", " "}]] &},                   {n, nmin, nmax, (nmax - nmin)/(s - 1)},                    {x, xmin, xmax, (xmax - xmin)/(sy - 1)}], 1];          $file = OpenWrite["bessel.txt"];           Export[$file, out[[1 ;; s]], "Table", "FieldSeparators" -> " "];          For[ i = 2, i <= s, i++,           WriteString[$file, "\n\n"]                Export[$file, out[[1 + (i - 1)*s ;; i*s]], "Table", "FieldSeparators" -> " "]]          Close[$file];


title: To obtain an equation for a given curve

text: I have obtained the graph, ![enter image description here](http://i.stack.imgur.com/zF1jj.jpg) I would like to know its equation. The graph seems to be a hyperbolic spiral which, its equation reads, $r = a/\theta$. I read here and also, but these are concerning the Cartesian coordinate system. How could one implement these methods for my case, i. e. the polar coordinate system? ### Edit (1) Here is the code:               ParametricPlot[       {Im[(4.85263 + I 1.15883) Exp[(-0.455 + I 1.099) t] +            (-2.21527 + I 2.36121) Exp[(0.455 + I 1.099) t] +            (-2.35438 + I 1.36651) Exp[(0.455 - I 1.099) t] +            (0.717016 - I 0.836553) Exp[(-0.455 - I 1.099) t]],         Im[(4.85263 + I 1.15883) (-0.455 + I 1.099) Exp[(-0.455 + I 1.099) t] +            (-2.21527 + I 2.36121) (0.455 + I 1.099) Exp[(0.455 + I 1.099) t] +            (-2.35438 + I 1.36651) (0.455 - I 1.099) Exp[(0.455 - I 1.099) t] +            (0.717016 - I 0.836553) (-0.455 - I 1.099) Exp[(-0.455 - I 1.099) t]]},        {t, 0, 4.47}]      ### Edit (2) Actually, by the above approach, I would like to obtain an explicit equation from some given parametric equations. I do not know whether there exist other approaches or not.


title: Using least independent rectangle area to separate every point

text: ## Description I want to add vertical line and horizonal lines between data to make every point have an independent rectangle area. In addtion, every independent rectangle has a number $1,2,3,4,5,\ldots$ ## Algorithm I have a method that adds a line between two points to separate them. However, it will yield many rectangles`(as the Kuba's answer shows)`. So I add a condition that _if the coordinate difference of two adjacent points is less than Δ, the line between them will be deleted._ Using this condition to reduce the number of rectangles. The ideal result would appear as shown below: ![enter image description here](http://i.stack.imgur.com/PGSpt.png) ## My method for use with a large data set **_Function GridLineData_** (yield the coordinate of line that between two points)               GridLineData[data_List, Δ_] := Block[      {sortData, length, OriginData, deleteData},       sortData = DeleteDuplicates@(Sort@data);       length = Length@sortData;       OriginData =         Append[           Prepend[sortData, 2 sortData[[1]] - sortData[[2]]],          2 sortData[[length]] - sortData[[length - 1]]];       deleteData =          List /@ (First /@ Select[          Thread[List[Range[length - 1], Differences@sortData]],         #[[2]] < Δ &]) + 1;       Delete[Total@#/2 & /@ Partition[OriginData, 2, 1], deleteData]     ]      **_Function GridNumber_** (yield the number that in one direction of point)               GridNumber[data_List, Δ_] := Block[        {length, intervalData},        length = Length@GridLineData[data, Δ] - 1;        intervalData =         Interval /@ (Partition[GridLineData[data, Δ], 2, 1]);        First@Pick[Range@length, IntervalMemberQ[intervalData, #]] & /@ data     ]      **_Function Grid2DNumber_** (yield the number that in two directions of point)               Grid2DNumber[data_List, Δx_, Δy_] := Block[      {xGridNumber, yGridNumber},       xGridNumber = GridNumber[data[[All, 1]], Δx];       yGridNumber = GridNumber[data[[All, 2]], Δy];       Thread[List[xGridNumber, yGridNumber]]     ]      **_Function FinalNumber_** (yield the number of point )               FinalNumber[data_List, Δx_, Δy_] := Block[      {length},       length = Length@GridLineData[data[[All, 1]], Δx] - 1;      (#[[2]] - 1) length + #[[1]] & /@        Grid2DNumber[data, Δx, Δy]     ]      **_Function ResultShow_**                 ResultShow[data_List, Δx_, Δy_,imageSize_, plotRange_, axes_] := Block[        {xGridLineData, yGridLineData},       xGridLineData = GridLineData[data[[All, 1]], Δx];       yGridLineData = GridLineData[data[[All, 2]], Δy];       ListPlot[           data, GridLines -> {xGridLineData, yGridLineData},           GridLinesStyle -> Directive[Red, Dashed], Axes -> axes,           AxesStyle -> Arrowheads[.02], ImageSize -> imageSize,            PlotRange -> plotRange,           AxesLabel -> (Style[#, FontFamily -> Times, 15, Italic] & /@ {"x", "y"}),           Epilog -> Style[Text @@@Thread[List[ FinalNumber[data, Δx, Δy], data]], Pink]          ]      ]      **Running**                 data= {{0.028, 0.}, {-0.02, 0.}, {0.024, 0.}, {0.02, 0.}, {0.016, 0.}, {0.012, 0.},         {0.008, 0.}, {0.004, 0.}, {0., 0.}, {-0.004,  0.}, {-0.008, 0.}, {-0.012, 0.},          {-0.016, 0.}, {-0.02, 0.01}, {-0.02, 0.0025}, {-0.02, 0.005}, {-0.02, 0.0075},         {-0.044, 0.01}, {-0.020587, 0.013708}, {-0.022292, 0.017053}, {-0.024947,0.019708},         {-0.028292, 0.021413}, {-0.032, 0.022}, {-0.035708, 0.021413},{-0.039053,0.019708},         {-0.041708, 0.017053}, {-0.043413,0.013708}, {-0.044, -0.022}, {-0.044, 0.006},          {-0.044, 0.002}, {-0.044, -0.002}, {-0.044, -0.006}, {-0.044, -0.01},          {-0.044,-0.014}, {-0.044, -0.018}, {0.028, -0.022}, {-0.0395,-0.022},          {-0.035, -0.022}, {-0.0305, -0.022}, {-0.026, -0.022}, {-0.0215, -0.022},         {-0.017, -0.022}, {-0.0125, -0.022}, {-0.008,-0.022}, {-0.0035, -0.022},          {0.001, -0.022}, {0.0055, -0.022}, {0.01, -0.022}, {0.0145, -0.022},         {0.019,-0.022}, {0.0235, -0.022}, {0.028, -0.018333}, {0.028, -0.014667},          {0.028, -0.011}, {0.028, -0.0073333}, {0.028, -0.0036667}, {-0.026706, -0.010328},         {-0.034728, -0.012831}, {0.018467, -0.012376}, {-0.033672, -0.0044266},          {-0.024279,0.011578}, {0.019797, -0.0054822}, {-0.038043, -0.013453},          {0.018601, -0.015411}, {-0.032133, 0.017284}, {0.022207, -0.01367},          {0.02517,-0.015686}, {0.02067, -0.019352}, {0.02517, -0.019352},          {0.022473,-0.0077456}, {0.021436, -0.0024283}, {0.025436, -0.006095},         {0.025436, -0.0024283}, {-0.035176, -0.01611}, {-0.036746, -0.019366},         {-0.041246, -0.015366}, {-0.041246, -0.019366}, {-0.014588, -0.010238},          {-0.010401, -0.010522}, {-0.0059502, -0.010666}, {-0.001707, -0.01075},         {0.0027348, -0.010777}, {0.0069474, -0.010685}, {0.011809, -0.010525},          {0.015791, -0.010112}, {-0.031333, -0.011604}, {-0.034199, -0.0089465},          {-0.034029, 0.0073707}, {-0.019569, -0.0096572}, {-0.023365, -0.0086418},          {-0.027463, -0.0060338}, {-0.030117, -0.0044689}, {-0.036952, 0.0042677},         {-0.03296, 0.011412}, {0.019397, -0.0083713}, {0.01274, -0.0065207},          {0.004545, -0.0070253}, {-0.0039107, -0.0070327}, {-0.012341, -0.0066635},          {-0.027235, -0.014212}, {-0.017628, -0.013516},          {-0.0081969, -0.01424}, {0.00069536, -0.01441}, {0.0099993, -0.014277},          {-0.037067, -0.0056532}, {-0.032986, -0.0011756}, {-0.033618, 0.0019697},          {-0.030062, 0.0019274}, {-0.029626, 0.0091141}, {-0.020326, -0.0053632},          {-0.026776, -0.0027828}, {-0.027211, 0.00041043}, {-0.026736, 0.010116},          {-0.040682, 0.0058344}, {-0.04027, 0.00043337}, {-0.04027, -0.0035666},         {-0.040797, -0.0080866}, {-0.040797, -0.012087}, {-0.025425, 0.015104},         {-0.028425, 0.017284}, {-0.036536, 0.015541}, {-0.039536, 0.013361},          {-0.040682,0.0098344}, {0.018361, -0.0030539}, {0.014361, -0.0030539},          {0.010379, -0.0034667}, {0.0063788, -0.0034667}, {0.0021662, -0.0035585},          {-0.0018338, -0.0035585}, {-0.0060769, -0.0034742}, {-0.010077, -0.0034742},          {-0.014264, -0.0031893}, {-0.018264, -0.0031893}, {0.025037, -0.012651},          {0.025037, -0.008984}, {-0.033431, -0.018744}, {-0.028931, -0.018744},          {-0.024304, -0.017468}, {-0.019804, -0.017468}, {-0.014824, -0.018048},          {-0.010324, -0.018048}, {-0.0058733, -0.018192}, {-0.0013733, -0.018192},          {0.0030686, -0.018218}, {0.0075686, -0.018218}, {0.012431, -0.018058},         {0.016931, -0.018058}, {-0.027843, 0.0035557}, {-0.027805,  0.0060751},          {-0.022061, -0.0021739}, {-0.024557, -0.0011545}, {-0.024953, 0.0045581},          {-0.022496, 0.0010194}, {-0.022496,  0.0035194}, {-0.022458, 0.0060387},          {-0.022458, 0.0085387}, {-0.024915, 0.0070774}, {-0.024991, 0.0020387},         {-0.024122, -0.0043477}, {-0.030694, 0.0050727}, {0.014861, -0.014117},         {0.0051372, -0.014437}, {-0.0037465, -0.014383}, {-0.012647, -0.014096},         {-0.022609,-0.012936}, {-0.031862, -0.015489}, {0.022073, -0.010635},          {-0.016529, -0.0063786}, {-0.0081538, -0.0069485}, {0.00033243, -0.007117},         {0.0087576, -0.0069335}, {0.016721, -0.0061079}, {-0.037363, 0.0096687},         {-0.028557, 0.013155}, {-0.037594, -0.010173}, {-0.036541, -0.0011333},         {-0.02943, -0.0012179}, {-0.030803, -0.0077199}, {-0.038491, -0.016732},         {0.022872, -0.0048566}, {0.02234, -0.016705}};            ResultShow[data, .0005, .0005, 800, {All, All}, {False, True}]      Yield ![enter image description here](http://i.stack.imgur.com/4ienB.png) ## Question As can be seen from the figure,some points share the same rectangle (are not independent as I require). So my question is _how can I modify my algorithm to achieve the effect of using least independent rectangle area to separate every point._


title: Demonstrating Ackermann's Function

text: The Ackermann function is an extremely fast growing function. There are some slightly different versions of the function, but the one that I am looking for can be defined as: $$ A_0(x)=x+1 \\\ A_{k+1}(x)=A_k^x(x) $$ where $A_k^i = \underbrace{A_k \circ \dots \circ A_k}_i$. It can be defined in `Mathematica` as,               A[0, 1, x_] := x + 1;     A[k_, 1, x_] := A[k - 1, x, x];     A[k_, i_, x_] := Nest[Function[y, A[k, 1, y]], x, i];      There might be faster implementations (I am looking for it too), but the above one works correctly. I want to demonstrate the function for a number of students and for myself so that it is understood deeply. How can I demonstrate how rapidly the Ackermann's function grows? Note that while computing the function for large numbers take a long time, there are fast lower bound for the function. For instance we know: $$A_0(x) = x + 1$$ $$A_1(x) = A_0^x(x) = 2x$$ $$A_2(x) = A_1^x(x) = x2^x \ge 2^x$$ $$A_3(x) = A_2^x(x) \ge \underbrace{2^{2^{{ ... }^2}}}_x = 2 \uparrow x $$ $$A_4(x) = A_3^x(x) \ge \underbrace{2\uparrow(2\uparrow\dots\uparrow(2\uparrow 2)\dots)}_x=2\uparrow\uparrow x$$


title: Numerical saddle point problem of a function of many variables

text: I want to find the following saddle point of the function of 10 variables: ![saddle_point](http://www.zaslike.com/files/2bc0lawbriuzydi6re38.png). I am not able to find the stationary points by setting the first derivatives to 0, so I need do optimize the function numerically. I think that that performing the above-mentioned optimization is equivalent to finding a set of {a1,a2,a3,a4,a5} that would maximize the following function:               InnerMin[a1,a2,3,a4,a5]:=NMinimize[f[a1,a2,a3,a4,a5,b1,b2,b3,b4,b5],{b1,b2,b3,b4,b5}]      That is how I would do the inner minimization, so I get the value of that function for the values of a1,a2,a3,a4 and a5 I provide as an input. Does anybody know how to find in practice a set of a1, a2, a3, a4 and a5 that would maximize the InnerMin function, or in the other words how to perform the outer optimization numerically (coupled with the inner minimization via the InnerMin function)?


title: EdgeRenderingFunction and Graph input output structure

text: I am trying to create an `EdgeRenderingFunction` but the `more information` does not help me at all as far as explaining what the mathematical structure of the input is and at what level , the number of @s, mathematica makes the function act and the mathematical structure of the output. I would like to be able to create a pure function that does:   * If the initial vertex is "j" then color should be "color[j]"   * If the end vertex is "k" then the thickness should be "Thickness[k]"   * If the relation is `"->"` then the label should be whatever" and position "somewhere", if the relation is `"-"` then the label should be "whateverelse" and position "somewhere else". Wolfram more information says: `EdgeRenderingFunction->g specifies that each edge should be rendered with the graphics primitives given by g[{ri..},{vi..},lbij], where ri , rj are the beginning and ending points of the edge,vi ,vj are the beginning and ending vertices, lbij the is any label specified for the edge. ` Typically, in math, if `"g"` is a function then `g[something]` signifies that the `"something"`is the **_input_** and `"g[something]"` is the **_output_**. But if `"ri"` are coordinates, `"vi"` are vertices and `"lb"` are labels then the `"something"`is intended to be the **_output_** of g[ ** _input_** ]. So I'm a bit confused by the "more information" and would appreciate some help here. My other questions are:   1. What is the mathematical structure of the input graph {1->2}? Someone showed me yesterday in chat but I have forgotten how to replicate it, that: `{1->2}` is collection of lists where the first list carries the vertices in order and the second list carries the direction in order. `{1->2} is stored as {{1,2},{Rule[1,2]}}`   1. what does this Rule look like? How can I write functions on this rule? Confusingly               (#2[[1]] &) @@ {{1, 2}, {"a"}}     a      But                (#2[[1]] &) @@ {1 -> 2}      2      but with an error message      On the other hand                (#[[2]] &) @@ {1 -> 2}      2      No errors.      So if a `Graph` is stored as a list of lists that I am atting `@@` at a second level then shouldn't I have found the Rule between 1 and 2?   1. How many `@@@` levels is mathematica gonna make my `edgerenderingfunction` act on to the input?


title: What are the most common (usual) ways to make palettes with non-trivial functionality?

text: What are the best (most robust and most convenient) ways to create palettes that can be installed permanently (using `Palettes -> Install Palette...`) and are safe to use? I'd be interested in how other people have done this in the past to learn more about idiomatic front end programming. I put some code illustrating the pattern I am using now at the end of this post. I'd appreciate some comments on it. **Notes and requirements:**   1. The palette should always work, regardless of whether the kernel has been quit or an evaluation is running.   2. The palette may have more than one button which share some code between them.   3. It must not pollute the `Global`` context or change the kernel state in a way that might break something unexpectedly.   4. I'm looking for an easy way to define palettes (minimal boilerplate code and extra work)   5. It would be nice (non-essential) if several versions of the palette could coexist independently (my current approach doesn't have this because it uses its own context to hide its function definition, but everything in this context is shared)   6. It would also be nice (non-essential) to integrate documentation in an easy way (help button bringing it up maybe?) * * * My current approach is illustrated below. It "localizes" its symbols by putting them in a separate context, and uses `DynamicModule` to ensure that all the definitions are done before any button code is run.               SetAttributes[paletteButton, HoldAll]     paletteButton[name_, tooltip_, func_, opt : OptionsPattern[]] :=       Tooltip[Button[name, Unevaluated[func], Appearance -> "Palette",         opt], tooltip, TooltipDelay -> Automatic]          Begin["SomePalette`"];          PaletteNotebook[      DynamicModule[{},       Column[{         paletteButton["One", "Button one", function[1]],         paletteButton["Two", "Button two", function[2]]         }],            Initialization :> (         function[x_] := MessageDialog[x]         )       ],      WindowTitle -> "Some Palette"      ]          End[];


title: Importing videos in Mathematica

text: Mathematica's `Import` command is purportedly able to import .AVI files. However, I find that many files that I want to import do only result in MMA showing a blank frame or another placeholder. All or some of my video-players are able to show these AVI files. This is an example where it works as advertised:               Import["http://er.jsc.nasa.gov/seh/jfkrice.avi", {"ImageList", 2}]      ![Mathematica graphics](http://i.stack.imgur.com/oarxf.png) However,               Import["http://people.sc.fsu.edu/~jburkardt/data/avi/ccvt_box.avi", {"ImageList", 2}]      doesn't work (VLC does). I get an empty white frame. More examples:               Import["http://people.sc.fsu.edu/~jburkardt/data/avi/sine_wave.avi", {"ImageList", 2}]      (works on VLC and mediaplayer classic)               Import["http://people.sc.fsu.edu/~jburkardt/data/avi/star_collapse.avi", {"ImageList", 2}]      **BIG-126 MB!!**   Should have looked like this: ![Mathematica graphics](http://i.stack.imgur.com/DZ32z.png) and works on Windows Media Player, VLC and mediaplayer classic, but I get a white box in MMA. This is on windows 7-64/MMA8.04. I have the k-lite codecs pack installed. * * * **UPDATE** Responding to Thomas' comment below I found most of the sample files I linked to in my original post gone. I tried to gather a new set and found some that worked and some that don't: Importable:               Import[#, "VideoEncoding"] & /@       {"http://er.jsc.nasa.gov/seh/jfkrice.avi",        "http://redmine.yorba.org/attachments/615/MVI_0572.AVI",       "http://www-eng-x.llnl.gov/documents/a_video.avi",       "http://redmine.yorba.org/attachments/628/MVI_4981.AVI",       "http://www.csoft.co.uk/video/original/earth.avi",       "http://www.mysticfractal.com/video/fp.avi",        "http://www.softage.ru/files/video-codec/uncompressed/suzie.avi",        "http://archive.org/download/Architects_of_Tomorrow/2007-12-10-02-39-00.avi"}      > {"msvc", "MJPG", "msvc", "MJPG", "msvc", "msvc", "YUV", "Uncompressed"} Don't import:               Import[#, "VideoEncoding"] & /@      {"https://code.ros.org/trac/opencv/export/7213/trunk/opencv/samples/cpp/tutorial_code/HighGUI/video-input-psnr-ssim/video/Megamind.avi",       "http://samples.mplayerhq.hu/avi/verona60avi56k.avi",       "http://samples.mplayerhq.hu/avi/filedoesitbetter.avi",       "http://www.infognition.com/ScreenPressor/browsing-divx.avi"       }      > {"XVID", "MP42", "MJPG", "DX50"}


title: How to receive the result of the integral $ \int\frac{1}{x}dx$ is $\ln|x|$?

text: When I input `\[Integral]1/x \[DifferentialD]x` in _Mathematica_ , I get `Log[x]`. How can I make the result of the integral $\displaystyle \int\dfrac{1}{x}dx$ to be $\ln|x|$?


title: Can kernel-specific variables be accessed from stylesheets?

text: I'm trying to create a modified version of the `Default.nb` StyleSheet that adds a docked cell to act as a status bar along the top of every notebook to display some basic information (user login name and login time, generated when my set of packages is loaded). My current implementation, which isn't functioning as I want it to, assigns the cell data I want to display in the status bar to a variable in the `Global` context:               $StatusBar = ToBoxes[Dynamic[Row[{           Item[            If[ValueQ[$PersonID],             Style[$PersonName <> " logged in at " <> $LoginTime,               Darker[Darker[Green]], FontFamily -> "Arial"],             Style["Not logged in!", Darker[Red], FontFamily -> "Arial"]             ]            ]           }],          TrackedSymbols :> {$PersonID, $PersonName, $LoginTime}]];      I've created a new stylesheet that inherits everything from `Default.nb`, but with modified Notebook Options Settings to add the desired `DockedCells` (I've omitted the non-relevant Options):               Cell[StyleData["Notebook"],           DockedCells->Cell[BoxData[$StatusBar]],           <...>     ]      Unfortunately, the `DockedCells` Option defined in the `StyleSheet` doesn't seem to recognize the `$StatusBar` variable I've created to populate it. All I get is a docked cell displaying `$StatusBar` (verbatim). I'm not sure if this is a context issue, an evaluation order issue, or something else altogether. It would be even more convenient if I could define the `$StatusBar` variable within the stylesheet so that it doesn't have to be recreated when my packages are loaded. However, I'm skeptical that this is possible. Is there any way to actually evaluate code within a StyleSheet?


title: How to expand all portions of an expression?

text: Consider a toy expression:               expr = Sin[x (a + b)]/(y (z + c))      I would like to expand all parentheses to get something like:               Sin[a x + b x]/(c y + y z)      I have been able to expand the argument of the `Sin` term using:               MapAll[Expand,expr]     (* Out[] = Sin[a x + b x]/(y (c + z)) *)      However, this leaves the denominator unexpanded. Is there a way to expand the entire expression?


title: How to display a different number of significant digits in each column of TableForm output?

text: Say I create a table with three columns of numbers. Is there a way to control the number of significant digits displayed in each column. To make this concrete, take the following command:               Table[{m, Sum[1/2.^n, {n, 1, m}], Sum[1./n, {n, 1, m}]}, {m, 1, 20.}] // TableForm      This produces the following table:               1   0.5         1.     2   0.75        1.5     3   0.875       1.83333     ...     18  0.999996    3.49511     19  0.999998    3.54774     20  0.999999    3.59774      The first column is fine as whole numbers, but I want the second column to have more decimal places, say, eight places, and the third column to have, say, four places. I tried putting one of the `Sum[]` functions inside the `N[]` function, but this had absolutely no effect. Is there another way to individually format each column of output?


title: Manipulating an equation into standard quadratic form?

text: Say I have an equation of the form $$u s + \frac{1}{v} + \frac{1}{p s + q} = 0$$ (or _any_ form that can be written as a standard quadratic, really, the above form is just an example; they'll all be equal to 0 from the start, however) and I want it in the form $$ s^2 + b s + c = 0 $$ i.e. the coefficient on $s^2$ is 1. How do I do this using Mathematica? More specifically, I'm interested in finding $b$ and $c$, but if the equation is written in this form, grouped properly, doing that is very easy by eye.


title: What is " (Dialog) Input [ ] := " after evaluating a cell?

text: I have done a time-consuming run and calculation. After many hours ( about 7 hours!), the black color which shows that the cell is evaluating, turn into gray and a strange text appears like this :               (Dialog) Input[157]:= (* my code in the cell *)      Does anyone know what it is and why this is happening ?!


title: Which Mathematica files may be deleted to save space

text: After installation Mathematica 8 for Linux takes more than 3GB in the /usr/local/Wolfram/ directory. I suspect that not all of it is relevant if I want to do some occasional computations. Are there subdirectories which can be deleted safely to save some space?


title: How to solve a system of partial differential equations?

text: Edit: since the upgrade to _Mathematica_ 10, this problem seems solved I just want to solve a system of partial differential equations, for example: $$ \left\\{ \begin{array}{l} \frac{\partial}{\partial a}[f(a, b, c)] = 4 \sin^2(b) \cos(c) \\\ \frac{1}{a} \times \frac{\partial}{\partial b}[f(a, b, c)] = 4 \cos(c) \sin(2b) \\\ \frac{1}{a \sin(b)} \times \frac{\partial}{\partial c}[f(a, b, c)] = -4 \sin(b) \sin(c) \\\ \end{array} \right. $$ And when I try to solve this system in _Mathematica_ , the output does not help:               In[1]:= DSolve[     {         D[f[a, b, c], a] == 4 Sin[b]^2 Cos[c],         (1/a) *D[f[a, b, c], b] == 4 Cos[c] Sin[2 b],         (1/(a Sin[b]))*D[f[a, b, c], c] == -4 Sin[b] Sin[c]     }, f[a, b, c], {a, b, c}]          Out[1]= DSolve[     {         Derivative[1, 0, 0][f][a, b, c] == 4*Cos[c]*Sin[b]^2,         Derivative[0, 1, 0][f][a, b, c]/a == 4*Cos[c]*Sin[2*b],         (Csc[b]*Derivative[0, 0, 1][f][a, b, c])/a == -4*Sin[b]*Sin[c]     }, f[a, b, c], {a, b, c}]      Obviously, this output is useless… Probably I doing something wrong… Thank you for your help Note : The solution is $f(a, b, c) = 4a \sin^2(b) \cos(c) + K$ (K : the integration constant).


title: Local variable names - Is there an easy way?

text: I apologize first, because this has been asked, like in Treat all variables as local in a module [duplicate] Variable scope similar to other languages But I don't get how to use them. Some codes in these answers don't work when I just copy-paste blindly (because I really don't understand them.) Are the above methods the standard way to "Treat variables as local by default (No need to specify them, like in Module)" in _Mathematica_? If so, please give me a working example, please. I think there should be a standard way to do this, but I can't find it in the documentation.


title: How to change a parameter dynamically inside NDSolve

text: I have no idea how to dynamically update a parameter inside `NDSolve`. For example consider following first-order DE:               Eq = x'[t] + (x[t] - λ) == 0;      where `λ` is a parameter. I want to solve this ODE but this parameter might change when `x'[t]` turns to zero:               WhenEvent[x'[t] == 0, λ -> x[t]].      I tried following code, but that doesn't work. Any idea?               λ = 1;     Eq = x'[t] + (x[t] - λ) == 0;     sol = NDSolve[{Eq, x[0] == 0,                    WhenEvent[x'[t] == 0., λ -> x[t]]                   }, x, {t, 0, 5}][[1]]


title: Remote kernel shuts down after several seconds

text: I have Mathematica 9 installed on two Windows Server 2008 R2 machines. Now i want to try using one of them as a frontend with local kernels and the other one for remote kernels. OpenSSH 6.5 for Windows is installed on both machines and key authentication is configured without a passphrase. SSH connection works normally. Here is the frontend configuration. In Preferences -> Parallel -> Remote Kernels i Add Host and use the custom launch command:               ssh -l username `1` "c:/progra~1/wolfra~1/mathematica/9.0/mathkernel.exe -mathlink -linkmode Connect `4` -linkname '`2`' -subkernel -noinit >& /dev/null &      For test purposes i set 2 remote and 2 local kernels in settings. After that in the notebook i try to call               Parallel`Settings`$MathLinkTimeout = 40     LaunchKernels[]      and launch Task Manager on both machines. At first two cmd windows appear and instantly close. Then i can see that two MathKernel.exe processes start on BOTH machines, but after nearly 20 seconds kernels shut down on remote machine. Local kernels stay running. After timeout i see an error output.               SubKernels`Protected`kernelFlush::time: Operation LinkWrite timed out after 40 seconds.     KernelObject::rdead: Subkernel connected through remote[1.1.1.1] appears dead. >>     SubKernels`Protected`kernelFlush::time: Operation LinkWrite timed out after 40 seconds.     KernelObject::rdead: Subkernel connected through remote[1.1.1.1] appears dead. >>     Out[9]= {KernelObject[7,local],KernelObject[8,local],$Failed,$Failed}      What am i missing? A solution would be greatly appreciated. Update: According to Szabolcs's comments i tried some other things.   1. My ssh command really had an open quote - removed.   2. Changed /dev/null redirections to ssh -f and -n keys.   3. Changed mathkernel.exe to math.exe in the path   4. Tried this solution. It works, so it's not a problem of connection or firewall. So now my ssh command looks like:               ssh -f -n user@remote_ip c:/progra~1/wolfra~1/mathematica/9.0/math -mathlink -linkmode Connect -linkprotocol TCPIP -linkname 'some_port@local_ip,some_port2@local_ip' -subkernel -noinit      And it doesn't work with the same behavior. When i try to run this command in the command line, math.exe starts on remote machine and then closes itself. After that on the local machine in the command line i see this message:               LinkConnect::linkc:     -- Message text not found -- (     LinkObject[some_port@local_ip,some_port2@local_ip, 3, 1])


title: Testing for arbitrary algebraic expression in given variable

text: I want to test, for example with `MatchQ`, if the argument of a function is an arbitrary expression in a single or several variables whose names can be assumed to be known. Except of these variables the expression should contain only numeric values. An approach would be to generate a list of unknowns in an expression and to compare this list to a given one. But I do not know either how to create that list for an arbitrary expression. By expression I mean a mathematical expression here. **Edit** Exampe:               (1-Exp[I*(x-5.6)*23.4])*Log[Abs[x-4.3]]/(1.7+3.2*I-x^2)      should be matched if I require it to be an expression in `x` and               (1-Exp[I*(x-y)*23.4])*Log[Abs[x-4.3]]/(1.7+3.2*I-x^2)      should not be matched in this case. Note that this does not mean that you can assume that the expression contains only these functions and rationals. My function               func[expr_?...,var]:=Module[{},...]      should evaluate only if the expression is e.g. of the first kind               func[(1-Exp[I*(x-5.6)*23.4])*Log[Abs[x-4.3]]/(1.7+3.2*I-x^2),x]


title: Basic question about Dynamic

text: Please consider the following:               InputField[Dynamic[X1], Number, Alignment -> Center];     InputField[Dynamic[X2], Number, Alignment -> Center];     Slider[Dynamic[Y1], {0, 200, 1}];     Slider[Dynamic[Y2], {0, 200, 1}];     Dynamic[FK, Dynamic[X1*(1 + Y1/100)]];     Dynamic[MK, Dynamic[X2*(1 + Y2/100)]];     Dynamic[HK, Dynamic[FK + MK]];     HeadTest = NumberQ[#] & /@ {X1, X2, Y1, Y2, FK, MK, HK}      Why would `FK`,`MK` and `HK` not have the head `Number`? (I guess I just did not understand how to use `Dynamic` and `DynamicModule`.)


title: Trouble avoiding computation in DynamicModule when input field is not defined

text: I'm having trouble detecting when my InputForm supplied String variable has a value. After looking at: How to compute values only if input fields are filled? I tried a StringQ test:               Clear[foo]     foo[t_] := If [ StringQ[t], {t, "defined"}, {t, "undefined"} ]          DynamicModule[{symbol},      Column[{        Row[{"Text field:", InputField[Dynamic[symbol], String]}],        foo[ Dynamic[symbol] ]        } ]      ]      Before the field is supplied this gives me what I expected: ![before field keyed](http://i.stack.imgur.com/uVCHv.jpg) but after keying the field, I see that my test hasn't worked: ![after keying text](http://i.stack.imgur.com/Uyj05.jpg) Based on How can I make sure all InputFields have values before processing a nb form? I tried:               Clear[foo]     foo[t_] := If [ !Equal[t, ""], {t, "defined"}, {t, "undefined"} ]          DynamicModule[{symbol = ""},      Column[{        Row[{"Text field:", InputField[Dynamic[symbol], String]}],        foo[ Dynamic[symbol] ]        } ]      ]      but this produces a kind of odd unevaluated If block: ![other try](http://i.stack.imgur.com/SuUlW.jpg) I'm clearly doing something wrong with how I'm testing or using the input variable or form, but it's not obvious to me what that is?


title: Non Commutative Multiply

text: > **Possible Duplicate:**   >  Non-commutative symbolic linear algebra I want to multiply two matrices, for example,               A = {{e, f}, {g, h}}     B = {{a, b}, {c, d}}      Using `A.B`, _Mathematica_ returns               {{a e + b g, a f + b h}, {c e + d g, c f + d h}}      I would like to get, however, the following result:               {{e a + f c, e b + f d}, {g a + h c, g b + h d}}      since, for me, the entries `{a,b,c,d,e,f,g,h}` are operators, i.e. they are non-commutative. I could solve this problem clearing the attribute `Orderless` in the built-in function `Times`:               ClearAttributes[Times, Orderless]      I know, however, this can be dangerous. I tried to define a function               Times2[a_,b_]:=Times[a,b]      and then use `ClearAttributes[Times2, Orderless]` but it doesn't work. How could I solve this problem? Thanks in advance


title: How to accelerate updating some parts of sparse matrices?

text: I am trying to update some parts of an specific matrix as rapidly as possible. In what follows, I first set up the basics things that I want to use               Clear["Global`*"]     SeedRandom[1234];     d = 300;     A = RandomReal[20, {d, d}];     n = Dimensions[A][[1]];     i = 1; num = 2;     Id = SparseArray[{{k_, k_} -> 1.}, {n, n}];     LU = LinearSolve[A];     mat = (1./(Norm[A, 2]^2))*ConjugateTranspose[A];     mat // MatrixPlot      wherein `Id`, denotes the Identity matrix, A is a dense input matrix, and then I wish to update the matrix `mat`, (which is an approximate inverse of the matrix `A`), by entering `num=2`, columns of the exact inverse that will be obtained by solving two linear systems (using `LinearSolveFunction`). To this end, I use the following piece of code, in which after obtaining the `num=2` columns of the matrix inverse, they must be replaced as the first and the second columns of the matrix `mat` at the end of each cycle of `While`: (please forgive me, if I write the codes in a very rough way!)               While[i <= num,       {ll = Id[[All, i]];        ith = Chop@LU[ll];        mat[[All, i]] = ith;        i++}       ];     mat // MatrixPlot      Considering the above dense matrix A, it works and can update the columns of the matrix `mat`. My problem is here, if I use a sparse matrix, then for low dimensions it works rapidly, while for higher dimensions it takes too much time to update the columns of the matrix `mat`. I mean, if we use the following matrix               A = SparseArray[{{i_, i_} ->       RandomReal[3], {i_, j_} /; Abs[i - j] == 1 -> RandomReal[2],     {i_, j_} /; Abs[i - j] == 8 -> RandomReal[1]}, {d, d}];      while `d=3000`. I would like to ask you experts about that: how we could accelerate (in terms of computational time) this process for dense and sparse matrices in a simple uniform piece of code? Any tip or help will be cheerfully thanked.


title: Mathematica rule substitution memory

text: First I present the specific programming question, and then I provide further background details. Given an expression in Mathematica, say `f=3x+7y`, there are two common ways to substitute information for `x` and `y`. The first is to use the `/.` rule, so something like                t=f/.{x->0,y->0};      would make the value of `t` equal to `0`. And the other is a more general substitution for `x` and `y` everywhere they appear, such as                x=0; y=0;      t=f;      This also makes the value of `t` equal to `0`. The difference in memory usage, however, becomes apparent with more complicated polynomials. I have uploaded a text file with a complicated polynomial to MediaFire : http://www.mediafire.com/?0ea3mhtqmc8c3r2 (it is about 4MB, and I'm not aware of a better way of sharing it). If you download it and then load it into Mathematica as I will demonstrate, you can see for yourself the significant memory loss: **Substitution Method**                In[1]:= << "/home/username/Downloads/p";      In[2]:= MaxMemoryUsed[]      Out[2]= 79833424      In[3]:= MemoryInUse[]      Out[3]= 76373112      In[4]:= t = p /. {x -> 0, y -> 0, z -> 0};      In[5]:= MaxMemoryUsed[]      Out[5]= 152124264      In[6]:= MemoryInUse[]      Out[6]= 112876080      **General Assignment Method**                In[1]:= << "/home/username/Downloads/p";      In[2]:= MaxMemoryUsed[]      Out[2]= 79831632      In[3]:= MemoryInUse[]      Out[3]= 75415960      In[4]:= x = 0; y = 0; z = 0;      In[5]:= MaxMemoryUsed[]      Out[5]= 79831632      In[6]:= MemoryInUse[]      Out[6]= 75420744      In[7]:= t = p;      In[8]:= MaxMemoryUsed[]      Out[8]= 112888664      In[9]:= MemoryInUse[]      Out[9]= 112875336      As you can see, during the substitution operation there was about 40MB of additional memory used to perform the substitution. The substitution method also takes much longer than the general method. The difference in the two methods becomes much higher (several GB) as the complexity of the polynomial increases, and ends up maxing out the available RAM. The problem is that for my program I cannot set `x, y, z` equal to zero in general. This seems to be an inefficiency with the way Mathematica performs substitutions. I would appreciate any suggestions for working around this problem. * * * **Further Background** The reason I cannot simply employ the general method is that the next step requires that I take derivatives of the original polynomial with respect to the variables `x, y, z`. The process would ideally be iterated as follows: Step 1: Given `p`, write the result of `p/.{x->0,y->0,z->0}` to a file. Step 2: Take derivatives of `p` with respect to `x, y, z`. Step 3: Perform some algebraic operations with the derivatives, creating the more complicated polynomials p1 and p2. Step 4: Repeat the process on each of p1 and p2. Since the process runs out of RAM when using the substitution rule, I have been working around this by performing several iterations of the process _without_ writing the output of `p/.{x->0,y->0,z->0}` to a file, and then applying the "General Assignment Method" (setting `x=0; y=0; z=0;` and writing the evaluation of each polynomial to a file). This is an unsatisfactory workaround, however, because it is impossible to know the proper number of iterations which will be required, and so it is possible that after performing all the iterations and writing the results to a file that I will need to run it again, this time performing more iterations. If the results could be written out to a file in the intermediate steps, I would be able to check them and determine if I should let the iteration continue or if I can stop it.


title: How to transfer my Mathematica Student licence from Linux to windows

text: I would like to ask if it is possible to transfer my windows licence to linux. I have already filled out system transfer form, but in the list of downloadable software I can see only windows version. Thank you for help.


title: Incorporating an additional graphics element when using Animate and ParametricPlot3D

text: I'm trying to animate some curves that wrap around a cylinder. OK so far:               Animate[ParametricPlot3D[{{Cos[α t], Sin[α t],      Sqrt[1 - α^2] t}, {Cos[α t],      Sin[α t], -Sqrt[1 - α^2] t}}, {α, -1, 1},      PlotRange -> {{-1, 1}, {-1, 1}, {-2 π, 2 π}}], {t, 0,      2 π}, AnimationRunning -> False]      But I'm struggling to incorporate the cylinder itself:               Graphics3D[Cylinder[{{0, 0, -2 π}, {0, 0, 2 π}}, 1]]      You can probably see the problem: the curves run around an invisible cylinder. I'd be much happier if I could see it! I've tried to squeeze the cylinder in in a few different ways (putting it into the `Animate[ParametricPlot3D[...]]` in different places, and using `Epilog`), but no luck. Any suggestions?


title: Scaling the time axis of an interpolated function (as in a solution from NDSolve)

text: I'm wondering how I can change the units of the x (time) axis when plotting a solution from NDSolve. I have obtained three solutions to a system of differential equations, all of which exist over the time scale [0 s, 1 ms]. However, I'm really only interested in the range [0 s, 5 ns]. To avoid having (x 10^-9) appended to every value along the x-axis when I plot these three functions (since the equations are solved in terms of seconds, not nanoseconds), I'd like to somehow scale the time axis to read 0, 1, 2, 3 ... (ns). It's fairly easy when working with symbolically specified functions- just multiply t by some constant wherever it appears in the function. However, this isn't possible here, since the solutions to the system are interpolated functions returned by NDSolve. Is there any efficient way to achieve this?


title: Bar Chart: How to adjust the font size for the bar labels as the chart size is manipulated

text: I have data that represents the binding energy of oxygen on different surfaces. Each bar is a different transition metal, and the length of the bar is the binding energy of oxygen. How do I make the font size of the labels larger while still keeping them centered on the bars? The way I have it right now, the chart works when it is large enough. When it is too small, the font overlaps and does not look good?               newElementsSmall = {"Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni",      "Cu", "Zn", "Zr", "Nb", "Tc", "Ru", "Rh", "Pd", "Ag", "Hf", "Ta",      "Re", "Os", "Ir", "Pt", "Au"}          stackData = {-1.69071, -1.48652, -1.42055, -1.16451, -2.51796, \     -1.81939, -1.04659, -1.14478, -1.2814, -2.13397, -1.30394, -1.29924, \     -1.35072, -1.49208, -0.966458, -1.0429, -1.41273, -1.31235, -2.3501, \     -1.45391, -1.25234, -0.963033, -1.10553, -1.01026}          BarChart[ stackData, ChartLabels -> {Placed[newElementsSmall, Above]},     PlotLabel -> Style["6M1@32Ag", Bold, 50], ChartLegends -> {"eV"} ]      ![overlap when small](http://i.stack.imgur.com/eZYbd.jpg) ![No overlap when large](http://i.stack.imgur.com/iV20t.jpg)


How to select all elements above the main diagonal of matrix? I need to create a list of them.


title: Computing symbolic norm of a vector

text: Consider the code:               n1 := Cos[α] Sin[β]     n2 := Sin[α] Sin[β]     n3 := Cos[β]     n := {n1, n2, n3}     Norm[n]      Why the result is               Sqrt[Abs[Cos[β]]^2 + Abs[Cos[α] Sin[β]]^2 + Abs[Sin[α] Sin[β]]^2]      that is $$\sqrt{\left| \sin (\alpha ) \sin (\beta )\right| ^2+\left| \cos (\alpha ) \sin (\beta )\right| ^2+\left| \cos (\beta )\right| ^2}$$ instead of $1$? How to compute the norm in a symbolic way simplifying some trigonometric identities?


title: How can I model composite 3D structures?

text: I know that Mathematica isn't built to model 3D, but most of my models are equation-defined so here's my question: is it somehow possible to combine ad- hoc 3D objects as well as ordinary/parametric/closed-form 3-dimensional plots into a single rendering? I know about the ability to export and recombine elsewhere, but I don't want to do that right now. (Also, for some reason, SolidWorks crashes when importing complicated models.)


title: Advice on Gather

text: Is there a better way to write this gather? I have a list of particles, "particlelist", and a list of particle coordinates, "coordlist" and I want to put all the particles into a 3-dimensional ng x ng x ng array of cubic boxes of width d. Each coordinate takes values between xmin and xmin + d x ng. boxIndx contains the correct box for any particle given the particle coordinates. I can then place the appropriate particle into its proper box. The code below is easy to read but it is a little slow. I know that AppendTo's are supposed to be no-no's but replacing it with Reap and Sow results in even slower times. The test problem typically takes .13-.17 on my Mac laptop. Thanks.               BoxEmUp3[coordlist_, particlelist_, ng_, d_, xmin_] :=         Module[{ParticleListByBox,particleIndx, boxIndx},            ParticleListByBox = ConstantArray[{}, ng^3];       Do[        boxIndx = 1 + Floor[(coordlist[[particleIndx, 1 ;; 3]] - xmin)/d].{1, ng, ng^2};             AppendTo[ParticleListByBox[[boxIndx]], particlelist[[particleIndx]]];,             {particleIndx, Length[particlelist]}];       Return[ParticleListByBox];]          xyztst = RandomReal[{-10, 10}, {10^6, 3}];     free = RandomSample[Range[10^6], 10^4];     BoxEmUp3[xyztst[[free]], free, 20, 1., -10] // Timing


title: How to calcuate the sum of 1/x, where x is an integer not containing the digit 9 and 10,000,000 ≤ x ≤ 88,888,888

text: My code is:               nonine[x_] := If[StringMatchQ[IntegerString[x], "*9*"], False, True];     SetAttribute[nonine, Listable];          tbl = Select[Range[10^2, 888], nonine[#] &];          Total[1.0/tbl]      got out of memory problem.