# Tag Info

## Hot answers tagged functions

148

You will find a lot of information in this answer. I will add a few personal notes. Module Use Module when you want to localize variables inside your function's body, and those variables will potentially acquire and/or change their values during the computation. Basic use For example: f[x_]:=Module[{y=x^2},y=y+x;{x,y}] Here, a local mutable variable ...

125

Yes, but this only exists in version 8 onwards and is undocumented: CompileCompilerFunctions[] // 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, InternalBag, InternalBagPart, BitAnd, BitNot, BitOr, ...

57

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

56

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

55

LongestCommonSequencePositions and LongestCommonSubsequencePositions Their use is analogous to LongestCommon(Sub)sequence but they return the position of the first match instead. ClipboardNotebook[] can be used to access the clipboard. NotebookGet@ClipboardNotebook[] will give a Notebook expression with the current contents of the clipboard. I use this ...

53

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

49

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

47

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

46

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

44

The differences between Module, Block and With are nicely summarized by the results of the following expressions: x = "global"; f[] := x Module[{x = "local"}, {x, f[], Hold[x]}] Block[{x = "local"}, {x, f[], Hold[x]}] With[{x = "local"}, {x, f[], Hold[x]}] which returns: {"local", "global", Hold[x$123]} (* Module *) {"local", "local", ... 40 I usually consider PatternTest as local to a specific pattern such as x_Integer?Positive and Condition as more general, often involving multiple patterns, e.g.: f[x_, y_] /; x+y < 10 := x*y An aspect of PatternTest that is different from Condition is that it is automatically applied to each element of a sequence, whereas Condition applies to the whole. ... 39 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 ... 38 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 ... 38 These three functions are similar (speaking commonly), and in some applications any of them could be used, yet they have very different special applications. Rudimentarily: Map wraps (sub)expressions in a given Head, and returns the modified input Apply replaces Heads in (sub)expressions, and returns the modified input Scan "visits" (sub)expressions, ... 37 InternalInheritedBlock (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; ... 37 Compose and Composition There is, but it is deprecated (in favor of Composition): Compose: MapThread[Compose, {{a, b, c}, {1, 2, 3}}] (* {a[1], b[2], c[3]} *) I still use Compose myself, but I would not take the responsibility to recommend this as a common practice. You can also use Composition[#1][#2] &, although this is hardly better than your ... 36 In my view, Cases and Position are in one camp (pattern-based functions used for general expression destructuring), while Select is in another: (more) special-purpose functions optimized to work on certain efficient data structures. As was mentioned already, both Cases and Select do generally unpack when used with packed arrays. What wasn't mentioned is ... 35 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 ... 34 Another useful thing to do when testing such things is to determine whether packed arrays are unpacking. For all of your cases there is a lot of unpacking going on (I've only shown the first of such messages...) In[1]:= On["Packing"] In[2]:= test = RandomInteger[{-25, 25}, {10^6, 2}]; In[3]:= (res1 = Cases[test, {_, _?Positive}]); // AbsoluteTiming ... 34 Intro I will treat your question in a somewhat broader context of parameter-passing semantics in Mathematica in general. Many points of confusion here come from analogies and comparisons with more traditional languages, and it is important to realize that Mathematica uses entirely different (from most other languages) mechanisms for parameter-passing. ... 34 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]); ... 33 Thinking about a recent answer made me wonder exactly which functions in Mathematica use Assumptions. You can find the list of System functions that use that Option by running Reap[Do[Quiet[If[Options[Symbol[i], Assumptions]=!={}, Sow[i], Options::optnf]], {i, DeleteCases[Names["System*"], _?(StringMatchQ[#, "$"~~__] &)]}]][[2, 1]] which (can be ...

33

One undocumented function I find useful is Precedence For example: {#, Precedence@#} & /@ {Plus, Minus, Times, Power, Apply, Map, Factor, Prefix, Postfix, Infix} // TableForm giving: Plus 310. Minus 480. Times 400. Power 590. Apply 620. Map 620. Factor 670. Prefix 640. Postfix 70. Infix 630. Precedence is described in a ...

33

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

33

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

32

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

32

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

32

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

31

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.

30

I'll cover a few typical uses of Block, neither of which is possible using Module or With. Temporarily removing definitions When you do Block[ {a = x}, ... ] the original definition of a is effectively replaced by whatever new definition is given in the first argument of Block, for the duration of the evaluation of Block only. If we give no ...

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