# Tag Info

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

129

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

60

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

56

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

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

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

45

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", Hold[x]}... 41 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. ... 41 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, ... 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 ... 39 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 ... 39 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; Print@... 37 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 ... 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 ... 35 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 ... 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 ... 35 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 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, since,... 34 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 (... 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 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 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

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

This is a new version of my answer in response to the edited question (the first version is here). It is based on the same idea, but the Weierstrass substitution rules are now generated by Mathematica (instead of entered by hand) and results with $\pm$ solutions are correctly returned. First, generate the Weierstrass substitution rules \$TrigFns = {Sin, ...

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

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

29

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

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