Tag Info

Hot answers tagged

82

Yes, but this only exists in version 8 and is undocumented: Compile`CompilerFunctions[] // Sort giving, for reference: {Abs, AddTo, And, Append, AppendTo, Apply, ArcCos, ArcCosh, ArcCot, ArcCoth, ArcCsc, ArcCsch, ArcSec, ArcSech, ArcSin, ArcSinh, ArcTan, ArcTanh, Arg, Array, ArrayDepth, Internal`Bag, Internal`BagPart, BitAnd, BitNot, BitOr, BitXor, ...


47

In Some Notes on Internal Implementation especially in Algebra and Calculus one finds interesting subtleties and differences between these two functions, e.g. The code for Solve and related functions is about 500 pages long. Reduce and related functions use about 350 pages of Mathematica code and 1400 pages of C code. There is much more than a ...


45

One convenient way to think of Flatten with the second argument is that it performs something like Transpose for ragged (irregular) lists. Here is a simple example: In[63]:= Flatten[{{1,2,3},{4,5},{6,7},{8,9,10}},{{2},{1}}] Out[63]= {{1,4,6,8},{2,5,7,9},{3,10}} What happens is that elements which constituted level 1 in the original list are now ...


42

A second list argument to Flatten serves two purposes. First, it specifies the order in which indices will be iterated when gathering elements. Second, it describes list flattening in the final result. Let's look at each of these capabilities in turn. Iteration Order Consider the following matrix: $m = Array[Subscript[m, Row[{##}]]&, {4, 3, 2}]; $m ...


40

Preamble The problem is not as trivial as it may seem on the first glance. The main problem is that many symbols are localized by (lexical) scoping constructs and should not be counted. To fully solve this, we need a parser for Mathematica code, that would take scoping into account. One of the most complete treatments of this problem was given by David ...


37

The answers from @LeonidShifrin and @Szabolcs are great, so I just want to share some incomplete thing I wrote for analyzing and visualizing Compiled "WVM" code. It's for compiler of Mathematica 7.0.1. Sorry if the code looks messy, it has been abandoned long ago.. (for the compiler version always got updated before I could figure out all the codes ...


34

In addition to Oleks list, there is of course a way to study what happens under the hood. f = Compile[{{x, _Integer, 1}}, Accumulate[x] ]; << CompiledFunctionTools` CompilePrint[f] (* 1 argument 1 Integer register 2 Tensor registers Underflow checking off Overflow checking off Integer overflow ...


30

Warning: The SetSystemOptions method to detect failed compilation, described below, is not 100% reliable. Please see the comments (e.g. trC = Compile[{{a, _Integer, 2}}, Tr[a]] won't warn). I assume you need the list of compilable functions to make sure that all of your code will be properly compiled, and it won't take any speed penalties (that why I was ...


30

Internal`InheritedBlock (IIB) is similar to Block, except that it preserves the original definition of the function being passed to it. The function can then be modified as we wish inside the IIB without affecting the external definition. Let's see how Block works first: f[x_] := x Block[{f}, Print@DownValues[f]; f[x_, y_] := x y; ...


29

The answer of @R.M. already explains the essence of the problem. You can streamline the process of removing the Combinatorica from the $ContextPath by loading it via Block[{$ContextPath}, Needs["Combinatorica`"]] (or use Get intead of Needs, although Needs is a preferred way to load a package). In this way, you don't have to do anything afterwards, ...


29

Both, And and Or should work for All and Any respectively. You may have to get creative in how you apply them, though. For instance, And @@ {True, False, True} works just like you would expect AllOf @ {True, False, True} to without any additional work. Similarly, Or @@ {False, True, False} works like AnyOf.


29

First let me note that I didn't write PositionIndex, so I can't speak to its internals without doing a bit of digging (which at the moment I do not have time to do). I agree performance could be improved in the case where there are many collisions. Let's quantify how bad the situation is, especially since complexity was mentioned! We'll use the ...


28

Since version 8, Solve and Reduce share a great deal of code. In fact, by Specifying Method -> Reduce in Solve, Solve will use Reduce behind the scenes to produce an answer. Off the top of my head, the key differences are as follows: 1) Reduce simplifies logical statements, while Solve solves equations. This means that given a logical statement ...


28

Let you have a function and an initial point f[x_] := Cos[x] x0 = 0.2; Then you can calculate a sequence seq = NestList[f, x0, 10] (* {0.2, 0.980067, 0.556967, 0.848862, 0.660838, 0.789478, \ 0.704216, 0.76212, 0.723374, 0.749577, 0.731977} *) and vizualize it with a so-called Cobweb plot p = Join @@ ({{#, #}, {##}} & @@@ Partition[seq, 2, 1]); ...


27

I didn't find my original code, but here's a start for implementing this: First, let's say that a "function" is a symbol that has DownValues but no OwnValues (this latter requirement is just for safety now). This needs a lot more work to get right: for example, many built-ins have no visible DownValues at all, yet they are not inert (e.g. check that ...


26

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" ...


25

Not really a concise syntax, but you can also do this using Switch, which removes the need for writting the checking, and also allows patterns: fun[num_Integer] := Switch[num, 1, "Red", 2, "Orange", 3, "Yellow", _?PrimeQ, "Purple", _, "LightGray"] I used strings just to make the output nicer to verify the behavior. Naturally you would switch ...


25

f = {1, 5, 9, 14}; v = {-1, 1, 3, 4, 6, 9, 10, 13, 14, 15}; BinLists[v, {Join[{-Infinity}, f, {Infinity}]}] {{-1}, {1, 3, 4}, {6}, {9, 10, 13}, {14, 15}}


24

Summary We can look at the code of DeleteDuplicatesBy and it turns out it uses GroupBy. The test cases proposed by Mr.Wizard are all handled by some part of the code of DeleteDuplicatesBy. Other parts of this code also seem to have some issues. Most of the members of the *By family of functions seem to have side effects. How DeleteDuplicatesBy works It ...


23

Going out on a limb here, but the exhibited expression looks like a brave but flawed attempt to implement the Y-combinator extremely concisely. The Y-combinator is a technical trick used to implement recursion in the lambda calculus. Here is an implementation that stoops to using some symbols: Y[f_] := #[#]&[Function[n, f[#[#]][n]]&] ... and ...


23

I assume that you have numeric values. A much more efficient way would be -Total[UnitStep[data] - 1]] or Total[1-UnitStep[data]] Note: While the second notation is certainly a bit more compact, it is about 35% slower than the double-minus notation. I have no idea why. On my system, it takes on average 0.22 sec vs 0.30 sec. Compare timings between the ...


23

You can implement equivalents of the any and all functions in MATLAB and python in Mathematica using the MemberQ and FreeQ functions as: any[x_List] := MemberQ[x, True] all[x_List] := FreeQ[x, False] For large lists, these will be about an order of magnitude faster in the worst case to several orders faster in the best case, when compared to the And and ...


23

For example you may do something like f[i_] := {Red,Orange,Yellow}[[i]] Edit You can easily add some robustness: f[l_List, i_Integer ] := l[[i]] /; 1 <= i <= Length@l; ll = {Red, Orange, Blue}; f[ll, 3]


23

Taking a limit depends on the path used to approach that limit. Consider the function in the question: f[x_, y_] := Piecewise[{{x y / (x^2 + y^2), x != 0 && y != 0}}, 0]; base = Plot3D[f[x, y], {x, -1, 1}, {y, -1, 1}, MeshStyle->Opacity[0.2], PlotStyle->Opacity[0.5]] (A plot of its graph, saved here as base, appears in subsequent figures.) ...


23

The following is based on the fact that the determinant of a matrix is equal to zero when two rows are the same. Thus, if you plug any of the points in, you get a true statement. SeedRandom[3]; pts = RandomReal[{-1, 1}, {5, 2}]; row[{x_, y_}] := {1, x, y, x*y, x^2, y^2}; eq = Det[Prepend[row /@ pts, row[{x, y}]]] == 0 (* Out: ...


22

I like to use Ctrl+. to discover how it's grouped. For example, in this example: Plot3D[Sin[x y], {x, 0, 3}, {y, 0, 3}, ColorFunction -> Hue[#] &] Putting your cursor position after & and pressing Ctrl+. two times, you will get all expression ColorFunction -> Hue[#] marked, so it's wrong, and you need to put () like this: Plot3D[Sin[x y], ...


22

Scoping constructs, lexical scoping and variable renamings It pays off to understand a bit deeper how the scoping constructs work and what happens behind the scenes when you execute one. In addition to the documentation, this was discussed in part here, but let us present some summary. When the lexical scoping construct Sc[vars, body] executes (where Sc ...


22

Head can return any head. There is no predefined list. expr = myArbitraryHead[1, 2, 3]; Head[expr] myArbitraryHead A head does not even need to be a Symbol: expr2 = (2 Pi)[x, y, z]; Head[expr2] 2 π Most heads are shown explicitly in the FullForm of the expression: FullForm[{"a" + "b", 1/3}] Head /@ {"a" + "b", 1/3} List[Plus["a", "b"], ...


22

test = {5, 6, 9, 3, 2, 6, 7, 8, 1, 1, 4, 7} MaxFilter[test, 1] (* {6, 9, 9, 9, 6, 7, 8, 8, 8, 4, 7, 7} *) You can also use Max /@ Transpose[{Rest[Append[#, 0]], #, Most[Prepend[#, 0]]}] &[yourList] which is competitive with the MM MaxFilter, but will allow you to change the 'slide' (e.g.pad with zeroes, or other arbitrary 'start').


21

For a continuous function you could do something like this: SetAttributes[argPlot, HoldAll]; Options[argPlot] = Options[Plot]; argPlot[exp_, {x_, x0_, x1_}, opt : OptionsPattern[argPlot]] := Module[{pts, pl}, pl = Plot[Arg[exp], {x, x0, x1}, PlotRange -> All, PlotPoints -> OptionValue[PlotPoints]]; pts = SortBy[Cases[pl, Line[pts_] :> ...



Only top voted, non community-wiki answers of a minimum length are eligible