# Tag Info

71

Yes, but this only exists in version 8 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, BitXor, ...

43

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

40

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

38

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

35

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

32

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

32

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

30

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

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.

28

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

27

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

26

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

25

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

25

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

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

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

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]

22

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

22

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

21

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

21

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

20

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_] :> ...

20

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

20

Answer: Fixed in 9.0.1. 9.0.1 is a free upgrade for registered 9.0.0 users, and is available for download from the Wolfram User Portal. Explanation as to why/how it was busted. This is not something I would typically post at all. Not because I'm afraid to show how the sausage is made (for those who have the stomach), but more because it seems off-topic ...

20

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

19

I believe there is such a list available but I can't remember the command off-hand. In the meantime, you can always load CompiledFunctionTools via. <<CompiledFunctionTools` And then use CompilePrint on a compiled function to see if MainEvaluate is present in the pseudocode. MainEvaluate tells us that something is going through the evaluator and ...

19

Do you mean CtrlShiftK? After typing Plo, press the key combination CtrlShiftK and a window will appear with possible options: As pointed by Yves，CtrlK will also work，but CtrlShiftK will work differently if you finish the function name. For an example, Type Plot3D; Use CtrlShiftK; Mathematica will show:

19

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

19

There was an update for Array, not done to the end. The method below does not work for earlier versions even though that Array is New in 1 | Last modified in 4 Moreover WRI forgot to update docs for error messages: Array::plen - the first example gives no error in V9. V9 Array[# &, n, {start, stop}] Array[# &, 10, {-1, 1}] {-1, ...

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