Skip to main content

Posts

Showing posts from April, 2014

interpolation - Extracting the function from InterpolatingFunction object

I've used Interpolation[] to generate an InterpolatingFunction object from a list of integers. f = Interpolation[{2, 5, 9, 15, 22, 33, 50, 70, 100, 145, 200, 280, 375, 495, 635, 800, 1000, 1300, 1600, 2000, 2450, 3050, 3750, 4600, 5650, 6950}] I'm using that to generate values like f[27] , f[28] , ... Is there any way to print or show the function used by Mathematica that produced the result of f[27] ? Answer Here is the example from the documentation adapted for the OP's data: data = MapIndexed[ Flatten[{#2, #1}] &, {2, 5, 9, 15, 22, 33, 50, 70, 100, 145, 200, 280, 375, 495, 635, 800, 1000, 1300, 1600, 2000, 2450, 3050, 3750, 4600, 5650, 6950}]; f = Interpolation@data (* InterpolatingFunction[{{1, 26}}, ] *) pwf = Piecewise[ Map[{InterpolatingPolynomial[#, x], x InterpolatingPolynomial[Last@#, x]] &@Partition[data, 4, 1]; Here is a comparison of the piecewise interpolating polynomials and the interpolating function: Plot...

distributions - How to generate random points in a region?

The Mathematica 10 documentation was updated for FindInstance adding support for regions. In my use case, I'm trying to sample points in a set of disks: region = DiscretizeRegion@RegionUnion@Table[Disk[RandomReal[4, {2}], RandomReal[1]], {10}] FindInstance[{x, y} ∈ region, {x, y}, Reals, 2] // N However the above code fails and generates the following error: FindInstance::elemc: "Unable to resolve the domain or region membership condition {x,y}∈" What's going wrong here? Answer There are already good answers, but I'm going to improve the performance, generalize to any region in any dimensions and make the function more convenient. The main idea is to use DirichletDistribution (the uniform distribution on a simplex, e.g. triangle or tetrahedron). This idea was implemented by PlatoManiac and me in the related question obtaining random element of a set given by multiple inequalities (there is also Metropolis algorithm, but it is not suitable here). The code is ...

How to generate an input cell?

For example I have a block of code Module[{}, a=1;b=2;...] I want to have a function called gencode , so when I run gencode , it will generate an input cell which contains this block of code just like I type them by hand. How to write this gencode ? Answer CellPrint plus ExpressionCell are tools for generating cells. They do not hold their arguments, so some control of evaluation is necessary ( Defer ). [Update: In response to Szabolcs' comment, may as well let options be passed.] ClearAll[gencode]; SetAttributes[gencode, HoldAll]; gencode[code_, opts : OptionsPattern[Cell]] := CellPrint@ExpressionCell[Defer@code, "Input", opts]; Examples: Or following Szabolcs: gencode[Module[{a, b}, a = 1; b = 2; a + b], GeneratedCell -> False]

export - Exporting graphics without X server

I have a Mathematica installation on a Linux server that is intended to be used for batch processing. Some of the things that will be processed will include rendering of graphics. However, if I use Export["/file/name.gif", graphicsobject] , Mathematica wants to connect to an X server. Yes, I can run Xvfb or similar, but this seems like inordinate overkill. Is this really the only option? Is there no way to get Mathematica to render to GIF (or PNG, or BMP, or TIFF, or whatever; I don't really care) without having an X server running? Update: I just ran this small program without an X server available: s=Graphics[Sphere[]]; Do[ Print[fmt]; TimeConstrained[ Export["/tmp/img-" fmt, s, fmt], 10, Print["Timeout"] ], {fmt, $ExportFormats} ] and found that the only files created that contained something other than just the text Graphics[Sphere[0, 0, 0]] or -Graphics- were DXF and JVX, both of which were very simple renderings with...

How to change default settings of cell formatting?

I find font size of Text cells too small and I like displaying them with background colour... I've read this question and learned about Menu/Format/Option Inspector... where I managed to change font size, but it affects all cells. I would like to change separately Text, Input and Output formatting and to save these settings as default for displaying any notebooks. So, when I next time select a cell, then go to Menu/Format/Style and choose Text or Input or Output; it applies my default formatting for Text, Input, Output or anything else. Is this supported with Option Inspector or some other tool?

plotting - Implementing GeoCallout?

Building off of a related question , I'm looking for a robust way of using Callout s for multiple locations in Geography. For example, I want to plot cities and their names with arrows and text: data = CloudGet @ CloudObject[ "https://www.wolframcloud.com/objects/cb8f1216-74dd-463e-85a4-e976b6fd3fd4"]; GeoListPlot[MapThread[ Callout[#1, #2, CalloutMarker -> "Arrow", "CalloutStyle" -> Red] &, data], GeoBackground -> "ReliefMap", GeoRange -> "World" ] Clearly, Callout 's are not supported in GeoGraphics (and don't issue any warnings if you didn't know that). However, my approach is to fake it by using Callout 's in a ListPlot and overlay on top of a blank GeoGraphics map background: bg = GeoListPlot[{}, GeoBackground -> "ReliefMap", GeoRange -> "World"]; plain = {Reverse@*First /@ data[[1]], data[[2]]}; Overlay[{bg, ListPlot[MapThread[ Callout[#1, #2, ...

string manipulation - Convert ASCII Characters to Mathematica Input Form

I have the following pure ASCII character list: list ={"a", "\\:1d62", "\\:2081", "\\[Beta]", "\\:2081", " ", "+", " ", \ "a", "\\:1d62", "\\:2082", "\\[Beta]", "\\:2082", " ", "+", " ", ".", \ ".", ".", " ", "+", " ", "a", "\\:2099", "\\:2081", "\\[Beta]", \ "\\:2099", " ", "=", " ", "b", "\\:1d62"} How can I convert it to Mathematica Input Form ? I tried: FromCharacterCode[ToString[#, "ASCII"] &/@list But it does not work. Answer As @Rohit suggests in the comments, one possibility is to use ToExpression . However, to be safer, one might want to use Symbol instead. So: Replace[ list, a_ /; StringLength[a] > 1 :> Check[SymbolName @ Symbol[a]...

bugs - Incompatibility of Row and TeXForm

Bug introduced in 9.0 and persisting through 11.0 Update: Since no one has been able to give a reason for this change in behavior or provide a solution I am tagging this as a bug. Please report it to Wolfram Support if this affects your use of Mathematica . In Mathematica 7 Row and TeXForm work harmoniously: {x^a, Sqrt@b, ArcSin[c]} // Row // TeXForm x^a\sqrt{b}\sin ^{-1}(c) As LaTeX: $x^a\sqrt{b}\sin ^{-1}(c)$ Unfortunately this is broken in more recent versions. Mathematica 10 returns: TeXForm::unspt: TeXForm of TemplateSlotSequence[1,] is not supported. >> This error was reported in version 9 as well. An attempt at a workaround is to substitute Grid for Row but the LaTeX code generated is different: {{x^a, Sqrt@b, ArcSin[c]}} // Grid // TeXForm And it formats differently: $\begin{array}{ccc} x^a & \sqrt{b} & \sin ^{-1}(c) \\ \end{array}$ The documentation for TeXForm indicates that it is extensible with rules for Format but I could not find a rule that worke...

graphics - How to fit the curve that this lines made? The length of lines are all fixed

but how to deduce it ? Thank you .

documentation - How has Hash changed in 11.3?

There are already few topic related to Hash[_String] : How does Hash calculate hash for strings? Incorrect calculating Hash SHA256 But it looks like changes are more severe: Hash[{}] returns the same in V11.2 and V11.3, but e.g. Hash[{}, "MD5"] does not. And I don't see an explanation in documentation: What is the complete list of changes? How to make old code compatible with those changes? Answer There is already discussion about String and ByteArray in the linked previous Q & A , so I'll comment a bit about general expressions. This only concerns the named hash algorithms like "MD5" or "SHA" etc. The single argument form Hash[expr] , which is equivalent to Hash[expr, "Expression"] is completely separate and based on the internal representation of expr . It has not been changed for 11.3. Using @Kuba 's example of a very simple expression, in 11.3 we have the following new hash value Hash[{}, "MD5"] (* 682444578...

numerical integration - Can you use "MaxErrorIncreases" when numerically integrating over a region?

How do you pass the option "MaxErrorIncreases" to NIntegrate[] when integrating over a region? Taking a simple ;) example from Problems with NIntegrate, errors NIntegrate::slwcon and NIntegrate::inumri : Ω = ImplicitRegion[ 0 (15 (23 fi = NDSolve[{ Derivative[0, 2][φ][x, y] + Derivative[2, 0][φ][x, y] == NeumannValue[0, x == 0 && -18 x == 34 && -18 20 15 12 DirichletCondition[φ[x, y] == 1.5, 0 DirichletCondition[φ[x, y] == 0.4, 23 φ, {x, y} ∈ Ω, "ExtrapolationHandler" -> {0 &, "WarningMessage" -> False}]; Then on this integral we get a warning that suggests raising "MaxErrorIncreases" : ClearAll[ff]; dxφ = Derivative[1, 0][φ] /. First[fi]; ff[x_?NumericQ, y_?NumericQ] := Quiet@Check[dxφ[x, y], 0.]; NIntegrate[ff[x, y], {x, y} ∈ Ω] NIntegrate::eincr: The global error of the strategy GlobalAdaptive has increased more than 2000 times....Increasing the value of the Glob...

bugs - Incorrect result while using SemanticImport for CSV file import

I might use this incorrectly. I want to use a .csv file that (as list) looks like: {{"Group", "data 1", "data 2"}, {"a", 1, 5}, {"a", 2, 3}, {"a", 4, 5}, {"b", 8, 9}} Now I want this as a Dataset , i.e. I try and import it with SemanticImport and would want to have as result However, I can't get it to work with SemanticImport . I can use the following code, but hoped SemanticImport would basically replace this: Import["testdata.csv"]; dataDim = Dimensions@data; a1 = Transpose@ Table[data[[1, i]] -> data[[1 + j, i]], {i, dataDim[[2]]}, {j, dataDim[[1]] - 1}]; testFullAss = Association[a1[[#]]] & /@ Range[dataDim[[1]] - 1]; Dataset[testFullAss] Answer Using SemanticImport["testdata.csv"] I get on the exported data you provided which is the dataset you seek. But SemanticImport has been reported to have a few bugs, maybe that's why you can't get it to work. In the mean...

plotting - Graphically representing error in a Riemann Sum

I am trying to graphically represent the error in a Riemann sum. My current code looks like: Show[DiscretePlot[Log[t], {t, 1, 10, 1}, ExtentSize -> Left, PlotMarkers -> "Point"], Plot[Log[t], {t, 1, 10}]] I would know like to plot JUST the curve-linear triangles above the plot of ln(x) that represents the error in the Riemann Sum. Answer If only visual matters - then use filling to mask everything under the curve: Show[DiscretePlot[Log[t], {t, 1, 10, 1}, ExtentSize -> Left, PlotMarkers -> "Point"], Plot[Log[t], {t, 1, 10}, Filling -> Bottom, FillingStyle -> White]] You can also get crafty to show with color varying size of error triangles. And also give a vague opaque hint on underlying vertical rectangles - as their discreteness is the reason for error: Show[ DiscretePlot[Log[t], {t, 1, 10, 1}, ExtentSize -> Left, ExtentMarkers -> {"Filled", "Empty"}, ColorFunction -> "Rainbow", ExtentE...

notebooks - Deleting Print results

While playing around with $Pre and $Post I created this very annoying piece of code: $Post = If[# =!= Null, (Print@"Are you sure you want to know the result?"; Print@Row@{Button["Yes", Print@#], Button["No", Null]}), Null] &; I have not yet found a use for it (other than possibly playing pranks on Mma newbies) but it led me to the following question: How can one delete a certain cell that was created by Print (i.e. without selecting the cell manually)? And furthermore, how can one create a button that deletes itself upon being clicked (still evaluating the action)? Ultimately I want the button to delete both itself and the "Are you sure..." cell. I found out in the documentation that PrintTemporary objects can be deleted using NotebookDelete . Is there a similar way for Print cells? I think something similar to what I want could be done using ChoiceDialog and the like, but I'm really interested in deleting the Print cells. Answ...

coding style - Can one identify the design patterns of Mathematica?

... or are they unnecessary in such a high-level language? I've been thinking about programming style, coding standards and the like quite a bit lately, the result of my current work on a mixed .Net/Mathematica project. In object-oriented programming, people talk a lot about "design patterns" , essentially, standard ways of approaching particular problems (There's even a conference ). The idea has been extended to other domains as well, e.g. for personal productivity . But some people argue that identified "patterns" are really just a sign that the language in question isn't abstracted enough. So what, if any, are the patterns of Mathematica programming? Or are they not necessary? Answer Leaving the general discussion on design patterns for some later time, I will try to collect a comprehensive information on some specific design patterns / idioms, one pattern per post. This time it will be memoization Basic memoization What is memoization Memoizatio...

graphics - Generating visually pleasing circle packs

EDIT: (my conclusion and thank you note) I want to thank you all guys for this unexpected intellectual and artistic journey. Hope you had fun and enjoyed it the same as I did. I would like to generate a circle pack that mimics this: (don't pay attention on numbers, and colors at all, at the moment I am interested in circle positions and radii only) or this: I am new in Mathematica, could you give me some guidance? Thnx. EDIT: The question was strictly for planar case (and remains so), however I see @Jacob Akkerboom in his answer added a solution for 3D generalization (thanks!), and, speaking of that, I just want here to bring to your attention this picture: EDIT 2: There are some applications of circle packing in irregular shapes, like this: (author Jerome St Claire, handpainted) ... and a font called Dotted: (author Maggie Janssen) ... and some logos: ... garden design: ... infographics: ... and these hypnotic images: (from percolatorapp ) Answer replacing RandomReal function...