title: Mathlink and multithreading

text: In order to make my computations faster I have developed a C/C++ application calling _Mathematica_ kernel and performing many operations using _Mathematica_ functions for equation solving. Now I want to use multithreading and in particular I plan on taking advantage of the _Posix_ library in order to do so (`pthread`). But how does the link behaves when many threads insist on it? I guess that being a buffered/packet approach, if two threads try to send stuff to the same link without a mutex in guard (of the link), everything is a mess. SO I should create as many links as many threads I create. So here my questions:   1. Is there a limit to the number of links I can create to _MathLink_?   2. Is there a way to perform parallel activities on the _Mathematica_ kernel in an automated way? I know about the parallel core of _Mathematica_ , but what happens when I am interfacing to _Mathematica_ through _MathLink_ from C/C++?


title: White noise $\eta(t)$

text: How to make a random function $\eta(t)$ to insert in a differential equation for NDSolve? Edit: example: to solve equations like $\frac{dx}{dt}=\eta(t)$


title: How can I find all values of $m$ such that my cubic equation has three different positive solutions?

text: I want to find all the values of $m$ such that the equation $$-m^3 + 2 m^2 x + (-2 m - 1) x^2 + m + x^3=0$$ has three different positive solutions. I tried               Clear[f];     f[x_] := -m^3 + 2 m^2 x + (-2 m - 1) x^2 + m + x^3;     sol = Solve[D[f[x], x] == 0, x];     d = Discriminant[D[f[x], x], x];     x1 = x /. sol[[1]];     x2 = x /. sol[[2]];     Reduce[{d > 0, x1 > 0, f[x1] f[x2] < 0, f[0] < 0}, m]      and               Clear[f];     f[x_] := -m^3 + 2 m^2 x + (-2 m - 1) x^2 + m + x^3;     sol = Solve[f[x] == 0, x];     x1 = x /. sol[[1]];     x2 = x /. sol[[2]];     x3 = x /. sol[[3]];     Reduce[{x1 > 0, x2 > 0, x3 > 0, x1 != x2, x1 != x3, x2 != x3}, m]      How can I solve this problem with _Mathematica_?


title: Sorting a matrix except its last row

text: Given               M = {{"Utah", 2}, {"Iowa", 1}, {"Maine", 3}, {"Total", 6}}      I want to obtain the reverse-sorted result like this:               Reverse@SortBy[Most@M, Last]~Join~{Last@M}      giving               {{"Maine", 3}, {"Utah", 2}, {"Iowa", 1}, {"Total", 6}}      Still learning the languange, I kindly ask you to propose a shorter and - probably faster -solution for a country with 10^6 federal states.


title: Problem of RuleDelayed, how to evaluate some parts of the right side of RuleDelayed

text: Problem of `RuleDelayed`               NameList = {"a", "b", "c", "d"};          rules = Table[NameList[[i]] <> "=" ~~ x__ ~~ "\n" :> NameList[[i]] <>                    "=" ~~ OptionValue["Position"] ~~ "\n", {i, Length@NameList}];      output of `rules[[1]]` is               a=~~x__~~  :>NameList[[i]]<>=~~OptionValue[Position]~~      Here, since I used `RuleDelayed`, `NameList` in the right-hand side is not evaluated. One workaround is to use Rule, but `Rule` may cause some warning errors concerning not a string.               rules = Table[k = i; NameList[[i]] <> "=" ~~ x__ ~~ "\n" -> NameList[[k]] <> "=" ~~                    OptionValue["Position"] ~~ "\n", {i, Length@NameList}];          rules[[1]]          (*         a=~~x__~~->a=~~OptionValue[Position]~~     *)      How to solve that in the `RuleDelayed` case? the effect like the `Rule` case?


title: How do I operate on a set of ordered pairs?

text: I have a calculation that will give me a lot of ordered pairs. For each such pair in a list, I want to square the elements and add them together. Here is an example of the kind of list I have               {{-3 a, 3 a}, {-1 a,  a}, {-1 a, a}, {-1 a,  a}}      In this instance I would have `18 a^2` for the first pair and so on.


title: Can I redefine a list as a set of variables?

text: Suppose I have a list               mydata = {3, 14, 15, 92, 65}      and in some cases I want to manipulate it as a list, like for reading from and writing to a file, or for operations to be applied to all members.   But I also want to access each member individually, and I like to name the first member `alice` instead of `mydata[[1]]`, and the second `bob` instead of `mydata[[2]]`, and so on. Something like `union` in C. Can _Mathematica_ do this? **edit** (attempt to clarify, on request) In the example I need a way to redefine mydata as               mydata = {alice, bob, cindy, dan, elise}      so that I can access members as               a = mydata[[1]]   (* assigns 3 to a *)     b = bob           (* assigns 14 to b *)      and               mydata[[2]] = 42       elise = 100             results in               mydata == (3, 42, 15, 92, 100}


title: All values for a function with two arguments without Outer

text: Given two lists $l_a = \\{a_1, a_2, a_3\\}$, $l_b = \\{b_1, b_2, b_3, b_4\\}$ and some function $f$ accepting two arguments, how can I produce a list of all values $f(a, b)$ for $a\in l_a$ and $b \in l_b$ using functional construction?


title: Compiled version of (Norm/@coordinates)

text: Here I define (`NormCoordinates`).               NormCoordinates[coordinates_]:=Norm/@coordinates;     NormCoordinates[{{2.2,4.4},{5.5,6.6},{-6.7,1.3},{-2.7,-0.3}}]          (* {4.91935, 8.59127, 6.82495, 2.71662} *)      As in the example above, I plan to only use it on elements with the Head `Real`. I notice (`Norm`) can't be compiled. Can anyone implement this using `Compile` and lower level functions in a way the runs much faster on a large list?


title: How to make a Tooltip display dynamic based on a parameter value?

text: If k=3, then I would like the following to say "Sine Curve, k=3" when you hover over the output of the `Tooltip` command:               Tooltip[Sin[k*x], "Sine Curve, k=", TooltipStyle -> FontSize -> 16]      I have made a number of attempts, using pure functions and substitutions, but none delivered the output I want. The ultimate goal is to put this into a `Manipulate` where `k` is a user selectable value and the `Sin[k x]` function is plotted.


title: How I can define a new function as a function argument?

text: I need to pass a function with t as independent variable as a function parameter and want to create a new function of the same through this provided the argument of another function. Here is my code.               f[t_] := t^2 + 5          Data2EWB[f[t], 0, 15, 10, "C:\Users\Jorge\Documents\desafio\aeste.txt"]          BeginPackage["Package`"];          Data2EWB::usage =        "Data2EWB(f_, tmin, tmáx, npts, “circelet.txt”) Salva \        arquivo com nome desejado para função de Entrada"          Begin["Private`"];     Data2EWB[y_, tmin_, tmax_, npts_, dir_] :=        Export[        dir,         MatrixForm[Table[{t // N, funcaot[y, t] // N}, {t, tmin, tmax, (tmax - tmin)/npts}]]];     funcaot[y_, t_] := fc[y, t];     fc[y_, t_] := y;     End[];     EndPackage[];      I need to resolve the function that was passed as a parameter, to save data in the txt, but do not know how to do this.


title: Make FactorInteger print its result with CenterDot and Superscript?

text: I know that if I use               CenterDot @@ (Superscript @@@ FactorInteger[x])      _Mathematica_ will pretty print the output. However, is it possible to tell _Mathematica_ to automatically format the output of `FactorInteger` with `CenterDot` and `Superscript`?


title: Minimizing the maximal residual in mathematica

text: With this:               d1 = 10; d2 = 4;     mat = RandomReal[{-1, 1}, {d1, d2}];     vec = RandomReal[{-1, 1}, d1];      `LeastSquares[mat, vec]` returns the `x`, that minimizes `Plus @@ ((mat.x-vec)^2)` What is the best way to make mathematica return the `x` that minimizes `Max @@ ((mat.x-vec)^2)` I ended up with this, thank you Daniel ;)               With[{L = Length[First[mat]]},     LinearProgramming[Prepend[ConstantArray[0, L], 1],     Prepend[#, 1] & /@ Riffle[mat, -mat], Riffle[vec, -vec],     Prepend[ConstantArray[-\[Infinity], L], 0]]]


title: Finding series expansion in parametric setting

text: Suppose $y=f(x;p_1,p_2,...)$ and $t=g(x;p_1,p_2,...)$ are given where $p_1,p_2,...$ are some parameters. We want to find a series expansion of $y$ in terms of $t$. Is there a direct command or publicly available program for doing this?


title: How do I convert this Nicomachus's Triangle to one with edges?

text: I want to put edges on this Nicomachus's Triangle               r = 7;     t = Table[2^(n - k) 3^k, {n, 0, r}, {k, 0, n}];     ColumnForm[t, Center]      Is there an easy way to do this? Using Mr. Wizard's method               triangleForm[t : {_List ..} /; Depth@t == 3] :=      Show[Graphics[{         Red,         (Line /@ Join[#, Riffle @@@ Partition[#, 2, 1]]) &@           Table[{(1 - i + 2 j - r)/2, i - r - 1}, {i, 0, r}, {j, i, r}],         MapIndexed[Text[Panel[#, FrameMargins -> 0], {#2 - #/2, -#} & @@ #2] &,     t, {2}]        }],       TextStyle -> FontSize -> 18      ]          triangleForm[t]      ![NicomachusTriangle](http://i.stack.imgur.com/5lKDL.png) http://math.stackexchange.com/questions/150259/question-about-the-collatz- conjecture-nicomachuss-triangle-and-more


title: Creating and editing new stylesheets

text:
I'm trying to create a stylesheet, but the process has become painful. I'm sure that this has to do something with resetting something in Mathematica everytime I make changes to the stylesheet. To explain my problem better I will describe the steps I take to create a very simple stylesheet with only one style defined. In a new notebook enter the following:               CreateDocument[{       Cell[StyleData[StyleDefinitions -> "Core.nb"]],       Cell[StyleData["Title"],        ConversionRules -> {          "TeX" -> {"\\title{", # &, "}"},          "HTML" -> {"
", # &, "\n
"}          },        FontSize -> 26,        FontWeight -> "Bold",        FontColor -> RGBColor[0, 0, 0]        ]       },      StyleDefinitions -> "StylesheetFormatting.nb",      Editable -> True,      Saveable -> True      ]      The new notebook that appears will contain two cells. It will have the style as all the stylesheets that you have seen and you will be able to edit and save it. Save this notebook in `$UserBaseDirectory/SystemFiles/FrontEnd/StyleSheets/`. I name this notebook `Style01.nb`. Once you have this enter this command:               MathLink`CallFrontEnd[FrontEnd`ResetMenusPacket[{Automatic, Automatic}]]      I found that command here, this command resets the menu so that _Mathematica_ can list your stylesheet in the menu. At this point we are ready to use the stylesheet. Open a new notebook and create a `Title` cell. Save this notebook as `TestNb.nb` in a directory of your choice. Go to `Format > Stylesheet > Style01`. # Test 1: The current view should be this: ![pic01](http://i.stack.imgur.com/RMqFN.png) Now we select the `Title` cell in `Style01.nb` and we show the expression by going to `Cell > Show Expression`. The next screenshot shows the view with the modifications: ![pic02](http://i.stack.imgur.com/BV3QT.png) Now we change back the title cell to how it was originally by doing `Cell > Show Expression` again. In a mac we can press `command + shift + E`. Now we see that the changes took effect. ![pic03](http://i.stack.imgur.com/nLxcw.png) No problem there. We can repeat this procedure to keep adjusting the `Title` cell. # Test 2: Now lets see if our conversions rules work. Lets create a new notebook called `ExportNb.nb` in the same directory as `TestNb.nb`. Put the following in it:               nb = NotebookOpen[NotebookDirectory[] <> "TestNb.nb"];     ExportString[nb, "HTML", "FullDocument" -> False]      This is what I obtained after evaluating those commands: ![pic04](http://i.stack.imgur.com/dDSK1.png) The conversion rules took effect. But, I made a mistake (purposely made when I created the style sheet). The angle bracket should have been on the top. In any case, let us correct this mistake: ![pic05](http://i.stack.imgur.com/O7pih.png) After we revert back, and save `Style01.nb`, we try to see if the new conversion rules will work. Unfortunately, the changes in the `ConversionRules` do not take effect. I have found that if I quit the Kernel by going to `Evaluation > Quit Kernel > local` and then I run the commands again then it works: ![pic06](http://i.stack.imgur.com/3zoGl.png) # Conclusion and Questions: It seems that if we want to the way your notebook looks like you can create styles and you will see how the changes take effect after you modify your stylesheet as I described in Test1. But, if you are to export your notebook as an HTML file or Tex, then you better beware of the `ConversionRules`. I'm sure you will keep making many mistakes when you change the `ConversionRules` but you will not be able to see the change of this unless you restart the kernel. Questions: Is there any way for Mathematica to know that there has been changes in the conversion rules? Is there something that we need to restart other than the Kernel to see that this changes have been made? If restarting the kernel is the only way, is there a command to restart it? I'm getting tired of having turning it off and on all the time manually.


title: Animating a 3-D arrow given the vector's x, y, and z components as a function of time

text: I am trying to show how a vector `M` varies over time. I have the following code:               Mx={4.74124,13.1038,33.0248,19.7323,24.5952,30.1253,27.9521,29.4089,28.0574,29.277};     My={-18.2975,-7.42215,-4.23518,-9.88457,-8.96098,-8.22531,-9.6019,-9.18352,-9.06551,-9.29939};     Mz={-0.12887,-7.57926,-1.4561,-1.59703,-4.53247,-2.09772,-2.91711,-3.56798,-2.6221,-3.48453};          Animate[          Graphics3D[{     Blue,Arrow[Tube[{{0,0,0},{Mx[[i]],My[[i]],Mz[[i]]}}]]     },Axes->True,AxesLabel->{"x","y","z"},Axes],          {i,1,Length[Mx],1}]      (In actuality, my lists `Mx`, `My`, and `Mz` are much longer, but the shorter lists above reproduce the error behavior.) I get the following error: > An improperly formatted option was encountered while reading a > Graphics3DBox. The option was not in the form of a rule. Do you know how I can fix this? I do not understand which option "was not in the form of a rule."


title: Formatting imported Excel spreadsheet to include tooltips on plot

text: I have an Excel spreadsheet with numbers on two columns and names in a 3rd. I would like to plot a 2d graph of the first 2 columns and see the respective name from the 3rd column as a tooltip. I understand how to create the 2d graph and how to create tooltips but not how to tell Mathematica that the 3rd column is essentially labelling the first two and for it to show me those names when I hover over each point. Is it possible?


title: Am I using the cell option setting PageBreakWithinGroup->False correctly?

text: I had expected that this option would prevent a page break occurring within a group of cells of which this cell is the "group leader". In my case it is a "Subsubsection" containing a group of graphics cells.               NotebookWrite[notebook,Cell["Title","Subsubsection",PageBreakWithin->False,GroupPageBreakWithin->False]];      Some more cells containing graphics are then written. When I look at the notebook generated I see page breaks between some of these Subsubsection cells and the cells immediately below when it is clear the page break could have been placed above this Subsubsection cell. What am I doing wrong / How do I force some groups of cells to be kept together (the equivalent of MSWord's KeepWithNext)? A fuller example...               notebook = NotebookCreate[];     Do[     NotebookWrite[notebook,Cell["Title","Subsubsection",PageBreakWithin->False,GroupPageBreakWithin->False]];     NotebookWrite[notebook,Cell[BoxData[ToBoxes[Plot[Sin[10x]Exp[-x],{x,0,1}]]]]];,{10}]      In the notebook created with the option ShowPageBreaks set to True in option inspector two page breaks show between title and the graphic beneath.


title: Is it possible to create a manipulate control with lower and upper value

text: I'm trying to create a manipulate controller to set four value. High and low temperature for both test and use conditions. The four values then go into a calculation. I can set these as four individual sliders - which takes quite a bit of room. I did find this code * * *                   Manipulate[     Column[{Dynamic@     Grid@Map[Pane[#, {60, 12}] &,        Transpose@points, {2}]}], {{points, ({#, 0} &) /@      Round[RandomReal[{-2, 2}, {4}], .001]},      LocatorPane[Dynamic[points, (points = {#, 0} & /@ First /@ #) &],      Graphics[{}, PlotRange -> {{-2, 2}, {-.1, .1}}, Axes -> True,       ImageSize -> 300, Ticks -> {Automatic, None}],      Appearance ->       Graphics[{EdgeForm[Gray], LightGray, Disk[]},        ImageSize -> 10]] &}]      * * * at Manipulating several values from the same interval So, my question is on labeling each of the points so they are unique to each of the four temperature values? I'd also like to pre assign values and keep the values created for use in calculations later in the manipulate.... is this possible? I think I need to get rid of the Random assignment of the five point, change it to four specific points, and that is where I get los on how to assign the results of someone moving the points to a variable. Guess two or three questions here.


title: Can I combine two FoldList into one?

text: I want get something like this:               {{x, x}, {g[x, 1], f[x, 1]}, {g[g[x, 1], 2],        f[f[x, 1], 2]}, {g[g[g[x, 1], 2], 3], f[f[f[x, 1], 2], 3]}}      one way is `Transpose@{FoldList[f, x, {1, 2, 3}], FoldList[g, x, {1, 2, 3}]}` Is it posibble only use `FoldList` once?


title: Need help scoring randomly generated SEC football rankings

text: So my task is to score all the possible rankings of the 14 SEC football teams and find the best one, using who won in head-to-head games as the sole criterion (so not factoring in strength of schedule or homefield advantage yet). `RandomSample[Range[14]]` gives me one random ranking of the 14 teams, then I score that ranking by seeing how many wins and losses it actually predicted. For example, if "1" represents Missouri (miss) and "3" represents Georgia (ga), then if the generated ranking has 1 listed before 3, that ranking gets +1 to its ranking score, since Missouri beat Georgia this season. If 3 is listed before 1, the ranking score receives a -1 to its score, for incorrectly ranking those teams with respect to each other. And so on for every head-to- head SEC match up from last year. Once I can correctly score one ranking, I would use `Permutations[RandomSample[Range[14]]]` and apply the scoring algorithm to all the permutations of a list of 14, and select the list (ranking) with the max ranking score (k). My main issue right now is comparing the positions of teams in the rankings. In the code, k is the ranking score and one test for Missouri being listed before Georgia is listed at the bottom, with the output below it. However {{7}} cannot be compared to {{5}} as in 7 > 5, and that's my problem. Here's the code:               list1 = RandomSample[Range[14]]          (* Out: {11, 6, 8, 13, 3, 9, 1, 4, 5, 12, 7, 14, 10, 2} *)          miss = Position[list1, 1]];       sc = Position[list1, 2];       ga = Position[list1, 3]];     vandy = Position[list1, 4];     fl = Position[list1, 5];     tenn = Position[list1, 6];     kent = Position[list1, 7];     aub = Position[list1, 8];     bama = Position[list1, 9];     lsu = Position[list1, 10];     tam = Position[list1, 11];     missst = Position[list1, 12];     olemiss = Position[list1, 13];     ark = Position[list1, 14];          k = 0;     If[miss > ga, k++, k--]     (* Output:  If[{{7}} > {{5}}, k++, k--] *)


title: Paths integrals in the complex plane

text: I can't find how to calculate path integrals of complex functions in the complex plane. For example: $$\oint_{\mid z \mid =2}\frac{1-e^z+z}{z^3 (z-1)^2}dz$$


title: What is modifying an init.m that changes menu Palettes order?

text: When I installed the mathStatica application, it seems to have made some kind of change deep in my Mathematica 8.0.4 system files. That change causes the mathStatica palette to appear out of alphabetical order in the `Palettes` menu. And the palette notebook does _not_ set any value for `MenuPosition`. In `$UserBaseDirectory/Autoload/PacletManager/Configuration/FrontEnd/init.m` I see:               SetOptions[$FrontEndSession,     PalettePath -> {ParentList, FrontEnd`FileName[{$UserBaseDirectory,       "Applications", "mathStatica", "FrontEnd", "Palettes"},     "PacletManager" -> True]} ....      (Note that on my Mac OS X 10.7.3 system, `$UserBaseDirectory` is the same as `$BaseDirectory`.) However, if I delete the `PalettePath` option there, quit Mathematica, and restart it with clean preferences and clean cache, nonetheless:   * that same `PalettePath` option reappears in the same `init.m`; and then of course   * the mathStatica palette appears again out of order in the menu `Palettes` list. Question: what changes to some system file might cause this annoying and persistent behavior. I've looked at all the `init.m` files I could find inside the `Mathematica.app` package (which is how the Mac bundles the entire `$InstallationDirectory`) but don't see anything suspicious.


title: Labels and tickmarks inside Frame

text: Is there a way to force Plot and related functions to place the tick labels inside, rather than outside a frame? For example, consider,               Plot[Sin[x], {x, 0, 10}, Frame -> True]      When this line is executed, the tick labels are outside the bottom and left edges of the frame: ![enter image description here](http://i.stack.imgur.com/sE8YQ.png) Is there an easy way to move them to the inside? (Why place tick labels inside the frame, you ask? I would like to export plots to PDF in a specified absolute size, so that one major tick on the plot is exactly 1 cm on the printout. If the labels were not placed on the outside, padding the image, this could be easily done using `ImageSize`, as described here.)


title: Spiral pattern and Fibonacci numbers

text: I'm want to generate a 2D spiral pattern like the the one shown in the following figure. I can generate the spirals one by one, but I think there ought to be a more efficient method for generating such a scattered point pattern. Could anybody give me a hint? ![sunflower pattern](http://i.stack.imgur.com/QtlCU.png)


title: OpenSQLConnection error

text: I used to be able to connect to a SQL Server database. I haven't run this program for a few months. I tried it today and it failed, so I went back to try OpenSQLConnection[] and got the following error:               StringJoin::string: String expected at position 2 in server:1433/<>database.      I began my program with:               Needs["DatabaseLink`"]     Needs["JLink`"];      I tried to connect to my database anyway, but that returned:               OpenSQLConnection[JDBC[Microsoft SQL Server(jTDS),     server:1433/ <> database],  "Catalog" -> TOA_DW,     Description -> The reinsurance data warehouse.  Connection     created on September 5, 2013., Location->     C:\Users\mkaplan\AppData\Roaming\Mathematica\     DatabaseResources\warehouse.m, Name -> warehouse,      Password ->  , Properties -> {},      ReadOnly -> False, RelativePath -> False, Timeout -> Automatic,     TransactionIsolationLevel -> ReadUncommitted,      UseConnectionPool -> False, Username -> , Version -> 2.]      When I ran SQLConnections[] I got nothing. Then I tried to connect to the demo database. Got the same initial error when I executed OpenSQLConnection[]. I manually tried to connect to demo through the UI and got a bunch more of the same "StringJoin" errors. However when I ran SQLConnections[] I did get:               {SQLConnection["demo", 1, Open, TransactionIsolationLevel -> ReadCommitted]}      Which I think means that it connected. There **have** been some changes to permissions that were put into place since the last time I ran this successfully. However OpenSQLConnections[] isn't specifying anything, so I wonder why I got that initial "StringJoin" error. Also, I **can** connect to my database using the SQL Management Studio. Can anyone suggest where to start looking for the problem?


title: Graphical Plots of PDF and CDF

text: I have a joint density and distribution function that I want to plot in a meaningful way, (i.e., want to be able to see how the functions behaves as changes in x and y happen simultaneously. If possible, I would like for the `x` axis to stay horizontal (left to right), and the `y` axis going into the screen. No particular choice is in mind at the moment such as (`Plot3D`, `ContourPlot3D`, or `DiscretePlot3D`). More than one way of plotting is encouraged just to see all useful possibilities of grasping useful information on how the functions behave. Maybe even an example including `Manipulate` would be very helpful as well. The functions are here below:                (pdf)...    f[x_, y_] := x^2 y E^(-x (y + 1)) UnitStep[x] UnitStep[y]           (cdf)...    F[x_, y_] := (1 - E^-x + ((y x + 1) E^(-x (y + 1)))/(y + 1) +                  (y E^(-x (y + 1)) - 2 y - 1)/(y + 1)^2) UnitStep[x] UnitStep[y]


title: Evaluating Erf[x] in arbitrary precision

text: Is it possible to evaluate `Erf[200]` with arbitrary precision? I only get `1.` as result but I would like to know if a arbitrary precision is possible because I need to compare a gaussian approximation to the hypergeometric distribution that for the values I'm using results in $\approx 10^{-6100}$. Should I instead rely on `NIntegrate` and specify directly there my precision?


title: Solving a tridiagonal system of linear equations using the Thomas algorithm

text: I'm trying to write a function that can solve a tridiagonal system of linear equations using the Thomas algorithm. It basically solves the following equation. (Details can be found at the Wiki page here Tridiagonal matrix algorithm.) $$ \begin{bmatrix} {b_ 1} & {c_ 1} & { } & { } & { 0 } \\\ {a_ 2} & {b_ 2} & {c_ 2} & { } & { } \\\ { } & {a_ 3} & {b_ 3} & \ddots & { } \\\ { } & { } & \ddots & \ddots & {c_{n-1}}\\\ { 0 } & { } & { } & {a_n} & {b_n}\\\ \end{bmatrix} \cdot \begin{bmatrix} {x_ 1 } \\\ {x_ 2 } \\\ {x_ 3 } \\\ \vdots \\\ {x_n } \\\ \end{bmatrix} = \begin{bmatrix} {d_ 1 } \\\ {d_ 2 } \\\ {d_ 3 } \\\ \vdots \\\ {d_n } \\\ \end{bmatrix} $$ This can be done easily in various ways in _Mathematica_ using the built-in functions such as `Solve`, `LinearSolve`, `LUDecomposition`, etc. Instead of using _Mathematica_ 's wonderful black box solvers, I have decided to follow the procedures in the algorithm and write my own version which I can better control. Here is the procedure in detail: $$ c'_i= \begin{cases} \begin{array}{lcl} \cfrac{c_i}{b_i} &&; i = 1 \\\ \cfrac{c_i}{b_i - c'_{i - 1} a_i} &&; i = 2, 3, \ \dots, n-1 \\\ \end{array} \end{cases} $$ $$ d'_i= \begin{cases} \begin{array}{lcl} \cfrac{d_i}{b_i} &&; i = 1 \\\ \cfrac{d_i - d'_{i - 1} a_i}{b_i - c'_{i - 1} a_i} &&; i = 2, 3, \dots, n. \\\ \end{array} \end{cases} $$ $$ \begin{array}{lcl} x_n&=&d'_n\\\ x_i&=&d'_i-c'_ix_{i+1} \end{array} $$ I tried to write the function in _Mathematica_ like this:               tridag[{a_, b_, c_}, d_] :=       Module[{n = Length[d], c1 = Range[Length[d]], d1 = Range[Length[d]], x = Range[Length[d]]},        c1[[1]] = c[[1]]/b[[1]];        d1[[1]] = c1[[1]]/c[[1]]*d[[1]];        Do[c1[[i]] = c[[i]]/(b[[i]] - a[[i]]*c1[[i - 1]]);          d1[[i]] = c1[[i]]/c[[i]]*(d[[i]] - a[[i]] d1[[i - 1]]);, {i, 2, n - 1}];        x[[n]] = d1[[n]];        Do[x[[i]] = d1[[i]] - c1[[i]]*x[[i + 1]], {i, n - 1, 1, -1}];      x]      where a, b, c are the three diagonal rows in the matrix. For a test case of               A = {{1, 2, 0, 0, 0}, {2, 2, 3, 0, 0}, {0, 3, 3, 4, 0}, {0, 0, 4, 4, 5}, {0, 0, 0, 5, 5}};     R = {5, 15, 31, 53, 45};      my function gives the same answer as _Mathematica_ 's linear solver:               LinearSolve[A, R]      > {1, 2, 3, 4, 5}               tridag[{PadLeft[Diagonal[A, 1], 5], Diagonal[A], PadRight[Diagonal[A, -1], 5]}, R]      > {1, 2, 3, 4, 5} Here are my questions:   1. Since I am just a novice, my function is simply a direct translation of the above procedurual equations. So I would like to learn a really functional _Mathematica_ way of implementing this function (other than using the built-in solver)?   2. A more general question is that, given an algorithm written in a procedure way, i.e., with implementation in a procedure language like C or Fortran in mind, how can it be translated into functional _Mathematica_ code? Can you give some examples or suggestions or guidelines? ### Edit As belisarius points out, "'the real elegant Mathematica way' is always to use an already implemented function". To be clear, I'm not asking how to implement a solver that is superior to the built-in solver. I'm just asking how to implement a solver in the _Mathematica_ way, i.e., in the functional way. I think knowing how to write one's own solver is helpful when using the built-in solvers. It gives the user confidence when the built-in solver does not work. An example may be the `HilbertMatrix`:               LinearSolve[ HilbertMatrix [10], Table[Random[], {10}]]      > LinearSolve::luc: "Result for LinearSolve of badly conditioned matrix {{1., > 0.5, 0.333333, 0.25, 0.2, 0.166667, 0.142857, 0.125, 0.111111, 0.1}, <<8>>, > {0. 1, 0.0909091, 0.0833333, 0. 0769231, 0.0714286, 0.0666667, > 0.0625,0.0588235, 0.0555556, 0.0526316}} may contain significant numerical > errors." Besides, I think trying to implement a simple solver is a good way for me as a new hand to learn the _Mathematica_ language.


title: How to manipulate some list-plot in Mathematica

text: I have two separated matrices in the form                X[[i*dx,j*dt]] and V[[i*dx,j*dt]]       where i & j are integers from (1 to N) & (1 to M). V & X are velocity and space respectively in phase space. I want to figure out a two dimensional (V-X) plot of these two matrices for different values of time (which is j*dt) in a sequence manner. I can use the following command to plot it for an specific time (e.g. j*dt=5) for all space:               ListPlot[Table[{V[[i,5]], X[[i,5]]}, {i, 1, N}];        But I'm in trouble to show it in sequence . I tried "Manipulate" command:               Manipulate[ListPlot[Table[{V[[i, j]], X[[i, j]]}, {i, 1, N}]], {j, 1, M}];      But unfortunately it doesn't work. Just notice that I need 2-D figure that represent a (V-X) plot of all space for different times. I don't know what should I do.


title: Efficiently appending points to a NearestFunction

text: I have a program which works with a list of points (in 3D, but it could be in 1D as well, it won't make a difference). Within a loop, it keeps adding new points to the list. To calculate the coordinates of a new point, it needs to use a NearestFunction generated from the list of existing points. When a new point is added to the list, the NearestFunction needs to be rebuilt as well. This is rather time consuming if I do it using the list of existing points. Is it possible to more efficiently append a new point to an already constructed NearestFunction? (Perhaps by making use of the knowledge of the internal structure of a NearestFunction) * * * Here's an example to illustrate the question better:               points = RandomReal[1, {1000, 3}]; (* we have lots of points ... *)     nf = Nearest[points];  (* ... and the corresponding NearestFunction *)     AppendTo[points, RandomReal[1, 3]]; (* we add an extra point, ... *)     nf = Nearest[points]; (* so we need to rebuild the NearestFunction,                               but doing it from scratch is inefficient *)      Rebuilding the NearestFunction for a large number of points is not very efficient. Is there a way to add a single point more efficiently, making use of the existing NearestFunction?


title: How can I find the average of the ordinate of an indefinite number of lists of points?

text: Suppose that I have three lists:               list1 = {{0, 1}, {0.1, 10}, {0.2, 100}};     list2 = {{0, 1}, {0.1, 10}, {0.2, 100}};     list3 = {{0, 2}, {0.1, 20}, {0.2, 200}};      In each list, the abscissas represent time (my system was measured at the times 0, 0.1, and 0.2 seconds, for example), whereas the ordinates are the measured values. I would like to create a function `f` that finds the average (i.e., the mean) of the ordinates. So:               f[list1, list2, list3]      should give the output: > {{0, 4/3}, {0.1, 40/3}, {0.2, 400/3}} I would like `f` to be able to take two or more lists as input. All lists are given to have the same number of points. I think that one way to write `f` is:               f[lists__] := Transpose[{First[{lists}][[All, 1]],        Map[Mean, Transpose[Map[#[[All, 2]] &, {lists}]]]}]      Can you please help me think of a cleaner, more succinct, and possibly faster way to do this?


title: What's wrong with my use of Do?

text: My code is: `Do[Print[number[[i ;; (i + 4)]]], {i, number}]`. The variable `number` here is a list consisting of 1000 digits. My aim is to `Print[]` a series of lists as follows: the first list consists of items 1 through 5 from `number`. The second list consists of items 2 through 6 of `number`, and so on. Instead, what I'm getting is this: ![enter image description here](http://i.stack.imgur.com/zu3cT.png) You can see that it does `Print` some lists, but it seems to be shuffling the digits around in some random kind of order, plus completely making up some numbers (e.g. where did the '5' in the first list come from??). Then suddenly it grinds to a halt and displays an error message saying 'Cannot take positions 0 through 4 in {the list}, before throwing up the entire 1000 digit list, and then continuing with further 5-member lists and repeating the pattern. I have no idea what's happened here so I'd be very grateful if somebody could explain to me what's going on - and more importantly, how I can get this code to work as intended. Thanks!


title: 2D ListPlot with separate color function

text: Suppose a data array of the form `{{x1,y1,z1},{x2,y2,z2}...}`, is it possible to use `ListPlot` where x,y specify the point position and z (Hue[z]) specify the color of each point?


title: Can I create a dynamic number of rows in TabView through an iteration?

text: I have written code, with the help of stackoverflow of course, and I want to make it user friendly so that other people in my lab can use it. I'm playing with DialogCreate and similar functions. I want to do something like this so far:                  CreateDialog[TabView[{        "General" ->         Column[{           Row[{TextCell["Project Name:"], InputField[Dynamic[Project]]}],           Row[{TextCell["Number of Wells:"], InputField[Dynamic[num]],              Button["Set", DialogReturn[num]]}]}],        "Row Selection" ->         Column[{Do[           Row[TextCell["Well " <> ToString[i] <> ":"],            FileNameSetter[Dynamic[Evaluate[Symbol["w" <> ToString[i]]]],           "Open"]], {i, 1, num}]}]}, ControlPlacement -> Left]      ]      I want to dynamically create more rows based on the input of "Number of Wells" within the same dialogbox but in a different tab. Is anything like this possible or some sort of alternative?


title: Writing CSV or alternative

text: I've tried to export a list to a CSV file. I shut it down after about 20 minutes of processing. The list has 261,000 rows and 30 columns. I finally exported it to a txt file and its size was 111 MB. txt went slowly but was acceptable. However the format is not nearly as good to work with. Is there a way to output a table that runs faster than Export? The data has integers, doubles, dates and strings. I did a test using the last 2 cols and output that. I learned a few things that help a lot. The last two columns look like:               Dimensions[aOutput]     aOutput[[1 ;; 2]]     {261136, 2}     {{14., "Casualty Treaty XS CM"}, {13., "Casualty Treaty XS Working"}}.      They're all pairs of an integer followed by a string. The 2 column test timed at 17 seconds, but took 6 minutes of "wall" time. I was outputting to a network share at a remote data center with a 100Mb connection. When I output the test to my C drive it took 8 seconds and about 10 seconds of wall time.


title: Help with Permutations

text: I am currently trying to generate a list of permutations of length 2 of elements of a list of strings. For example:               Permutations[{"s1", "s2", "s3", "s4"}, {2}]     {{"s1", "s2"}, {"s1", "s3"}, {"s1", "s4"}, {"s2", "s1"}, {"s2", "s3"}, {"s2", "s4"}, {"s3", "s1"}, {"s3", "s2"}, {"s3", "s4"}, {"s4", "s1"}, {"s4", "s2"}, {"s4", "s3"}}      which is quite correct. Now, my problem starts when attempting the same operation for a really big list of strings imported from a tsv file - we are talking of a bit more than 10000 strings. All sort of characters can be expected in strings. This is the code that I am using:               t1 = Import["/home/bla/work/parsed_names.tsv"]     t2 = Table[t1[[i]][[1]], {i, 1, Length[t1]}]     Permutations[t2, {2}]      After evaluation of the last line, I get no output. If I evaluate it twice, all the symbols defined previously (t1, t2) become undefined, and Permutations finally give this output:               Permutations[t2, {2}]     Permutations::normal: Nonatomic expression expected at position 1 in Permutations[t2,{2}]. >>     Permutations[t2, {2}]      Which is the output for an undefined value of t2. I tried to debug the problem: the import operations seems to go fine, each element of t2 is a proper string:               Length[t2]     10525          Tally[Table[Head[t2[[i]]], {i, 1, Length[t2]}]]     {{String, 10525}}      I tried running Trace to understand what is going on, but Mathematica still kept quiet during the first evaluation. The second evaluation again forces all the symbols to be cleared, and the output of Trace is unhelpful:               {Permutations[t2,{2}], {Message[Permutations::normal,1,Permutations[t2,{2}]],      {MakeBoxes[Permutations::normal: Nonatomic expression expected at position 1 in Permutations[t2,{2}]. >>,StandardForm],       RowBox[{StyleBox[RowBox[{Permutations,::,normal}],MessageName],: ,        "Nonatomic expression expected at position \!\(1\) in \!\(Permutations[\(\(t2, \(\({2}\)\)\)\)]\). \!\(\*ButtonBox[\">>\", ButtonStyle->\"Link\",          ButtonFrame->None, ButtonData:>\"paclet:ref/message/General/normal\", ButtonNote -> \"Permutations::normal\"]\)"}]},Null},Permutations[t2,{2}]}      Is there something obviously wrong that I am doing? If not, how can I debug this problem further?


title: Extraneous Keyboard Shortcut for ctrl + '^' in Mathematica 8

text: I would like to use the keyboard shortcut `Ctrl``^` to enter a superscript. I have tried to type this two different ways, and each time i have gotten an undesirable result. According to the file `KeyEventTranslations.tr`, the binding is correct:               Item[KeyEvent["^", Modifiers -> {Control}], "Superscript"]      I am running Mathematica 8 on Windows Vista, and I currently have two keymaps installed--The standard QWERTY and a Progammer Dvorak--using Windows IME. My first attempt to type it is in standard QWERTY, I type the key sequence `Shift``Ctrl``6`. This sequence results in a dialog box as if I had entered the menu command `File -> Revert...`. On my Programmer Dvorak, I type the key sequence `Shift``Ctrl``]`. This sequence results in the dialog box as if I had entered the menu command `Edit -> Preferences...`. In both cases, the key sequences that I am referring to are the physical keys that I press, not the character produced, because in both cases, I type a '^' character. I am very confused, because neither of these dialog boxes seem to have an keyboard shortcuts assigned, so I do not understand why I am reaching them. I have also looked in `MenuSetup.tr`, but I did not see anything noteworthy. What is happening, and is there a way to correct this behavior?


title: Results of ArgMax as a function of a parameter with InterpolatingFunctions

text: I would like to obtain a function and its derivatives, where the function is defined as the solution to a maximization problem. The obvious approach               Clear[f]     f[a_?NumericQ] := NArgMax[-(x - a)^2, x]     f[1]     f'[1]      fails to give the numeric `f'[1]`. So I used the following:               Clear[f]     f = FunctionInterpolation[ArgMax[-(x - a)^2, x], {a, 0, 2}]     f'[1]      The actual function I would like to maximize has no closed form, thus an InterpolatingFunction object must be used:               Clear[f, g]     g = FunctionInterpolation[-(x - a)^2, {x, 0, 2}, {a, 0, 2}];     f = FunctionInterpolation[ArgMax[g[x, a], x], {a, 0, 2}]     f'[1]      This gives the error > FunctionInterpolation::nreal: Near {a} = {0}, the function did not evaluate > to a real number. How to avoid this error and get the correct `f'[a]` for any `a`?


title: Windows IME Chinese blocking shortcut for ctrl + space

text: I currently use the Windows IME on Windows Vista to allow myself to type Chinese characters (not in _Mathematica_ ), and by default typing `Ctrl``Space` switches between the English keyboard and the Chinese keyboard. When in Mathematica, I would like to use the default shortcut `Ctrl``Space` to move out of subscripts and superscripts. Is it possible to retain the functionality of this keyboard shortcut in Mathematica? I cannot figure out how to remove the shortcut from the IME, which is an acceptable solution, since i do not use this shortcut to switch languages.


title: How to the take derivatives of a parametric function?

text: I have a parametric curve of the form $x(t)=2t^3+3t^2-12t,\ y(t)=2t^3+3t^2+1$ How do I take the derivative of that function in _Mathematica_? Is there a certain function I should use?


title: Data structure for a list of actions

text: **The idea:** I need to generate a sequence of events then run a "propagator" over the list of events where the "propagator" will update the state of the following event. I can then write functions that tally results or makes visualizations. The following is a mix of code I have found here and some of my own. This example is a short prof of concept.               Clear[CircleMinus]     sys_\[CircleMinus]sub_ := sub /. sys     sys_\[CircleMinus]sub_[n_] := (sub /. sys)[[n]]     sys_\[CircleMinus]sub_[f_Function] :=      Module[{s}, s = Select[(sub /. sys), f];     (*remove redundant {}*)s /. {x_List} :> x];          Clear[keypos]     (*local Function*)     keypos[s_, key_] := Module[{v},     v = Flatten[Position[Map[#[[1]] &, s], key]];     If[Length[v] > 0, v[[1]], "Null"]     ];          Clear[ud]     ud[sys_, sub_, val_] := Module[{pos, sysin},     sysin = sys;     pos = keypos[sys, sub];     If[pos == "Null",       AppendTo[sysin, (sub -> val)],       sysin[[pos]] = (sub -> val)     ];     Return[sysin]     ]          Clear[PropView]     PropView[dt_, x_, v_, a_: 0] := x + v dt + 1/2 a dt^2;      Now for a list of actions with minimal input.               actions = {       {"Pos" -> {0, 0},       "Vec" -> {1, 1},       "StartTime" -> 0,       "dTime" -> .1,       "State" -> {"Pen" -> 1, "Color" -> {1, 0, 0}}       },       {       "dTime" -> .1,       "State" -> {"Pen" -> 1, "Color" -> {1, 1, 0}}       },      {      "a" -> {-2, 2},      "dTime" -> .1,      "State" -> {"Pen" -> 2, "Color" -> {0, 0, 0}}      },      {      "dTime" -> .1,      "State" -> {"Pen" -> 1, "Color" -> {0, 1, 1}}      }      }      Notice I only need to include information in the actions where states change. For example at step actions[[3]] there is an acceleration. Now for the propagator:               Do[       pos = actions[[i]]\[CircleMinus]"Pos";       vec = actions[[i]]\[CircleMinus]"Vec";       st = actions[[i]]\[CircleMinus]"StartTime";       dt = actions[[i]]\[CircleMinus]"\[Delta]Time";       a = actions[[i]]\[CircleMinus]"a";       If[a == "a", a = 0];       actions[[i + 1]] = ud[actions[[i + 1]], "Pos", PropView[dt, pos, vec, a]];       actions[[i + 1]] = ud[actions[[i + 1]], "Vec", PropView[dt, vec, a, 0]];       actions[[i + 1]] = ud[actions[[i + 1]], "StartTime", st + dt],      {i, 1, Length[actions] - 1}]      At this point the actions list is filled with state information. (Each event now has a key value pair for "Pos" etc.) This is just a very simple example that shows the main idea. In my real problem my actions list will be much more complicated. I would like to have a few levels of information. Like what is shown in the actions list above with the "State" key. But in the example I have not used or modified the "State" key's value. **The Question:** How do I easily modify key-values at lower levels? My simple "ud" function will not work                 ud[actions[[2]]\[CircleMinus]"State", "Color", {1, 1, 1}]       I would love to be able to do something like this:                 actions[[2]]\[CircleMinus]"State"\[CircleMinus]"Color"={1,1,1}      Where "Color" would be created if it did not exist and so would the sub- structure if "State" did not exist. I would prefer a solution that did not involve coping my actions list for each operation of my functions. I'm also open to solutions or ideas that take me from my initial thoughts. **Update and Partial Solution** Accessing the data is the same as above:               Clear[CircleMinus]     sys_\[CircleMinus]sub_ := sub /. sys;     sys_\[CircleMinus]sub_[n_] := (sub /. sys)[[n]];     sys_\[CircleMinus]sub_[f_Function] :=      Module[{s}, s = Select[(sub /. sys), f];      (*remove redundant {}*)s /. {x_List} :> x];      This code I found here on this website and I'm sorry I could not find the reference again. The next part is an extension on what István Zachar did in the dynamic part of his answer: István Zachar               Clear[ud]     (*ud[obj_]:=obj;*)     ud[obj_, field_, val_] := Module[{pos},      If[ListQ[obj], pos = Position[obj, field, {0, \[Infinity]}, 1],          pos = {}];      If[pos === {},           If[ListQ[obj], Join[obj, {field -> val}], {field -> val}],          ReplacePart[obj, {First@First@pos, 2} -> val]]];           ud[obj_, field_, field2_, val_] :=          ud[obj, field, ud[obj\[CircleMinus]field, field2, val]];           ud[obj_, field_, field2_, field3_, val_] :=       ud[obj, field,              ud[obj\[CircleMinus]field, field2,                  ud[obj\[CircleMinus]field\[CircleMinus]field2, field3, val]               ]       ];      I can now easy add and update key value pairs down to the third level. However I do not consider my additions good code because it is not generalized for updating to the $n^{\text{th}}$ level.


title: How to use ScientificForm in computation

text: Lets say I want to add 2 values :               ScientificForm[Quantity[0.6884806137833915, "Millimeters"], 2] +         ScientificForm[Quantity[0.0629737394087381, "Millimeters"], 2]      To get result               ScientificForm[Quantity[0.75, "Millimeters"], 2]      Edit: Small example, it seems more complicated because context and comments are lost. Idea here is, to get formula first and then after adding input data I get the values also. This works, but I want to keep only 2-3 most significant digits - here is where ScientificForm seems to be inapplicable. ![enter image description here](http://i.stack.imgur.com/7Xo4l.jpg) Source:               l = a/b (Overscript[Subscript[s, 1], _] -           Overscript[Subscript[s, 2], _]);     m["Subscript[U, c](Overscript[l, _])"] =       Sqrt[(D[l, a] m["Subscript[U, C](a)"])^2 + (D[l, b] m[            "Subscript[U, C](b)"])^2 + (D[l,             Overscript[Subscript[s, 1], _]] m[            "Subscript[U, C](Subscript[s, 1])"])^2 + (D[l,             Overscript[Subscript[s, 2], _]] m[            "Subscript[U, C](Subscript[s, 2])"])^2]     a = Subscript[na, 1] - Subscript[na, 2];     b = Subscript[nb, 1] - Subscript[nb, 2];     m["Subscript[U, C](b)"] =       m["Subscript[U, C](a)"] =        Sqrt[(m["Subscript[U, c](Subscript[na, 1])"]*            D[a, {Subscript[na, 1]}])^2 + (m[             "Subscript[U, c](Subscript[na, 2])"]*            D[a, {Subscript[na, 2]}])^2]     m["Subscript[U, C](Subscript[s, 2])"] =       m["Subscript[U, C](Subscript[s, 1])"] = (Sqrt[(Subscript[              t, \[Infinity], \[Beta]] Subscript[e, p, kruvik]/              3)^2 + (\[Beta] Subscript[L, kruvik])^2])     m["Subscript[U, c](Subscript[nb, 2])"] =       m["Subscript[U, c](Subscript[nb, 1])"] =        m["Subscript[U, c](Subscript[na, 2])"] =         m["Subscript[U, c](Subscript[na, 1])"] =          Sqrt[(Subscript[               t, \[Infinity], \[Beta]] Subscript[e, p, joonlaud]/               3)^2 + (\[Beta] Subscript[L, joonlaud])^2]     \[Beta](*usaldatavus*)= 0.95;     Subscript[        t, \[Infinity], \[Beta]](*studenti tegur*)= \     \!\(TraditionalForm\`Round[          InverseCDF[StudentTDistribution[10000], \[Beta]], 0.1]\);     Subscript[t, v, \[Beta]]=        Round[InverseCDF[StudentTDistribution[v], \[Beta]], 0.1];     Subscript[e, p, kruvik]=        Quantity[0.004, "Millimeters"];     Subscript[L, kruvik]=        Quantity[0.005, "Millimeters"];     Subscript[L, joonlaud]=        Quantity[0.5, "Millimeters"];     Subscript[e, p, joonlaud]=        Quantity[0.2, "Millimeters"];     a = Subscript[na, 1] - Subscript[na, 2];     b = Subscript[nb, 1] - Subscript[nb, 2];     a = Quantity[0.78, "Meters"];      b = Quantity[0.112, "Meters"];      Subscript[s, 1] = {Quantity[3.67, "Millimeters"],         Quantity[3.63, "Millimeters"], Quantity[3.65, "Millimeters"],             Quantity[3.65, "Millimeters"]};      Subscript[s, 2] = {Quantity[2.82, "Millimeters"],         Quantity[2.8, "Millimeters"], Quantity[2.8, "Millimeters"],             Quantity[2.8, "Millimeters"]};      Overscript[Subscript[s, 1], _] = Mean[Subscript[s, 1]];     Overscript[Subscript[s, 2], _] = Mean[Subscript[s, 2]];     m["Subscript[U, c](Overscript[l, _])"]     m["Subscript[U, C](Subscript[s, 2])"]     m["Subscript[U, C](b)"]     m["Subscript[U, c](Subscript[nb, 2])"]


title: Conditions for Piecewise[ ] Command

text: I am trying to plot a function in which is piecewise defined. I found the Fourier coefficients of this, and my question is how to define `even` & `odd` conditions for the `Piecewise` command? I used _2n_ and _2n+1_ for even & odd respectively, but this does not suffice. I have a `MWE` below.               Clear[f,a,b,F]     f[t_]=Piecewise[{{-Sqrt[9+t+t^2],-2<t<0},{Exp[Sin[t]],0<=t<=2}}]     a0=23/9;     a[k_]=Piecewise[{{20/(k^4Pi^4),2k},{-83/(k Pi),2k+1}}]     b[k_]=Piecewise[{{-92/(k^3 Pi^3),2k},{-53/(k Pi)+14/(k^2 Pi^2),2k+1}}]     F[t_]=a0/2+Sum[a[k]Cos[(k Pi t)/2]+b[k]Sin[(k Pi t)/2],{k,1,20}];     Plot[{f[t],F[t]},{t,-1,1}]      ![Mathematica graphics](http://i.stack.imgur.com/yktUT.png)


title: Customizing the Screen Environment

text: Is it possible to make Mathematica notebooks as stylish as this below with custom backgrounds and predictive text coloring? As shown in the snippet below? And possibly have the option to save the preferred setting and choose it on each start up, or possibly have it automatically loaded when the notebook is launched. ![enter image description here](http://i.stack.imgur.com/0jwMg.png)


title: Find the value of parameter so that the equation has one solution

text: Let $(E_l) : x^4-4x^3+x^2(5-l^2)+4 x l^2-4l^2 = 0$ be an equation with $l$ as a parameter and $x$ as an unknown and $S_l$ the set containing all the real solutions of $(E_l)$. Then there is a unique value of $l$ verifying $card(S_l) = 1$. Is there a way in Mathematica to find an approximate value for this $l$ ?


title: Why Fourier doesn't show me the peaks?

text: I'm trying to identify the frequencies in my time history samples, and I can see a frequency in the time history, but can't see it in its Fourier transform. Here it is : the sample data:               dt = 0.01;(*0.01 second per sample*)     ls={7.18384,9.08503,7.13301,9.03243,7.23692,8.82911,7.48153,8.50053,7.8291,8.09453,8.22514,7.67123,8.60473,7.29656,8.90489,7.02926,9.07228,6.91356,9.07469,6.96968,8.90404,7.19156,8.58122,7.54573,8.15062,7.97689,7.67665,8.41549,7.23096,8.78898,6.88426,9.03305,6.69172,9.10231,6.68698,8.97821,6.87272,8.6724,7.22283,8.22643,7.68225,7.70488,8.17857,7.18711,8.62957,6.75303,8.9597,6.47266,9.10889,6.39174,9.04594,6.52704,8.77139,6.85901,8.32088,7.33824,7.7584,7.88776,7.16829,8.41967,6.64141,8.84366,6.2609,9.0868,6.08919,9.10045,6.15615,8.87392,6.45525,8.43236,6.94108,7.83828,7.53853,7.17843,8.15053,6.55427,8.67686,6.06288,9.02603,5.78403,9.13458,5.76455,8.97352,6.01177,8.55858,6.48966,7.94428,7.12458,7.22101,7.8152,6.49678,8.4485,5.88528,8.91739,5.48272,9.13786,5.35709,9.06375,5.53107,8.69409,5.98259,8.07629,6.64157,7.29757,7.40537,6.47512,8.14882,5.73434,8.74894,5.19349,9.09985,4.93916,9.13459,5.01757,8.83338,5.41929,8.23096,6.08644,7.41062,6.91285,6.49317,7.76769,5.61863,8.50777,4.92325,9.00806,4.51966,9.1747,4.47503,8.96814,4.80297,8.40434,5.455,7.55984,6.33198,6.55581,7.29271,5.54458,8.18165,4.6821,8.847,4.10633,9.17184,3.91187,9.08704,4.13559,8.59066,4.74753,7.74309,5.65489,6.66645,6.71462,5.51928,7.75486,4.47976,8.6024,3.70977,9.10911,3.33653,9.17844,3.42289,8.77952,3.96388,7.95795,4.87716,6.82561,6.02223,5.55073,7.21349,4.32513,8.25592,3.34263,8.96977,2.75835,9.22521,2.67336,8.96055,3.10556,8.19668,3.99626,7.03496,5.20525,5.6427,6.54315,4.23034,7.78851,3.01522,8.73391,2.19205,9.20894,1.89461,9.11841,2.17992,8.45091,3.00859,7.29079,4.25733,5.80068,5.727,4.20335,7.18224,2.74288,8.37806,1.64996,9.10926,1.10137,9.23383,1.19232,8.70843,1.91736,7.5871,3.1692,6.02681,4.75307,4.25335,6.41448,2.53923,7.8804,1.14864,8.89922,0.307694,9.28655,0.154088,8.95041,0.725381,7.91675,1.93765,6.31868,3.60713,4.38985,5.46625,2.41628,7.21338,0.707136,8.55287,-0.470752,9.2482,-0.919297,9.15831,-0.561298,8.26386,0.562301,6.67532,2.27715,4.61492,4.31759,2.39053,6.34975,0.340327,8.03907,-1.21045,9.08947,-2.01384,9.30485,-1.9283,8.61208,-0.958302,7.08603,0.756819,4.93354,2.94639,2.47094,5.26353,0.0706556,7.32281,-1.89254,8.77714,-3.10504,9.358,-3.36416,8.93794,-2.61487,7.53742,-0.963082,5.34406,1.33854,2.66827,3.9233,-0.0836731,6.37173,-2.49189,8.2693,-4.17005,9.28401,-4.84777,9.20861,-4.3986,8.01348,-2.88195,5.83756,-0.523299,2.99222,2.304,-0.10749,5.14496,-2.98081,7.52648,-5.18357,9.04878,-6.32959,9.4304,-6.18952,8.56459,-4.73628,6.56344,-2.13332,3.70414,1.31944,0.401559,5.19872,-2.85418,9.0291,-5.5357,12.3241,-7.17454,14.6869,-7.4465,15.8834,-6.29832,15.9227,-3.97558,15.044,-0.986409,13.6463,2.07958,12.1451,4.72194,10.8576,6.6742,9.93404,7.90659,9.37837,8.56294,9.10124,8.84598,8.99267,8.93815,8.96116,8.95636,8.95544,8.95677,8.95391,8.95455,8.95365,8.95341,8.95371,8.95173,8.95356,8.95088,8.95381,8.9499,8.95321,8.94933,8.95282,8.94887,8.9513,8.94838,8.95018,8.94857,8.94853};      Fourier transform function:               DFT[A_, ht_] := RotateRight[ht/Sqrt[2 \[Pi]]*Fourier[RotateLeft[A, Length[A]/2 - 1],                    FourierParameters -> {1, 1}], Length[A]/2 - 1];     (*shift the zero frequency to the center*)      plot the time history:               ListPlot[ls, PlotRange -> All, Joined -> True, DataRange -> {0, dt*Length[ls]}, Axes -> False, Frame -> True]      ![enter image description here](http://i.stack.imgur.com/4hnHe.png) We can see there are a fast frequency with period about 0.02s and a slow frequency with period about 1.5s, but in the Fourier transform we only see the fast frequency(except the zero frequency)               ListPlot[Abs[DFT[ls, dt]]^2, PlotRange -> All, Joined -> True, DataRange -> {- 1/dt/2, 1/dt/2}, Axes -> False, Frame -> True]      ![enter image description here](http://i.stack.imgur.com/3qthH.png) So where is the low frequency? * * * **Update** As Simon and bill suggest, the slow oscillation is the beating of two close high frequencies. Since the Fourier transform resolution is 2Pi/(N*dt), where N is the number of sample points, so if I increase the resolution by increasing the number of sample points I should see two separated peaks. So I tried to increase the number of sample points, but I can only see one peak all the time. Here is how I did it:               w = 5.0; dt = 0.66125;     f[x_] := Sin[w x]          ls = Table[f[x], {x, dt, 200 dt, dt}];      we see beating in the plot               ListPlot[ls, PlotRange -> All, Joined -> True, DataRange -> {dt, 200 dt}]      ![enter image description here](http://i.stack.imgur.com/h30HL.png) but one on peak in the Fourier transform:               ListPlot[Abs[DFT[ls, dt]]^2, PlotRange -> All, Joined -> True, DataRange -> {-1/dt/2, 1/dt/2}, Axes -> False, Frame -> True]      ![enter image description here](http://i.stack.imgur.com/U8r7E.png) If we increase the number of sample points, we still only see one peak:               ls2 = Table[f[x], {x, dt, 800 dt, dt}];          ListPlot[Abs[DFT[ls2, dt]]^2, PlotRange -> All, Joined -> True, DataRange -> {-1/dt/2, 1/dt/2}, Axes -> False, Frame -> True]      ![enter image description here](http://i.stack.imgur.com/ynyfB.png) So where is the problem?


title: How to create automatically some matrices for symbolic manipulation?

text: I want to create in an automatic way some matrices to do symbolic calculations with them. They look like these: $$ \left( \begin{array}{cccc} a & 0 & b & 0 \\\ 0 & 1 & 0 & 0 \\\ b & 0 & a & 0 \\\ 0 & 0 & 0 & 1 \end{array} \right) $$ So they have entry $a$ in at position $(1,1)$ and $(3,3)$ and entry $b$ at position $(1,3)$ and $(3,1)$ and the rest of the entries are 1 on the diagonal and zero elsewhere. So in general i want a symmetric $n\times n$ matrix with $b$ at position $(i,j)$ and $(j,i)$ and $a$ at position $(i,i)$ and $(j,j)$ How can i create these kind of matrices automatically? Probably it is possible to write some function T[n,i,j] that gives as value the corresponding matrix. (I have no insight into possible implementations of the solution, so additional Tags are welcome!)


title: How do i import a list of files, choosing the name

text: I have this list of files, i'm using FileNames[{"*.txt"}, NotebookDirectory[]] to import it, but i just want the ones without inelastic on the name. How can i select just by the name? Thanks > > {"10.txt","11.txt","12.txt","13.txt","14.txt","15.txt","16.txt","17.txt","18.txt","19.txt","1.txt","20.txt","2.txt","3.txt","4.txt","5.txt","6.txt","7.txt","8.txt","9.txt","inelastico1.txt","inelastico2.txt","inelastico3.txt","inelastico4.txt","inelastico5.txt","inelastico6.txt","inelastico7.txt","inelasticov2-10.txt","inelasticov2-1.txt","inelasticov2-3.txt","inelasticov2-4.txt","inelasticov2-5.txt","inelasticov2-6.txt","inelasticov2-7.txt","inelasticov2-8.txt","inelasticov2-9.txt","inelasticov3-10.txt","inelasticov3-11.txt","inelasticov3-12.txt","inelasticov3-13.txt","*inelasticov3-14.txt","inelasticov3-14.txt","inelasticov3-15.txt","inelasticov3-16.txt","inelasticov3-1.txt","inelasticov3-2.txt","inelasticov3-3.txt","inelasticov3-4.txt","inelasticov3-5.txt","inelasticov3-6.txt","inelasticov3-7.txt","inelasticov3-8.txt","inelasticov3-9.txt"}


title: Frequencies represented in a DFT list (Fourier[])

text: I have a sound sample (sample rate: 44100). When I have a list `l` with `n` successive elements from the sample, `Fourier[l]` returns a list with n elements. Which frequency is represented at the nth place in the fourier list?


title: Fighting Less::nord at the root: Any unintended consequences?

text: After being plagued too much by `Less::nord` and companions, I've decided to try to fight it at the root: The comparison operators. I noticed that typically, the bad value contains `+ 0. I`. And indeed, evaluating `0. I < 1` gives `Less::nord` and an unevaluated equation. Interestingly, `0. I == 0` gives `True`, but `0. I <= 0` again gives `LessEqual::nord` and doesn't evaluate (despite the "or equal" part which should give true). Therefore I've now written the following code, which according to a few tests seems to completely eliminate `Less::nord` and companions from `NMinimize`, despite the fact that it only handles the special case of two-element comparison (the `Min` and `Max` definitions are there because after eliminating `(comparison)::nord`, I got `Max::nord` from `NMinimize`; again, the two-argument definitions seem to suffice):               (Unprotect[#];      Module[{op, rep = True},        #[a_?NumericQ, b_?NumericQ]/;rep :=          Block[{rep = False},            If[Im@a == 0 && Im@b == 0, #[Re@a, Re@b], #[a, b]]]];      Protect[#])& /@ {Less, LessEqual, Greater, GreaterEqual};          Unprotect[Min, Max];     Min[a_?NumericQ, b_?NumericQ] := If[a<b, a, b];     Max[a_?NumericQ, b_?NumericQ] := If[a<b, b, a];     Protect[Min, Max];      After that, I can use complex expressions in `NMinimize` without problems, at least in my (admittedly few) test calls, such as:               NMinimize[{(a + I b)(a - I b), a + b == 5}, {a, b}]     (*     ==> {12.5\[VeryThinSpace]+0. I,{a->2.5,b->2.5}}     *)      Now, apart from the performance cost this undoubtedly has (I didn't measure, though), and of course the fact that not all possible cases are covered (so I might one day get a non-prevented `::nord` — but in that case, I would have gotten it anyway), could those definitions have some unexpected consequences (especially, wrong results)? Of course, also improvements are welcome. **Edit:** Unfortunately most of the reactions are basically a general "don't override built-ins", which of course is a good general guideline, but doesn't really answer my question. Let me remind you of another rule of thumb: All absolutes are wrong. I didn't ask "is it in general a good or bad idea to overload built-in functions" ( _in general_ is is indeed a bad idea), I asked "are there unintended consequences _in this case,_ **apart** from what I _already mentioned in my question?_ " By asking my question I already explicitly acknowledged that there _might_ be unintended consequences. If I blindly assumed that there are none, I would not have asked my question. On the other hand, given the very limited nature of my overload, I cannot imagine any way this might lead to wrong results (and wrong results are what I'm concerned about). I asked to make sure that this is not only my lack of imagination. However from the reactions I conclude that nobody even had a closer look on my code (otherwise it would, for example, have been obvious that `LessEqual` is already covered by my code). The only concrete points which were raised were points I already had acknowledged in my question:   * It gives a performance hit. On the other hand, if the performance hit saves me working time, it may well be worth it (especially given the fact that why Mathematica works, I can work on something different, but while I tweak the code, I can't). After all, most of the code I write ( _especially_ the code using optimization routines) is not production code to be reused, but one-time code to get a single result, which generally won't ever be run again. Of course the overload is nothing which belongs into the init file. It is to be applied selectively.   * It might not catch all cases. Indeed, I already acknowledged that it _does_ not catch all cases. And that's _intentional:_ It catches exactly as many cases to stop the problem really occurring. By catching as few cases as possible, it also reduces both the risk of introducing bugs, and the performance hit: Every calculation which does not go through my code cannot be affected by it, and the performance hit for that case will be reduced to determining that my code isn't to be used. Also, it is merely a _limitation_ of the code. Any calculation which doesn't get caught by my overload and still gives a `::nord` would _also_ have gotten a `::nord` without it, and therefore with my overload I'm no worse off in that case than without it (and I then might find another specific overload which catches that one as well). Note, BTW, that the `Sign` method of comparison works correctly out of the box, unless you test the result with inequality operators (which is what my overload is about). And about the suggestion to paper over the problem with `Quiet`: I'm not concerned about the messages as such, I'm concerned about the wrong results which often occur in that case. Quieting the message doesn't fix that; instead it removes a sign that something bad happens. And there's indeed some irony to suggest a "solution" which is _known to_ sometimes give wrong results over a solution which _might possibly_ give wrong results. **However,** there was one constructive suggestion by Leonid Shifrin, which is unfortunately buried in his comment, therefore I quote it here so it doesn't get lost, because it actually is a very good advice: > At the very least, I would create local environment and use > Internal`InheritedBlock to localize the effect of these redefinitions. Leonid, if you make _that_ one a separate answer, I'll accept it (assuming you don't also suggest in that answer to use `Quiet` — you don't fight a fire by deactivating the fire alarm). Yes, I'll do so even if you re-state there that in general overloading built-in functions is a bad idea.


title: Why is this Mandelbrot set's implementation infeasible: takes a massive amount of time to do?

text: The Mandelbrot set is defined by complex numbers such as $z=z^2+c$ where $z_0=0$ for the initial point and $c\in\mathbb C$. The numbers grow very fast in the iteration.               z = 0; n = 0; l = {0};     While[n < 9, c = 1 + I; l = Join[l, {z}]; z = z^2 + c; n++];l      If `n` is very large, the numbers become too large and impossible to calculate in practical time limits. I don't know what it would look after long time but doubting whether it would look like here. **What is wrong with this implementation? Why does it take so long time to calculate?**


title: How to make certain mathematical characters be written as bold by default

text: In a notebook, when writing `\[RightVector]` over a variable I always end up bolding it to make it more visible. But it'd be easier if it could be set up to bold that character by default. I haven't ventured into setting key bindings yet (just starting out), but I'm wondering if it's possible to set the combination `Esc``vec``Esc` to turn on bolding, insert the appropriate symbol, then turn off bolding. If there's an even easier way, that'd be even better.


title: NDSolve with Euler method

text: I want to solve this equation with `NDSolve[]` using the Euler method:               x'[t] == 0.5*x[t]-0.04*(x[t])^2      with initial condition and step size               x[0] == 1, h == 1       and final time = 10. I also don't know how to make a table including `x'[t]` and `x[t]` and time.


title: Solve differential equation with 3 variables and plotting contour

text: Suppose we have this equation: $$ 2 - x g(z) f \left(x, \frac{\partial y}{\partial x}\right) = 3y $$ using initial condition $y = 2$ where $g = \left| \frac{3}{2-iz} \right|$ and $f = \frac{2x}{1-3\frac{\partial y}{\partial x}} $ I want to plot the contours of $ \frac{\partial y}{\partial x}$ within axes $x$ and $z$. How do I go about doing it? I tried using $NDSolve$ but it doesn't quite work.               g := Abs[3 / (2 - iz)]     f := 2x / ( 1 - 3D[y[x,z],x] )     NDSolve [ {2-x*g*f == 3y[x,z] ,y[x,z]==2}, D[y[x,z],x], {x,0,1}, {z,0,1}  ]      * * * Too long for a comment - Your answer works, but I improvised this to my current problem and it doesn't seem to work.. I want to find the contours of $ \frac{\partial T_e}{\partial P_{local}} $ in axes $P_{probe}$ against $w$ in the limit $P_{local} \rightarrow 0, T_e \rightarrow 0.2 $.               Clear["Global`*"]     C1 = 10^(-10);     C2 = 0.1*C1;     R = 50;     Tb = 0.1;     Geb = 5*10^-15;     Z0 = 50;     L[Te_] := 10^-9 + 10^-9*(Te - 0.1);     Zlcr[Te_, w_] := (1/R + 1/(I*L[Te]*w) + I*C1*w)^-1;     Zload[Te_, w_] := -I*w*C2 + Zlcr[Te, w];     \[CapitalGamma][Te_, w_] := (Zload[Te, w] - Z0)/(Zload[Te, w] + Z0);     x[Te_, w_] := Abs[\[CapitalGamma][Te, w]];     y[Te_, w_] := (Abs[\[CapitalGamma][Te, w]])^2;               eqn1 [Te_, Pprobe_, w_, Plocal_] := 1 - 2 Pprobe*D[x[Te, w], Plocal] ==  Geb*D[Te, Plocal]     sol = First@NDSolve [{eqn1[0.2, Pprobe, w, 0]},{D[Te, Plocal]},{Pprobe,0,10^(-15)}, {w,0,10^9}]          Plot3D[Evaluate@D[Te, Plocal] /.  sol, {Pprobe,0,10^(-15)}, {w,0,10^9} ]


title: Evaluate open cell segments in a notebook

text: The Evaluate > EvaluateNotebook evaluates the whole notebook. Is it possible to somehow evaluate **ONLY** the open sections of a notebook?


title: Missing some packages?

text: I am trying to use a program written by someone else. When I run the program, I am supposed to get a number as a result, however, what I got is some complicated result with "InterpolatingFunction" and "Developer`PackedArrayForm". I am wondering whether there is any package I should load in that causes this problem? I upload the program I am trying to run in the following link: https://user.iter.org/filesharing/?uid=d2bc26f7-c4c4-406b-8337-cb2d26772db4 Thank you very much for your help!


title: Convert String to List of Numbers

text: I want to create a function that when a string is entered it will turn it into a list of numbers, these numbers are the numerical form of the characters in the string. e.g. a=1, b=2, c=3, d=4 and space = 27 (other punctuation may be needed). So if I had the string "hello", my result would be: {8, 5, 12, 12, 15} I had a look at StringReplace, StringSplit and Characters, but not sure what is optimal. How would I go about doing this?


title: Calculating the conditional probability of discrete samples

text: I have two lists:               a = {0, 1, 1, 1, 0, 1}     b = {1, 0, 1, 1, 0, 0}      I'd like to calculate the conditional probability of a given b; for example, $p(a=1 | b=0)$. Is there a built in function to do this? The `Probability` function seems to only work with symbolic arguments?


title: InputField equations and Solve

text: I'm trying to get this piece of code to work:               Panel[      DynamicModule[{f = x, g = -x},       xmax = 10;       Column[{        InputField[Dynamic[f], ContinuousAction -> True],         InputField[Dynamic[g]],         Dynamic[ Show[Plot[{f, g}, {x, -xmax, xmax}, AspectRatio -> 1,                                   PlotRange -> {{-xmax, xmax}, {-xmax, xmax}}]                     ]               ]             }]                   ]          ]      This works and updates dynamically the graphs of `f` and `g`. Now, I would like to add the intersections, dynamically, if any (so with a `IF` testing), and I tried different things, without success:               solution = Dynamic[Solve[f == g, {x,y}]      gives me indeed the dynamically updated solution. But I can't use this information to plot points, nor even get `Length[solution]` update dynamically... Any help with this?


title: How to define delayed coupon payment for FinancialBond?

text: When the coupon calculation end date falls on a holiday, it is customary to delay the coupon payment to the next working day. E.g. a bond may have a monthly coupon calculation period of 2013 Jul 18 to 2013 Aug 18 (Sunday), the actual payment is delayed to 2013 Aug 19 (Mon). The price of the bond should depend on the actual payment date of Aug 19. How do I achieve this using `FinancialBond`?


title: How can I define a sequence of functions?

text: I need to define a function `fun`, and then re-define this function iteratively. The code is given at the end. First, a function `fun[x_, y_, d_]` is defined, which is a polynomial in $x$ and $y$, and $d$ is the degree of this polynomial. My goal is to modify `fun` according to some of its coefficients, see the definition `fun2[x_, y_, d_]` for example. The problem is that, these coefficients are $0$ if $d$ is not substituted by a "real" number, like $d = 1$. See the code between the definitions of `fun` and `fun2`. Just after the definition of `fun2`, I compute `fun2[x, y, d]` and it is the same as `fun1[x, y, d]`. The reason is that $d$ is not assigned a value. But `fun2[x, y, 1]` gives the desired answer, which is different from `fun[x, y, 1]`. The problem is that I want to repeat this process many times, say               fun3 = fun2 + Coefficient[fun2, x^2]     fun4 = fun3 + Coefficient[fun3, x^3]     ....     fun"d" = fun2 + Coefficient[fun"d-1", x^(d-1)]      (This is just an example, the real process I need is far more complicated and can not be deined in one go. In this example, one can just use `Sum[Coefficient...]`.) Of course I don't want introduce so many functions. I want to define `fun` and modify it in a for loop. But the code below shows that `Coefficient[fun[x, y, d], ...]` is always $0$, since $d$ is not assigned a value. I can't use a variable like `temp` in this for loop, because               For [i =...       ....       temp = fun[x, y, d]       temp = temp + Coefficient[temp, x^i]       ...       will just give `fun[x, y, d]`, as `Coefficient[temp, x^i]` is always $0$ as mentioned above. _**I need a suggestion on how to do such work more elegantly._** ![screen shot](http://i.stack.imgur.com/vA7ZU.png)


title: Find a best fitting curve for some data with no regular pattern

text: Suppose some data with no regular pattern is given, so common patterns of functions all fail to fit it. Then how can one find the best fitting curve? I believe there will be some data for which we can not find any regular pattern. One can try with the following data (luckily, we know that this sequence has a limit):                 {{1, 0.08888888888888872},{2, 0.13842641081508972},{3, 0.17153280014540232},        {4, 0.19586894934728782},{5, 0.21482500502852542},{6, 0.23017213935351592},        {7, 0.24294479920054762},{8, 0.25379708095478332},{9, 0.26316771779066082},        {10, 0.27136463872018062},{11, 0.27861184976714762},{12, 0.28507709754351612},        {13, 0.29088903838678592},{14, 0.29614834727916052},{15, 0.30093516063430942},        {16, 0.30531421254734282},{17, 0.30933847047870212},{18, 0.31305176609215322},        {19, 0.3164907360488469}}      Any help or suggestion will be appreciated!


title: ListLinePlot not showing filling

text: My code is               ListLinePlot[{         {{0, 185}, {-10, 187}, {-20, 186}, {-30, 158}, {-40, 159}, {-60, 116}},          {{0, 155}, {-10, 132}, {-20, 165}, {-30, 112}, {-40, 85}, {-60, 95}}},        Filling -> {1 -> {2}}]      Why doesn't `Filling` work on my plot?


title: StringCases functionality

text: I have a list of strings in where each element of the list is in this form:               {"created_at":"Thu Aug 08 20:53:26 +0000 2013","id":365576505679568896,"id_str":"365576505679568896","text":"Who wears it better? #TBT http:\/\/t.co\/vAXNgiRmYo","source":"web"      I am trying to extract some specific parts of each element. I prepared this function:               extract[string_] := StringCases[string, {         "\"created_at\":\"" ~~ Shortest@x__ ~~ "\",\"id\":" :> x,         "\",\"id\":" ~~ Shortest@b__ ~~ ",\"id_str\":\"" :> b,         ",\"id_str\":\"" ~~ Shortest@c__ ~~ "\",\"text\":\"" :> c,         "\",\"text\":\"" ~~ Shortest@d__ ~~ "\",\"source\":\"" :> d,         "\",\"source\":\"" ~~ Shortest@e__ ~~ "\",\"truncated\":" :> e        }     ]      And then               extract/@listOFelements      But as example for the element above I get this result:               {"Thu Aug 08 20:53:26 +0000 2013", "365576505679568896", "web"}      Some elements like the text flanked by `"\",\"text\":\""` and `"\",\"source\":\""` are not detected from the string. How should I make it possible to detect it?


title: PlotRange problems

text: I have a Delay Differential Equation of the form:               model =  NDSolve[{B'[t] == 562.86 B[t - 2.5] (1 - B[t - 2.5]/(2 10^9)) - 0.3 B[t],       B[t /; t <= 1950] == 1100000000}, B, {t, 1950, 1970}];      plot = Plot[B[t] /. logistic[[1]], {t, 1950, 1970}]      If I put `All` as input to `PlotRange` for my graph, no graph appears: it seems there is a limit as to the range of function values that can be displayed in a Mathematica graph. What is this limit?


title: Mathematica PDF import and fonts

text: I am trying to put nice LaTeX labels on my Mathematica plots. I can do this manually, or by introducing an extra GNUPlot step into my workflow, but it would streamline the process considerably if everything could be done within Mathematica--yielding a publication ready figure, ideally one that is resolution independent. My solution so far has been to put a call to sciencesoft's LaTeX CGI routine as follows:               Import["http://sciencesoft.at/image/latexurl/?dev=png&template=math&src=\gamma_2"]      which yields a nicely typeset gamma like so: $$\gamma_2.$$ However, this produces a png and my preference would be to use a PDF version that is resolution independent so that I don't have to fiddle with getting the resolution on the PNG correct to match my output. Entering the URL http://sciencesoft.at/image/latexurl/?dev=pdfwrite&template=math&src=\gamma_2 into my browser produces the kind of PDF that I am looking for and I can view said PDF in Acrobat and check that it has the fonts embedded. However, when I try to import this into Mathematica with               Import["http://sciencesoft.at/image/latexurl/?dev=pdfwrite&template=math&src=\gamma_2"][[1]]      I get something that looks like this (sorry for the ASCII rendition: as a new user I can't post images)               #         #     #         #     #         #  ##     #         #   #     #         #   #     #         #   #     ###########   #                   #                   #      which appears to be the product of some kind of missing font problem. Does anyone know if/how I can get the PDF properly imported into Mathematica?


title: How Can I Use Conditional with Rational Domain Restrictions

text: I am reasking this question in a new thread. My previous post How Can I Use Solve/Reduce Output? seemed to have led to a an interesting dissussion of how to (better) solve the problem that produced the output rather than in how to use the output further as I had intended. [Perhaps it indirectly answered my question by telling me that if I wanted to know more I needed to reformulate the problem and the solution as qiven was as far as Mathematica could go with the original formulation.] My questions is "Can I use the following result for further Mathematica calculations?" [i.e. I am not particularly interested in this solution other than using it as an **example** expression of a conditional with restricted domain.]               solQ= (x | y) \[Element] Rationals && -1 <= x <=       1 && (y == -Sqrt[1 - x^2] || y == Sqrt[1 - x^2])       I do know of one Mathematica function that will accept this as input:               In[9]:= FindInstance[solQ, {x, y}, 10]          During evaluation of In[9]:= FindInstance::fwsol: Warning: FindInstance found only 3     instance(s), but it was not able to prove 10 instances do not exist. >>             Out[9]= {{x -> -1, y -> 0}, {x -> 100/2501, y -> 2499/2501}, {x -> 1,        y -> 0}}      [However (as an aside) this function has strange behavior when I ask for 50 instances it can only find 2 for sure!]               In[11]:= FindInstance[solQ, {x, y}, 50]          During evaluation of In[11]:= FindInstance::fwsol: Warning: FindInstance found only 2     instance(s), but it was not able to prove 50 instances do not exist. >>          Out[11]= {{x -> -1, y -> 0}, {x -> 1, y -> 0}}      Are there other Mathematica functions that will accept these types of solutions (like solQ) as a valid input expressions that would help me further explore the solution? Perhaps some graphics functions? Perhaps in an Assumption? ...? Perhaps the solution as given above satisfies a Mathematician (which I am not) by "proving" that a solution exits and giving a few examples? Thank you all for your patience with these rather poorly defined questions [coming from a 75 year old physicist in retirement, with no cohort for discussion, just trying to (re)learn some math and Mathematica.]


title: How to make Fourier behave like FourierTransform?

text: I'm not very experienced with Fourier Transforms, so there may be something inherently wrong with attempting to do this, but how can I make the discrete Fourier behave like the continuous FourierTransform? What is the equivelent way of doing the following with Fourier?               Func[x_] := Sin[x];          LogLogPlot[      Abs[FourierTransform[Func[t] UnitStep[t], t, \[Omega]]], {\[Omega],        1*^-1, 1*^5}, PlotRange -> All]      ![Fourier Transform of Sin\(x\)](http://i.stack.imgur.com/6LdcJ.png) My unsuccessful attempt at this is the following:               Func[x_] := Sin[x];          ListLogLogPlot[      Abs[Fourier[Table[ Func[t] UnitStep[t], {t, 1*^-1, 1*^5} ]]],       PlotRange -> All]      ![enter image description here](http://i.stack.imgur.com/9qSGV.png)


title: Parallel compiled functions running on parallel sub-kernels

text: # Question Why is it, that compiled, `Listable`, parallel functions which work perfectly fine on the main kernel, do not run in parallel on sub-kernels? # Details ## First Example Let me give a first example. I compile a function $f:\mathbb{R}\to\mathbb{R}$ which is a simple sum of sine-functions with the options `CompilationTarget -> "C"`, `RuntimeAttributes -> {Listable}` and `Parallelization -> True`. Due to the `Listable` attribute I can now call the function with tensor parameters and due to the parallelization, the values in the tensor are processed in parallel. If you are on a slow machine, adjust `n` to be not that high:               f = Compile[{{t, _Real, 0}},          #, CompilationTarget -> "C", RuntimeAttributes -> {Listable},           Parallelization -> True] &@        Sum[Sin[2.0 Pi k t]/k, {k, 1000}];     data = With[{n = 1000000}, Table[t, {t, 0, 1, 1/(n - 1)}]];     f[data];      Looking at the system monitor during the calculation shows, that all processors are running at 100% ![enter image description here](http://i.stack.imgur.com/6NUDc.png) If you like you can compare the speed of this execution with for instance `f /@ data`. ## Under the hood _This may be only correct for Linux and OS X!_ What happens when you use `Compile` with the "C" option is, that a shared library is created from your _Mathematica_ -code which contains a function that can be called. The libraries are stored in a folder which is specific to the process id of a specific kernel. Let's make a short function, to print the important stuff of such a compiled function. I extract from a `CompiledFunction` the information, where the shared library is placed and what type the function is. Additionally, I add `$KernelID` and `$ProcessID`:               printCFuncLibrary[HoldPattern[CompiledFunction[__, lib_]]] :=       StringJoin["{KernelID: ", ToString[$KernelID], ", ProcessID: ",            ToString[$ProcessID], "} -> ", ToString[lib, InputForm]]      Using this on `f` and I get               printCFuncLibrary[f]          (*       {KernelID: 0, ProcessID: 3809} ->        LibraryFunction["/home/patrick/.Mathematica/ApplicationData/\         CCompilerDriver/BuildFolder/lenerd-3809/compiledFunction0.so",       "compiledFunction0", {{Real, 0, "Constant"}}, Real]     *)      Please note that that the build-folder has the process id of my main-kernel in it: "lenerd-3809". If you try now to execute this on different sub-kernels, you see that shared library function which is used stays the same. This is kind of expected:               ParallelTry[printCFuncLibrary, {f, f, f, f}, 4]      What _is_ kind of unexpected is, that when I call `f` even on only 1 sub- kernel, I lose the vector-parallelization completely and only one processor is working on the task               ParallelTry[f, {data}, 1];      ![enter image description here](http://i.stack.imgur.com/hnX96.png) I would have expected, that when calling the compiled function (compiled on the main-kernel) in sub-kernels, that there are some clashes whatsoever. ## Compiling the function **on** the sub-kernels Since I could not explain the above behavior, but I could surely imagine, that having only one shared library function which is maybe only loaded one time, is not the best situation when several processes want to access it. But why not compile the function on all sub-kernels. With this every sub- kernel gets its own copy of the shared library and loads its own version of the function:               ParallelEvaluate[       fsub = Compile[{{t, _Real, 0}},            #, CompilationTarget -> "C", RuntimeAttributes -> {Listable},             Parallelization -> True] &@          Sum[Sin[2.0 Pi k t]/k, {k, 1000}];       ];          ParallelEvaluate[printCFuncLibrary[fsub]]      I skip my output here, but what you should see is, that every sub-kernel gets its own copy of the shared library, place in a folder which is named like the process id of the sub-kernel. Additionally, on our main-kernel there doesn't exist a function `fsub` and therefore calling it with a numeric value stays unevaluated. On the other hand, `ParallelEvaluate[fsub[.1]]` calculates the correct results. If you now try to supply the vector `data` to the compiled function on the sub-kernel you see, that this is not processed parallel               ParallelTry[fsub, {data}];      I tried several other things to get some insight in the behavior, but nothing really helped me to understand, what's going on. ## You might ask... ... when your compiled function is parallelized so nicely, isn't it pretty useless, to take a second layer of parallelization? The answer is, yes, but for my real problem this is not the case. Assume you have a minimization problem and you parallelize your target-function only. Still, since the minimization method runs serially and only the calls to the target-function are parallel, there is still much cpu-time left. In such a cases, it would be reasonable to run two or more minimizations at the same time.


title: DSolve gives complex function although the solution is a real one

text: I have a problem with the DSolve[] command in mathematica 8. Solving the the following 4th order differential equation spits out a complex solution although it should be a real one. The equation is:               y''''[x] + a y[x] == 0      Solving this equation by hand yields a solution with only real parts. All constants and boundary conditions are also real numbers. The solution I get by hand is:               y1[x_] = (C[5] E^(Power[a, (4)^-1]/Power[2, (2)^-1] x) +      C[6] E^(-(Power[a, (4)^-1]/Power[2, (2)^-1]) x)) Cos[     Power[a, (4)^-1]/Power[2, (2)^-1]     x] + (C[7] E^(Power[a, (4)^-1]/Power[2, (2)^-1] x) +      C[8] E^(-(Power[a, (4)^-1]/Power[2, (2)^-1]) x)) Sin[     Power[a, (4)^-1]/Power[2, (2)^-1] x];      Now I have to solve for the constants `C[5]...C[8]`. This arises a similar issue. I use the `Solve[]` command with the boundary conditions               Solve[{y1''[-c] == ic0, y1''[c] == ic0 , y1'''[-c] == ic1 ,      y1'''[c] == - ic1 }, {C[5], C[6], C[7], C[8]} ];      The constants `C[5]...C[8]` are now real if using `//Simplify` and complex if using `//FullSimplify`. Any idea what the reasons are? The notebook with my calculations can be downloaded under: http://dl.dropbox.com/u/4920002/DGL_4th_Order_with_own_solution.nb In further work I have to use DSolve[] and I would like to understand the issue here.


title: Cannot access the Database using the JDCB - ODBC

text: Runnig this code after building the `ODBC` connection for my access application named `WPC` :               Needs["DatabaseLink`"];     OpenSQLConnection[JDBC["odbc", "WPC"]];      I get this message : > JDBC::error: [Microsoft][ODBC Driver Manager] The specified DSN contains an > architecture mismatch between the Driver and Application >> I am using _Microsoft Access 2010 (32 bit)_ and _Windows 7 (64 bit)_ so I have built the `ODBC` with _odbcad32_. Some one has an idea what is the problem/solution ?


title: Want Interactive PlotRange of Graphics[{}]

text: I am trying to do:               EventHandler[Graphics[{ (*stuff*) }],{{"MouseDragged","p"}:>(*pan the graphics*),       {"KeyDown","z"}:>(*zoom in/out as the mouse moves up/down in the graphics*) }]      This would be similar to what we can do with Graphics3D, except when I "pan" the Graphics I want to change the `PlotRange` rather than move the Graphics around the window. BTW I will be using `"MouseDown"` for custom modification of the Graphics, and that's one of the reasons why I want pan/zoom associated with pressing keys.


title: BoxWhiskerPlot - how to specify boxes position on the horizontal axis

text: Let's say I have a folowing set of data:   * k = 1 : list of values    * k = 3 : list of values    * k = 10 : list of values I know that to make a `BoxWhiskerChart` I have to give it a list of listen of these values as data and ks as labels. How do I force the offset between the boxes for different ks to be proportional to the values of ks? This is like combining `ListPlot` and `BoxWhiskerChart` \- list plot gives appropriate position of boxes relative to the x-axis.


title: Plotting DSolve results

text: I am attempting to make a plot of the solution an ODE. I want to plot the solution using `PolarPlot`, `x` is the polar angle in this case. I cannot get _Mathematica_ to make a plot, and I'm not sure where I'm going wrong. I tried going about it this way:               sol = DSolve[r'[x] == Sqrt[-r[x]^2 - 2*A*r[x]^5 + 3*A^[2/3]*r[x]^4], r[0] == 0, r[x], x]     PolarPlot[sol, {x, 0, 8*Pi}]       but nothing is produced on the graph. Is this wrong?


title: Something wrong with RectangleChart and Tooltip?

text: Currently I'm working on a diagram showing the merit order of power plants in the Netherlands. On the horizontal axes you see the cumulative power and on the vertical axes you see the costs per MWh. The cheapest units on the left and the more expensive to the right. The function `RectangleChart` looks just fine to make this diagram. The width is the maximum power of each power plant and the hight is the cost/MWh. There are a lot of units and that's why I would like to use the Tooltip wrapper to display the power plants name when I hover the mouse cursor over the rectangle. When i use:               RectangleChart[Tooltip[{{1, 1}, {2, 2}}, "test"]]      I get two rectangle bars and, when I hover over them, I get the Tooltip "test". But when i use:               RectangleChart[{{1, 1}, Tooltip[{2, 2}, "twee"]}]      the second rectangle bar does not show. When I wrap also the `{1, 1}` with `Tooltip`, I get the error message: > RectangleChart::ldata : {{1, 1}, {{2, 2}} is not a valid dataset or list of > datasets.>> When I add a third rectangle bar and wrap it with `Tooltip`, all seems to be OK again.               RectangleChart[{Tooltip[{1, 1}, "een"], Tooltip[{2, 2}, "twee"], Tooltip[{3, 3}, "drie"]}]      I'm using _Mathematica_ version 9, on a MAC OSX 10.8.3. Do you see the same behavior when using only two rectangle bars in `RectangleChart`?


title: How to solve a simple inequality

text: I am having trouble getting _Mathematica_ to solve really simple inequalities. I started with               Solve[{y^x >= 2*y - 1}, x]      but _Mathematica_ can't solve it. So I tried               Solve[{y^x >= 2*y - 1, x > 10, y > 10}, x, Reals]       with still no luck. I tried `Reduce`, but that didn't work either. An obvious solution is $x \geq \frac{\ln(2y-1)}{\ln(y)}$. How can I persuade _Mathematica_ to give me that?


title: How do I get a list of digits for a number?

text: I have this 200 digit number where I want to get the `IntegerDigits`, but the decimal point is in the way.               5.9786377666105440959755656271823065138015646836250389374946790881539\       7157216930920631092404062126177741432101097347028242720848122219396854\       08452395344964186804        What do I need to do to strip the decimal point to get a list of the digits?


title: Mathematica 7: Problems when evaluating Fourier inside a ParallelTable

text: after I got such a great response for my first question on this site, I'm very encouraged to asked my second one! So here it is, very generally: To speed up a "row-wise" (i.e. 1D) operation on a matrix, I tried to use the ParallelTable instead of the Table function. I don't know why, but due to some reason this fails. It seems that the expression inside the ParallelTable gets not evaluated correctly. Maybe somebody knows why? I start with my functions: The "FftShift1D" is simply to reorder the result of the Fourier function. The "eqn" function is just an arbitrary function to test the parallelization later on.               ClearAll["Global`*"]          FftShift1D[x_?VectorQ] :=       Module[{n = Ceiling[Length[x]/2]}, RotateRight[x, n]]          eqn[kx_?MachineNumberQ, y_?MachineNumberQ] :=       2/3 Exp[-I kx] (1 + I kx) + Sin[y]/y      Now, I create a matrix with the help of the "Table" function. The following definitions are used to change the size of the matrix easily.               kxmin = -100; kxmax = 100; kxdiv = 2000; kxinc = (kxmax -          kxmin)/(kxdiv - 1);     zmin = -5; zmax = 5; zdiv = 200; zinc = (zmax - zmin)/(zdiv - 1);          kspace = Table[        eqn[kx, z], {kx, kxmin, kxmax, kxinc}, {z, zmin, zmax, zinc}];      So I want to apply a FFT only on the "kx" direction, i.e. there are "zdiv" times a 1D FFT. This is how I've done this "serially":               res = Table[        FftShift1D[Fourier[N[        kspace[[;; kxdiv, i]]     ]]], {i, 1, zdiv}];      This works properly, and it results in "res" being a matrix (or Table, however you like to call it) with the same size as "kspace". Changing now to               SetSharedVariable[kxmin, kxmax, kxdiv, kxinc, zmin, zmax, zdiv, zinc,        kspace, res];          res = ParallelTable[        FftShift1D[Fourier[N[        kspace[[;; kxdiv, i]]     ]]], {i, 1, zdiv}];      fails with the following messages:               Fourier::fftl: Argument {eqn[-100.,-5.],eqn[-99.8999,-5.],     eqn[-99.7999,-5.],<<6>>,eqn[-99.0995,-5.],<<1990>>}     is not a nonempty list or rectangular array of numeric quantities.      You see, that although I call "N", the "eqn" gets not evaluated properly... Does someone knows why? Kind regards Clemens PS: I've found something not completely unlike my problem here, but not as in ParallelTable and Table do not give same result my problem does not change when using `Parellelize[Table[...]]` instead of `ParellelTable[...]`


title: How to split list into disjoint lists?

text: I wonder if there is any simple way to split a list into its disjoint sublists, e.g. from               list={{a,b},{e,f},{b,c},{c,d},{f,g,h}}      get a result               listdis={{{a,b},{b,c},{c,d}},{{e,f},{f,g,h}}},      so that one gets disjoint sublists such that any element can be connected with another element through other elements inside that list (like a disjoint chains of elements). Obviously sublists are of any length.


title: Conditional statements in intial conditions?

text: This is potentially a daft question, but I thought I'd ask it; I have some material free to diffuse in a boundary between rn and ro; I've been able to get it working nicely for neumann type boundary conditions, and the relevant section of code is here; q[r] is a defined funtion, and all other constants specified and it all works rather nicely;               eqn = D[Ef[r, t], t] - Def5*( D[Ef[r, t], r, r] + (2/(r )) D[Ef[r, t], r])      +  q[r ]Ef[r, t];               ic = {Ef[r, 0] == 100, Derivative[1, 0][Ef][rn, t] == 0,      Derivative[1, 0][Ef][ro, t] == 0};     s = NDSolve[{eqn == 0}~Join~ic, Ef, {r, rn, ro}, {t, 0, 60}];      But here's my question; what if the material was free to diffuse out of the ro boundary into the infinite medium around it? The confinement at rn still holds of course; so if this were the case, Ef[Infinity,t] ==0. Mathematica doesn't like this, so I'm using a real valued high value to simulate such behaviour. My initial conditions now look like               ic = {Ef[r, 0] == 100, Derivative[1, 0][Ef][rn, t] == 0,  Ef[ro + 100000, t] == 0};      This produces a warning that boundary and initial conditions are inconsistent, which of course they are; Ef[r,0] == 100 only holds between the boundaries of ro and rn, and is initially zero beyond ro. Is there any way to put this condition into NDSolve? Essentially, I want to tell Mathematica that the initial conditions ONLY applies between rn and ro, and that initially, Ef[r > ro,t] == 0 ; I should add I'll still only be plotting the solutions over rn-ro, but I imagine this should fall over time as material diffuses beyond ro and I'd like to see that behaviour! Thanks! Edit--- The initial conditions and functions are               Def5 = 5.5*10^-11; Do2 = 2*10^-9;  f = 2.6835*10^-7;     po = 100; ro = 500*10^-6;     a = 5.9336*10^-6; rl = Sqrt[(6*f*Do2*po)/a];     rn  = ro*(0.5 - Cos[(ArcCos[1 - (2*(rl^2))/(ro^2)] - 2*Pi)/3]);     const1 = a/(6*f*Do2); const2 = 2*(rn^3);     p[r_] := po + const1 (r^2 - ro^2 + const2 (1/r - 1/ro));          kd = 0.049; kmn = 1.9 ; kme = 3.45; qm = 9.34*10^-4;          q[r_] := qm (((p[r])/(p[r] + kmn)) ((kme)/(kme + p[r])) + kd);


title: How to make Header/Footer print options default

text: I have a certain style what to write where in my Mathematica printouts. But for each notebook I have to define it again. Can I make my style somehow the default used by every notebook?


title: Running CUDA or OpenCL using Mathematica on Raspberry Pi

text: I am wondering if someone can use CUDA and (or) OpenCL on a Raspberry Pi as in any normal PC equipped with a GPU. The main processor runs at 700 MHz and maybe will be slow for some imaging applications unless it can exploit the embedded GPU! I will try to answer my question as soon as I get the hardware but in the meantime I couldn't resist asking.


title: ListPlot with PlotRange -> Automatic giving unexpected results in V.9

text: There seem to be a problem with `ListPlot` auto ranging in _Mathematica_ 9\. Here's my code:               n = 10;     dn = 10;     data = Table[If[Divisible[i - n, dn], i, 1], {i, 1,  100}];     ListPlot[data, PlotRange -> Automatic]      In version 8 it works as expected (y ranges from 0 to 100), but in version 9 it only shows y going from 0 to 2. Is there something wrong with my code? A bug in _Mathematica_?


title: Check remaining Wolfram|Alpha calls

text: As Wolfram|Alpha calls are limited, and on the other side increasingly frequent, I'd like to be able to check how many calls am I able to make at a given time. Is there a function or system variable that keeps this information? Bonus points if it does not include making a call to W|A.