Skip to main content

Posts

Showing posts from August, 2016

pattern matching - Split a Unicode string maintaining uppercase characters

I want to split a string according to a predefined set of substrings (lowercase), though the actual text can contain uppercase characters anyplace. The task is to find the matches, longer preferred over shorter (like "tt" over "t" hence the order of alt ) and to maintain upper/lowercase status. Since StringCases has a quirk not being able to correctly recognize some upper/lowercase characters (cf. here ), the solution is not trivial. The following code matches every element in alt correctly, though it also converts everything to lowercase: alt = "tt" | "t" | "a" | "á"; word = "TtattÁatT"; StringCases[ToLowerCase@word, alt] {"tt", "a", "tt", "á", "a", "tt"} The next one, while correctly maintains capital letters, fails to recognize "Á" as the uppercase version of "á" (or of a , see later). StringCases[word, alt, IgnoreCase -> Tru

syntax - Parentheses in pure functions: # & vs. ( # &)

I've been using Mathematica for years, and over time I have developed the habit of using: Select[data, (# == 1 &)] instead of Select[data, # == 1 &] I learned this by mimicking the style of more experienced users. I'm pretty sure that there are reasons for flanking the function with parentheses, but I'm not sure that I have seen a reason for why this is necessary or a good habit to get into. Would someone be able to comment? Answer It is a good habit to get into because you can often get tripped up by precedence rules (no one remembers everything!). For instance, PatternTest binds very tightly . See the difference between these two definitions: Clear@f f[_?(# == 2 &)] := Print@"foo" f[_] := Print@"bar" f[2] (* "foo" *) Clear@g g[_?# == 2 &] := Print@"foo" g[_] := Print@"bar" g[2] (* "bar" *) You can see that the second function does not behave as expected. Further inspection of the patterns wil

list manipulation - Scramble matrix under some condition

Assume I have a matrix. (mat = Partition[Range@9, 3]) // MatrixForm mat $=\left( \begin{array}{ccc} \color\red1 & \color\red2 & \color\red3 \\ \color\green 4 & \color\green5 & \color\green6 \\ \color{blue}7 & \color{blue}8 &\color{blue} 9 \\ \end{array}\right)$ I would like to scramble matrix mat colunmn-wise to generate all possible new matrix newMat under some condition. Conditions are: 1) Column elements of mat must stay in their column, i.e. 1st column of newMat must be one of the elements of the Permutations[{1, 4, 7}, {3}]={{1, 4, 7}, {1, 7, 4}, {4, 1, 7}, {4, 7, 1}, {7, 1, 4}, {7, 4, 1}} ; And similarly col2 $\in$ Permutations[{2,5,8}, {3}] and col3 $\in$ Permutations[{3,6,9}, {3}] . 2) 1st row of mat is {1,2,3} and thus 1st Row entries of newMat , should not contain any of element of this set= {{1, 2}, {1, 3}, {2, 3},{1,2,3}} i.e. pairs or triple. The same for row 2 and row 3. ............... .................. $\{1,4,7\}$ must stay in the 1s

plotting - How to place more than one ChartLabel in a BarChart

I have the following data: data = {{493, 416}, {1330, 1586, 1579, 1424, 1667, 1023, 665}, {1963, 428, 1797, 1832, 1697, 549, 526}, {1742, 2040, 1767, 1876, 1680, 668, 531}, {1751, 1565, 1577, 1693, 1691, 584, 523}, {1356}}; days = {{Saturday, Sunday}, {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}, {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}, {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}, {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}, {Monday}}; daysnum = {{1, 2}, {3, 4, 5, 6, 7, 8, 9}, {10, 11, 12, 13, 14, 15, 16}, {17, 18, 19, 20, 21, 22, 23}, {24, 25, 26, 27, 28, 29, 30}, {31}}; I want to plot a BarChart and to use more than one ChartLabel. I have created a handmade picture so that you can know what I mean. How can I create a ChartLabel at the x-axis and at the center and the top of the BarChart? Is it possible to color a ChartLabel according to the Bars colors? Answer The

Pass the list of variables into function to change their values

I'm new to Mathematica, so I don't really know, how do what I want, and I don't even know how to google it. Doing one Mathematica task for my supervisor, I faced the following problem. I need to write a function with such a syntax: f[{{var1, val1}, {var2, val2}, ..., {varn, valn}}] Here $var_i$ is a variable and $val_i$ is a value, which will be assigned to this variable. So this functions is a "parallel" analogue of the function Set[]. $var_i$ has already its value, and it can be evaluated (but it's not what I want). Number of variables $n$ can vary. Apparently, I need to set Hold attribute for $f$, but what should I do next? The first thing I've tried to do was just f[l_] := l[[All, 1] = l[[All, 2]] , but it didn't worked due to some part assignment restrictions. But if I try to extract variables like vars = l[[All, 1]] and than do vars = l[[All, 2]] , it doesn't work too, because vars just become replaced with values from l[[All, 2]] . I know,

plotting - Styling individual bars in a BarChart with grouped data

Consider the following: fakedata = RandomReal[{4, 9}, {5, 10}]; BarChart[fakedata, BarSpacing -> {0, 0.4}, ChartBaseStyle -> EdgeForm[], ChartStyle -> {{Magenta, Blue, Red, Orange, Green}, Opacity[#] & /@ Range[0.1, 1, 0.1]}] This is all well and good, but what I really want is the following, but grouped, so that the bars are opaque, the ticks come out how I want them, and the little space in between the groups (from the BarSpacing option) shows up: BarChart[Flatten@fakedata, BarSpacing -> {0, 0.4}, ChartBaseStyle -> EdgeForm[], ChartStyle -> Flatten@Outer[Blend[{{0, White}, {0.7, #1}, {1.1, Black}}, #2] &, {Magenta, Blue, Red, Orange, Green}, Range[0.1, 1, 0.1]]] Unfortunately if I create a "matrix" of colours as the value of the ChartStyle option, only the second list is picked up, and I get this: BarChart[fakedata, BarSpacing -> {0, 0.4}, ChartBaseStyle -> EdgeForm[], ChartStyle -> Outer[Blend[{{0, White}, {0.7, #1}, {1.1,

packages - MaTeX for Mathematica 9

There's a great package called MaTeX that @Szabolcs wrote which allows one to easily use LaTeX within Mathematica for things like axes labels. After hours trying out various other solutions I downloaded a Mathematica 10 trial and the MaTeX package. So easy, you should give it a try if you haven't. Anyway, it's not compatible with Mathematica 9 and I hoped somebody might have already tweaked the code for themselves to allow compatibility with their version 9? Maybe not, but you never know.

plotting - Extract ticks from plot

I am trying to extract the ticks settings of a plot to re-design the plot in a custom plot function (effectively, giving the plot a custom design but automatically). I think the ticks should be accessible using AbsoluteOptions . However, in this example: plot = Plot[Sin[x], {x, 0, 20}] xticks = First[Ticks /. First[AbsoluteOptions[plot, Ticks]]] the major ticks on the x-axis of the plot are at 0,5,10,15,20. xticks , on the contrary, looks like: { {0., 0., {0.00625, 0.}, {GrayLevel[0.], AbsoluteThickness[0.25]}}, {2.5, 2.5, {0.00625, 0.}, {GrayLevel[0.], AbsoluteThickness[0.25]}}, {5., 5., {0.00625, 0.}, {GrayLevel[0.], AbsoluteThickness[0.25]}}, {7.5, 7.5, {0.00625, 0.}, {GrayLevel[0.], AbsoluteThickness[0.25]}}, {10., 10., {0.00625, 0.}, {GrayLevel[0.], AbsoluteThickness[0.25]}}, {12.5, 12.5, {0.00625, 0.}, {GrayLevel[0.], AbsoluteThickness[0.25]}}, {15., 15., {0.00625, 0.}, {GrayLevel[0.], AbsoluteThickness[0.25]}}, {17.5, 17.5, {0.00625, 0.}, {GrayLevel[0.], AbsoluteThicknes

interpolation - How to restrict InterpolatingFunction to a smaller domain?

How can I reduce the domain of an InterpolatingFunction ? For example, consider if = FunctionInterpolation[x^2, {x, 0, 3}] . Is it possible to define if2 as the restriction of if to {x,1,2} ? Not only should the domain change, but if2 should not contain the information of if on $[0,1]$ and $[2,3]$. I've noticed the package InterpolatingFunctionAnatomy but I don't know what methods would be useful here. Answer you can do: FunctionInterpolation[if[x], {x, 1, 2}] which will actually sample the interpolation function and generate a new one. Alternately you can extract the data and use Interpolation Interpolation[ Select[ Transpose[{#[[3, 1]], Flatten[#[[4]]]}] , 1 <= #[[1]] <= 2 &]] &@if This second method may not exactly match your desired domain boundaries unless they happened to be sample points on the original interpolation. In both cases the result will not be precisely the same as the original interpolation. yet another thing you can do, which see

pattern matching - Calling Table with custom iterator

I often find myself in situations where I, for example, need to build a table for some expression, but want to set the number of points rather then the step size, so the code ends up looking like this lower = 0.2; upper = Pi^2; points = 100; Table[Sin[x], {x, lower, upper, (upper - lower)/(points - 1)}] // ListPlot I think that the typical Table syntax is much nicer in cases where we want to set the stepsize, but would much rather prefer to just think of the iteration specifications to be of the form {var,min,max,num} in these cases. Initially I though I would to this by just defining a function that takes this other iteration specification and returns the traditional equivalent, but since Table has holdall, you'd need to wrap everything in Evaluate which isn't pretty either example: myIter[L_]:={L[[1]],L[[2]],L[[3]],(L[[3]]-L[[2]])/L[[4]]} Table[Sin[x], Evaluate@myIter[{x, 0.2, Pi^2, 100}]] // ListPlot So to get around this I added a pattern to modify the way Table is called i

bugs - Cell @ CellGroupData[... in Cells family

Bug introduced in V10.4 or earlier and persisting through V11.3 Background This question originates from two already posted questions updated with further doubts I've faced. I deleted one and merged content here. Those issues are closely related, hard to separate and probably could be caused by the same internal features so I decided to make one question CellGroupData assumptions First of all, according to tutorial/TheStructureOfCells a cell of the form Cell[CellGroupData[...],...] is a valid Cell so in my opinion we should expect consistent behavior. CellGroupData second argument allows to specify which cells are visible. It could be Open , Closed , {cells indices} , or even {} to show no cell. That is not the case in general: Issues Inner CellGroupData expression are transparent to parent's visibility spec: CellGroupData[ { Cell[...] , Cell @ CellGroupData[...] , Cell[...] } , {2} ] I'd expect the structure above to show only and exactly what Cell @ Cel

graphics3d - Creating 3D dice

How to create an image of a 3D die from the 2D images? There is an example in the Documentation Center I tried but it doesn't work. Answer By using a cube with rounded corners, from this answer , and by applying the images as "stickers" onto the sides of this cube, the dice can be made to look a little bit more realistic. The black border does not translate well to a 3D visualization, so I hid it by fiddling with the vertex coordinates. faces = Import /@ { "http://i.stack.imgur.com/FdfMj.png", "http://i.stack.imgur.com/Qv7w6.png", "http://i.stack.imgur.com/WayOQ.png", "http://i.stack.imgur.com/mgjkA.png", "http://i.stack.imgur.com/qa5bK.png", "http://i.stack.imgur.com/T8szh.png" }; polygons = With[{eps = 0.01, k = 0.05}, { {{k, k, 0 - eps}, {k, 1 - k, 0 - eps}, {1 - k, 1 - k, 0 - eps}, {1 - k, k, 0 - eps}}, {{k, 0 - eps, k}, {1 - k, 0 - eps, k}, {1 - k, 0 - eps, 1 - k}, {k,

Formatting notebook files

This question has probably been asked before, but I cannot find it. Before I used mathematica I have worked with VisualStudio from MS (C++), Python (PyCharm), Java (Eclipse, NetBeans). In all that IDEs it is possible to format the source code, so that is easy readable. In mathematica I am looking for a solution which makes out of the following example code: Do[x = i; Do[y = j; Do[z = k;, {k, 1, 3}];, {j, 1, 3}];, {i, 1, 3}] the formatted code: Do[ x = i; Do[ y = j; Do[ z = k; , {k, 1, 3} ]; , {j, 1, 3} ]; , {i, 1, 3} ]

differential equations - NDSolve in NIntegrate function, numerical values as a symbolic variables

I'm trying to implement the following iterative scheme $g_{n+1}=g_n-\int_0^t\Phi(g_n) dt$ , where $g_n$ is a source term in a PDE and $\Phi$ is the solution of an adjoit problem associated to the PDE which use the solution of the PDE as final data. to this aim we need many steps : 0) Take $g_0=0$ . 1) Solve the PDE to obtain the solution $u(t,x,g_n)$ . 2) Solve the adjoint PDE to obtain $\Phi(t,x,g_n)$ . 3) Calculate $g_{n+1}(x)=g_n(x)-\int_0^t\Phi(t,x,g_n) dt$ , and go to 1). I tried this one nsol = NDSolve[{D[u[t, x], t] == D[u[t, x], x, x] + #, u[0, x] == 1, u[t, 0] == u[t, 1] == 1}, u, {t, 0, 1}, {x, 0, 1}] &; (* Solve the pde with source # *) nasol = NDSolve[{D[v[t, x], t] == -D[v[t, x], x, x], v[1, x] == First[u[1, x] /. nsol[#]] - umes[x], v[t, 0] == v[t, 1] == -0.05}, v, {t, 0, 1}, {x, 0, 1}] &; (* Solve the adjont problem *) Phi := NIntegrate[Evaluate[First[v[t, #2] /. nasol[#1[x]]]], {t, 0, 1}]&; (* Calculate the integral in step 3). Here is the problem !!

performance tuning - In a list of points, how to efficiently delete points which are close to other points?

Consider a list of points: pts = Partition[RandomReal[1, 10000], 2]; ListPlot[pts] I'd like to delete points so that the minimum distance between two points is 0.05. The following code does the job: pts2 = {pts[[1]]}; Table[If[Min[Map[Norm[pts[[i]] - #] &, pts2]] > 0.05, AppendTo[pts2, pts[[i]]]], {i, 2, Length[pts], 1}]; // AbsoluteTiming (* -> 1.35 *) ListPlot[pts2] But it becomes slow for large lists, probably because of AppendTo which does not know what type is going to come next. How could this be done more efficiently? Note: there is no uniqueness of the resulting list, but that's not a problem. Just for better referencing, let me give another formulation of the question: How to delete points in a neighbourhood of other points of a list? Answer The following is a much faster, but not optimal, recursive solution: pts = RandomReal[1, {10000, 2}]; f = Nearest[pts]; k[{}, r_] := r k[ptsaux_, r_: {}] := Module[{x = RandomChoice[ptsaux]}, k[Co

plotting - Placing a ContourPlot under a Plot3D

I would like to combine a 3-dimensional graph of a function with its 2-dimensional contour-plot underneath it in a professional way. But I have no idea how to start. I have a three of these I would like to make, so I don't need a fully automated function that does this. A giant block of code would be just fine. The two plots I would like to have combined are: potential1 = Plot3D[-3600. h^2 + 0.02974 h^4 - 5391.90 s^2 + 0.275 h^2 s^2 + 0.125 s^4, {h, -400, 400}, {s, -300, 300}, PlotRange -> {-1.4*10^8, 2*10^7}, ClippingStyle -> None, MeshFunctions -> {#3 &}, Mesh -> 10, MeshStyle -> {AbsoluteThickness[1], Blue}, Lighting -> "Neutral", MeshShading -> {{Opacity[.4], Blue}, {Opacity[.2], Blue}}, Boxed -> False, Axes -> False] and contourPotentialPlot1 = ContourPlot[-3600. h^2 + 0.02974 h^4 - 5391.90 s^2 + 0.275 h^2 s^2 + 0.125 s^4, {h, -400, 400}, {s, -300, 300}, PlotRange -> {-1.4*10^8, 2*10^7}, Contours -> 1

calculus and analysis - How to represent a continuous monotonic phase of Airy functions?

Note: In this question I am concerned only with real-valued variables and functions. DLMF, §9.8 Airy Functions, Modulus and Phase , formula $9.8.4$ defines the phase of Airy functions: $$\theta(x)=\arctan\frac{\operatorname{Ai}x}{\operatorname{Bi}x}.$$ The corresponding Mathematica definition is θ[x_] := ArcTan[AiryAi[x]/AiryBi[x]] Apparently, in this form the phase has a countable infinite number of jump discontinuities for negative values of $x$. I need to construct a Mathematica expression that represents a continuous monotonic version of the phase $\theta(x)$ (let's name it $\vartheta$), where all pieces between discontinuities are properly shifted and stitched, as shown on the following graph: One approach would be to get the derivative of $\theta(x)$: $$\theta'(x)=-\frac1\pi\frac1{\operatorname{Ai}^2 x+\operatorname{Bi}^2 x},$$ so that all information about jumps is lost, and then consider the definite integral: $$\vartheta(x)=\frac1\pi\int_x^\infty\frac{dz}{\operatorna

list manipulation - How to programmatically specify multiple iterators?

How to use Row[Table[{B[i],0,i},{i,0,2}],","] directly in Do command? I mean that the following command Row[Table[{B[i],0,i},{i,0,2}],","] gives {B[0], 0, 0},{B[1], 0, 1},{B[2],0,2} But, the following command returns the error "Do::nliter: Non-list iterator Row[Table[{B[i], 0, i}, {i, 0, 2}], ,] at position 2 does not evaluate to a real numeric value." Do[Print[B[0]+B[1]+B[2]],Row[Table[{B[i],0,i},{i,0,2}],","]] Of course, one can type instead by hand the following: Do[Print[B[0]+B[1]+B[2]],{B[0],0,0},{B[1],0,1},{B[2],0,2}] But, I feel that typing an output by hand again is not really an optimal method. Answer What you actually want is to create a Sequence from the Table to be used as your iterators. You can do this with Do[Print[B[0] + B[1] + B[2]], Sequence @@ Table[{B[i], 0, i}, {i, 0, 2}] // Evaluate] (*0 1 2 1 2 3*) Or, so you don't have to force evaluation, Do[Print[B[0] + B[1] + B[2]], ##] & @@ Table[{B[i], 0, i}, {

plotting - Where is the other half of my fourth degree Bézier curve?

Bug introduced in 10.0.0 and fixed in 10.2 When I enter the following command, half of the fourth-degree spline is missing from the graph (i.e. it doesn't touch the last point). Is this a bug in Mathematica or am I fundamentally misunderstanding something about Bézier curves? Manipulate[ Graphics[{BezierCurve[pts, SplineDegree -> 4], Dashed, Green, Line[pts]}, PlotRange -> {{-.5, 1.5}, {-.5, 1.5}}, Frame -> True], {{pts, {{0, 0}, {.5, 0}, {.5, .5}, {1, .5}, {1, 1}}}, Locator, LocatorAutoCreate -> True}] Here's a screenshot of the output: What makes me suspicious is that the same behavior shows up in Mathematica 's own help file on BezierCurve . Answer Since there is really something wrong with the BezierCurve , I made this work-around: Clear[bezierCurve]; bezierCurve[pts_] := First@ParametricPlot[ BezierFunction[pts, SplineDegree -> Length[pts] - 1][t], {t, 0, 1}] Manipulate[ Graphics[{bezierCurve[pts], Dashed, Green, Line[pts]}, PlotRange ->

front end - How to add named characters to Mathematica 10 or later?

Any news regarding this for Mathematica 12? It appears that native support for the Klingon alphabet has been removed from version 10: \[KlingonA] Syntax::tsntxi: "\"!(\[ KlingonA])\" is incomplete; more input is needed.!(\"\")" (Curiously "Klingon" remains in the $CharacterEncodings list.) As an exercise I wish to restore support of this character set but the underlying character system has been modified; specifically I cannot find the UnicodeFontMapping.tr file and I assume it no longer exists. Quoting TechnicalNotes.nb found in the Prerelease folder: On all systems, the Mathematica family of fonts (Mathematica*1-7) has been replaced with a single Mathematica font. On Windows, the single Mathematica font is no longer installed under "c:\windows\fonts". Instead, the user interface loads the font from the installation directory. For prerelease testing, we are interested in learning about any issues related to this change. UnicodeCh

plotting - Force VectorPlot3D to show One arrow

I am plotting a curl, and I only want VectorPlot3D to show one arrow, I have tried adjusting VectorPoints-> 1, but the plot show's no arrows at all. Is 2 the minimum VectorPoints I can have? If I cannot make use of VectorPlot3d in this way, how can I use the Arrow function to point in the direction of a vector field at a certain point? Thank-you Answer I don't think it's possible. I assume the vector scaling routine needs at least two vectors. You can fake it though: VectorPlot3D[{x, y, z}, {x, -1, 1}, {y, -1, 1}, {z, -1, 1}, VectorPoints -> {0.9999999 {0.5, 0.5, 0.5}, {0.5, 0.5, 0.5}}]

implementation details - How is pattern specificity decided?

Mathematica has a notion of pattern specificity, which is a partial ordering on patterns. The rules (e.g. DownValues , SubValues , etc) attached to a symbol are linearly ordered, with this ordering determined by the order in which the values and the specificity ordering. During evaluation, the rules are tried according to this ordering. As each rule is added, if its left hand side is more specific than the left hand side of an existing rule, it is inserted before the first such existing rule, and otherwise it is added at the end. This is briefly described in the Mathematica documentation, at http://reference.wolfram.com/mathematica/tutorial/PatternsAndTransformationRules.html . The general intention of pattern specificity is that it corresponds to the range of expressions that the pattern could match. The actual implementation of pattern specificity in Mathematica is much weaker, of course; this ideal notion of specificity would of course be undecidable. As an example, _?f and _?g ar

differential equations - No result from DSolve (evaluation keeps running)

No answer is given and no error message as well for this expression. DSolve[X*Y''[X] + (3*X^3 - 1) Y'[X] == C, Y[X], X] Hope someone can help me. I really appreciate that. Answer Try: sol = First@Block[{Integrate}, DSolve[X*Y''[X] + (3*X^3 - 1) Y'[X] == C, Y[X], X] /. {Integrate -> Inactive[Integrate]}] // Simplify $\left\{Y(X)\to \int _1^X\exp \left(\int _1^{K[3]}\left(\frac{1}{K[1]}-3 K[1]^2\right)dK[1]\right) \left(c_1+\int _1^{K[3]}\frac{C \exp \left(-\int _1^{K[2]}\left(\frac{1}{K[1]}-3 K[1]^2\right)dK[1]\right)}{K[2]}dK[2]\right)dK[3]+c_2\right\}$ Activate[sol] (* Integrate can't find closed solution *) Solution by Maple 2017.3 :

replacement rules from a pattern and a matching expression

(This seems to be a very basic necessity in a language having pattern-matching capabilities such as Mathematica, yet I struggled for many hours to find a common solution to this problem.) Suppose there is a pattern with some of its sub-elements named, and there is an expression that matches it. How do I generate a list of replacement rules that maps sub-element names into their values in the matching expression? E.g., patt=f_[_, s_, x___]; expr=ab[c, d, e, f]; mkMatchRules[expr,patt] >> {f -> ab, s -> d, x -> Sequence[e, f]} I have written a solution to this, collectAllPattVars[patt_] := Union[Map[Part[#, 1] &, Cases[patt, _Pattern, {0, Infinity}, Heads -> True]]]; mkMatchRules[expr_, patt_] := Module[ {pattVars = collectAllPattVars[patt], mkRhs}, mkRhs = Block[{$}, ReleaseHold[Hold[patt :> $] /. $ -> With[{$ = Map[List, pattVars]}, $]]]; If[MatchQ[expr, patt], MapThread[Rule[#1, If[Length[#2] == 1, #2[[1]], Sequence @@ #2]] &,

probability or statistics - Create a ProbabilityDistribution

I am trying to wrap my head around the function ProbabilityDistribution. For training purpose, I'd like to recreate the binomial distribution (without using it) so that the two code lines return the same output. PDF[BinomialDistribution[n, p], k] PDF[MyBinomialDistribution[n, p], k] My try I would construct this function more or less like this MyBinomialDistribution = ProbabilityDistribution[ Binomial[n, k] p^k (1 - p)^(n - k), {k, 0, Infinity}, {n, 0, Infinity}, {p, 0, 1} ] PDF[MyBinomialDistribution[n, p], k] but it obviously doesn't work! Thanks for your help! Answer You made several mistakes MyBinomialDistribution should be a function of n and p . There is only one variable k . n and p are parameters The correct definition is MyBinomialDistribution[n_, p_] := ProbabilityDistribution[Binomial[n, k] p^k (1 - p)^(n - k), {k, 0, n, 1}] PDF[BinomialDistribution[n, p], k] PDF[MyBinomialDistribution[n, p], k]

Convert C program using mathlink to WSTP

I have been using heavily a custom frontend to mathematica based on mathlink. I derived it from http://library.wolfram.com/infocenter/Demos/174/frontend.c?file_id=4692 . I just learned that mathlink was replaced by WSTP. Is there a dictionary to translate my old program to WSTP or maybe a WSTP version of the mentioned frontend example? Answer It is not necessary to translate anything. Mathematica 10 comes with two developer kits. One is called "WSTP" and one is called "MathLink". The only difference is in the naming conventions used by the functions. Simply use the one called "MathLink". It may be necessary to adjust one thing though: The default MathLink API version in Mathematica 10 is 4 . When compiling older programs, it's better to use the older version 3 API. Do this by compiling everything with -DMLINTERFACE=3 ( pass this command line option to the compiler ) and by linking against the libraries ending in i3 , not i4 . References: one and

undocumented - What's purpose of the Internal`ToEquivalenceClass

There is a kernel function Internal`ToEquivalenceClass .I don't know how to use it.There are some right example right to run Internal`ToEquivalenceClass[{1, 2, 3}] (* {1, 2, 3} *) Internal`ToEquivalenceClass[9] (* 9 *) Internal`ToEquivalenceClass[{1, 2., 3}, 9] (* {1, 2., 3} *) But the Internal`ToEquivalenceClass[{1, 2., 3}, {5, 6}] will give a error information And we can find a option of it. Internal`ToEquivalenceClass // Options {Heads -> True} Can anybody the usage and the intention about this function?

recursion - How can I express this recurrence function in Mathematica?

\begin{equation} r_{i+1}=r_{i}+V_{i}{\Delta}t \end{equation} Where \begin{equation} V_{i}=(0.01, 0.40) \end{equation} and ${\Delta}t$ is the difference in time. My implementation (this is for ${\Delta}t$ = 1): V = {0.01, 0.4}; list = List[Do[Print[V*t], {t, 1, 10}]]; * $RecursionLimit::reclim: Recursion depth of 1024 exceeded. * This generates the correct values but I can't change ${\Delta}t$ and the values aren't stored as a list (for use with ListPlot[...]). I have tried other implementations such as r[t_]=r[t]+V*t and r[t_+1]=r[t]+V*t but this didn't work. Answer With v = {0.01, 0.4}; you can define r[n_, dt_] := r[n, dt] = r[n - 1, dt] + v dt r[0, dt_] = {0, 0} Now Table[r[n, 1], {n, 1, 10}] {{0.01, 0.4}, {0.02, 0.8}, {0.03, 1.2}, {0.04, 1.6}, {0.05, 2.}, {0.06, 2.4}, {0.07, 2.8}, {0.08, 3.2}, {0.09, 3.6}, {0.1, 4.}} and Manipulate[ ListPlot[Table[r[n, deltat], {n, 1, 10}], PlotRange -> 20], {{deltat, 1, "Δt"}, 0, 5}]

Property assignment on a graph vertex using PropertyValue does not work inside a function

I created this function: AddStone[board_Graph, v_, s : white | black | empty] := PropertyValue[{board, v}, VertexState] = s This function should change the VertexState property of vertex v in graph board to one of white , black , or empty . That's simple enough, right? Then I created a graph: board = GridGraph[{5, 5}]; But then if I execute: AddStone[board, 8, white] I get an error: "Set::setraw: Cannot assign to raw object PropertyValue[{ ... ,8},VertexState]=white." where the "..." stands for an image of the graph board , which I obviously need not draw here. In the Documentation for PropertyValue it is stated that one can set properties this way. In fact, the code PropertyValue[{board, 4}, VertexState] = white does work without issuing any messages. Answer By default, a function evaluates it's arguments before plugging them into the function definition, so in effect AddStone is trying to set the property of the value of board instead of board i

performance tuning - Improving speed of code computing number of nonrepeating partitions

I need to answer the following for a number of parameters: How many ways can the integer $k$ be written as a sum of $n$ different integers ranging from $1$ to $m$? My initial attempt was the following function: NumberOfWays[k_, n_, m_] := Count[Map[Length, Map[DeleteDuplicates, IntegerPartitions[k, {n}, Range[m]]]], n]; This works, but becomes very slow as the parameters get big. I then thought I might do it using a generating function and attempted the following: GenFuncy[m_] := Product[1 + y*x^j, {j, 1, m}]; NumberOfWays2[k_, n_, m_] := Coefficient[GenFuncy[m], x^k*y^n]; Again this works, but surprisingly (to me) it is even slower. Is there any way I can speed these functions up, or maybe another faster way to do the calculation altogether? Answer This seems pretty quick, particularly on larger cases / larger k , e.g. 451, 29, 101 finishes in a few seconds on the loungebook. N.B. - I have not tested this exhaustively, just thrown together from ideas... If[Min[#3, #1

graphics - Interpolation on a regular square grid spanning a triangular domain

Bug introduced in 10.0 and fixed in 10.1 Context I am trying to identify contours of a function which is sampled on a cartesian grid within an irregular (triangular) region. Here is the data tab = ReadList[ "https://dl.dropboxusercontent.com/u/659996/tabOmega1.txt"] // Flatten[#, 1] &; It looks like this: Map[Point, Map[Most, tab], 1] // Graphics g3 = ListPointPlot3D[tab , PlotRange -> Full] Now Mathematica (v10.0.2) happily makes contours of it: g = ListContourPlot[tab , PlotRange -> Full] But if I try to produce an interpolation function out of it tabint = tab /. {rp_, ra_, v_} -> {{rp, ra}, v}; func = Interpolation[tabint, InterpolationOrder -> All]; It produces unrealistic numbers func[1, 2] (* 37.9231 *) Indeed the interpolation is completely off: Plot3D[func[x, y], {x, y} ∈ dg] Question How can I get Mathematica to interpolate properly though this evenly sampled data on an irregular region? Attempt Following this post I can use func = Neares