Tag Info

Hot answers tagged

56

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


32

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


28

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


27

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


25

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


25

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


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


24

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


23

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.


23

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 looking for this information before). People have shown you how to print the compiled code and check that there are no calls to MainEvaluate in it. There is an alternative and simpler way of ...


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


22

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


20

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


20

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


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

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


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

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


18

Here's an alternative approach than Spartacus' answer. What he did is splitting up the piecewise function into many different functions valid in only a small domain; what I am doing here is directly plotting the piecewise function as given, while the coloring is done using ColorFunction. I'll use the same function as Spartacus, f = Piecewise[{{#^2, # <= ...


18

A faster way than those already given avoids iterating over the list to remove unwanted values, instead replacing Indeterminate wherever it appears by redefining it as -Infinity using Block: maxNoIndeterminate[lst_] := Block[{Indeterminate = -Infinity}, Max[lst]]; Note that any list containing Indeterminate cannot be a packed array, so there is no reason ...


18

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


17

I've had a need for such a function several times, and I found this implementation of C-style *printf functions, by Vlad Seghete. To use it, all you need to do is extract the files to $UserBaseDirectory/MathPrintF/ and you're all set. Here's an example once you've installed it: <<MathPrintF` sprintf["%d %s %d %s, %s %s %s %s", Sequence @@ ...


17

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


17

Probably the most common use of Unique is in situations when you need a large number of local variables (and sometimes a variable number of local variables) so using Module is either inconvenient or impossible. In that case you can use the construction: vars= Table[Unique[x],{n}] or something of this kind. You can find a few examples in the archives of the ...


17

This confused me as well, but using Trace revealed what is going on: Trace@Pick[{1, 2, 3, 4, 5}, selection, elem_ /; elem =!= 0] {{selection,{0,1.2,3,0.,5}}, Pick[{1,2,3,4,5},{0,1.2,3,0.,5},elem_/;elem=!=0], {{0,1.2,3,0.,5}=!=0,True}, {1,2,3,4,5}} The key is the 4th line: note that the pattern is applied to the full list, at level 0. The full list ...


17

Shadowing occurs only when there are two functions with the same name that are in $ContextPath. So right after you do <<Combinatorica`, do the following: $ContextPath = Rest@$ContextPath; What this does is that it removes Combinatorica (which is the package you just loaded). Now the only Graph function that's on the path is System`Graph and you can ...


17

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


17

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


16

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



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