title: Numerically solving a system of PDEs where one function is composed with the other

text: I'm trying to solve the following system using `NDSolve`: $$ \begin{align} u_t(x,t) &= u_{xx}(x,t) - v(x,t) \\\ v_t(x,t) &= u(v(x,t),t) \end{align} $$ with $$ u_x(-1,t) = 0, \quad u_x(1,t) = 0, \quad u(x,0) = \tanh(10x), \quad v(x,0) = 1/3. $$ I tried the following code in Mathematica 7.               NDSolve[{         Derivative[0, 1][u][x, t] == Derivative[2, 0][u][x, t] - v[x, t],         Derivative[0, 1][v][x, t] == u[v[x, t], t],              Derivative[1, 0][u][-1, t] == 0,         Derivative[1, 0][u][1, t] == 0,              u[x, 0] == Tanh[10 x],         v[x, 0] == 1/3       }, {u, v}, {x, -1, 1}, {t, 0, 5}]      This produces an error: `NDSolve::delpde: Delay partial differential equations are not currently supported by NDSolve.` I think this is coming from the second differential equation, because if it doesn't have a composition, for example if I change the second equation to $$ v_t(x,t) = u(x,t)+v(x,t), $$ and try the code               NDSolve[{         Derivative[0, 1][u][x, t] == Derivative[2, 0][u][x, t] - v[x, t],         Derivative[0, 1][v][x, t] == u[x, t] + v[x, t],              Derivative[1, 0][u][-1, t] == 0,         Derivative[1, 0][u][1, t] == 0,              u[x, 0] == Tanh[10 x],         v[x, 0] == 1/3       }, {u, v}, {x, -1, 1}, {t, 0, 5}]      then I get a result. Is there anything I can do to help `NDSolve` solve the original system (with the composition)?


title: EquationTrekker-like behavior for state space?

text: `EquationTrekker` is great for phase space plots, however I want to plot the results of $$\phi '(t)=-b \sin (\phi (t))+g \sin (\Phi (t)-\phi (t))+1\\\\\Phi '(t)=g y \sin (\phi (t)-\Phi (t))-J (\Phi (t)-\phi (t))$$ I modified this to create this:               Manipulate[      Show[ParametricPlot[        Evaluate[         First[{ϕ[t] , Φ[t]} /.            NDSolve[{ϕ'[t] ==                1 - b Sin[ϕ[t]] +                g Sin[Φ[t] - ϕ[t]], Φ'[t] ==                y g Sin[ϕ[t] - Φ[t]] -                J (Φ[t] - ϕ[t]),              Thread[{ϕ[0] , Φ[0]} ==                point]}, {ϕ, Φ}, {t, 0, T}]]], {t, 0, T},         PlotStyle -> Red, PlotRange -> R]], {{T, 20}, 1, 100}, {{R, 2}, 0,        10}, {{b, 1.79}, -1, 4}, {{g, 0.32}, -1, 4}, {{y, 0.26}, -1,        4}, {{J, 0.51}, -1, 4}, {{point, {1.3, 0.2}}, Locator},       SaveDefinitions -> True]      which lets me click on various portions of the graph and have a look at the time evolution in state space. I'd like to get similar behavior in EquationTrekker, where it shows me the solution of a two-dimensional system in state space. The main thing I need is the "memory" bit, that previously drawn curves stay put instead of getting erased. Is there any way I can get this to work with `EquationTrekker`? If not, is there any way to modify my example so that it "imprints" a line wherever the `Locator` is put? Additionally: A way to `StreamPlot` the gradient in the same graph would be nice.


title: Can one force a linear regression fit to go through the origin?

text: As the question says, can one force a fit through the origin $(0,0)$ as one can when fitting a trendline to your data in MS Excel? If so, how do you do that?


title: How to find pieces of code responsible for syntax errors?

text: _Especially: How to find the piece of code responsible for a missing parenthesis problem caused by a misplaced_ `SuperScriptBox`    For last 30 minutes (and I was lucky today, sometimes I spend 5 times as much time) I have been removing code little by little from my large one cell, (have to be one cell, it is `Manipulate` demo stylesheet) in order to find where the syntax error is (since _Mathematica_ , with all its might and power, can't tell the user which line number the syntax error is located at). Each time I see the red line show up on the right side of the notebook, indicating a syntax error, I know that I will now waste another hour at least looking for the syntax error. Why is it that hard for _Mathematica_ to tell the user where the syntax error is? I zoomed down to this little 5 character code, and I copy it to new notebook to examine it: ![enter image description here](http://i.stack.imgur.com/w6Opn.png) So, there is a hidden bad character there. Sometimes, with my big fingers and my small keyboard (can't find big keyboards any more, everything is so tiny), I must have hit wrong key combination, which must have injected some bad character to the notebook, and this happens. I will keep this cell on its own in order to find what the problem is. I tried to select the cell, and do convert to input form, but nothing happened. no output came of it. Then I did `cell->ShowExpression`, and this came up               Cell[BoxData[      RowBox[{"(",        RowBox[{"k", "h"}],        SuperscriptBox[")", "2"]}]], "Input",      CellChangeTimes->{3.536893041212217*^9},      EmphasizeSyntaxErrors->True]      ![enter image description here](http://i.stack.imgur.com/N8h1r.png) So, what does all this mean? Do you see from the above what is the problem? I think I entered the superscript as I always do, using `Ctrl+^` then `2`. I think the notebook interface is powerful and allows many things not possible otherwise, but because of problems such the above, I wish sometimes I am using plain text editor like emacs, where I can see what I have and not worry about hidden things I do not see, but I tried that once, and it is not practical overall setup to work with. Btw, originally, I had lots of code like the above inside strings, i.e. inside `" "` for formatting, and now I am removing all the strings to do some other way of formatting. I do not know if this has anything to do with it. But as you can see, now there is no string around the expression. Here is a screen shot of the earlier version of the notebook, from the same location of the code, showing how the above was inside a string, and I simply was removing the outside string quotes, that is all: ![enter image description here](http://i.stack.imgur.com/Fufj0.png)


title: Automating FTP upload within Mathematica?

text: I have MMA-generated html and would like to automate uploading to a named directory to a web host via SFTP or HTTP POST, ideally without creating local temp files. The closest question I could find on MMA.SE is this question which doesn't really address this issue. Based on this "minimal http upload gci" in Python, and HTTP Request- Authentication flow-chart, it seems that uploading by FTP may be relatively easier. Sjoerd C. de Vries suggested this question may answer the POST part. Others have found FTP in non-interactive mode to be difficult. But one would think authentication, put and closing the session in interactive mode could be managed within MMA. However, Run is not meant to capture output from the external program. From the sparse documentation, I think `RunThrough` is meant to capture external program output, but I can only manage to capture an exit condition code:               RunThrough["sftp", "####@understars.org:temp.understars.org"]      Doesn't output to the front end, but does set the Out[] to 256. So how can an interactive FTP session be automated? (Note I've tagged this "html" as well since ultimately that is what I want to export.)


title: What is the purpose of Dump contexts?

text: ## Motivation I've been trolling through some internal code, trying to glean design practices WRI developers employ when extending Mathematica using top-level code. During my `??...`\-- type searches, I've encountered a number of contexts named either like `SomePackageDump` or with `Dump` appended as a subcontext of `SomePackage`. ## Question What is the designed purpose of these `Dump` contexts and how exactly are they employed (in the overall scheme of evaluation)? Note: I understand the use of `Private` subcontexts. :)


title: How to find out available fonts from within Mathematica?

text: How to find out available fonts on the system from within Mathematica? When I do               Style["foobar", FontFamily -> "Foobar"]      how do I know which font the displayed output is using/falling back to use?


title: Changing scroll rate for page down key?

text: I have a presentation remote that allows me to advance Mathematica slides when in the SlideShow environment. The control sends a `page down` key. Some of my slides extend below the screen window, and `page down` scrolls a page at a time. Is there a way to change the scroll rate associated with a `page down` key- stroke? I'd like to advance the slides by half a page at a time, or a quarter, for example, or even cell-by-cell. The notebook options associated with `ScrollingOptions` seem not to control what I need. My system is MacOSX, running Mathematica 8.0.4.


title: calling a batch or executable application on Windows

text: How to run a batch file, send commands and collects output on windows               Run["!C:\\runme.bat"]      it outputs 1 and a window appears and then disappears. I also want to send my script file to python shell and collect its output in mathematica. How to do on Windows?               ReadList["!C:\\Python27\\python.exe", "my_script_file.txt"]


title: How to adjust the correct ImageSize between two plots

text: Let's consider the following simple plot               P0 = Plot[Sin[x], {x, -7, 7}, Frame -> True, Axes -> False, PlotLabel ->           Style["Test 1", FontSize -> 20, Black, FontFamily -> "Helvetica"],          AspectRatio -> 1, ImageSize -> 550];      The second one is much more complicated ad we need to create some data in order to replicate the situation               n = 5000;     data = Table[{RandomReal[], RandomReal[], RandomReal[{10^-2, 10^4}],      RandomInteger[{0, 2}]}, {i, 1, n}];      Define a color function               valrange = {-2, 4};     data[[All, 3]] = Rescale[Log10[data[[All, 3]]], valrange];     colfunc[x_, cf_] := If[x[[4]] == 0, Gray, ColorData[cf][1 - x[[3]]]];      Create a colrbar               Clear[colorbar]     colorbar[{min_, max_}, colorFunction_: Automatic, divs_: 150] :=        DensityPlot[y, {x, 0, 0.1}, {y, min, max}, AspectRatio -> 10,        PlotRangePadding -> 0, PlotPoints -> {2, divs}, MaxRecursion -> 0,        Frame -> True, FrameLabel -> {{None, "test"}, {None, None}},        LabelStyle -> Directive[FontFamily -> "Helvetica", 17],        FrameTicks -> {{None, All}, {None, None}},        FrameTicksStyle -> Directive[FontFamily -> "Helvetica", 15, Plain],        ColorFunction -> colorFunction]      A simple contour               C0 = ContourPlot[x^2 + y^2, {x, -1, 1}, {y, -1, 1}, Contours -> {0.5},          ContourStyle -> {{Black, Thickness[0.005]}}, AspectRatio -> 1,           ContourShading -> False, PlotPoints -> 200,           PerformanceGoal -> "Quality"];      and finally the modified density plot               With[{opts = {ImageSize -> {Automatic, 550}}, cf = "Rainbow"},          Row[{Show[          ListPlot[List /@ data[[All, {1, 2}]],           PlotStyle -> ({PointSize[0.005], colfunc[#, cf]} & /@ data),           AspectRatio -> 1, Frame -> True, RotateLabel -> False,           Axes -> None, FrameTicks -> True, FrameLabel -> {"x", "y"},           LabelStyle -> Directive[FontFamily -> "Helvetica", 20],           ImagePadding -> {{60, 20}, {60, 20}}, opts,           PlotLabel -> Style["Test 2", FontSize -> 20, Black,           FontFamily -> "Helvetica"]], C0, PlotRange -> 0.9,           PlotRangeClipping -> True],           Show[colorbar[valrange, ColorData[cf][1 - #] &],           ImagePadding -> {{20, 60}, {60, 40}}, opts]}]]      There are two issues regarding this second complicated plot: (a). For large data sets, (`n` > 10000) the programs needs more than 10 minutes so as to create the plot! Is there any way to speed up the process? (b). Even though I set `PlotRange -> 0.9, PlotRangeClipping -> True`, we see that the frame in all directions does not end at exactly 0.9 but in 0.9 + dx. Why? Now, if we put together the two plot ![plot](http://i.stack.imgur.com/8QyBW.jpg) it becomes evident that size of them do not match. For both plots I used `ImageSize -> 550` but it seems that the second one (the complicated) is smaller. I suspect, that this has to so with the colorbar it carries together. So, my question is: how can I get the second plot match in size with the first? **EDIT** Apparently, each (x,y) point should be treated as a separate list by using `List /@ data[[All, {1, 2}]]`. That's the reason why the code is very slow when we have many points. Unfortunately and strangely enough I cannot use `ListDensityPlot` simply because stupidly it joins by default the points without giving you an option for that!


title: Understanding `Paste` and how to get a string from the Clipboard to use with `ImportString`

text: Trying to work on this question I got distracted by my first naive attempt of copying the data and then typing               dat = ImportString[Paste[], "Table"]      > ImportString::string: First argument Null is not a string. >> >   >   >     ImportString[Null, "Table"] >   I do know that typing `dat = ""` and then pasting within the quotation marks does work. Particularly nice is this other solution that unfortunately is limited to MS Windows .NET. But what I want is to understand what is going on, what is `Paste` giving if not a string, and how can I find out what the object is. As a bonus, making the output of `Paste[]` work within `ImportString` would be nice.


title: how to Export raster data as a tiff unmolested

text: I feel certain there is a simple answere here.. how do I export image data to a tiff without any scaling? I want to read back in the exact data.               g = Show[Graphics[{Black, Disk[#, 1]}] & /@ Table[RandomReal[{-10, 10}, 2], {50}]];     datain = ImageData[Rasterize[Style[g, Antialiasing -> False], "ColorSpace"-> "Grayscale"]];      as a more simple example just use:               datain = Table[0, {300}, {400}];          Export["test.tiff", Raster[datain], "BitDepth" -> 1, "ColorSpace" -> "Grayscale" ,            ImageSize -> Reverse[Dimensions[datain]]];     dataout = Reverse[ImageData[Import["test.tiff"]]];     datain == dataout    ->> False     GraphicsGrid[{{        Graphics[Raster[datain]],        Graphics[Raster[dataout]],         Graphics[Raster[(1 + datain - dataout)/2]]}}]      ![enter image description here](http://i.stack.imgur.com/kZ4ft.jpg) What you see is the image has been shrunk to accomodate an white margin of about 10 pixels. (Most annoying you wouldn't notice this if you didn't look carefull..) example 2.. ![enter image description here](http://i.stack.imgur.com/ozzFS.jpg) Edit Bill S has the solution.. Either `Image[datain]` or `Image[Raster[datain]]` or this mess:               Graphics[Raster[datain],            PlotRange -> {{0, Dimensions[datain][[2]]}, {0,Dimensions[datain][[1]]}}]      does the job. The last form I guess gives a clue, presumably Export calls Graphics which is padding by default. None of the documented options ImagePadding, ImageMargins, etc turn this off though. Edit 2.. need BOTH of these options...go figure               Graphics[Raster[datain], ImagePadding -> None,  PlotRangePadding -> None]


title: Use NotebookWrite with Graphics?

text: I am trying to use NotebookWrite to paste a plot into another notebook. The code looks something like: `ptemp = Show[Plot[x^2,{x,-2,2}],Plot[x^3,{x,-2,2}]]; nb = CreateDocument[]; NotebookWrite[nb,ptemp];` But when I run the code I get an error message: `An unknown box name (Graphics) was sent as the BoxForm for the expression.` Is there any way to use NotebookWrite to insert a graphic? Does there exist any sort of wrapper for Graphics that would make it NotebookWrite-able?


title: How can preserve my manual edit of an expression when exporting to LaTeX?

text: **Context** I would like to use the _Mathematica_ front end to pre-process expressions before exporting them to LateX, for the sake of readability. **Example** Say I have this expression                  (16*((-3 + r^2)*BesselI[0, r^2/8]^2 - ((-48 + 16*r^2 + r^4)*BesselI[0, r^2/8]*        BesselI[1, r^2/8])/r^2 +         15*BesselI[1, r^2/8]^2)*Cos[2*\[Theta]])/(3*Sqrt[3]*E^(r^2/4))      which looks like this in _Mathematica_ ![Mathematica graphics](http://i.stack.imgur.com/uriYq.png) Once I edit it by hand within _Mathematica_ , it might look like this: (notice that its more publishable in that form) ![Mathematica graphics](http://i.stack.imgur.com/05BZq.png) (This is a great feature of the Front-End by the way!). If I then select the expression and choose the export to latex menu, _Mathematica_ exports the original (unedited) equation. **Question** How do I tell _Mathematica_ to mind its own business and export to LaTeX the result of my edit, not its re-processing of it? **EDIT** Following the suggestion of @Nasser, I tried ![Mathematica graphics](http://i.stack.imgur.com/fzLvV.png) So it does not really preserve the original expression?


title: Parallelizing sparse array construction

text: I have a very large sparse array, and the computation of individual matrix elements is fairly expensive. The Matrix is Hermitian and traceless, so I would like to construct only the sub-diagonal elements explicitly. A sketch of my attempt:               M = SparseArray[{}, {imax, imax}];     SetSharedVariable[M];     ParallelDo[       If[j < i, M[[i, j]] = f[i, j]],       {i, 1, imax}, {j, 1, imax}];      My understanding is that setting M as a shared variable this way is very expensive. Is there a good way to parallelize this process? Note: I have seen examples where people calculate dense matrices by constructing the submatrices on separate kernels, but for my matrix the computation time of a submatrix is difficult to estimate so trying to distribute the computation time manually is difficult.


title: Constructible numbers

text: Can Mathematica detect constructible numbers? I know it has `MinimalPolynomial` but for degrees higher than 4 it's not obvious whether a given polynomial yields a constructible number or not. See, e.g., http://en.wikipedia.org/wiki/Constructible_number#Transformation_into_algebra or http://mathworld.wolfram.com/ConstructibleNumber.html


title: How to set path of IMPORT from excel into Mathematica?

text: I was able to IMPORT from excel data at the start of my project when both the .nb and EXCEL XLS files were sitting in MyDocument (or some other location), but upon moving both files into my Dropbox location, when I opened my .nb file again, IMPORT fails with 'File not found during Import'? I assume having both in the same directory is not suffice, but rather IMPORT only looks for file as defined by path setting within Mathematica? If so how to change it so that regardless of where I put the .nb and excel files, as long as they are both in the same directory I can do IMPORT?


title: Changing the x-axis data range

text: I have a series of data and Ive ploted them by mathematica.how can I change the x-axis scale?for example instead of "x" being between 0-300, I want to plot my data between 0-2 scale. this is my code:               data = Import["Desktop/kmc final result.txt", "List"];     bb = SmoothKernelDistribution[data];     cc = SmoothKernelDistribution[data];     h[y_] = ((1/207) PDF[bb, y])*(PDF[cc, y]);     time = 100;     J[y_] := -1/time Log[h[y]];     plt1 = Plot[J[y], {y, 0, 300}, Frame -> True,        PlotStyle -> {Blue, PointSize[0.004]}, PlotRange -> All]


title: Adapting old Arrow expressions

text: I have an old notebook that uses the now obsolete `Arrow` package. For example, I have an expression containing               Arrow[{1,2}, {6,7}, HeadLength -> 0.005, HeadCenter -> 0.5]      I suppose I know how to translate this in absence of options. I should have               Arrow[{{1,2}, {6,7}}]      but how can I obtain the same arrow shape as given by the old-style options using `Arrowheads`?


title: Indicating the probability that a weather datum is above/below some given value on a geographic map

text: With help of the previous questions here, I am analyzing weather data as daily `MeanWindSpeed` of some cities with the following code:                 {date, year, month, day, wind} = {1, 1, 2, 3, 2}            cityWind1 = WeatherData["Bodo", "MeanWindSpeed", {{1973, 1, 1}, {2013, 5, 1},"Day"}];       cityWind1[[All, date, year]] = 0            slowWinddays1 = Select[cityWind1, #[[wind]] < 21 &];       DateListPlot[{cityWind1, slowWinddays1}, ImageSize -> 600]      I have two problems.   1. I want to calculate the probability of the days that mean wind speeds higher than 21 km/hr and show it in the plot. It could be monthly or weekly outlet. I know the algorithm is too easy, but sorry guys I am new in town!    2. Most important, how can I show this probability in different geographic regions based on data from the available stations of that region. For example, assign a color to Norway and vary intensity to indicate the probability on the geographic map. That is to say, the more intense the color, the higher the probability.


title: Put random points into a specific 2D subregion

text: I want to cover a particular subregion of the x-y plane with a random distribution. As this particular region is not a circle I encounter some problems declaring the permitted zone where to put points. The points must NOT be drawn in the blue zone. As in the graph![enter image description here](http://i.stack.imgur.com/R1IsX.png) And I use the following code to drawing the graph:               mu = 0.000954;     h = x^2 - y^2 + 2 (1 - mu)/Norm[x + mu] + 2 mu/Norm[1 - x - mu];     S =        RegionPlot[h < 3.07, {x, -2, 2}, {y, -2, 2},          Mesh -> None, PlotPoints -> 200, Axes -> True, Frame -> False]      Where `h` is the function. **P.s.:** the drawing process is a bit long if you use more then 200 points, so keep this not so high.


title: Anti-aliasing a fractal-like bitmap image

text: I have a .bmp image 9600x5400 that shows a lot of points at various intensities. There are no lines inside this picture - only a lot of points. I would like to apply anti-aliasing on the image to make it smoother (and more beautiful). Can Mathematica help me on that? ![enter image description here](http://i.stack.imgur.com/FzHKm.jpg)


Binomial Distribution (binomial model inspired by Merton) Hi I want to do the following and I hope that anyone of you can help me out. In short, I have a portfolio consisting of 10 companies, whereas their asset values are driven by a common economic background factor u and the assets in question are correlated. Now I want to calculate the probability that e.g. **3 of 10 companies default simultaneously**. In order to do so, I choose a mixed binomial Merton model. whereas the probability that a given number of companies default is given by: ![enter image description here](http://i.stack.imgur.com/H6bht.png) whereas u is the common economic background factor and a standard normal random variable. C(i) is given by: ![enter image description here](http://i.stack.imgur.com/J3Tuz.png) whereas I substituted r with μ Then I entered the following definitions:               V1 = 100; D1 = 70; μ1 = 0.2; σ1 = 0.1;     V2 = 110; D2 = 75; μ2 = 0.25; σ2 = 0.2;     V3 = 95; D3 = 72; μ3 = 0.1; σ3 = 0.2;     V4 = 120; D4 = 100; μ4 = 0.4; σ4 = 0.3;     V5 = 120; D5 = 110; μ5 = 0.2; σ5 = 0.2;     V6 = 100; D6 = 65; μ6 = 0.25; σ6 = 0.12;     V7 = 99; D7 = 85; μ7 = 0.3; σ7 = 0.05;     V8 = 125; D8 = 76; μ8 = 0.2; σ8 = 0.3;     V9 = 105; D9 = 100; μ9 = 0.23; σ9 = 0.02;     V10 = 100; D10 = 75; μ10 = 0.2 ; σ10 = 0.2;          T = 5; ρ = 0.5; \[ScriptU] = 0.25;          Evaluating Subscript[C, i]          C1 = (Log[V1/D1] + (μ1 - 0.5*σ1^2)*T)/(σ1*Sqrt[T]);          C2 = (Log[V2/D2] + (μ2 - 0.5*σ2^2)*T)/(σ2*Sqrt[T]);          C3 = (Log[V3/D3] + (μ3 - 0.5*σ3^2)*T)/(σ3*Sqrt[T]);          C4 = (Log[V4/D4] + (μ4 - 0.5*σ4^2)*T)/(σ4*Sqrt[T]);          C5 = (Log[V5/D5] + (μ5 - 0.5*σ5^2)*T)/(σ5*Sqrt[T]);          C6 = (Log[V6/D6] + (μ6 - 0.5*σ6^2)*T)/(σ6*Sqrt[T]);          C7 = (Log[V7/D7] + (μ7 - 0.5*σ7^2)*T)/(σ7*Sqrt[T]);          C8 = (Log[V8/D8] + (μ8 - 0.5*σ8^2)*T)/(σ8*Sqrt[T]);          C9 = (Log[V9/D9] + (μ9 - 0.5*σ9^2)*T)/(σ9*Sqrt[T]);          C10 = (Log[V10/D10] + (μ10 - 0.5*σ10^2)*T)/(σ10*Sqrt[T]);      Now i am not sure How to calculate the individual probabilities and add them up. Would you suggest first to integrate the terms on the right hand side of the integral or is it possible to enter the whole function in Mathematica considering both the Normaldistribution and the Binomialdistribution? I would be very thankful for any advise. Thanks.


title: Function that puts zero after a certain decimal in every element of the matrix

text: We know that in Mathematica there is some default precision, which you can also change. This means, that after a certain decimal(fixed by the precision), the computer puts pseudo random numbers. I am looking for a function F that would put everything zero after a certain decimal. Let us say I want this to be the fourth decimal, then F[0.12345678]=0.12340000 Does such function exist? Thank you


title: Multiple scripts run using same kernel

text: I have an external program that calls Mathematica scripts upon certain events. Each script requires a large Mathematica library to load (takes a while). Is there some way to run an initial script that loads the library, then each following script call uses the same Kernel?


title: Front End - Bug in Edit->Find?

text: As a beginner I make notes in my notebooks on what I am learning as I go along, and I have also referenced the help files by pasting hyperlinks from them - this seems to break the Find function. Is it really a bug (in V9), and if so is it likely to have any other effects? To reproduce the issue, try this... Create a blank notebook, enter some text including a keyword (e.g. MinValue) in a text cell. Select the keyword and press F1. Right click the target word in the help windw where it first appears in blue beneath the heading and select copy hyperlink. Paste the clipboard content at the beginning of the text cell, which now contains the pasted hyperlink (1st) and original typing 2nd. Go to the beginning of the notebook, invoke Find, enter e.g. MinValue. Find next will find the pasted hyperlink. Pressing Find Next again will not move the found location. **Update - Bug Confirmation** WRI Case 652039: they confirmed by email 20/03/2014 that they had reproduced it and had passed it to development to fix, they hope to fix it in the next release.


title: Chain rule while differentiating

text: I am trying to find the derivative of a function defined in polar coordinates with respect to $x$ and $y$. My function is defined as follows: $ v_x(r, \theta ) = v_r \cos (\theta ) - v_{\theta }\sin (\theta ) $ To do this, I start by defining the relation between Cartesian and Polar coordinates:               (* Define the mapping between Cartesian and Polar coordinate systems. *)     x[r_, θ_] = r Cos[θ];     y[r_, θ_] = r Sin[θ];      Then I define the function and find its derivative with respect to $x$:               Subscript[v, r][r_, θ_] = Subscript[v, r][r, θ] Cos[θ] - Subscript[v, θ][r, θ] Sin[θ];     D[Subscript[v, r][r, θ], x]      I am getting 0 because _Mathematica_ is not considering the relation between $r$ and $x$. Is there anyway to tell _Mathematica_ to use the chain rule to find the derivative of $v_x$ with respect to $x$? The other problem is that _Mathematica_ is considering the subscripts to be variables (which is reasonable), is there anyway to tell it that the subscripts are only notational symbols? **EDIT** : The function is better defined as:               vx[r_, θ_] = vr[r, θ] Cos[θ] - vtheta[r, θ] Sin[θ];      to avoid evaluating subscripts and possibly having recursion.


title: Creating a list of PopupMenus that dynamically update an element in a list

text: So as the title says I am trying to make a list where each element is determined by a users choice of an element in a PopupMenu. My first attempt:               test = Table["A", {5}];     Table[PopupMenu[Dynamic[test[[n]]], {"A", "B", "C"}], {n, 5}]      Returned the following error               Part::pspec: Part specification n is neither an integer nor a list of integers.      For some reason the dynamic(?) would not allow me to refer to specific elements in the list. I then tried to circumvent this issue by introducing an extra variable _temp_ :               Table[temp = n;PopupMenu[Dynamic[test[[temp]]], {"A", "B", "C"}], {n, 5}]      However, all this did was create 5 PopupMenus that all referred to the $5^{\text{th}}$ element of the list _test_. I tried to put a `Setting[]` around the `Dynamic[]`, but since that removes that effect of `Dynamic[]` nothing happened at all. Any suggestions would be greatly appreciated.


title: How to draw a network from a dataset reporting the labels of nodes of every link?

text: I have a dataset in format `.txt` of a directed network, containing a matrix `A` of dimension `m x 2`, where each row gives the labels of two nodes showing a direct link. For example, when the network has $4$ nodes, the matrix `A` could be               A = [1 2; 1 3; 2 1; 2 4; 3 2; 4 1; 4 2]      where the first row means that there is a link from `1` to `2`, the second row means that there is a link from `1` to `3`, etc. Could you suggest me a way to draw the network specified by `A` in _Mathematica_?


title: Plot 3D density

text: I have data that is in four columns. The x y and z are just the coordinates and the fourth is my data. This is not a function. This is electron density in a copper cell and I'm trying to display it in a way that makes sense. Any help would be appreciated. I was semi-successful in gnuplot but it was hard to see and I could only specify certain boundaries. using `($1:$2:($4>0 && $4<2 ? $3/0)` This might be slightly wrong, but you get the picture. I was saying to only plot z if the data was between certain bounds. There must be a better way and I need your help. Thanks. Here is the structure. ![enter image description here](http://i.stack.imgur.com/f2m3U.png)


title: MathLink wrapper for NIntegrate

text: I wonder if I can benefit from the Mathematica numerical quadrature routines in a way which integrates completely into an existing C-program. To be more specific I have C-program which does numerical quadrature using C-libraries like GSL (Gnu Scientific Library). These library functions are used by initializing data structures and running quadrature routines which take pointers to C-functions representing the the integrand and a pointer to a parameter structure which is fed to the integrand function as second parameter. Finally the data structures are freed. There is a set of functions for various kinds of integrands, but obviously there are some routines in Mathematica which are not implemented in the GSL. I wonder now if it is worth attempting to write wrapper functions for `NIntegrate` using MathLink such that I can use Mathematicas integration routines in just the same way as I would use C-library functions. Maybe there are MathLink examples out there which come close to what I want to achieve?


title: PDF for Gamma Distribution not what I expect

text: I have plotted the the PDF for a Gamma Distribution with various parameters (e.g. 3 and 5) using `Manipulate`:               Manipulate[       Plot[PDF[GammaDistribution[α, β], x], {x, -1, 20}],        { α, -1, 8}, { β, -1, 6}]      However, the plots that I get are quite different to what I get using R and which I know to be correct. For example the `PDF` with $\Gamma(3,5)$ should have a peak in the curve at 0.4. The plot that _Mathematica_ produces gives me a peak that is more like `11`. Does anybody have any ideas what I am doing wrong here?


title: NIntegrate returns zero for non zero integrand, 4d Integration

text: I am trying to calculate the following integral.               sigma1 = 10.0; sigma2 = 5.0; delta = 0.5;     t[x1_, y1_, x_, y_] := 100*HeavisideLambda[sigma1^-1*(x - x1), sigma2^-1*(y - y1)];     B2[x1_, y1_, x_, y_] := HeavisideTheta[(delta/2)^2 - (x - x1)^2, (delta/2)^2 - (y - y1)^2];     trans[x1_, y1_, x2_, y2_] :=         NIntegrate[B2[x1, y1, xz, yz]*t[xz, yz, xp, yp]*            (B2[x2, y2, xz, yz] - B2[x2, y2, xp, yp]),             {xp, x2 - 2.0*sigma1, x2 + 2.0*sigma1},             {yp, y2 - 2.0*sigma2, y2 + 2.0*sigma2},             {xz, x1 - 0.5*delta, x1 + 0.5*delta},              {yz, y1 - 0.5*delta, y1 + 0.5*delta},          WorkingPrecision -> 12, AccuracyGoal -> 8, MinRecursion -> 8, MaxRecursion -> 100];      I am interested in the value of the integral for the following inputs:               trans[0, 0, delta, 0]      Here is my problem: for values of delta greater than 0.5 (I tried 1.0, 0.9, 0.8, 07, 0.6, 0.515), the result is a negative number, and it takes some time for _Mathematica_ to come up with the result. For any value of delta smaller than 0.5, _Mathematica_ immediately returns 0, and doesn't give any hints about what is wrong. This is a part of a refinement study and I need to choose smaller and smaller values for delta. Do you know how I can make this work?


title: Bandpassing EEG's using Mathematica's Bandpass Function

text: Let's say we have an EEG signal approximated using a fractional Brownian motion:               EEG[hurst_,t_low,thigh_,tinc_]=RandomFunction[      FractionalBrownianMotionProcess[hurst], {tlow, thigh, tinc}, 1]      for some parameters hurst_, tlow_, thigh_, tinc_. The literature on EEG's state that alpha waves are obtained by using a bandpassing filter in the range 14-40 Hz, more or less...               data = EEG[0.4,0,1,0.01]     BandpassFilter[Flatten[data[[2, 1]]], {0.14, 0.40}];      My question is with regards to the BandpassFilter parameters. Does choosing 0.14 and 0.40 effectively yield the 14-40Hz range? Basically, what are the units of the BandpassFilter function in Mathematica


title: Plot: how to have the y-range automatically scale to min-max on the x-range?

text: I have a long list of {date,value}. I would like to use DateListPlot to plot only a subrange, from date1 to date2, with the range on the y-axis automatically chosen to be between the min and max value between those two dates (i.e. trivial automatic zooming). I am sure Mathematic will do it with a simple option choice, but I must be dumb and cannot find it. Can you help? Thanks. PS: here is simple code to show the issue using financial data:               spx = FinancialData["SP500", All];          DateListPlot[spx,       PlotRange -> {{{1987, 10, 1}, {1987, 11, 30}}, Automatic},       PlotLegends -> Placed[namesFrom83, {Left, Bottom}],       PlotLabel -> "1987"]


title: Alternative updating of a dynamic expression

text: I am looking for a solution to selectively update a dynamic expression `expr` which is dependent on multiple control variables `{x, y, ...}`. I need to update `expr` differently (using `xUpdate` and `yUpdate`) according to which controller is manipulated, i.e. which control variable triggers an update, but without including update code in any of the controllers! That is, `Dynamic[expr]` itself has to include the different update modes. **Question: Is there a method to update a dynamic expression differently depending on which parent-variable triggers an update?** ## 1\. Include update in controller The easy way would be to simply include the different update codes in the controllers, but as I said, this is not the desired way. The code is included here only for reference:               xUpdate[xin_, yin_] := {"x-trigger", yin + xin, yin};     yUpdate[xin_, yin_] := {"y-trigger", yin*10, yin};          x = y = 0; expr = yUpdate[x, y];     {Row@{"update x: ",         Slider[Dynamic[x, (x = #; expr = xUpdate[x, y]) &]]},       Button["Update y", y = RandomReal[]; expr = yUpdate[x, y]]}     Dynamic[expr]      This works as expected, but in my use case I cannot update `expr` directly from the controllers. I have to do it in a way that is restricted to the last line, i.e. the `expr` itself has to do the updating according to which controller was manipulated. ## 2\. Using `$ControlActiveSetting` An alternative method is to rely on the global value of `$ControlActiveSetting`:               xUpdate[xin_, yin_] := {"x-trigger", yin + xin, yin};     yUpdate[xin_, yin_] := {"y-trigger", yin*10, yin};          x = y = 0;         {Button["Update y", y = RandomReal[]],       Row@{"update x: ", Slider[Dynamic@x]}}     Dynamic[expr = If[$ControlActiveSetting, xUpdate[x, y], yUpdate[x, y]]; expr,       TrackedSymbols :> {x, y}]      This correctly differentiates between the two update modes, but it incorrectly reverts to `y-trigger` whenever the x-slider is released. This is unwanted behaviour. A second problem with this is that `$ControlActiveSetting` cannot differentiate between multiple sliders (i.e. imagine a third `z` controller). ## 3\. Intermediate solution a'la `$ControlActiveSetting` A global flag (`trigger`, substituting `$ControlActiveSetting`) is set to either `"x"`, `"y"` or `"z"`, depending on which controller is being manipulated. This works as expected and can be extended to any number of controllers, but has the problem that I still have to set `trigger` in each controller, which I want to avoid.               xUpdate[xin_, yin_, zin_] := {"x-trigger", yin + xin, yin, zin};     yUpdate[xin_, yin_, zin_] := {"y-trigger", yin*10, yin, zin};     zUpdate[xin_, yin_, zin_] := {"z-trigger", zin*20, yin - 1, zin};          x = y = z = 0;     trigger = "x";         {Button["Update y", trigger = "y"; y = RandomReal[]],       Row@{"update x: ", Slider[Dynamic[x, (trigger = "x"; x = #) &]]},       Row@{"update z: ", Slider[Dynamic[z, (trigger = "z"; z = #) &]]}}     Dynamic[Switch[trigger, "x", xUpdate[x, y, z], "y", yUpdate[x, y, z],        "z", zUpdate[x, y, z]], TrackedSymbols :> {x, y, z}]      But it brings me closer to my real question: **Question:** **Is there a way to check globally which control variable is being actively manipulated/changed in the front-end?** Surely `Dynamic[expr]` knows about it as it has the `TrackedSymbols` option, but I cannot access this information from inside the `Dynamic`. I think of something like `CurrentValue["ManipulatedVariable"]` or `CurrentValue["ActualDynamicUpdatingTrigger"]` (which are nonexistent).


title: Creating Correlation Table (and Working) With Missing Data

text: I am working with data that contains missing values (I have several variables (across the columns) and several observations (across the rows) in an excel spreadsheet). Example of the data structure:               obs var1 var2 ... var30     1    100  1     2    .    0     3    30   1     4.   20   .     ...      After importing the data:               names = Import["Example_Data.xls", {"Data", 1, 1}];          data = Drop[Import["Example_Data.xls", {"Data", 1}], 1]      I want to create a simple correlation table:               corrm = Correlation[data] //MatrixForm      **Questions:**   1. How can I calculate the Correlation here given that I have missing data?    2. More generally, how do I work with missing data in mathematica? I have previously worked with Stata where missing values are taken care of under the hood. With that said, will I get the same correlation values here if I simply remove the missing values as I would if I tried to calculate the correlation using a statistical package such as e.g. Stata?  **[EDIT]** For question #2 above I found the following entry useful (http://www.ats.ucla.edu/stat/stata/output/stata_corr_output.htm). It seems that the standard procedure for statistical programs such as Stata is to delete each observation containing a missing value for one or more of its variables. As such, I would appreciate a method for answering question #1 using a similar method. **NOTE:** After a preliminary search I found the following resources helpful (but they did not answer my questions): http://mathematica.stackexchange.com/questions/29159/correlation-with-missing- data http://reference.wolfram.com/language/howto/ReplaceOrRemoveInvalidOrMissingData.html


title: Matrix and random, weighted assignment of rows

text: I asked a question in this category previously but my problem has changed. On one hand, I have a large number of data files as _.dat_ format, and on the other hand, I have a matrix `A` which must be filled with these data. Each of rows of the `A` must be devoted to each of the data files BUT NOT WITH THE SAME CHANCE. Actually, my desire is to put each of data files in each row (after importing them) but in a RANDOM WAY. For example ( **just for example** here, there are 5 data files): (the number of the row of `A` is the same of the number of data files and the number of the column of that is fixed to 10). However, in the elements shown below, n has 11 because, as I will explain, I don't want to add the first element from a data file to the matrix.               m = {8, 1, 5, 3};     n = {6, 2, 7, 11, 3, 8, 10, 12, 14, 1, 4};     k = {10, 3, 6, 8, 2};     S = {7, 1, 9};     R = {9, 4, 6, 1, 5};      I mean, the `k` is the most significant relative the other elements and must have the highest chance of getting the first row of the matrix; For example with the weight 10 (just for example). After `k`, `R` (with the weight 9) must have the next highest chance to get the first row of the matrix. Then with decreasing chance: `m` with weight 8. `S` with weight 7, and so on. Every previously assigned weight of each data element is given in the first element of the element. For instance, `n` might be assigned to the second row even though `n` has the less chance than `R` to occupy the second row. As a matter of fact, the random generator, giving attention to the weights, will decide which data element to assign to which row.


title: How to transpose unequal lists

text: As the titel says I want to transpose a matrix containing rows of unequal length, to be able to transport them to excel (in row form, there are too many datapoint to write them in a cell. In another topic if found to use flatten : Transpose uneven lists However, this does not give me the right result: Example:               list = {{1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3}, {1, 2, 3}, {1, 2, 3, 4,5}, {1, 2, 3, 4, 5}};     Flatten[list, {{2},{1}}]      Results into:               {{1, 1, 1, 1, 1, 1}, {2, 2, 2, 2, 2, 2}, {3, 3, 3, 3, 3, 3}, {4, 4, 4, 4}, {5, 5}}      But the result I want is:               {{1, 1, 1, 1, 1, 1}, {2, 2, 2, 2, 2, 2}, {3, 3, 3, 3, 3, 3}, {4, 4,"" , "" , 4, 4}{,"" , "" , "" , "" , 5, 5}}      So I want to keep the rows together as they are, but only print them into columns. Is this possible?


title: Modelling Hysteresis with a Differential Equation

text: I want to implement the bulk ferromagnetic hysteresis model (mostly the Jiles- Atherton Model), see http://drum.lib.umd.edu/bitstream/1903/6043/1/PhD_99-1.pdf page 44 equation (30). The needed equations are $$ \delta = \text{sgn}(\dot{H})\\\\[1ex] H_\text{eff}=H+\alpha M \\\\[1ex] M_\text{an}(H_\text{eff})= M_\text{sat}\cdot\mathcal{L}(H_\text{eff}/a)\\\\[1ex] \delta_\text{M}=\begin{cases}0 & \dot{H}<0\text{ and }M_\text{an}-M>0\\\0 & \dot{H}>0\text{ and }M_\text{an}-M<0\\\1&\text{else}\end{cases}$$ and the main equation is $$ \frac{\text{d}M}{\text{d}H}=\frac{\frac{k\delta c}{\mu_0}\frac{\text{d}M_\text{an}}{\text{d}H_\text{eff}}+\delta_\text{M}(M_\text{an}-M)}{\frac{k\delta}{\mu_0}-\delta_\text{M}(M_\text{an}-M)\alpha-\frac{k\delta \alpha c}{\mu_0}\frac{\text{d}M_\text{an}}{\text{d}H_\text{eff}}}$$ Short explanation: $\delta$ takes into account wheter we are at the upper hysteresis branch or the lower one, $H_\text{eff}$ is needed to shift the Langevinfunction $\mathcal{L}(x)$ to achieve a hysteresis, $M_\text{an}$ is the anhysteretic Magnetization and $\delta_\text{M}$ is necessary to prevent unphysical behaviour. ## How I tried to implement it There were two approaches I tried: The first one is based on ParametricNDSolve, and, as I understand it, the values need to go from $0$ to $H_\text{max}$ (this is no problem and works) then down to $-H_\text{max}$ and up again to $H_\text{max}$ (this is the part I'm unsure how to achieve). My first guess was to define the function piecewise, with an implemented shift (Beware monster ugly function below!):               \[Micro]0 = 4 \[Pi]*10^-7;     BulkFerromagneticHysteresisModelComplete = ParametricNDSolveValue[{Mges'[Happlied] ==       Piecewise[{{((k*c/\[Micro]0)*             Msat (a/(Happlied + \[Alpha]*Mges[Happlied])^2 -                Csch[(Happlied + \[Alpha]*Mges[Happlied])/a]^2/a) +             Piecewise[{{0,                 Msat*Piecewise[{{#/3,                      Abs[#] < 10^-5}, {Coth[#] - 1/(#),                      True}}] &@((Happlied + \[Alpha]*Mges[Happlied])/                     a) - Mges[Happlied] > 0}, {1,                 True}}]*(Msat*                  Piecewise[{{#/3, Abs[#] < 10^-5}, {Coth[#] - 1/(#),                      True}}] &@((Happlied + \[Alpha]*Mges[Happlied])/                  a) - Mges[Happlied]))/((k/\[Micro]0) -             Piecewise[{{0,                 Msat*Piecewise[{{#/3,                      Abs[#] < 10^-5}, {Coth[#] - 1/(#),                      True}}] &@((Happlied + \[Alpha]*Mges[Happlied])/                     a) - Mges[Happlied] > 0}, {1,                 True}}]*(Msat*                  Piecewise[{{#/3, Abs[#] < 10^-5}, {Coth[#] - 1/(#),                      True}}] &@((Happlied + \[Alpha]*Mges[Happlied])/                  a) - Mges[Happlied])*\[Alpha] - (k*               c*\[Alpha]/\[Micro]0)*             Msat (a/(Happlied + \[Alpha]*Mges[Happlied])^2 -                Csch[(Happlied + \[Alpha]*Mges[Happlied])/a]^2/a)),          Happlied <           20000}, {((-k*c/\[Micro]0)*             Msat (a/(-Happlied +                  40000 + \[Alpha]*Mges[-Happlied + 40000])^2 -                Csch[(-Happlied +                  40000 + \[Alpha]*Mges[-Happlied + 40000])/a]^2/a) +             Piecewise[{{0,                 Msat*Piecewise[{{#/3,                      Abs[#] < 10^-5}, {Coth[#] - 1/(#),                      True}}] &@((-Happlied +                      40000 + \[Alpha]*Mges[-Happlied + 40000])/a) -                   Mges[-Happlied + 40000] > 0}, {1,                 True}}]*(Msat*                  Piecewise[{{#/3, Abs[#] < 10^-5}, {Coth[#] - 1/(#),                      True}}] &@((-Happlied +                     40000 + \[Alpha]*Mges[-Happlied + 40000])/a) -                Mges[-Happlied + 40000]))/((-k/\[Micro]0) -             Piecewise[{{0,                 Msat*Piecewise[{{#/3,                      Abs[#] < 10^-5}, {Coth[#] - 1/(#),                      True}}] &@((-Happlied +                      40000 + \[Alpha]*Mges[-Happlied + 40000])/a) -                   Mges[-Happlied + 40000] > 0}, {1,                 True}}]*(Msat*                  Piecewise[{{#/3, Abs[#] < 10^-5}, {Coth[#] - 1/(#),                      True}}] &@((-Happlied +                     40000 + \[Alpha]*Mges[-Happlied + 40000])/a) -                Mges[-Happlied + 40000])*\[Alpha] - (-k*               c*\[Alpha]/\[Micro]0)*                  Msat (a/(-Happlied +                  40000 + \[Alpha]*Mges[-Happlied + 40000])^2 -                Csch[(-Happlied +                  40000 + \[Alpha]*Mges[-Happlied + 40000])/a]^2/a)),          20000 < Happlied < 60000},{((k*c/\[Micro]0)*             Msat (a/(Happlied +                  40000 + \[Alpha]*Mges[Happlied - 80000])^2 -                Csch[(Happlied +                  40000 + \[Alpha]*Mges[Happlied - 80000])/a]^2/a) +             Piecewise[{{0,                 Msat*Piecewise[{{#/3,                      Abs[#] < 10^-5}, {Coth[#] - 1/(#),                      True}}] &@((Happlied -80000 + \[Alpha]*Mges[Happlied -80000])/a) -                   Mges[Happlied -80000] > 0}, {1,                 True}}]*(Msat*                  Piecewise[{{#/3, Abs[#] < 10^-5}, {Coth[#] - 1/(#),                      True}}] &@((Happlied -80000 + \[Alpha]*Mges[Happlied -80000])/a) -                Mges[Happlied -80000]))/((k/\[Micro]0) -             Piecewise[{{0,                 Msat*Piecewise[{{#/3,                      Abs[#] < 10^-5}, {Coth[#] - 1/(#),                      True}}] &@((Happlied -                      80000 + \[Alpha]*Mges[Happlied - 80000])/a) -                   Mges[Happlied - 80000] > 0}, {1,                 True}}]*(Msat*                  Piecewise[{{#/3, Abs[#] < 10^-5}, {Coth[#] - 1/(#),                      True}}] &@((Happlied -                     80000 + \[Alpha]*Mges[Happlied -80000])/a) -                Mges[Happlied -80000])*\[Alpha] - (k*               c*\[Alpha]/\[Micro]0)*                  Msat (a/(Happlied -                  80000 + \[Alpha]*Mges[Happlied - 80000])^2 -                Csch[(Happlied -                  80000 + \[Alpha]*Mges[Happlied -80000])/a]^2/a)),          60000 < Happlied < 100000}}],      Mges[0] == 0.0001}, {Mges}, {Happlied, 0, 100000}, {Msat, a,      k, \[Alpha], c}];      Unfortunately this doesn't work (I suspect because of `Mges[Happlied-80000]` respectively `Mges[-Happlied+40000]`? If yes, how can I workauround this?). **EDIT:** To be more precise, compiling the above shown works, proceeding with               modelcomplete[Msat_, a_, k_, \[Alpha]_, c_][Happlied_] := Through[BulkFerromagneticHysteresisModelComplete[Msat, a,        k, \[Alpha], c][Happlied], List] /; And @@ NumericQ /@ {Msat, a, k, \[Alpha], c, Happlied};      leads after several seconds (it looks as if it is already done for some time with compiling) to the error:               Mathematica Kernel for Windows has stopped working     Problem Event Name: APPCRASH     Application Name: MathKernel.exe     ...     Fault Module Name: mathdll.dll     ...      * * * Another possible approach is described in Computer-aided Analysis of Electric Machines: A Mathematica Approach from Vlado Ostovic, but the book is from the early 90s, so the code presented there doesn't work - the main idea is to use a periodic function to achieve the hyteresis effect. It seems I got the virgin curve working there as well:               Ms = 2*10^6;     a = 1100;     kon = 0.0004;     alpha = 1.6*10^3;     mu0 = N[4*Pi*10^(-7)];     c = 0.2;     Hmax = 8000;     omega = N[2*Pi];          eq = {Mges'[t] == (Ms (Coth[(Hmax*Cos[2 Pi t] + alpha Mges[t])/a] -            a/(Hmax*Cos[2 Pi t] + alpha Mges[t])) -         Mges[t])/((1 + c) (kon/mu0 -           alpha (Ms (Coth[(t + alpha Mges[t])/a] -                 a/(Hmax*Cos[2 Pi t] + alpha Mges[t])) - Mges[t]))) +      c/(1 + c) (Ms (a/(Hmax*Cos[2 Pi t] + alpha Mges[t])^2 -           Csch[(Hmax*Cos[2 Pi t] + alpha Mges[t])/a]^2/a)), Mges[0] == 0}          tests = NDSolve[eq, {Mges}, {t, 0, 1}]          Plot[Evaluate[Mges[t] /. tests], {t, 0, 1}, PlotRange -> All]      But instead of the `Mges[t]` it would be necessary to use `Mges[Hmax*Cos[2 Pi t]]`, sadly _Mathematica_ crashes if I try to use this expression. **EDIT:** To be more precise here: If I use `Mges[Hmax*Cos[2 Pi t]]` throughout `eq` I get the following error:               NDSolve::derivs: No derivatives of dependent variables were found in the equations. NDSolve is designed to solve differential or differential algebraic equations. Use NSolve or FindRoot to numerically solve algebraic equations. >>      I suspect this is due to Mathematica not recognizing `Mges[Hmax*Cos[2 Pi t]]` as $M(x)$ but as $M(f(x))$. * * * Does anyone have any idea how to overcome these obstacles? Thanks a lot in advance, I really appreciate any help!


title: Radial Random Walk

text: I'm trying to generate a spherical distribution of **radial** random walk points in 3D space. The following code works, but the random walk lines aren't radial. Why ? Where is my mistake ?               MinSprite := 0.006; (* min radius of sprites *)     MaxSprite := 0.03; (* max radius of sprites *)     SpriteOverlap := 0.75; (* min separation between sprites *)     IterationStep := 0.1;     NumberOfSteps := 20;     thickness = 0.09;     pointsmean = 20;     pointssd = 12;          SpriteSize[p_] := MinSprite + (MaxSprite - MinSprite)Norm[p];          SeedRandom[];     RandomWalk = Flatten[Table[{x,y,z}={dist Sqrt[1 - cosinus^2]Cos[phi],dist Sqrt[1 - cosinus^2]Sin[phi],dist cosinus};         {u,v, w}={0.0, 0.0, 0.0};         dist = RandomReal[{5,10}];         phi = RandomReal[{0,2Pi}];         cosinus = RandomReal[{-1,1}];         velocity = Abs[RandomReal[NormalDistribution[0,s]]];          Line[NestList[(         u+=velocity Sqrt[1 - cosinus^2]Cos[phi];         v+=velocity Sqrt[1 - cosinus^2]Sin[phi];         w+=velocity cosinus;         #+IterationStep{u,v, w})&,{x,y, z},NumberOfSteps]],{s,0.25,0.75,0.007}][[All,1]],1];          CloudsParticles = Flatten[Table[(#+RandomReal@LaplaceDistribution[0,thickness])&/@#,{Max[1,IntegerPart@RandomReal@NormalDistribution[pointsmean,pointssd]]}]&/@RandomWalk, 1];          max=Max[Norm/@CloudsParticles];     NormalizedParticles = CloudsParticles/max;          MinSeparation[p_] := SpriteOverlap SpriteSize[p];     KeepPoint[{p_,q_}] := Norm[p]<Norm[q]||Norm[p-q]>MinSeparation[p];     FilterOnce[pts_] := With[{nf=Nearest[pts]},Select[pts, KeepPoint[nf[#,2]]&]];     PointsCoords = FixedPoint[FilterOnce,NormalizedParticles];          ListPointPlot3D[PointsCoords,BoxRatios->{1,1,1},ImageSize->800,SphericalRegion->True,PlotStyle->{Blue,PointSize[Small]}]      Here's a sample of the output. As you can see, this isn't a radial distribution : ![This distribution isn't radial](http://i.stack.imgur.com/FhfTK.jpg) The mistake most probably lies in the **RandomWalk** declaration, but I can't see it. Anyone has an idea of what may be wrong ? Take note that I'm using _Mathematica 7.0_ only. **EDIT :** I must admit that this method isn't a clever way of defining a random distribution of points around radial lines. I'll have to do it differently.


title: Understanding Bilinear ImageResize

text: In trying to understand basic image transformations, I have attempted to code my own image resize function that uses bilinear interpolation. I checked my work against Mma's `ImageResize[...,Resampling->"Bilinear"]` command and the results are similar, but not the same. The following minimal example demonstrates how I do not fully understand Mma's algorithm. Let `im={{1,.5,0}}`, a `3x1` picture of grayscale values. "Common sense" and knowledge of bilinear interpolation tell me that resizing this image to `5x1` should give `{{1,.75,.5,.25,0}}`. However, `ImageData[ImageResize[Image[{{1, .5, 0}}], {5, 1}, Resampling -> "Bilinear"]]` returns `{{1,.8,.5,.2,0}}`. Resizing to a `6x1` gives `{{1., 0.875, 0.625, 0.375, 0.125, 0.}},` where the middle 4 terms are equally spaced at `.25` apart, but the first and last two elements are spaced `0.125` apart. Resizing to a `9x1` gives `{{1., 1., 0.833333, 0.666667, 0.5, 0.333333, 0.166667, 0., 0.}},` which further confuses me as the first and last two entries are repeated. These results are similar to what MATLAB produces, though Octave (I am told) produces what I think should be right - where all entries are equally spaced apart from `1` down to `0.` I checked with two image editing programs, and one gave results similar to Mma and one gave results similar, but not exactly the same, to my "common sense." Can anyone explain how _Mathematica_ is implementing bilinear interpolation?


title: InstallJava::fail error when importing an image with a Raspberry Pi

text: I'm trying to import an image in Mathematica on my Raspberry Pi. The code is simple but I get an error when importing:               $ wolfram     Wolfram Language (Raspberry Pi Pilot Release)     Copyright 1988-2014 Wolfram Research     Information & help: wolfram.com/raspi          In[1]:= SetDirectory["~/"];          In[2]:= i=Import["small.jpg"];      > >     InstallJava::fail: A link to the Java runtime could not be established. >   This is the image I'm trying to import: http://i.stack.imgur.com/zzSLr.jpg It's 1.5 MB large so the Pi should have no problem importing it. Why do I get this error and how can I prevent it? * * * UPDATE: I believe this is caused when the computer is running out of memory. I don't know a sure way to reproduce it but it keeps happening if I do other memory-intensive tasks on my Raspberry Pi. I'd like to know if there's a way to prefevnt this. and I got this error: > /opt/Wolfram/WolframEngine/10.0/SystemFiles/Kernel/Binaries/Linux- > ARM/WolframKernel: error while loading shared libraries: > /opt/Wolfram/WolframEngine/10.0/SystemFiles/Libraries/Linux- > ARM/libWolframEngine.so: cannot make segment writable for relocation: Cannot > allocate memory


title: Rotating & Trimming grids

text: I want to draw a graphic $20\times20$ grid, rotate it by $\theta$ around $(0,0)$, and trim off the part on the right of the y-axis, so I came up with               ImageTrim[Rotate[GraphicsGrid[Table["", {20}, {20}], Frame -> All], Dynamic[\[Theta]], {0, 0}], {-1000, -1000}, {0, 1000}];      But it gives no output, but an error message instead > ImageTrim::imginv: Expecting an image or graphics instead of [an oblique > orange square wich usually indicates something's wrong] What should I do?


title: How to plot the output of a calculation with a changing variable

text: The following code successfully manages to plot the cross-section, and give me the maximum depth of a weld pool, for a given set of parameters. What I would ideally like to be able to do is to plot a graph of how the the maximum depth of a weld pool varies with a parameter (ie. `v` between `0.915` and `1.5`). I think I am essentially looking to make a for loop so I can plug many different values for v in, However `Do` does not seem to work in this case. Any help would be greatly appreciated!               k = 15.75;     α = 5.79*10^-6;     T = 1015;     η = 0.6;     Q = 600;     v = 0.915;     y = 0;          g[x_?NumericQ] :=        Quiet[ FindRoot[T == (η Q)/(2 π k Sqrt[x^2 + y^2 + z^2])*Exp[                                                (-v (x + Sqrt[x^2 + y^2 + z^2]))/(2 α)],                         {z, -0.0001, -0.1, -0.0000001}][[1, 2]]]          p = Plot[ g[x], {x, -0.00001, -0.0037}, Filling -> Axis,      FillingStyle -> Orange, AspectRatio -> Automatic]          FindMinimum[g[x], {x, -0.001}][[1]]


title: Trouble understanding a piece of code found on Wolfram Blog

text: I am trying to go through this Wolfram Blog example: http://blog.wolfram.com/2009/02/12/flag-analysis-with-mathematica/ on country flag analysis. I am having a problem understanding the following piece of code:               countryColors =       (# -> Catch[Intersection[               StringSplit[                If[Head[#] === Missing, Throw[""], #]& @                 CountryData[#, "FlagDescription"]],               colorNames]]) & /@ CountryData[];      where `colorNames` is just a list of colors. I do not understand `&@` in the above piece of code. What I know is that `&` is used to define a pure function, and `@` is used as a Prefix. If, for example, the `If` yields true, then it returns a country name. What does it mean to have `&@` after that?


title: Does $x>0$ imply that $x\in\mathbb{R}$?

text: Let’s assume I input               Assuming[x > 0, expression]      Is it assumed by _Mathematica_ that $x$ is a real number? Or that the real part of $x$ is positive? Something else? A simple _Mathematica_ illustration would be welcome.


title: Functions, Options and Symbols

text: In the normal _Mathematica_ language, where no built-in symbols are redefined and no evil things happen, is it a valid assumptions, that no function symbol (`Plot`, `Print`, `Attributes`) is also an option name (like `PlotRange`, `ColorSpace`, `ImageSize`). Furthermore, is it save to assume that symbols carrying an `OwnValue` (`$MaxNumber`, `Pi`, `$Failed`) are in neither of the other two groups? To say it straight out: Does someone find a function, which is used as an option too?


title: How to partition a list in a specific way

text: I have a list:               a = {{1, 2, 3, 4, 1, 2, 3, 4}, {5, 6, 7, 8, 5, 6, 7, 8}};      Using `Partition` and `Map` I get:               Partition[#, 4]& /@ a      > >     {{{1, 2, 3, 4}, {1, 2, 3, 4}}, {{5, 6, 7, 8}, {5, 6, 7, 8}}} >   And now, I would like to get a list which looks like:                {{{{1, 2},{3, 4}}, {{1, 2},{3, 4}}}, {{{5, 6},{7, 8}}, {{5, 6},{7, 8}}}}      I tried to play around with `Partition` and `Map`, but I did not manage to create such a list. Of course there are easy ways to do it using `Do` loops and `AppendTo`, but I very much need to avoid `Do` loops. Does anybody see the way to create the list?


title: Speeding up mathematica by subsitituting numerical values

text: According to this Wolfram Blog post, one can speed up Mathematica code by substituting numerical values as soon as possible. How does one substitute before the main expression is evaluated? The following timings show the problem:               In[881]:= Timing[      meanFirstPassage[N[.95* tenDesigner + (1. - .95) tenRandomUser], si,        gi]]          Out[881]= {0.46267, 4.3469}          In[880]:= Timing[      meanFirstPassage[       N[k* tenDesigner + (1. - k) tenRandomUser /. k -> .95], si, gi]]          Out[880]= {2.77539, 4.3469}      When I use the function above in `Plot` it reverts to the slow version in which the inner expression involving `k` is symbolically evaluated. As noted by the response below, `With` does the trick. My main goal was to speed up `Plot`. Here is a self-contained example:               In[961]:= d = 100;     m1 = Table[RandomReal[], {d}, {d}];     m2 = N[Table[RandomInteger[], {d}, {d}]];          In[964]:= .95*m1 + (1. - .95)*m2; // AbsoluteTiming          Out[964]= {0.009045, Null}          In[965]:= k*m1 + (1. - k)*m2 /. k -> .95; // AbsoluteTiming          Out[965]= {0.059908, Null}          In[966]:= With[{k = .95}, k*m1 + (1. - k)*m2]; // AbsoluteTiming          Out[966]= {0.008615, Null}          In[967]:= Plot[Mean[k*m1 + (1. - k)*m2], {k, 0, 1}]; // AbsoluteTiming          Out[967]= {10.182414, Null}          In[968]:= Plot[With[{k = x}, Mean[k*m1 + (1. - k)*m2]], {x, 0., 1.}]; // AbsoluteTiming          Out[968]= {1.821481, Null}


title: Choosing $n$ equidistant points on a circle with given radius and center

text: I would like to have a function `circle` which takes two inputs: a tuple `{x,y}` and a real number `r` and outputs the cooridinates of points on the circumference of a circle that is centered at $(x,y)$ which has radius $r$. Importantly, I want the points to be equidistant on the circle. I tried to implement the procedure here described as Circle Point Picking. But I don't get equidistant points. Kindly help me. Here is the code I tried:               num = 20; r = 50;     circle = Module[{},       random = RandomReal[{-2, 2}, {num + 10, 2}];       random = Take[DeleteCases[random, #1^2 + #2^2 >= r^2 &], num];       Table[r {(x[[1]]^2 - x[[2]]^2)/(x[[1]]^2 + x[[2]]^2),           2 x[[1]] x[[2]]/(x[[1]]^2 + x[[2]]^2)}, {x, random}]       ]      The above code will output `num=20` points on a circle that are not equidistant on the circumference. Here is the output represented as a `ListPlot`:               ListPlot[circle]      ![](http://i.stack.imgur.com/zgcee.png) _Irrelevant as such for the question, but if anyone is curious:_ The context for getting equidistant points is that I want to embed a graph with _some_ vertices located on the points. If you instead know how to do this, kindly tell me. I cannot find a use for `CircularEmbedding` because I only want a circular embedding on some vertices of the graph, not all vertices. The only way I see is to explicitly give the vertex cooridinates as points on a circle.


title: Connecting to a remote machine

text: The simple answer is               ssh username@hostname      Enter your password and you are set. My problem is that I wish to connect to a computer in my university. There are several machines which everyone can access but before doing so we have to go through the login machine. So say the name of the login machine is login.school.edu Then I would do               ssh login.school.edu      From there then I would ssh to one of the several machine names               ssh ld00      They have 112 machines, so I can do ld00 through ld112. The reason I'm asking this is because I want to run the Mathematica Kernel in one of these machines but in the Kernel configuration it asks for the hostname. The hostname cannot be the login machine because this machine does not have Mathematica installed and this machine wasn't meant for computations. Any way I can bypass this? # Update: So it seems that those machines are not public in the internet. Now that I'm in the deparment I connected to the network and now I can do a simple               ssh username@hostname      The administrator of the machines did say something interesting: > I do not know what SSH implementation is currently part of MacOS. Under > OpenSSH (used on Linux machines) it is theoretically possible to make > creative use of the ProxyCommand directive to make it appear as if those > hosts are directly available to SSH. I cannot tell you how to do this, > however; I've only seen mention of it. So, does anyone know how to do this so that I can connect to the kernel from outside the school?


title: NumberOfSpanningTrees command not working correctly

text: I am attempting to use the Combinatorica `NumberOfSpanningTrees` command for all `n-cycle` graphs from 3 to 30. I am trying to get a table form showing whether it is true or false that `n-cycle` graphs have `n` spanning trees. However Mathematica does not seem to recognize the command. Am I am pre- loading the Combinatorica packages correctly?               << Combinatorica`     Table[{i, NumberOfSpanningTrees[CycleGraph[i]] == i}, {i, 3, 30}] // TableForm      The output I get is: ![enter image description here](http://i.stack.imgur.com/CqKsL.png) I have also tried loading Combinatorica using the `Needs["Combinatorica`"]. Any ideas?


title: Polar Differential Equation

text: I have a polar differential equation (this is the reduced variant) as: $$r' = 0, \theta' = 1$$ I figured out (from previous answers) that I can nicely convert this to Cartesian and use StreamPlot as:                 field = {0, 1};            TransformedField["Polar" -> "Cartesian", field, {r, \[Theta]} -> {x, y}]            StreamPlot[{-(y/Sqrt[x^2+y^2]),x/Sqrt[x^2+y^2]},{x,-2,2},{y,-2,2},        StreamColorFunction->"Rainbow"]      This generates the correct phase portrait and worked great. I was even able to animate it. My question now is how can this field (polar DEQ) be solved as a polar DEQ? Can't this be solved as such and plotted using polar plots to arrive at the same phase portrait? Am I missing something? I tried NDSolve without luck, so think I must be missing something basic here. Is something special required for polar type DEQs in Mathematica?


title: How to copy hyperlink addresses using the keyboard

text: I would like to copy the address of a hyperlink in _Mathematica_ using the keyboard. I found code for copying hyperlink addresses in `ContextMenus.tr`:               MenuItem["&Copy Address", FrontEndExecute[      {FEPrivate`FrontEndExecute[FrontEnd`CopyToClipboard[       CurrentValue[{ButtonBoxOptions, ButtonData}]]]      }     ], MenuEvaluator->None]      but using this to make a keyboard shortcut in KeyEventTranslations.tr as follows doesn't seem to work.               Item[KeyEvent["c", Modifiers -> {Control, Option}], FrontEndExecute[      FrontEnd`CopyToClipboard[ CurrentValue[{ButtonBoxOptions, ButtonData}]]]     ]      (`KeyEvent["c", Modifiers -> {Control, Option}]` didn't seem to work at all as a shortcut combination, but other combinations that worked for other actions didn't work for copying the hyperlink address.) One problem is that I'm not sure whether the hyperlink has to be selected or what.


title: Trying to model Heat flow trough different materials with NDsolve

text: What I'm trying to achieve is model of the heat flow, in this case for the simplest 1D case,its relatively easy to do for the steady state case, but when I try to do it with NDsolve so I get the distribution of heat over time,I fail to come up with a good way to connect the two differential equaions, I recently modeled a gravity field where the same differential equation is applied many times to different bodies, that I got to work, but I dont understand how to link "differeet" ODE/PDE's This is my code, so far, and I intend to display that solution with Manipulate and Plot: :ps I added the [] in u[1] and u[2] last minute to see if it changes anything before they were just called u1[] and u2[] respectively, it might be nonsensical but my original question remains thanks in advance!               heateqs = {D[u[1][x, t], t] == D[u[1][x, t], {x, 2}],         D[u[2][x, t], t] == 0.5 D[u[2][x, t], {x, 2}]};          bcs = {u[1][0, t] == 300, u[1][5, t] == u[2][5, t],         Derivative[1, 0][u[2]][10, t] == 0};          ics = {u[1][x, 0] == u[2][x, 0] == 0};          sol = NDSolve[{heateqs, bcs, ics}, u, {x, 0, 10}, {t, 0, 10}]          NDSolve::bcedge: Boundary condition u[1][5,t]==u[2][5,t] is not specified on a single edge of the boundary of the computational domain. >>


title: add a color bar legend to a 3D plot

text: This has a connection to the previous post here: puzzled with a color function Also, a recent post of mine appeared here: Create a color bar plot legend but I should have solved the problem with the color function before asking the question about color bar. If opening a new thread goes against the forums policies I apologize. Thanks to the answers I got, I have now what I wanted               h = ParametricPlot3D[lst, {u, 0, 2*Pi}, {v, 0, Pi}, Mesh -> False,          ColorFunction -> (Function[{x, y, z, u, v}, Hue[Rescale[dam, {0, 1}]]]),          ColorFunctionScaling -> False, ImageSize -> 800];     g = Plot3D[Rescale[dam, {0, 1}], {u, 0, 2*Pi}, {v, 0, Pi}, Mesh -> False,          ColorFunction -> (Function[{u, v, z}, Hue[Rescale[dam, {0, 1}]]]),          ColorFunctionScaling -> False, PlotRange -> All];     Row[{h, Show[g, ImageSize -> 400]}]      What I further want is to add a color bar to each plot. Something like               Legended[h, BarLegend[{colFun,{min,max}}]] (*version 9*)      which does not give the requested color bar. Also,               colourBar =        DensityPlot[y, {x, 0, 1}, {y, 0, 1}, AspectRatio -> 5,         PlotRangePadding -> 0,         FrameTicks -> {{None, Range[0, 1, 0.1]}, {None, None}},         ColorFunction -> colFun];     Row[{Show[gr1, ImageSize -> Large],        Show[colourBar, ImageSize -> Small]}] (*vesrion 8 alternative*)      does not work as well. Thanks in advance for any advice. Dimitris


title: Problem with #1's in DSolve

text: I've entered the following functions into my notebook, but the solution to them contains #1's that I can't seem to make any sense of. The functions are:               z := R[r, t]     P := D[R[r, t], t]     eqn := P^2 - (2 x[r])/z - 2 y[r] == 0      sol = DSolve[eqn, z, t]      and the solution returns the following:               {      {R[r, t] ->        InverseFunction[-((Log[Sqrt[#1] y[r] + Sqrt[y[r]] Sqrt[x[r] + #1 y[r]]] x[r])/         y[r]^(3/2)) + (Sqrt[#1] Sqrt[x[r] + #1 y[r]])/y[r] &][-Sqrt[2]t + C[1]]},       {R[r, t] ->        InverseFunction[-((Log[Sqrt[#1] y[r] + Sqrt[y[r]] Sqrt[x[r] + #1 y[r]]] x[r])/         y[r]^(3/2)) + (Sqrt[#1] Sqrt[x[r] + #1 y[r]])/y[r] &][Sqrt[2] t + C[1]]}     }      Any thoughts on the matter?


title: Best way to add KeyEvents and faster Quit

text: Many users have asked how to add `KeyEvent`s to speed/improve keyboard input. This is just a random example. The technique is always the same. It requires that you _manually_ modify `KeyEventTranslations.tr` (an important system file). It always struck me as a bit odd that even power users propose to manually do this. Surely this system file is loaded into _Mathematica_ at the start of a session (or not?), so it is perhaps possible to _programmatically_ add the necessary KeyEvents to an already running _Mathematica_ session. Of course in this case the new key bindings will only be temporary, but this might even be preferable in some cases. So the question is: is it possible to _programmatically_ add the necessary `KeyEvent`s to an already running _Mathematica_ session, without changing the `KeyEventTranslations.tr`? Alternatively: can we program _Mathematica_ to backup `KeyEventTranslations.tr` and programmatically modify it? I know this is possible, I just wonder if someone has done it. And perhaps automatically reload the new version so that it takes effect right away? * * * **The art of Quitting.** I take the occasion to post another item related to "saving keystrokes for your retirement": It recently came to my attention that many/most users when they want to quit the kernel, type `Quit[]`. Well...the good news are that you just need to type `Quit` (saving two keystrokes).


title: InterpolationOrder for ContourPlot

text: How do I acheive something like `InterpolationOrder` in `ListContourPlot` for `ContourPlot`? My main problem is I want to smooth the contours in `ContourPlot`. I have some points which I'm going to call data, which is 10,000 points and looks like this:               {{24.3,40.0},{29.2,56.0} ... }      I create this distance function:               D[x_,y_]=(#[[1]]-x)^2+(#[[2]]-y)^2&/@data      Now, my function is supposed to count the number of points within a certain distance of any x,y position and divide by the total number of points:               F[x_,y_,r_]:=Length[Select[D[x,y],(#<r^2)&]]/Length[data]      Now I can plot my function,               ContourPlot[F[x,y,5],{x,0,100},{y,0,100}]      The problem is my function is not naturally smooth. I know about `SmoothDensityHistogram` and `DensityHistogram`, but I like the more simple look of smoothed contours. Can anyone help with this?


title: Sample of the random times at which the random walk crosses the boundary

text: I defined a security boundary for a random walk:               p = 5000;(*steps*)     tc = 15;(*cube edge length*)     tp = 0.2;          random = Accumulate[     Join[{RandomReal[{-tc, tc}/2, 3]},      RandomVariate[NormalDistribution[0, tp], {p, 3}]]];          periodizedWalk = Mod[random, tc, -tc/2];     splitPeriodizedWalk =      Split[periodizedWalk, EuclideanDistance[#1, #2] < tc/2 &];          With[{cube = First[PolyhedronData["Cube"]]},      Graphics3D[{{Opacity[0.1], Scale[cube, tc]}, Line[random]},      Boxed -> False]]      and now i want to obtain a sample of the random times at which the random walk crosses the boundary for the first time. Something like this:               W = {}; For[i = 1, i <= 5000, i++,     PosFinal = {0, 0}; EME = 1;     While[True,     PosFinal = PosFinal + step[Random[]];     If[Norm[PosFinal] > 15, Break[]];          EME = EME + 1;     ];     W = Append[W, EME];     ]      but i want these two codes to be related. Would like some help please :)


title: HypergeometricPFQ

text: I am trying to get a simple but relatively ugly result out of the following summation, however, mathematica gives me an expression which includes HypergeometricPFQ. Obviously, I am doing something wrong, which is pretty classical for me. Can somebody please point me out what went wrong? The result should be an expression involving factorials and product (maybe). thank you!               a[j_, q_, k_] := (q! (j + q - 1)!)/((j! (q - j)!) (j - k + q - 1)!);     aa[i_, q_, k_] := a[i - q + k + 1, q, k];     b[j_, q_, k_] = (-1)^j Sum[aa[i, q, k]*aa[j - i, q, k], {i, 0, j, 1}]          ((-1)^j k! (j + k)! (q!)^2 HypergeometricPFQ[{-j, 1 + k,       1 + k - 2 q, -1 - j - k + q}, {-j - k, 2 + k - q, -j - k + 2 q},      1])/(j! (1 + k - q)! (1 + j + k - q)! (-1 - k + 2 q)! (-1 - j -        k + 2 q)!)


title: simplify assuming a variable equals zero

text: How can one simplify an expression by assuming that one of the variables is equal to zero? For instance, while `Simplify[%,a>0]` gives the desired output, `Simplify[%,a=0]` produces the following error:               $Assumptions::bass: 0 is not a well-formed assumption. >>


title: plot function against composite variable

text: How can one plot $f(x,y)$ as a pseudo-univariate function of $x/y$ (or some other composition of these variables) over the domain $a<\frac{x}{y}<b$. `Plot[f,{x/y,a,b}]` produces the following error               Plot::write: Tag Times in x/y is Protected. >>      The alternative is to redefine the function in terms of a single variable (i.e., replace all occurrences of `x/y` with a new variable `z`); however, I wish to avoid tedious manual redefinition if possible. **Edit:** As a simple example, consider the function $$f(x,y) = \frac{y^2}{x^2}\times\exp(x/y)+5\frac{x}{y}.$$ This function could be redefined as $$g(z)=\frac{\exp(z)}{z^2}+5z$$ where $z\equiv x/y$. One could redefine their function $f(x,y)$ as $g(z)$, but it would be more convenient if one could simply plot $f(x,y)$ against $x/y$ as a pseudo- univariate function.


title: rasterListContourPlot With PlotLegends in Mathematica 9

text: Jens Nöckel has write functions about (List) Contour Plots with rasterized shading in Mathematica: http://pages.uoregon.edu/noeckel/computernotes/Mathematica/rasterContourPlot.html It works well. But in Mathematica 9 it can not work with PlotLegends. How to modify? I can use Grid to combine a result of rasterListContourPlot with a legend, but this lost the link of the graphic with the legend.               rasgrap = rasterListContourPlot[RandomReal[1, {10, 10}], InterpolationOrder -> 3]     mylegend = BarLegend["LakeColors"];          Grid[{{rasgrap, mylegend}}]      rasterListContourPlot can be found in the above link.


title: Why do quote marks appear in output when saved with Save Selection As?

text: _Update:_ As Simon Woods astutely observed this problem only occurs when you select the cell _contents_ rather than the entire cell via the bracket. Those two tested this and reported, please check again selecting only the contents and see if the behavior appears. * * * In version 10 quote marks (i.e. `ShowStringCharacters`) appear in output when it is saved as an image using **Save Selection As...** :               CharacterRange["a", "z"]      Appearance in the Notebook: > {a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, > z} When saved as a PNG: ![enter image description here](http://i.stack.imgur.com/jWDIq.png) These quote marks do not appear in export from version 7, at least as I had it configured. ### Why do they appear? ### Can I keep them from appearing?


title: MapThread gives different results from ToExpression when trying to assign variables from a list

text: I have the following data set:               data = {{"Jakarta","Surabaya","Bandung"},{1,2,3}}      and I'd actually like to assign the numerical values to the categorical data so that Jakarta = 1, Surabaya = 2 and Bandung = 3. If I use `MapThread[Set, {ToExpression[data[[1]]], data[[2]]}]`it works fine but when I try to assign the variables individually I keep on getting error messages:               ToExpression[data[[1, 1]]] = data[[2, 1]]     Set::write: "Tag ToExpression in ToExpression[Jakarta] is Protected."      However, `ToExpression[data[[1,1]]` works fine May I know why my second approach is not working?


title: How can I return the color at a coordinate in an image?

text: I have an imported and cropped image:               TestPicture = Import["filepath.jpg"];     TestPictureCropped = ImageCrop[TestPicture, Min[ImageDimensions[TestPicture]]];      How can I specify a coordinate in the image and return the color of the nearest pixel to the coordinate? Thanks for any help!


title: How to modularize custom controls for Manipulate?

text: **Background:** My `Manipulate` programs are becoming (too) long. I want to split them up in to independent modules, if at all possible. Take this program as a prototype:               Manipulate[        {i, 2 i, 3 i},        {{i, i, "i="}, -11, 11, 1},        Initialization -> {i = 0}     ]      Suppose this is in fact a custom control with parameters {`label, begin, end, step}`                  {{i, i, "i="}, -11, 11, 1},      Ideally I would be able to code something like               Manipulate[         {i, 2 i, 3 i},         = = = = CustomSlider[i, " i= " , -11, 11, 1 ]  = = = =         Initialization -> {i = 0}     ]      **Question:** So the question is about how to get a function to work as a control in a `Manipulate`, if that is at all possible? Any Ideas or other suggestions to handle my need of refactoring my `Manipulate` code?


title: Filter a list generated with Tuples

text: I generated with               Tuples[{{1, 2, 3, 4, 5}, {1, 2, 3, 4, 14}, {1, 2, 3, 4}, {1, 2, 3, 4},             {1, 5, 6, 7, 8}, {5, 6, 7, 8, 10}, {5, 6, 7, 8}, {5, 6, 7, 8}}]       elements like `{1,2,3,4,5,6,7,8}`, with all the possible combinations but I want to exclude elements with the same numbers in different places like `{1,1,3,4,5,6,7,8}` or `{1,2,3,5,5,6,7,8}`. How can I do that in a simple way?


title: Tuples without self-loop

text: I have a simple question coincerning the _Mathematica_ function `Tuple`. Currently, I apply the following code               x = {1, 2, 3};     Tuples[x, 2]      Obviously I get: ![enter image description here](http://i.stack.imgur.com/osE2C.png) How can I delete all self-loops from this list, i.e., delete `{1, 1}, {2, 2}, {3, 3}`? Is there a built-in function?


title: Finding parameters for first positive root of solution to differential equation to be equal to a desired value

text: I have a differential equation with parameters. The objective is to vary the parameters such that the first positive root of the solution is equal to a desired value `obj`. As the equation is very involved, I decided that I'd use `user1084363`'s question in Find all roots of an interpolating function (solution to a differential equation), which inspired the first part of my solution. Currently, my solution is to manually manipulate the parameter `k` to obtain the desired solution. For example, if I'd like the first root of the equation to be `1.6`, I would use the following line of code               obj=1.6;     Manipulate[Flatten[Reap[NDSolve[     {1.09 x''[t] - k* x'[t] + 1.1759 Sin[x[t]] == 0,  x[0] == Pi/3, x'[0] == 0}, x, {t, 0, 50},      Method -> {"EventLocator", "Event" -> x[t],"EventAction" :> Sow[t]}]]][[2]]-obj,      {k, 0.01, 0.1}]      and manually vary the value of `k` till I obtain a value of zero. However, this is quite time consuming and I was wondering whether there was a way to automate the process. My first thought was to use `Root`, with `k` as the variable, but this doesn't work as of now due to the presence of the differential equation.


title: Is there any way to collect only variables with a specific power?

text: Suppose I've got this:               In[13]:= Expand[(a + b) (b + c) (c + a)]          Out[13]= a^2 b + a b^2 + a^2 c + 2 a b c + b^2 c + a c^2 + b c^2      And I want to collect only terms involving a^2. In other words, I want the following output:               a^2(b + c) + a b^2 + 2 a b c + b^2 c + a c^2 + b c^2      How can I do this? If I use the following:               Collect[%, a^2]      Then it simply groups terms into the highest power of a, even if the highest term is less than 2. So it results in this:               In[14]:= Collect[%, a^2]          Out[14]= b^2 c + b c^2 + a^2 (b + c) + a (b^2 + 2 b c + c^2)      Ideally, I would like to extend this further to collect all a^2, b^2, and c^2 in one expression. So that running my command would transform the original fully expanded expression into the following:               a^2(b + c) + b^2(a+c) + c^2(a+b) + 2 a b c      In a single command. It this possible?


title: Why is MapIndexed better than mapping over a range?

text: ### Background I'm working on an application in which I need to create and control two sets of locators. I know from reading the _Mathematica_ documentation and certain posts on _Mathematica_.SE that this means I can't base my application on a `Manipulate` expression. I have very little experience with interactive applications based on the dynamic objects that sit below `Manipulate`, so I searched "multiple locators" to see what I could learn. Quite a bit as it turned out. However, to keep this short, I'll just say I finally settled on a approach described by jVincent in his answer to this question. ### Question In my situation I am going to have one set of locators that are displayed as black squares and a second set displayed as red dots. The application will start out by showing no locators in its content pane. The user will create as many of each kind as he/she wants by clicking on buttons provided for the purpose. My adaptation of jVincent's code to my situation is as follows:                DynamicModule[{black = {}, red = {}},          Grid[{{            Framed@Graphics[               {Dynamic@MapIndexed[                   With[{i = #2[[1]]},                       Locator[Dynamic[black[[i]]],                         Style[\[FilledSquare], Black]]]&, black],                Dynamic@MapIndexed[                   With[{i = #2[[1]]},                      Locator[Dynamic[red[[i]]],                         Style[\[FilledCircle], Red]]] &, red]},               PlotRange -> {{0, 1}, {0, 1}}],            SpanFromLeft},            {Button["Add Black", AppendTo[black, RandomReal[1, 2]]],              Button["Add Red", AppendTo[red, RandomReal[1, 2]]]}}]]      ![two sets of locators](http://i.stack.imgur.com/VeEYm.png) The code works well. I have no complaints. One expression in the code surprises and intrigues me, however. This is:               {Dynamic@MapIndexed[         With[{i = #2[[1]]},             Locator[Dynamic[black[[i]]],               Style[\[FilledSquare], Black]]]&, black]      It's clear what this does: it creates a list of locators based on a list of locations (pairs of real numbers). It's clear that the `With` trick is needed to work around the `HoldFirst` attribute of `Dynamic`. What is clever and surprising -- I would have never thought of it -- is the use of `MapIndexed` to obtain the indexes that must be inserted into `black[[...]]`. What I would have thought of is:                {Dynamic@(With[{i = #},           Locator[Dynamic[black[[i]]], Style[\[FilledSquare], Black]]] &             /@ Range@Length@black)      which is much more banal but gets the job done. I wonder why jVincent chose `MapIndexed`? Is it really that more efficient than mapping over a `Range`? Or is there some other deeper advantage beyond my ability to fathom. I will say I don't think creating a range every time the expression in question is evaluated is much more expensive than what `MapIndexed` does to create the pairs it uses, but I could be wrong. I'm afraid I'm one those _Mathematica_ programmers who knows the value of everything but the cost of nothing (remembering an old joke made about Lisp programers).


title: Creating Recursive Sequences

text: Quite a simple question, I reckon, however, even quite an extensive search hasn't helped me. I want to define a recursively defined sequence that starts with defined `f[1]` and `f[2]` and distinguishes the input like so: `f[3k]`, `f[3k+1]`, `f[3k+2]`. Each of these would have its own expression. For further clarification, an example: $$ f(3n) = f(n)+1 $$ $$ f(3n+1) = f(n)+2 $$ $$ f(3n+2) = f(n)+3 $$ How does one go about that? I do know how to write simple recursion formulas on the level of Fibonacci or a factorial, it's only the distinguishing the input part. Also, this should be possible without any `if` statements, etc. Thanks for any help!


title: What technical obstacles prevent all Mathematica code compiling to C

text: The following represents an attempt at a very simple view of the levels in Mathematica code: ![enter image description here](http://i.stack.imgur.com/DB7Xi.png) We have had lots of questions about deployment and compiling Mathematica code to C. Some of these for speed, others for deployment. My interests go to deployment. While some have mentioned in various comments that compiling "symbolic code" presents a "hard" problem or that lots of Mathematica has lots of complicated things that make it difficult to compile, I don't have a clear grasp of what really stands in the way of Wolfram doing this. At some point all code that runs on a computer gets expressed at a machine code level. The C code to which some Mathematica code can compile clearly sits above this. The answers to How to specify Mathematica as a programming language? provide some context for thinking about all of this. I appreciate that Wolfram might have other business priorities. Those don't concern me in this question. To my mind the design of a programming language/tool as compiled or interpreted seems more like a business/marketing decision rather than a hard choice that completely locks a language into one or the other. Why should such a design choice limit a universal machine? I have wondered if everyone would regard such a question as this as out of scope here, but I do think someone could provide a specific answer and an answer would go a long way to understanding what we can do, what we could do, and perhaps what Mathematica will never enable us to do. So, simply and directly, I'd like to know what **technical obstacles** prevent all Mathematica code from compiling to C (byte-code would do too ;-)? ![enter image description here](http://i.stack.imgur.com/EdnEy.png)


title: Difference between Map[f[#] + g[#] &, {a, b, c}] and Map[f[x]+g[x]&, {a, b, c}]

text: Map[f[#] + g[#] &, {a, b, c}] vs Map[f[x]+g[x]&, {a, b, c}]      My question is: why is the output different?               Map[f[#] + g[#] &, {a, b, c}]          (* {f[a] + g[a], f[b] + g[b], f[c] + g[c]} *)      and               Map[f[x] + g[x] &, {a, b, c}]          (* {f[x] + g[x], f[x] + g[x], f[x] + g[x]} *)


title: Using a variable to tell Mathematica which existing variable to manipulate

text: I have an estimation routine I have coded up, I want now to do some tests on it where I pick a particular parameter and run the estimation for differing values of that parameter. What I want is to be able to specify the parameter name I am interested in changing at the top of the file and from then on just run a loop substituting different values into the chosen parameter. So for example I want something to the effect of               paramToVary = a;     paramValues = Range[0, 1, 1/20];          Do[MyEstimation[a, b], {paramToVary, paramValues}]      except this wont work as written, `paramToVary` takes the values of `paramValues` whereas I want these to be going into `a` instead. Any ideas on how to do this or alternative solutions?


title: Measure perimeter of black edge in Mathematica

text: I have a pattern like the one below. How could I measure the total length of the perimeter of the black/white edge? This would give me a measure of spatial frequency. Any tips would be great! Thanks! ![](http://i.stack.imgur.com/7jt0I.gif)


title: Why does Simplify with TimeConstraint return Removed[$$Failure]?

text: Bug existed in version 7 and is fixed in version 10.0.0 * * * I have a rather ugly _Mathematica_ expression (edit: shown below) that I would like to simplify with a time constraint; simplifying without a time constraint or memory constraint does not return as long as I've had the patience to wait (a couple of hours). The problem, which I have not seen before, is that when I execute               Simplify[ expression, TimeConstraint -> 3]      I get an output that contains things like > >     ...10000 E^(29599743/514000) Removed[$$Failure]... >   The only warning message I receive during execution is > >     Simplify::time: Time spent on a transformation exceeded 3.` seconds, >     and the transformation was aborted. Increasing the value of > TimeConstraint option may   >     improve the result of simplification >   Is this a known issue? I can't find anything about it. I expect when using `TimeConstraint` that I will not get the simplest answer back, but I also expect to get a usable answer (which this is not). If you think it would be helpful to see the expression I'm trying to simplify, I can post it here. The simplest example in which I've had this problem has a `LeafCount` of `651` and `ByteCount` of `17312`. **EDIT** On the suggestion of @JacobAkkerboom, I am adding some more information so someone can try to reproduce the effect. Here is a compressed version of `expression`. > > > expression=Uncompress["1:eJxTTMoPSmNiYGAoZgESATmlxWnMIB4rkAjJzE0thkhyAImgxJLM/LzEnMzEyQoMnsJAEUNzYzNDQ0MDS2NzUwMIgCgH6Q7IL08tKmYEslwzf////x/Vlsz/cCF0xSA+YUc84Q5hygwEKUV1PaZKT6CxnjxAEZgbwe5kJWQBJycDQ6bFLnV1NFdmcsEtRVEP8lAmEw4H4bNo/Xnbn5kNH34xYQ0OLBoMjgFtYmSE2YTP7MJrq5hIMlvgDobZ+DV8UAYGEzYNIG5AZuY/jKgn7Oqp3w4yeEoCRYxMTAxNDMyMkGMOWzIbTQODPg1AMjzBEG9YqMGYqc+AYdRoDA+NGAabUIk/8ghFiicfKBoNLUwQEQmOXmIdeyAW6liwiqo0RpjtzvnFGVjUg+QzL7ADLcCiEl+4gzWCEgo4GPxd0thQdGQm3sZRx5EQwqMJf0glfHgKCs7MIzKtIVSSktYg5SkzSRkrs/7wt/+eQkARYwNTQ3NTcwtDI7wNN4KJD57VCHtAnuvXf3CDDZZZsFhYiQhKUrItwcYiKI9kMoS80kINMLARhHVfff3nP7i9ixxeFAUbllQFKTHA3scaPqPlwNAoB9CSE85+DvakTrDUIBifoLaTJzeQMDQ2RU2ko2lnEKcdUkPkctGr/55iQBFjy9H+0XBIANgKDyxG/QQp/UKC3WiORRl/wdpYRyqd0GJptHU7YhMmeuuWzP4R9eq5QdBHJK/dDgDIdwSQ"]; >   As mentioned, I get the problem simply by running               Simplify[ expression, TimeConstraint -> 3 ]      (or any other value of `TimeConstraint` I've bothered to check) `expression` contains standard arithmetic operations, the constants `E` and `Pi`, the operations `Cosh` and `Sinh`, and three variables named `y`, `z`, and `OD` (and yes, I should make `OD` lower case, but it's hard for me to see optical depth as anything but capitals). **FURTHER EDIT** I have now reproduced the problem in an expression without a time constraint. The new `expression1` has a `LeafCount` of `186`, so it's not really that complicated. > > > expression1=Uncompress["1:eJxTTMoPSmNiYGAoZgESATmlxWnMIB4rkAjJzE0thkhyAImgxJLM/LzEnMzEyQoMnsJAEUNzYzNDQ0MDS2NzUwMIgCgH6Q7IL08tKmYEslwzf////x/Vlsz/cCF0xSA+QgaXI36KMDBkNmjAlMJdj6myeas0g6cQUMTY3MTU0NDc0ALhWhYC1oD1WZobGaCCzO03mRnAzq1E8wOaa1gJmc8P5JgaWpggG+7JiBwASEGDxXMHYoHBwAiUBauoSmOEWe+cX5yBRT1IPvMCO9ACLCrxhTdYIxdIGCTn70LYa4JAjq6JGSK0wZ4DxRuxnvugjOy5SoSTgzPziPQcQiUpnoOkTmaSojKz/vC3/5B0ZmBqaG5qbmFohDdXEEy48Lgl7AGZL6v/ZgYixQ4WCyvBviI5nRAsDkDJNZMh5JUWaoCBjSDs8quv//z35AGKWBhbWBqYQYKMvPCCJxc0WyH+hgYMM6YU8YFFMN0RKk/ABYenGFDEDCVbGKAkFDx+BAcXH6jQsLQ0QpRkhGPpJ9A7mV9IKFkE7gA1IEITpeDGWvQhhRuppSANiwoySzfio3woFPHklYIAG9m/tw=="]; >     Simplify[ expression1 ] >   This returns nearly instantly with three instances of `Removed[$$Failure]`. Since there is no `TimeConstraint` set here, I have no idea what the problem is. I submitted a help request to _Mathematica_ , and I'll let you know if they give any useful response. In the meantime, thoughts are most welcome. Especially if you can tell me if the problem exists (or not) in other versions of _Mathematica_. I am running 9.0.1 on Mac OS 10.8.3. Thank you to Mr. Wizard for verifying the problem exists in MMA 7 on Windows.


title: Expand expression into quotient of negative power series

text: I have a function T(z) ![enter image description here](http://i.stack.imgur.com/DN5ZX.png) and want to expand it to the following form: ![enter image description here](http://i.stack.imgur.com/Sc5lL.png) At the end I want to have a list of equations, which can calculate a0, a1, a2, b0, b1 and b2 with different values of h1, h2, w01, w02 and T. The variable z does not matter. In the code I replaced T(z) with f to not get confused.               f = (((1 - z^-1)/(1 + z^-1))^2 + 2*h1*Tan[(w1*T)/2]*((1 - z^-1)/(1 + z^-1)) + (Tan[(w1*T)/2])^2)/(((1 - z^-1)/(1 + z^-1))^2 + 2*h2*Tan[(w2*T)/2]*((1 - z^-1)/(1 + z^-1)) + (Tan[(w2*T)/2])^2)      At first I tried to expand f with the Mathematica-fuction _Series_ in the way it is described here: How to expand a function into a power series with negative powers?               Series[f, {z, Infinity, 2}]      But the result is not what I need.               (2 h1 tan((T w1)/2)+tan^2((T w1)/2)+1)/(2 h2 tan((T w2)/2)+tan^2((T w2)/2)+1)+((-4 h1 tan((T w1)/2)-4)/(2 h2 tan((T w2)/2)+tan^2((T w2)/2)+1)+(4 (2 h1 tan((T w1)/2)+tan^2((T w1)/2)+1) (h2 tan((T w2)/2)+1))/(2 h2 tan((T w2)/2)+tan^2((T w2)/2)+1)^2)/z+((4 (2 h1 tan((T w1)/2)+tan^2((T w1)/2)+1) (2 h2^2 tan^2((T w2)/2)-h2 tan^3((T w2)/2)+3 h2 tan((T w2)/2)-2 tan^2((T w2)/2)+2))/(2 h2 tan((T w2)/2)+tan^2((T w2)/2)+1)^3+(4 h1 tan((T w1)/2)+8)/(2 h2 tan((T w2)/2)+tan^2((T w2)/2)+1)+(4 (-4 h1 tan((T w1)/2)-4) (h2 tan((T w2)/2)+1))/(2 h2 tan((T w2)/2)+tan^2((T w2)/2)+1)^2)/z^2+O((1/z)^3)      I would like to have, more or less, one polynomial series in the enumerator and a second in the denominator. Thank you.


title: How can I draw a hyperboloid given its generatrix?

text: I want to see how a hyperboloid of revolution is generated by its generatrix, _i.e._ by rotating one (say the one passing point $(1,0,0)$ and $(0,1,1)$) of the skew lines around another (say the _z_ axis). My trial:               Manipulate[               Show[                    ParametricPlot3D[{Sqrt[t^2 + (t + 1)^2] Cos@\[Theta],                     Sqrt[t^2 + (t + 1)^2] Sin@\[Theta], 1 + t}, {t, -1, 1}, {\[Theta],                   0, \[Beta]}, BoxRatios -> {1, 1, 1},                    PlotRange -> {{-2, 2}, {-2, 2}, {0, 2}}],                     ParametricPlot3D[{1 - t, 1 + t, 1 + t}, {t, -1, 1}]], {\[Beta], 0.1,              2 \[Pi]}]      However, the generatrix $(1 - t, 1 + t, 1 + t)$ doesn't match the hyperboloid. So how can I do it correctly?


title: Daubechies scaling function

text: In _Mathematica_ in wavelet package with the following codes               Phi[x_, j_, k_] := 2^(j/2) WaveletPhi[DaubechiesWavelet[3], 2^(j) x - k]       _Mathematica_ computes `Phi` for various values of $x,j,k$. How does _Mathematica_ do this computation? My guess is cascade algorithm. If it is cascade algorithm, again how _Mathematica_ does this computation because until now i have seen cascade algorithm just for $j=0$ and $k=0$. If _Mathematica_ does not use cascade algorithm what is the algorithm?


title: How to plot contours in the faces of a cube

text: I'm trying to plot contours of a function `f[x,y,z]` on the faces of a cube as the example below, which represents the domain of this function. Is there a way to do it in _Mathematica_? The `ContourPlot3D` evaluates the contours along the domain and I just want them in the faces, colored by the function. ![enter image description here](http://i.stack.imgur.com/2Ggat.jpg)