Skip to main content

Posts

Showing posts from April, 2016

graphics - How to generate a closed B-spline curve?

I wrote a function called deBoor using the Cox-de Boor algorithm to generate a B-spline curve. (*Search the index of span [ui,ui+1)*) searchSpan[knots_, u0_] := With[{max = Max[knots]}, If[u0 == max, Position[knots, max][[1, 1]] - 2, Ordering[UnitStep[u0 - knots], 1][[1]] - 2] ] (*The definition of α coefficient*) α[{deg_, knots_}, {j_, k_}, u0_] /; knots[[j + deg + 2]] == knots[[j + k + 1]] := 0 α[{deg_, knots_}, {j_, k_}, u0_] := (u0 - knots[[j + k + 1]])/(knots[[j + deg + 2]] - knots[[j + k + 1]]) (*Implementation of de Boor algorithm*) deBoor[pts : {{_, _} ..}, {deg_, knots_}, u0_] := Module[{calcNextGroup, idx = searchSpan[knots, u0]}, calcNextGroup = Function[{points, k}, Module[{coords, coeffs}, coords = Partition[points, 2, 1]; coeffs = {1 - #, #} & /@ (α[{deg, knots}, {#, k + 1}, u0] & /@ Range[idx - deg, idx - k - 1]); {Plus @@@ MapThread[Times, {coords, coeffs}], k + 1}] ]; Nest[calcNextGroup[Sequence @@ #] &,

special functions - Using NSolve for Elliptic Equations over Fundamental Parallelogram in Complex Plane

I'm considering solving elliptic functions over a fundamental domain of the torus with half-periods $\omega_{1}=\pi/2$ and $\omega_{2} = \pi \tau /2$, where $\tau$ is the modular parameter of the torus. The equation I want solutions of is: $$\wp(u \, | \, \omega_{1}, \omega_{2})= -\frac{1}{3}E_{2}(\tau)$$ which definitely must have two solutions $u$ in the parallelogram for all $\tau$. Or perhaps one solution or order 2. My main issues are not knowing how to effectively parameterize the fundamental parallelogram in Mathematica, as well as my NSolve routine not working properly. My idea was to fix $\omega_{1}$ and $\omega_{2}$ and then have mathematica consider the domain: $$\{x\omega_{2} + y \omega_{2} \, | \, 0 \leq x \leq 2, -1 \leq y \leq 1\} \subseteq \mathbb{C}.$$ I think this is OK, but I'm also worried it might be a bad parameterization causing my NSolve issues. The code I have is: tau = 0 + (3/2)*I; w1 = Pi/2; w2 = Pi*tau/2; inv = WeierstrassInvariants[{w1, w2}]; E2[t_]

list manipulation - Can ReplacePart be sped up?

Test case: data = RandomReal[1, {1000, 1000}]; pos = RandomInteger[{1, 1000}, {5*10^5, 2}]; r1 = ReplacePart[data, pos -> 0]; // AbsoluteTiming (data[[##]] = 0) & @@@ pos; // AbsoluteTiming data == r1 (* {3.433196, Null} {1.892108, Null} True *) The similar matlab code only takes about 0.16 second: tic; A=rand(1000,1000); pos= randperm(5e5); A(pos)=0; toc; (*Elapsed time is 0.166717 seconds.*) I am looking for a more efficient way. Answer I think it's worth noting that the two random position codes you list aren't the same. If you want to do something like randperm in Mathematica you should use RandomSample . In addition to this, what you are trying to do is effectively to simultaneously address a large number of positions in the matrix. In Mathematica I do not believe you can do this for matrixes and other things with larger dimensions, however for a single list you can do this with speeds similar to MATLAB: SeedRandom[322112432] data = Flatten[RandomReal[1., {1000, 1

functions - How to prove an expression by method of mathematical induction?

I want to prove the expression $$1^2 + 2^2 + 3^2 + \cdots + n^2 = \dfrac{n(n+1)(2n+1)}{6}$$ by method of mathematical induction with Mathematica, but I do not know how to start. How do I tell Mathematica to do that? Answer f[n_] := (n (n + 1) (2 n + 1))/6 Easy. The proof by induction involves two steps: Prove the relation for a starting value. We'll take n=1. So f[1] must equal 1^2: f[1] == 1 True Prove that, if the relation holds for a certain n, it also holds for n+1. In this case, for n+1 we have to add (n+1)^2 to the sum you get for n: f[n] + (n + 1)^2 == f[n + 1]// FullSimplify True

calculus and analysis - SumConvergence difficulty

Backslide introduced in 9, persisting through 11.2. Consider the series $\sum_{n=1}^\infty\sin\frac{50}{n^2}$. The terms are eventually positive. ListPlot[Table[Sin[50/n^2], {n, 1, 40}]] Which produces this image. Therefore, I was able to use the Limit Comparison Test. a[n] := Sin[50/n^2] b[n] := 50/n^2 Limit[a[n]/b[n], n -> ∞] Which produced an answer of 1. Because this limit is strictly positive and $\sum_{n=1}^\infty\frac{50}{n^2}$ is convergent ($p$-series with $p=2>1$), by the Limit Comparison Test, the series $\sum_{n=1}^\infty\sin\frac{50}{n^2}$ is also convergent. However, SumConvergence[Sin[50/n^2], n] does not produce a "True" response. I also tried: Assuming[n >= 10, SumConvergence[Sin[50/n^2], n]] Which was also unsuccessful. Is this something I should report?

segmentation - How to segment a textured image using Gabor Filters?

I am following a matlab implementation of texture segmentation using Gabor filters. My test image ( img ) is from Brodatz and as follows: Below is what I have done so far. {nrows, ncols} = ImageDimensions[img]; wavelengthmin = 4/Sqrt[2]; wavelengthmax = Sqrt[nrows^2 + ncols^2]; n = Floor[Log2[wavelengthmax/wavelengthmin]]; wavelength = Table[{2, 2} 2^i, {i, 0, n - 2}]; deltaTheta = Pi/4; orientation = Table[i, {i, 0, Pi - deltaTheta, deltaTheta}]; gabormag = Flatten[Table[ ImageAdjust[ GaborFilter[img, 1, wavelength[[i]], orientation[[j]]]], {i, 1, Length@wavelength}, {j, 1, Length@orientation}]]; gaborWavelength = Flatten[ConstantArray[ Table[Norm[wavelength[[i]]], {i, 1, Length@wavelength}], Length@orientation]]; K = 3; gabormagfiltered = gabormag; Table[ sigma = 0.5 gaborWavelength[[i]]; gabormagfiltered[[i]] = GaussianFilter[gabormag[[i]], K sigma] , {i, 1, Length@gabormag}]; After this, I am stuck on how to use this filtered images to get the fina

Partition string into chunks

This seems like it should be trivial, but how do I partition a string into length n substrings? I can of course write something like chunk[s_, n_] := StringJoin[#] & /@ Partition[Characters[s], n] so that chunk["ABCDEF",2] -> {"AB","CD","EF"} but this appears unnecessarily cumbersome. Answer Try this: StringCases["ABCDEFGHIJK", LetterCharacter ~~ LetterCharacter] {"AB", "CD", "EF", "GH", "IJ"} or for more general cases (i.e. not just for letters, but any characters, and for any partition size): stringPartition1[s_String, n_Integer] := StringCases[s, StringExpression @@ Table[_, {n}]]; It is more elegant though to use Repeated (thanks rcollyer): stringPartition2[s_String, n_Integer] := StringCases[s, Repeated[_, {n}]]; stringPartition2["longteststring", 4] {"long", "test", "stri"}

plotting - Interactively extract points from a plot (ListPlot or SmoothDensityHistogram)

Is there a way to dynamically define a polygon on a plot (I'm working with ListPlot and SmoothDensityHistogram ) to select a cluster of interest, and give the positions of those points in the original list of data? I'd appreciate any help! Here's just an example set of points: x = { {RandomReal[{0, 5}, 20], RandomReal[{4, 4.5}, 10]}, {RandomReal[1, 20], RandomReal[{1.5, 2}, 10]} }; points = Transpose[Join @@@ x] ~RandomSample~ 30; SmoothDensityHistogram[points, ColorFunction -> "TemperatureMap"] ListPlot[points, PlotRange -> {{0, 5.5}, {0, 2.5}}] Answer This is basically the same as what b.gatessucks is doing. The main addition is that I've put all the locators in one list. To add vertices to the polygon you just click somewhere on the graph. I've also added a reset button and a button that prints the indices of the points inside the polygon which makes it easier to copy. points = RandomSample[ Transpose[{Flatten[{Rand

plotting - Making a plotted curve interactive

Is it possible to make a plotted curve interactive in the sense that when hovering over it a line is drawn from the "hovered" point to one (or both) of the axes. I did do my homework, I just can't figure it out. Edit: Let's say I plot this curve: Manipulate[Plot[Sin[a x],{x,0,Pi}],{a,1,5}] Whenever the mouse hovers over a point on the curve a line is drawn from that point to the x-axis.

Joining strings in lists of strings

I have a list: lis = {{"abc","def","ghi"},{"jkl","mno"}} and wish to get: res = {"abc def ghi","jkl mno"} This: Table[StringJoin[lis[[i]]], {i, Length[lis]}] doesn't produce the desired " " between the original elements in lis . As always, thanks for suggestions! Answer You can use StringRiffle : StringRiffle /@ lis {"abc def ghi", "jkl mno"}

fonts - Greek letters do not export correctly

Here is a simple plot P0 = Plot[x, {x, -7, 7}, Frame -> True, FrameLabel -> {"Ω", "Y"}] Then I want to export as .pdf it using E0 = Export["test.pdf", P0, "PDF"]; but the Greek capital letter Omega does export correctly and at its place I get an empty little square. If I export it as an .eps I get nothing, not even the little square. Only when I export it as .jpg everything is OK. I'm using MMA v 9.0 in Win XP SP3 but this is irrelevant because I tried it in different versions and OSs and the problem remains. Any ideas?

Want to compute the permutations of {1, 2, ..., 11} with only 3 GB of memory

There is another way to calculate Permutations [{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}] without triggering an error, I have 3 GB of RAM with WIN 7 Edit: This short code is the one that broke my head for a while, are 11 variables that must meet a very specific condition, their difference must be 1. either can take the 11 values, hence all permutations, this code is an adaptation of another code I saw here, which helps me to what I need. juan[{a_, b_, c_, d_, e_, f_, g_, h_, i_, j_, k_}] := Abs[Differences /@ ({{a, b}, {a, c}, {b, c}, {b, f}, {b, e}, {c, e}, {c, f}, {c, g}, {d, f}, {d, g}, {e, b}, {e, a}, {e, f}, {e, i}, {e, h}, {f, g}, {f, j}, {f, i}, {f, h}, {g, i}, {g, j}, {h, i}, {h, k}, {i, j}, {i, k}, {j, k}})] // Flatten *(*per = Permutations[Range@11]*) (this line is calculated as 799 consecutive files in HD thanks to the collaboration of rasher) (*per=Import["C:\\Users\\M\\Desktop\\per.txt"]*)(as I upload the files sequentially and that its securities are

pdf format - Custom fonts show as boxes when opening Mathematica-made PDFs with Illustrator

If I export a PDF from Mathematica, then open it with Illustrator, the font glyphs will sometimes appear as boxes, depending on what font was used. Why does this happen? Is there a workaround? I experimented with several fonts in Graphics[{Text[Style["text", FontFamily -> "Arial"]]}] . Helvetica, Times, Helvetica Neue, Zapfino, Futura all appeared as boxes. Calibri, Arial, Georgia, Baskerville, Times New Roman all appeared correctly. What is the difference between these? All are accessible to Illustrator otherwise. I have already read Edit a Mathematica plot in Illustrator, missing font problem . I have copied the Mathematica fonts to to ~/Library/Application Support/Adobe/Fonts and since then glyphs appear fine in Illustrator if I don't specify a custom font at all . The difference between this question and that one is that now I am asking about the situation when custom (non-default) fonts are used. The fonts which don't work are all already accessibl

list manipulation - Finding Local Minima / Maxima in Noisy Data

I'm trying to find local minima / maxima in noisy data, consisting of data values taken at certain time intervals. Ideally, the function should take a pair of lists (one containing time values and one containing observed data values) and return the coordinates of the maxima and minima. An example of the data is found below: temptimelist = Range[200]/10; tempvaluelist = Sinc[#] &@temptimelist + RandomReal[{-1, 1}, 200]*0.02; While the questions here , here and here have a good range of answers, they don't fit with my requirements since (as far as I can see) they determine whether data is a local maximum / minimum by comparing it with the adjacent values. If I apply such an algorithm, my extrema will be identified as follows: What I've done is to write the following code. NoisyExtremaFinder = Function[{timeList, valueList, aroundRange}, (*NoisyExtremaFinder[] takes a pair of lists timeList_ and valueList_ and determines extrema in valueList_, returning a list contain

Finding All Chordless Simple Cycles In A Graph

I am doing a research on networks which consists of polygons with different number of sides. I am trying to find all simple cycles in a network which are chordless. As an example, consider the following graph: graph = Graph[ { 1 <-> 2, 2 <-> 3, 3 <-> 4, 4 <-> 5, 5 <-> 6, 1 <-> 6, 3 <-> 7, 7 <-> 8, 8 <-> 9, 9 <-> 10, 10 <-> 11, 11 <-> 3, 4 <-> 12, 12 <-> 13, 13 <-> 11 }, VertexLabels -> "Name" ] {1,2,3,4,5,6}, {3,4,11,12,13},{3,7,8,9,10,11} are rings and we can extract them: cycles = FindFundamentalCycles[graph]; rings = Sort @* VertexList @* Graph /@ cycles But the above solution doesn't always work as it might give non-chordless cycles. Consider the following example: grapht = Graph[ { 1 <-> 2, 1 <-> 3, 2 <-> 4, 4 <-> 5, 5 <-> 6, 4 <-> 6, 6 <-> 7, 3 <-> 5, 3 <-> 9, 5 <-> 8, 8 <

plotting - How to get exact coordinate of a point from a plot?

I am using BodePlot[] to plot the magnitude and phase of a function as below. BodePlot[1000/((1 + s/10^3)*(1 + s/10^6))] After plotting the function, is there a way to get the exact coordinate of a point from the plot? I tried to use Ctrl + D and the tool get coordinate but it doesn't return the exact coordinate at all. Answer Is there a way to get coordinate of just a particular point? You can convert Line into the corresponding set of Point s each of which will be a Button which Print s the coordinates of that Point when you click on it (try this!): plot = BodePlot[1000/((1 + s/10^3)*(1 + s/10^6))]; plot /. Line[pts_] :> Map[Button[Point[#], Print[#]] &, pts, {-2}] Or (as Michael E2 suggests) you can copy the coordinates of the Point into the clipboard instead of Print ing: plot /. Line[pts_] :> Map[Button[Point[#], CopyToClipboard[#]] &, pts, {-2}] You can elegantly get the advantages of the both above approaches using (new in version 10.3) Echo as sugges

programming - Return a Part by Reference? (For accessing hierarchical / structured data)

Is there a way to return a part of a list by reference, for reading and writing? I want to do this so I can easily manipulate "rule-styled structured", i.e., hierarchical data that is loaded from a MAT file with struct 's. Example: obj = {"Name" -> "Something", "Age" -> 10}; I think this is a relatively simple way to get / set fields, which deals with nested structures by limiting Position to levelspec 1: RuleQ[x_] := False; RuleQ[rule_Rule] := True; RuleQ[{}] := True; (* An empty list can be a Rule set... *) RuleQ[rules_List] := SameQ[Head[First[rules]], Rule]; StructQ[x_] := False; StructQ[rules_List?RuleQ] := True; FindFirst[list_List, item_] := Module[{res}, res = Flatten[Position[list, item, 1]]; Return[If[Length[res] > 0, First[res], {}]]; ]; FieldRule[field_] := field -> _; GetFieldIndex[obj_?StructQ, field_] := FindFirst[obj, FieldRule[field]]; SetField[obj_?StructQ, field_, value_] := Module[{index}, index =

list manipulation - Slope and frequency of line-like structure in image

I have the following image: A linear structure of parallel bright stripes is seen going from the lower left to the upper right edge of the image. I want to determine the mean slope and frequency of these stripes. To measure the slope, I tried the following code. ed = 22; edgeImg = EdgeDetect[img, ed]; lines = ImageLines[edgeImg]; The first 20 lines are: HighlightImage[img, {Red, Thickness[0.01], Line /@ lines[[1 ;; 20]]}] The mean slope is then: Mean@Table[(lines[[i, 2, 2]] - lines[[i, 1, 2]]) / (lines[[i, 2, 1]] - lines[[i, 1, 1]]), {i, 1, 20}] How would you determine the slope and what do you propose to measure the stripe frequency? Answer Here's an extremely simple way to do this: First, load the image and calculate gradients: img = Import["https://i.stack.imgur.com/f4iZt.png"]; pixels = ImageData[img][[All, All, 1]]; sigma = 10; (* roughly the with of a line *) gradient = GaussianFilter[pixels, sigma, {0, 1}] + I GaussianFilter[pixels, sig

differential equations - Simple PDE with Neumann BC

i have looked up solutions for my problems but they are either not related or to complicated, since my problem is rather simple: I want to impose 2 Dirichlet and 2 Neumann BCs on a rectangle. The analytical solution for the problem is known for comparison: u(x,y)=x1*x2 My first approach would be: bcdiri = {u[1, x2] == x2, u[x1, 0] == 0}; bcneu = {(-D[u[x1, x2], x1] /. x1 -> 0) == -x2, (D[u[x1, x2], x2] /. x2 -> 1) == x1}; NDSolveValue[{Derivative[0,2][u][x1,x2]+Derivative[2,0][u][x1,x2]==0}~Join~bcdiri~Join~bcneu,u[x1,x2],{x1,0,1},{x2,0,1}] But this does not work. I also tried this: bcneu = NeumannValue[-x2, x1 == 0]; Which works somehow...but the other Neumann BC is not included...Lists or something like && also does not work. So...how to do it? Thanks alot in advance! Answer You should check help page on NeumannValue . sol = NDSolve[{Derivative[0, 2][u][x1, x2] + Derivative[2, 0][u][x1, x2] == -NeumannValue[-x2, x1 == 0] + NeumannValue[x1, x2 == 1], u[1,

Import a given column from an excel file?

It seems that I can get the first column of excle data, say "test.xls", if I know the total length... data = Table[{i}, {i, 6}]; Export["test.xls", data]; Import["test.xls", {"Data",1,Range[len],1}] But the problem is, If I don't know the total length, can I do the same thing? especially consider the data scale is quite large. Answer The answer you are looking for is here: Import a Spreadsheet . Thus you can use: Import["~/test.xls", {"Data", 1, All, 2}] The syntax in your case is {"Data", # of sheet(s), # of row(s), # of column(s)} .

graphics3d - Finding points in a plane

The end of the Star Wars saga is near, so I feel compelled to design a Mouse Droid . Based upon the Paul Murphy's schematics I've reconstructed the outline of the top shell: Since my goal is to create a 3D-printable object, I'd like to carve out the inside of the shell, and this objective has tested the limits of my trigonometry knowledge. The goal is to create an identical shape (excluding the brim) that is scaled to provide an arbitrary thickness in the x,y,z directions (in practice, the x and y thicknesses will be identical and typically thinner than the z thickness). Because the object will be 3D printed, thickness must be defined in the [x,y,z] dimensions, so the approach I'm using is to assign the z thickness, find points in a new plan that intersect with the shell outline, and translate as appropriate in the x and y directions to get the coordinates for the cutout. I'm stuck here: pts = {{1.53685, 1, 0.6}, {2.77444, 2.81657, 7.6187}, {15.5486, 2.81657, 7

Replacing multiplication of matrix elements by application of these elements as functions

I want to realize the following idea in Mathematica. I've got a matrix {{a,b},{c,d}} which is multiplied to a vector {h,k} leading to {{a h + b k}, {c h + d k}}. Imagine now that a is an operator and I want to apply it to h , instead of multiplying. Primitive substitution {a h -> a@h} helps, but it is not quite a good approach while it's not working in more sophisticated cases. Thank you! EDIT1: The problem is solved partially, all comments are very useful. But still I am a little bit stacked, so I'm posting the update trying to explain my exact problem. The problem is following. I want to construct the matrix {{a[x], b},{c, d}} where a[x] is an operator (function) and b,c and d are arbitrary expressions (which are symbolic in general). After applying the operation {{a[x], b},{c, d}}.{{h}, {k}} I want to obtain {{a[h] + b k}, {c h + d k}} I want this operation to work not only for numbers and functions as it was proposed in answers below but with arbitrary symboli

plotting - Create a slider to illustrate Fubini theorem

I would like to illustrate the Fubini theorem in Calculus like the following picture (taken from this page ): This is what I tried: a := 1; B4 := ParametricPlot3D[{a, y, z}, {y, 3 + (-8 + a)* (1/13 + (0.01 + 0.0022*(-4 + a))*(5 + a)), 4.8 + Sin[a]}, {z, 0, 0.01*(a + 5)^2}, PlotPoints -> 100, Mesh -> 20, PlotStyle -> Directive[Blue, Opacity[0.4], Specularity[White, 30]]];(*The blue plane*) B1 := ParametricPlot3D[{x, y, 0.01*(x + 5)^2}, {x, -5, 8}, {y, 3 + (-8 + x) (1/13 + (0.01 + 0.0022*(-4 + x))*(5 + x)), 4.8 + Sin[x]}, Mesh -> 20, PlotStyle -> Opacity[0], MeshStyle -> Opacity[.8], PlotStyle -> Directive[Blue, Opacity[0.3], Specularity[White, 30]]]; B2 := ParametricPlot3D[{x, 3 + (-8 + x) (1/13 + (0.01 + 0.0022*(-4 + x))*(5 + x)), z}, {x, -5, 8}, {z, 0, 0.01*(x + 5)^2}, PlotPoints -> 100, Mesh -> 20, MeshStyle -> Opacity[.1], PlotStyle -> Directive[Green, Opacity[0.3], Specularity[White, 30]]]; B3 := Para

functions - Solving $L=frac{3}{2} sqrt{4 pi ^2 A^2+W^2}-frac{sqrt{5 W sqrt{4 pi ^2 A^2+W^2}+6 pi ^2 A^2+3 W^2}}{sqrt{2}}+frac{3 W}{2}$ for $W$

When I solve the aforementioned equation for $W$ or $A$ on Mathematica I get a long and ugly equation in return, namely one of the solutions for $W$ is: (attempt to read at your own health) Solve[L == (3 W)/2 + (3 Sqrt[4 A^2 Pi^2 + W^2])/2 - Sqrt[6 A^2 Pi^2 + 3 W^2 + 5 W Sqrt[4 A^2 Pi^2 + W^2]]/Sqrt[2], W] $W=\frac{3 L}{10}-\frac{1}{2} \sqrt{\frac{\sqrt[3]{-243200 \pi ^6 A^6+176832 L^2 \pi ^4 A^4+3600 L^4 \pi ^2 A^2+2160 L^6+\sqrt{-7962624000 \pi ^{12} A^{12}-8626176000 L^2 \pi ^{10} A^{10}+717410304 L^4 \pi ^8 A^8+3308138496 L^6 \pi ^6 A^6+911879424 L^8 \pi ^4 A^4+17252352 L^{10} \pi ^2 A^2+4672512 L^{12}}}}{15 \sqrt[3]{2}}+\frac{9 L^2}{25}-\frac{4}{15} \left(10 \pi ^2 A^2+3 L^2\right)+\frac{4 \sqrt[3]{2} \left(640 \pi ^4 A^4-246 L^2 \pi ^2 A^2-3 L^4\right)}{15 \sqrt[3]{-243200 \pi ^6 A^6+176832 L^2 \pi ^4 A^4+3600 L^4 \pi ^2 A^2+2160 L^6+\sqrt{-7962624000 \pi ^{12} A^{12}-8626176000 L^2 \pi ^{10} A^{10}+717410304 L^4 \pi ^8 A^8+3308138496 L^6 \pi ^6 A^6+911879424 L^8 \pi ^4 A^4+172

scoping - Passing lists to functions in a manner that works like pass-by-reference in other languages?

Is it possible to use a list as a variable, i.e., to pass it by reference to a function? In particular, I have a two-dimensional array and a function to get one element specified by its position: s = {{1, 1, 1, -1}, {1, 1, -1, -1}, {-1, -1, 1, -1}, {-1, 1, -1, 1}}; valueAtPos[positionX_, positionY_, lattice_List] := Flatten[Take[lattice, {positionY, positionY}, {positionX, positionX}]] This works just fine, it does exactly what I want. Now, what I'm actually aiming at is "flipping" the value at a certain position, i.e. $-1 \rightarrow 1$ and vice versa. I tried it with a function and a fixed list and it worked, but since I have more than one list, I want to pass the actual list not a copy as an argument as well. So I tried this: flip[posX_, posY_, lattice_List] := Module[{latticeLocal = lattice, x = posX, y = posY}, latticeLocal = ReplacePart[latticeLocal, {y,x} -> -valueAtPos[x, y, latticeLocal]] //. {{1} :> 1, {-1} :> -1};] If I run, for e

programming - How to use RunProcess to import external function?

I have a functions written in an external language called GO. How can I quickly load them into the kernel for use as Mathematica functions? The two ways I've tried are with MathLink and LibraryLink and it's overly complicated, however in version 10 there is RunProcess[] Can anyone find a way of using this new feature to install an external function? Answer Taking user5601's suggestion to do a little demo, I quickly whipped this up as an example of ProcessLink being used to do non-trivial communication between Mathematica and an external program, but with much less ceremony than using ProcessLink or MathLink. Let's take this little Go program: package main import "net/http" import "bufio" import "os" import "fmt" import "html" import "strings" func main() { http.ListenAndServe(":8080", http.HandlerFunc(render)) } func render(w http.ResponseWriter, req *http.Request) { var img, response, input

core language - Row vectors and column vectors (Mathematica vs Matlab)

As far as I know, Mathematica does not distinguish between row vectors and column vectors: all vectors are seen as lists. I know ways to bypass this as suggested here Product between a column vector and a row vector - error and get Matlab-style matrix multiplication. My question is why Mathematica and Matlab behaves differently in this context? I have seen a clear explanation in https://groups.google.com/forum/#!forum/comp.soft-sys.math.mathematica several years ago but I cannot recall it anymore. I guess it has to do with something fundamental. Answer This is a limitation of MATLAB, as MATLAB is only able to work with matrices. It does not have true vectors. It cannot even represent a character array as a 1D array or a structure array as a single element—it always must be 2D. Mathematica takes a much more general view. It works with arbitrary, $n$ -index tensors. A 1-index tensor is called a vector. A 2-index one is called a matrix. What is commonly called a "row vector"

plotting - ContourPlot with certain contour values omitted

Suppose I want contour plot of $x^2-y^2$, for $x,y\in[0,1]$ (my actual function is more complicated). Over this interval, $x^2-y^2$ is sometimes positive and sometimes negative. Using ContourPlot I get all the contours, negative as well as positive. But what if I wanted only those contours with values $\geq 0$ to show, while those contours whose value is less than zero are not displayed or (worst case) shown by the same color (say white). I doubt if this is possible at all, but any help is much appreciated. Answer You can use the option RegionFunction : ContourPlot[x^2 - y^2, {x, 0, 1}, {y, 0, 1}, RegionFunction -> (#^2 >= #2^2 &)] Or use ConditionalExpression ContourPlot[ConditionalExpression[x^2 - y^2, x^2 >= y^2], {x, 0, 1}, {y, 0, 1}, Contours -> 4]

differential equations - Derivative of function solved from NDSolve can't be plotted

I have used NDSolve to solve for a function (an angle of a triple pendulum), and now I wish to plot the derivative of that function (the angular velocity). Mathematica plots an empty plot. I had this issue before with a double pendulum system and ended up having to copy and paste cells into a new notebook one by one, and reevaluating everything. Then it suddenly started working (for the double pendulum). Doing that is not working in the case of my triple pendulum; the plot is still empty. Needs["VariationalMethods`"] ClearAll[Global] variables = {Subscript[θ, 1][t], Subscript[θ, 2][t], Subscript[θ, 3][t]}; Subscript[r, 1] = Subscript[l, 1] {Sin[Subscript[θ, 1][t]], -Cos[Subscript[θ, 1][t]]}; Subscript[r, 2] = Subscript[r, 1] + Subscript[l, 2] {Sin[Subscript[θ, 2][t]], -Cos[Subscript[θ, 2][t]]}; Subscript[r, 3] = Subscript[r, 2] + Subscript[l, 3] {Sin[Subscript[θ, 3][t]], -Cos[Subscript[θ, 3][t]]}; Subscript[l, 1] = 1; Subscript[l, 2] = 1; Subscript[l, 3] = 1; Subscrip

compile - How to boost the performance of my own BSplineFunction

In my CAGD package, I implemented a CAGDBSplineFunction[] like built-in BSplineFunction[] . Here is a performance comparison: pts = Table[{ Cos[2 Pi u/6] Cos[v], Sin[2 Pi u/6] Cos[v], v}, {u, 6}, {v, -1, 1, 1/2}]; f = BSplineFunction[pts] g = CAGDBSplineFunction[pts] ParametricPlot3D[f[u, v], {u, 0, 1}, {v, 0, 1}] // AbsoluteTiming ParametricPlot3D[g[u, v], {u, 0, 1}, {v, 0, 1}] // AbsoluteTiming Obviously, my CAGDBSplineFunction[] is far slower(about 20 X ) than the built-in BSplineFunction[] The CAGDBSplineFunction[] mainly uses an auxiliary function functionalNonzeroBasis[] to compute the coordinate of a parameter pair $(u,v)$. To improve the performance, I refactor the functionalNonzeroBasis[] to compiledNonzeroBasis[] searchSpan[{deg_, knots_}, u_] := With[{un = knots[[-(deg + 1)]]}, If[u == un, Position[knots, un][[1, 1]] - 2, Ordering[UnitStep[u - knots], 1][[1]] - 2 ] ] coeff[u_, U_, i_, p_] := If[U[[i + p + 1]] != U[[i + 1]], (u - U[[i + 1]])/(U[[i

code review - How to deal with the condition that a function own many options?

Assming that I have a function myFunc which has some options. Options[myFunc]={ firstOpt->1, secondOpt->"A", thirdOpt->True }; where, I set the values of firstOpt to 1 or 2,and set the value secondOpt to "A" or "B". myFunc[arg1_,arg2_,OptionsPattern[]]:= Module[{method}, method= OptionValue/@{firstOpt,secondOpt,thirdOpt}; Switch[ method, {1,"A",True},subFunc1[...], {2,"A",True},subFunc2[...], {1,"B",True},subFunc3[...], {2,"B",True},subFunc4[...], {1,"A",False},subFunc4[...], {2,"A",False},subFunc5[...], {1,"B",False},subFunc6[...], {2,"B",False},subFunc7[...], ] ] Obviously, this is a fussy and awkward solution.So I would like to know how to deal with condition when myFunc has many options. Or is it possible to know Mathematica how to deal with many options? For instance, Length@Options@ArrayPlot (*48*) An example(Implementati

legending - How to add own description to BarLegend?

Is there a default-option possibility to add own defined names of the contour-labels in BarLegend ? I want to have a string "hot" for 1 and "cold" for -1 for this: ContourPlot[Sin[x] Cos[y], {x, 0, 2 Pi}, {y, 0, 2 Pi}, Contours -> {Automatic, 10}, ColorFunction -> "Rainbow", PlotLegends -> BarLegend[Automatic, None]] How can I do this without writing a separate function?

syntax - Extract what symbol is set by SetDelayed, Set, TagSet, UpSet, SetAttributes, etc

One of the recent features of the Mathematica Plugin for IntelliJ IDEA ( www.mathematicaplugin.halirutan.de ) is a Structure View which let's you see information about several definitions that are done in a source file. It currently looks like the left side of the image below: To provide such a feature, I need to extract which symbol is set when the user uses things like lhs = rhs or lhs := rhs s /: patt = rhs or s /: patt := rhs lhs ^= rhs or lhs ^:= rhs Options[sym] = rhs , Attributes[sym] = rhs , SyntaxInformation[sym] = lhs , Format[sym] ] = rhs , N[sym] = rhs , Default[sym] = rhs sym::tag = rhs Since in IDEA I cannot evaluate code like one can in Mathematica , I have to extract all those information from inspecting the abstract syntax tree ( TreeForm in Mathematica). For this, I have a so-called visitor which walks through the tree and collects information. One can easily write such a visitor (or expression parser) in Mathematica itself. I have written a very basic ver

mathematical optimization - Principal Axis Maximization

I know that, in order to use PrincipalAxis , for example in FindMaximum function: FindMaximum[ f[x,y], {{x,x0,x1},{y,y0,y1}}, Method -> "PrincipalAxis"] You have to provide two initial points, for each argument. However, PrincipalAxis also seems to work when just one initial point is given. Do you know what actually Mathematica does in such a case? Answer The starting point is the Principal Axis Method tutorial : For an $n$-variable problem, take a set of search directions $u_1,u_2,...,u_n$ and a point $x_0$. Take $x_i$ to be the point that minimizes $f$ along the direction $u_i$ from $x_{i-1}$ (i.e. do a line search from $x_{i-1}$), then replace $u_i$ with $u_{i+1}$. Two distinct starting conditions in each variable are required for this method because these are used to define the magnitudes of the vectors $u_i$. I think that the first parameter is the starting point, $x_0$, and, combined with the second parameter, both define the magnitude of the search direction.

front end - Copying Greek text from notebooks as unicode

Possible Duplicate: How to “Copy as Unicode” from a Notebook? How can I copy Greek text from notebooks as proper Unicode that can be pasted into other applications? If I type some Greek text into a notebook, and then try to paste it elsewhere, it ends up as a set of character names in Mathematica's notation. The screenshot below illustrated the problem. It doesn't really matter if the Greek text is typed elsewhere, then pasted into Mathematica, or if it's typed directly into Mathematica: when copying from Mathematica, Greek letters are converted into character names. If you don't have a Greek keyboard layout installed, this can be useful for testing. Use case: analysing Greek text and copying results from a notebook.

graphics3d - Help recreating a gif

For my math class I am trying to recreate a mathematical GIF. Here is the GIF I wish to make: At this point I think I have a 3D function that would work to lay the hexagons on to. Manipulate[Show[ParametricPlot3D[{t Cos[s], Cos[a - t] Sinc[t], t Sin[s]}, {t, 0, 5}, {s, 0, 2 Pi}, PlotRange -> All], PlotRange -> All], {a, 0 , 2 Pi}] While this might not be the perfect function but I think it will work. The next step is getting the hexagons to lay on the surface as it moves. What would be the best way to have the hexagon on the surface? A quick clarification. I want to know how to get the hexagons on to the surface I will turn it in to a real GIF once I get that to work.

programming - How to construct custom operators with precedence?

I need to combine data structures in operations analogous to addition, subtraction, multiplication and division (and more). I need more than one operation of each type, i.e. more than one method of addition, subtraction, etc. I have made some progress. Using the Notation palette, i can for example define !/! and %/% as different operators for division. But how can I set precedence? My impression is that this is not possible. I have explored the existing symbols without in-built meanings, such as CirclePlus and CircleMinus . These symbols without in-built meanings have precedence while allowing the meaning to be defined by the user. But I can't find enough of them to meet my needs. For example, there is no " CircleDivide ". Might it be possible to use subscripts and have $/_a$ and $/_b$ for different types of division while retaining the precedence of the division operator? If I could do it for division, then I could do it for the other operators of interest too. ADDEND