# What are the most common pitfalls awaiting new users?

As you may already know, Mathematica is a wonderful piece of software.
However, it has a few characteristics that tend to confuse new (and sometimes not-so-new) users. That can be clearly seen from the the fact that the same questions keep being posted at this site over and over.

• Focus on non-advanced uses (it's intended to be useful for beginners and as a question closing reference)
• Include a self explanatory title in h2 style
• Explain the symptoms, the mechanism behind the scenes and all possible causes and solutions you can think of. Be sure to include a beginner's level explanation (and a more advance one too, if you're in the mood)

## Index

• ### How to use both initialized and uninitialized variables

-

We're looking for long answers that provide some explanation and context. Don't just give a one-line answer; explain why your answer is right, ideally with citations. Answers that don't include explanations may be removed.

Few suggestions: 1. old definitions in memory and "overloaded" functions like f[x_]:=a; f[x_Integer]=b; 2. Forgotten underscore in patterns f[x]=a 3. Set vs SetDelayed; 4. m = {{1, 2}, {3, 4}} // MatrixForm and then Eigenvalues[q]; 5. Plotting complex function produces empty plot without any warnings. –  Nick Stranniy Jan 24 '13 at 22:23
I want to throw $HistoryLength in there, a memory management in general category including MaxMemoryUsed and MemoryConstrained etc – ssch Jan 25 '13 at 0:03 Suggestion: If appropriate to the problem, force Mathematica to use approximate numerical algorithms to avoid the computational overhead of their symbolic counterparts. There are several ways to do this (e.g., NIntegrate vs. Integrate, using real approximate numbers instead of integers in equations, etc). – David Skulsky Jan 25 '13 at 3:51 Suggestion: mathematica.stackexchange.com/q/18483/193 (Using the result of functions that return replacement rules) – belisarius Jan 26 '13 at 7:46 Maybe there should be a (short) answer about security. Most people don't realize mathematica has a large set of functions that are capable of taking over your computer entirely, or as a more specific example, activating your webcam (CurrentImage). – Jacob Akkerboom Aug 8 '13 at 11:19 ## 23 Answers ## What the @#%^&*?! do all those funny signs mean? Questions frequently arise about the meaning of the basic operators, and I hope it will prove useful to have a sort of index for them. It would be nice to have them organized by sign instead of topic, but they do not have a natural order. One can use the find/search feature of a browser to locate an operator in the list. Below are links to documentation explanations for most of those shorthand signs together with a short example. Read the documentation for an explanation and more examples. See also the guide to Mathematica Syntax, which has links to most of these. In a couple of cases, I give different links that seem more helpful to me. All those operators come with a specific precedence. Assuming a certain, incorrect, precedence of your operators can wreak havoc with your programs. For instance, the & operator, part of a pure function specification, has a rather unexpected low precedence and constructions using it quit often need to be protected with parenthesis in order to make things work as intended. So, please have a look at this gigantic precedence table. Most (but not all) of these can be looked up using the ?-syntax, for example evaluating ? /@ will show help for Map. Function application • @, [...], // [ref] -- f @ x = f[x] = x // f (Prefix, circumfix and Postfix operators for function application] • ~ [ref] -- x ~f~ y = f[x, y] (Infix; see Join [ref] for a Basic Example.) • /@ [ref] -- f /@ list = Map[f, list] • @@ [ref] -- f @@ list = Apply[f, list] • @@@ [ref] -- f @@@ list = Apply[f, list, {1}] • //@ [ref] -- f //@ expr = MapAll[f, expr] • @* [ref] -- f @* g @* h = Composition[f, g, h] (new in V10) • /* [ref] -- f /* g /* h = RightComposition[f, g, h] (new in V10) Infix ~ should not be confused with: • ~~ [ref] -- s1 ~~ s2 ~~ ... = StringExpression[s1, s2, ...] • <> [ref] -- s1 <> s2 <> ... = StringJoin[s1, s2, ...] Pure function notation • #, #1, #2, ... [ref] -- # = #1 = Slot[1], #2 = Slot[2], ... • ##, ##2, ... [ref] -- ## = ##1 = SlotSequence[1], ##2 = SlotSequence[2], ... • #0 [ref] gives the head of the function, i.e., the pure function itself. • & [ref] -- # & = Function[Slot[1]], #1 + #2 & = Function[#1 + #2], etc. Assignments • = [ref] -- = = Set (not to be confused with == -- Equal!) • := [ref] -- := = SetDelayed • =. [ref] -- =. = Unset • ^= [ref] -- ^= = UpSet • ^:= [ref] -- ^:= = UpSetDelayed • /: = [ref] -- /: = = TagSet • /: := [ref] -- /: := = TagSetDelayed • /: =. [ref] -- /: =. = TagUnset Equivalence and equality • == [ref] -- == = Equal (not to be confused with = -- Set, or with Equivalent!) • === [ref] -- === = SameQ • != [ref] -- != = Unequal • =!= [ref] -- =!= = UnsameQ • <-> [ref] -- <-> = UndirectedEdge Rules and patterns • -> [ref] -- -> = Rule • :> [ref] -- :> = RuleDelayed • /; [ref] -- patt /; test = Condition[patt, test] • ? [ref] -- p ? test = PatternTest[p, test] • _, _h [ref] -- Single underscore: _ = Blank[], _h = Blank[h] • __, __h [ref] -- Double underscore: __ = BlankSequence[], __h = BlankSequence[h] • ___, ___h [ref] -- Triple underscore: ___ = BlankNullSequence[], ___h = BlankNullSequence[h] • .. [ref] -- p.. = Repeated[p] • ... [ref] -- p... = RepeatedNull[p] • : [ref] or [ref] -- x : p = pattern p named x; or, as a function argument, p : v = pattern p to be replaced by v if p is omitted. • _. [ref], [ref] -- Represents an optional argument to a function, with a default value specified by Default. • | [ref] -- | = Alternatives (not to be confused with || -- Or!) • /. [ref] -- expr /. rules = ReplaceAll[expr, rules] • //. [ref] -- expr //. rules = ReplaceRepeated[expr, rules] Logical operators • &&, ∧ [ref] -- && = And (not to be confused with & -- Function!) • ||, ∨ [ref] -- || = Or • !, ¬ [ref] -- ! = Not • , \[Implies] [ref] -- = Implies • , \[Equivalent] [ref] -- = Equivalent • ⊼ [ref] -- ⊼ = Nand • ⊽ [ref] -- ⊽ = Nor • ⊻ [ref] -- ⊻ = Xor History of evaluations • % [ref] gives the last result generated. %% gives the result before last. %n gives the result on the nth output line. Not to be confused with Percent [ref]. Other • [[ ]] [ref] -- expr[[n]] = Part[expr, n]; also expr[[n1, n2,...]] = Part[expr, n1, n2,...]. • *^ is equivalent to *10^ (e.g. 1*^2=100). • ^^ gives a way to enter a number that is in a different base (e.g. 2^^100101 represents the binary number 100101_2 = 37). See more info in the documentation of BaseForm. • ,  [ref], [ref] -- Indicates Precision, Accuracy, respectively. There is a table of typical examples in the tutorial Numerical Precision. • $ is not an operator; it can be used in variable names (e.g. my$variable). It commonly used for System constants and parameters (e.g. $Version) and for local variables generated by scoping constructs (e.g. Module[{x}, x] $\rightarrow$ x$9302). - Thank you, thank you, thank you... I don't think I can say it enough times. – Black Milk May 23 '13 at 1:16 Nice compilation. – rcollyer May 23 '13 at 13:16 It is probably nice to know that for quick reference, just entering the notation in the documentation search bar will give you the right page in most cases. – Jacob Akkerboom Dec 11 '13 at 9:36 and here I always thought that UpSet is :-( ... sorry – jens_bo Dec 11 '13 at 10:20 Btw, this is called grawlixes. – m0nhawk Oct 21 '14 at 6:53 ## Understand the difference between exact and approximate (Real) numbers Unlike many other computational software, Mathematica allows you to deal with exact integers and rational numbers (heads Integer and Rational), as well as normal floating-point (Real) numbers. While you can use both exact and floating-point numbers in a calculation, using exact quantities where they aren’t required can slow computations down. Also, mixing the data types up in a single list will mess up packed arrays. The different data types are represented differently by Mathematica. This means, for example, that integer zero (0) and real zero (0.) only equal numerically (0 == 0. yields True) but not structurally (0 === 0. yields False). In certain cases you have to test for both or you will run into trouble. And you have to make sure that List index numbers (i.e. the arguments to Part) are exact integers not real numbers. As with any computer language, calculations with real numbers is not exact and will accumulate error. As a consequence, your real-valued calculation might not necessarily return zero even when you think it should. There may be small (less than$10^{-10}$) remainders, which might even be complex valued. If so, you can use Chop to get rid of these. Furthermore, you can carry over the small numerical error, unnoticed: Floor[(45.3 - 45)*100] - 30 (* ==> -1 instead of 0 *)  In such cases, use exact rational numbers instead of reals: Floor[(453/10 - 45)*100] - 30 (* ==> 0 *)  Sometimes, if you are doing a calculation containing some zeros and some approximate real numbers, as well as algebraic expressions, you will end up with approximate zeros multiplied by the algebraic elements in the result. But of course you want them to cancel out, right? Again, use Chop, that removes small real numbers close to zero (smaller than$10^{-10}$according to the default tolerance level). Some solvers (Solve, Reduce, Integrate, DSolve, Minimize, etc.) try to find exact solutions. They work better with exact numbers for coefficients and powers. As just mentioned, if approximate real numbers are used, terms that should cancel out might not, and the solver might fail to find a solution. Other solvers (NSolve, FindRoot, NIntegrate, NDSolve, NMinimize, FindMinimum, etc.) try to find approximate solutions. Generally they work well with either exact or approximate numbers. However, some of them do symbolic analysis and sometimes perform better with functions or equations that are given in terms of exact numbers. keywords: real integer number-type machine-precision - ## Basic syntax issues 1. Symbol names cannot contain underscore. _ is a reserved character used for pattern matching. 2. Avoid using subscripted symbols in your code. While it can be done, it causes a lot of confusion and is harder to use than just sym[j] or whatever your symbol might be. The reason is that subscripted symbols are not plain symbols, so you can’t assign values (strictly speaking, DownValues) to them directly. 3. Avoid single-capital-letter names for your variables, to avoid clashes (consider using the double-struck EscdsAEsc and Gothic letters EscgoAEsc instead). Mathematica is case-sensitive. More generally, avoid capitalising your own functions if you can. 4. Mathematica uses square brackets [] for function arguments, unlike most other languages that use round parentheses. See halirutan's exemplary answer for more detail. 5. Learn the difference between Set (=) and SetDelayed (:=). See this question and this tutorial in the Mathematica documentation. 6. Use a double == for equations. See this tutorial in the Mathematica documentation for the difference between assignments (Set, =) and equations (Equal, ==). 7. When creating matrices and arrays, don't use formatting commands like //TableForm and //MatrixForm in the initial assignment statements. This just won't work if you then want to manipulate your matrix like a normal list. Instead, try defining the matrix, suppressing the output of the definition by putting a semicolon at the end of the line. Then have a command that just reads nameOfMatrix//MatrixForm -- you can even put it on the same line after the semicolon. The reason for this is that if you define the object with a //MatrixForm at the end, it has the form MatrixForm[List[...]], instead of just List[..], and so it can't be manipulated like a list. If you really want to display the output as MatrixForm on the same line you can do (nameOfMatrix=Table[i+j,{i,5},{j,5}])//MatrixForm 8. Functions are defined with e.g. func[x_, y_] := x + y, not func[x, y] := x + y. The expression x_ is interpreted as Pattern[x, Blank[]]. See Blank and Pattern. - I've been using subscripted symbols for simple linear equations, like point slope, i.e (y_1 - y_0)=m(...); Solve[%,y_1]. It works ok; but there is definitely conflicts if I combine a symbol and subscripted version of that same symbol, i.e.( y - y_0)-m(...); Solve[%,y] causes conflicts for me. I guess this problem can become even more severe in more complex operations? Pitty, cause when I use pad and paper, I love mixing 'y' and 'y_0' /etc.. – Adam Dreaver Jan 26 '13 at 4:19 On point 6, I often use (mat = matrixExpression)//MatrixForm which first evaluates matrixExpression and assigns it to mat and only then displays the result (i.e. mat) in MatrixForm – fairflow Nov 19 '13 at 21:52 ## How to use both initialized and uninitialized variables A variable in Mathematica can play two different roles. As an initialized variable, the variable's value will replace its name when an expression is evaluated. By contrast, upon evaluation, the name of an uninitialized variable will be propagated throughout every expression in which it takes part. For example, starting with the more familiar behavior of an initialized variable as in most programming languages, we have a = 5.3; (5 a)^2 ===> 702.25 If the variable a becomes uninitialized again, as by the use of Clear, we see the following result from the identical input expression: Clear[a]; (5 a)^2 ===> 25 a^2 This behavior is VERY different from that of most other programming languages, and it can indeed be quite confusing to a newcomer. Mathematica can even seem to be perverse or crazy when this distinction has not been understood. As a particularly important case, variables whose values are to be found by Solve (and similar functions such as Reduce and FindInstance) MUST be uninitialized. One saving grace is that in Mathematica's front end, the color of an initialized variable is different from the color of an uninitialized variable. Check your system to see what colors are in use. Getting into the habit of watching the colors of variables in the front end can be tremendously helpful in making sense of Mathematica's uniquely powerful capabilities. - Using scoping constructs like Block[ ] or formal symbols like \[FormalX] is more robust than looking at the syntax coloring, I believe – belisarius May 13 at 1:10 I'm sure you are right. My answer is only about understanding what is going on with the language. New users often type in things which don't work, and then get more confused when Mathematica returns answers that they find incomprehensible. – Ralph Dratman 2 days ago # Using Sort incorrectly ### Sorting mathematical expressions without numeric conversion New users are often baffled by the behavior of Sort on lists of mathematical expressions. Though this is covered in the documentation of Sort itself they expect that expressions will be ordered by numeric value but they are not. Instead expressions are effectively ordered with Order which compares expression structures. (The full details of that ordering remain undisclosed but any specific pairing can be tested with Order.) To sort a list of expressions by their numerical values one should use SortBy, or somewhat more verbosely Ordering. These methods have much better computational complexity than using the ordering function parameter of Sort. exp = {Sqrt[2], 5, Sin[4]} Sort[exp] SortBy[exp, N] exp[[Ordering @ N @ exp]]  {5, Sqrt[2], Sin[4]} {Sin[4], Sqrt[2], 5} {Sin[4], Sqrt[2], 5}  An independent Q&A on this issue: Ordering problem ### Using the ordering parameter of Sort when SortBy is adequate As mentioned above it is far preferable to use SortBy, if it can be applied, rather than the ordering parameter of Sort. Using Sort[x, p] causes pairs of elements in x to be compared using p. If a problem can be recast such that every element is independently given a value that can sorted by the default ordering function faster vectorized application can be used. Taking the problem above as an example: Needs["GeneralUtilities"] (* Mathematica 10 package *) BenchmarkPlot[ {Sort[#, Less] &, SortBy[#, N] &}, Array[Sin, #] &, "IncludeFits" -> True ]  ### Converting to a List before sorting Sort is capable of natively operating on all normal non-atomic expressions: Sort /@ {7 -> 2, Hold[2, 1, 4], Mod[c, b, a], 1 | 4 | 1 | 5, "b"^"a"}  {2 -> 7, Hold[1, 2, 4], Mod[a, b, c], 1 | 1 | 4 | 5, "a"^"b"}  Additional reading: - ## Lingering Definitions: when calculations go bad One aspect of Mathematica that sometimes confuses new users, and has confused me often enough, is the Lingering Definition Problem. Mathematica diligently accumulates all definitions (functions, variables, etc.) during a session, and they remain in effect in the memory until explicitly cleared/removed. Here's a quick experiment you can do, to see the problem clearly. 1: Launch (or re-launch) Mathematica, create a new notebook, and evaluate the following expression: x = 2 + 2  2: Now close the notebook document without saving (and without quitting Mathematica), and create another fresh notebook. Evaluate this: x  The result can be surprising to beginners - after all, you think you've just removed all visible traces of x, closing the only notebook with any record of it, and yet, it still exists, and still has the value 4. To explain this, you need to know that when you launch the Mathematica application, you're launching two linked but separate components: the visible front-end, which handles the notebooks and user interaction, and the invisible kernel, which is the programming engine that underpins the Mathematica system. The notebook interface is like the flight deck or operating console, and the kernel is like the engine, hidden away but ready to provide the necessary power. So, what happened when you typed the expression x = 2 + 2, is that the front-end sent it to the kernel for evaluation, and received the result back from the kernel for display. The resulting symbol, and its value, is now part of the kernel. You can close documents and open new ones, but the kernel's knowledge of the symbol x is unaffected, until something happens to change that. And it's these lingering definitions that can confuse you - symbols that are not visible in your current notebook are still present and defined in the kernel, and might affect your current evaluations. This also affects subscripted expressions - consider the following evaluation, where the initially innocent symbol i is assigned an explicit value: If you want to use subscripted symbols in a more robust fashion, you should use e.g. the Notation package. There are a couple of things you can learn to do to avoid problems caused by Lingering Definitions. Before you provide definitions for specific symbols, clear any existing values that you've defined so far in the session, with the Clear function. Clear[x]  Or you can clear all symbols in the global context, using ClearAll. ClearAll["Global*"]  When all else fails, quit the kernel (choose Evaluation > Quit Kernel from the menu or type Quit[], thereby forgetting all the symbols (and everything else) that you've defined in the kernel. Some further notes: • Mathematica offers a way to keep the namespaces of your notebooks separate, so that they don't share the same symbols (see here). • Mathematica does have garbage collection, but most of the time you don't have to care about it being completely automatic. • Some dynamic variables can remain in effect even if the kernel is quit, as such variables are owned by the frontend. Be sure to remove all generated dynamic cells (via the menu option Cell > Delete All Ouput) before quitting/restarting the kernel. • See also this Q&A: How do I clear all user defined symbols? - I'd mention that the notebooks can be logically separated by setting their default contexts to something other than Global . – rcollyer Jan 27 '13 at 18:02 +1 I'd like more a title like "Lingering definitions: Why your notebook calcs may return weird results", which links the problem with the perceived symptoms – belisarius Jan 27 '13 at 20:43 I added a bit about subscript issues, not sure if it should be a separate answer, but it fits nicely into the scope of this one... – Yves Klett Jan 28 '13 at 10:15 Another important part of this separation is that saving the notebook only saves what is shown, not the values of symbols defined in it. So if you save the notebook with the definition of x and then open it again in a new Mathematica session, you might expect to be able to immediately use x again in the notebook. But you can't do that, you first have to evaluate the definition again. – celtschk Jul 26 '13 at 12:19 BTW, another way lingering definitions can bite you is when you change the pattern part of a function definition as well as the corresponding code part by editing the notebook and then executing the cell, but failing to first Clear the old version. Then you don't overwrite the definition, but add a new one, and it may happen that one of your calls happens to better fit the old version. Bugs of that type are very hard to find because all traces of the actually executed code have been removed from the notebook by the edit. – celtschk Jul 26 '13 at 12:29 ## The default $HistoryLength causes Mathematica to crash!

By default $HistoryLength = Infinity, which is absurd. That ensures Mathematica will crash after making output with graphics or images for a few hours. Besides, who would do something like In[2634]:=Expand[Out[93]].... You can ensure a reasonable default setting by including ($HistoryLength=2), or setting it to some other small integer in your "Init.m" file.

-

## Multiple front-end undo is not available in versions less than 10

As the title already claims, in versions less than 10, there is no overall option to undo certain steps in Mathematica files. Nevertheless, inside the boxes one can undo as long as one stays inside.

Personal recommendations: 1. Never delete some code except if what you were doing was completely wrong. 2. If you want to create a notebook for presentation, take an additional file as sandbox aside where you test all the things that should later appear in the notebook.

## Kernel undo is still not available

However, starting from version 10, multiple-undo is available. However, it is important to keep in mind that this is a front-end undo, not a kernel one. Thus, doing something like:

x:=4
Clear[x]


and then undoing the clear will not actually change the value of x back to 4.

-
Re Personal recommendation 2: Give your sandbox a separate context, as described here mathematica.stackexchange.com/a/3484/1200 , so that definitions from the Sandbox don't leak into the presentation. –  David Speyer Feb 19 '13 at 0:08
@DavidSpeyer: Good recommendation. This is something I should keep in mind! –  strpeter Aug 11 '14 at 9:19

## Avoiding procedural loops

People coming from other languages often translate directly from what they are used to into Mathematica. And that usually means lots of nested For loops and things like that. So "say no to loops" and get programming the Mathematica way! See also this excellent answer for some guidance on how Mathematica differs from more conventional languages like Java in its approach to operating on lists and other collections.

1. Use Attributes to check if functions are Listable. You can avoid a lot of loops and code complexity by dealing with lists directly, e.g. by adding the lists together directly to get element-by-element addition.
2. Get to know functions like NestList, FoldList, NestWhileList, Inner and Outer. You can use many of these to produce the same results as those complicated nested loops you used to write.
3. Get to know Map (/@), Apply (@@ and @@@), Thread, MapThread and MapIndexed. You'll be able to operate on complex data structures without loops using these.
4. Avoid unpacking/extracting parts of your data (via Part or Extract) and try to handle it as a whole, passing your huge matrix directly to Map or whatever iterative function you use.
5. See also this Q&A: Alternatives to procedural loops and iterating over lists in Mathematica

keywords: loop for-loop do-loop while-loop nestlist foldlist procedural

-
Rather than post a separate answer perhaps something about packed arrays could be added to this answer. This is a handy link: library.wolfram.com/infocenter/TechNotes/391 –  Mike Honeychurch Jan 25 '13 at 3:27
What are the performance advantages of avoiding procedural loops? I suppose some people may resort to them for readability. –  Black Milk May 23 '13 at 1:17
@BlackMilk late answer, I know, but triply nested For loops are NOT more readable than the alternatives. –  Verbeia Dec 24 '13 at 3:53
dont follow this advice or you wont be able to read your code. Procedural programming is the most used paradigm at the moment (over 90% of all languages) –  TraceKira Dec 11 '14 at 13:58
@timoftebogdan. I disagree- this is a site about Mathematica, so it is not relevant if nested loop-itis is popular in other languages. And Map is a lot more readable than For...etc –  Verbeia Dec 11 '14 at 18:11

## Mathematica's own programming model: functions and expressions

There are many books about Mathematica programming, still one sees many people falling to understand Mathematica's programming model and usually misunderstand it as functional programming.

This is, because one can pass a function as an argument, like

plotZeroPi[f_] := Plot[f[x], {x,0,Pi}];
plotZeroPi[Sin] (* produces Plot[Sin[x],{x,0,Pi}] *)


and so people tend to think that Mathematica follows a functional programming (FP) model. There is even a section in the documentation about functional Programming. Yes, looks similar, but it is different - and you will see shortly why.

### Expressions are what evaluation is about

Everything in Mathematica is an expression. An expression can be an atom, like numbers, symbol variables and other built-in atoms, or a compound expression. Compound expressions -our topic here- have a head followed by arguments between square brackets, like Sin[x].

Thus, evaluation in Mathematica is the ongoing transformation from one expression to another based on certain rules, user-defined and built-in, until no rules are applicable. That last expression is returned as the answer.

Mathematica derives its power from this simple concept, plus a lot of syntactic sugar you have to write expressions in a more concise way… and something more we will see below. We don't intent to explain all the details here, as there are other sections in this guide to help you.

In fact, what happened above is the definition of a new head, plotZeroPi via the infix operator :=. More over, the first argument is a pattern expression plotZeroPi[f_], with head (as pattern) plotZeroPi and a pattern argument. The notation f_ simply introduces an any pattern and gives it a name, f, which we use in the right hand side as the head of another expression.

That's why a common way to express what f is, is that plotZeroPi has a function argument - although is not very precise-, and we also say that plotZeroPi is a function (or a high-level function in FP lingo), although is now clear that there is little abuse of language here.

Bottom line: Mathematica looks as functional programming because one is able to define and pass around heads.

### Putting evaluation on hold

But, note that Plot does not expect a function, it expects a expression! So, although in a functional programming paradigm, one would write Plot with a function parameter, in Mathematica plot expects an expression. It is a design choice in Mathematica and one would argue that it makes it quite readable.

This works because Plot is flagged to hold the evaluation of its arguments (see non-standard). Once Plot sets its environment internally, it triggers the evaluation of the expression with specific values assigned to x. When you read the documentation, beware of this subtlety: it says function although a better term would have been expression.

So, what happens if one needs to perform a complex operation and once that is done, a function is clearly defined? Say you want to compute Sin[$\alpha$ x], where $\alpha$ is the result of a complex operation. A naive approach is

func[p_, x_] := Sin[costlyfunction[p] x]


If you then try

Plot[func[1.,x], {x,0,Pi}]


you can be waiting long to get that plot. Even this does not work

func[p_][x_] := Sin[costlyfunction[p] x]


because the whole expression is unevaluated when entering Plot anyway. In fact, if you try func[1.] in the front-end, you will see that Mathematica does not know a rule about it and can't do much either.

What you need, is something that allows you to return a head of an expression. That thing will have costlyfunction calculated once before Plot takes your head (the expression's, not yours) and gives it an x.

Mathematica has a built-in, function that gives you that.

func[p_] := With[{a = costlyfunction[p]}, function[x, Sin[a x]] ];


With introduces a new context where that costly function is evaluated and assigned to a. That value is remembered by function, which is nothing but a head that you can use when needed. For those familiar with functional programming in other languages, a is part of the closure where the function is defined; and function is the way one enters a lambda construct into Mathematica.

Another way to do it, more imperative if your like, is using Module and what you already know about defining rules -which is more familiar to procedural programming-:

func[p_] := Module[{f, a},
a = costlyfunction[p];
f[x_] := Sin[a x];
f
];


In it, a new context is introduced with two symbols, f and a; and what it does is simple: it calculates a, then defines f as a head as we want it, and finally returns that symbol f as answer, a newly created head you can use in the caller.

In this definition, when you try say, func[1.], you will see a funny symbol like f$3600 being returned. This is the symbol that has the rule f[x_] := Sin[a x] attached to it. It was created by Module to isolate any potential use of f from the outside world. It works, but certainly is not as idiomatic as function. The approach with function is more direct, and there is syntactic sugar for it too; you will see it in regular Mathematica programming func[p_] := With[{a = costlyfunction[p]}, Sin[a #]& ];  Ok, let's continue. Now that func really returns a function, i.e. something that you can use as the head of an expression. You would use it with Plot like With[{f = func[1.]}, Plot[f[x],{x,0,Pi}]]  and we bet that by this time you will understand why Plot[func[1.][x],{x,0,Pi}] is as bad as any of the previous examples. ### On returning a expression A final example is Piecewise (from the documentation) Plot[Piecewise[{{x^2, x < 0}, {x, x > 0}}], {x, -2, 2}]  So, what if the boundary on the condition is a parameter? Well, just apply the recipe above: paramPieces[p_] := Piecewise[{{#^2, # < p}, {#, # > p}}] &;  One shouldn't do paramPieces[p_] := Piecewise[{{x^2, x < p}, {x, x > p}}];  because Piecewise does not have the hold attribute and it will try to evaluate its argument. It does not expect an expression! If x is not defined, you may see a nice output when you use it, but now you are constrained to use the atom (variable name) x and although Plot[paramPieces[0], {x, -1, 1}]  seems to work, you are setting yourself for trouble. So, how to return something you can use in Plot? Well, in this case, the parameter is not a burden to the calculation itself, so one sees this kind of definitions being used paramPieces[p_, x_] := Piecewise[{{x^2, x < p}, {x, x > p}}]; Plot[paramPieces[0, x], {x,-1,1}]  And, if x is undefined, paramPieces[0, x] is nicely displayed in the front-end as before. This works because, again, Mathematica is a expressions language, and the parameter x makes as much sense as the number 1.23 in the definition of paramPieces. As said, Mathematica just stops the evaluation of paramPieces[0, x] when no more rules are applied. ### A remark on assignment We have said above several times that x gets assigned a value inside Plot and so on. Again, beware this is not the same as variable assignment in functional programming and certainly there is (again) abuse of language for the sake of clarity. What one has in Mathematica is a new rule that allows the evaluation loop to replace all occurrences of x by a value. As appetiser, the following works Plot3D[Sin[x[1] + x[2]], {x[1], -Pi, Pi}, {x[2], -Pi, Pi}]  There is no variable x[1], just a expression that gets a new rule(s) inside Plot every time it gets a value for plotting. You can read more about this in this guide too. Note to readers: Although these guides are not meant to be comprehensive, please, feel free to leave comments to help improve them. - I have heard Mathematica being called a multi paradigm language. – Jacob Akkerboom Dec 30 '13 at 10:08 +1 I believe that once you understand the Mathematica evaluation and the use of With you can do almost anything with Mathematica. – faysou Dec 30 '13 at 10:15 @JacobAkkerboom, I've heard the same, so I will add some notes to reach a wider audience. Thanks! – carlosayam Dec 31 '13 at 0:10 But in Mathematica everything is an expression, so it's not wrong to call a function an expression. – RunnyKine Jul 6 '14 at 23:52 An easy way to understand Mathematica's evaluation: consider a function/tree f[a,b]. Without any particular attribute for f the leafs/arguments will be evaluated before the parent f. With f having a HoldAll attribute you don't evaluate the leafs but go directly in the evaluation of f. a and b will be evaluated as soon as they are used in a function that doesn't hold again their evaluation. Example SetAttributes[f, HoldAll]; f[a_,b_]:= a Hold[b]; f[2^2,2^2] – faysou Dec 23 '14 at 20:38 # Leaving the Suggestions Bar enabled The predictive interface (Suggestions Bar) is the source of many bugs reported on this site and surely many more that have yet to be reported. I strongly suggest that all new users turn off the Suggestions Bar to avoid unexpected problems ranging from massive memory usage to peculiar evaluation leaks. - ## Assuming commands will have side effects which they don't: Consider: In[97]:= list = {1, 2, 3} Out[97]= {1, 2, 3} In[98]:= Append[list, 4] Out[98]= {1, 2, 3, 4} In[99]:= list Out[99]= {1, 2, 3}  When I was first learning Mathematica, I assumed that Append[list, 4] would take the list list and append the element 4 to it, overwriting the previous list. But this is not right: Append[] returns the result of appending 4 to list without overwriting the input list. In general, a command which alters its inputs, or other global variables, is said to have a side effect. Mathematica in general avoids side effects whenever it would be reasonable to do so, encouraging (but not forcing) a functional programming style, returning values instead of variables (addresses/pointers/names/etc. in other languages). If one wants to store a value (instead of passing it right away to another function) one has to "save" it explicitly into a variable. I think it is a safe statement that the Mathematica documentation will always say explicitly when a command has a side effect. For example, the documentation (version 7) for Delete[] reads Delete[expr,n] deletes the element at position$n$in$expr$. If I encountered this sentence in the documentation of a language I had never seen before, I would assume that Delete[] altered the expression expr. However, with experience reading Mathematica documentation, I am confident that if this side effect existed, it would be stated explicitly and, indeed, Delete[] has no side effects. I remember finding many of the list commands confusing because their names are verbs which, in English, would seem to suggest that the list was being restructured. In particular, note that Append[], Prepend[], Take[], Drop[], Insert[], Delete[], Replace[], ReplacePart[], DeleteDuplicates[], Flatten[], Join[], Transpose[], Reverse[] and Sort[] are all side effect free. For completeness, I should mention that for some functions there are side-effect-having alternatives, usually with an added prefix at the end of the function name, like AppendTo (for Append), AddTo (for Add), SubtractFrom (for Subtract), TimesBy (for Times), etc. These functions not only perform the calculation but also save the new result into the variable they were called with. Because of this, they must be called with a symbol instead of a number or an explicit list. - "Special forms of assignment" :reference.wolfram.com/mathematica/tutorial/… – belisarius Mar 14 '13 at 11:56 Would the "...prefix at the end..." be a postfix? – mikuszefski Jan 27 at 10:29 @mikuszefski (and DavidSpeyer), I think 'suffix' is the more common English word. – Jade NB Apr 27 at 2:42 Well, sort of... @JadeNB for further reading english SE – mikuszefski Apr 27 at 6:48 ## User-defined functions, numerical approximation, and NumericQ Frequently there are questions, to which the answer is to use x_?NumericQ, about defining functions that call or sometimes are passed to • FindRoot, NIntegrate, NMaximize, NMinimize, FindMaximum, FindMinimum, NDSolve, ParametricNDSolve, FindFit, LinearModelFit, NonlinearModelFit, and so on. Sometimes the analogous VectorQ, MatrixQ, or ArrayQ is the answer (see this answer). The Wolfram Knowledge Base Article, "Using ?NumericQ to Affect Order of Evaluation" gives a good explanation of how to use NumericQ. ### Answers in which NumericQ figured Here are links to some of the answers in which NumericQ was a key to the solution of the problem. The headings include the command(s) and sometimes some error messages characteristic of this problem. Some answers deal with multiple commands and they are not sorted into combinations, except NIntegrate/FindRoot which is a particularly common problem; connections with other functions indicated next to the links. • NIntegrate/FindRoot -- 1), 2) • FindRoot - FindRoot::nlnum -- 1) (NArgMax), 2) SingularValueList, 3), • NIntegrate - NIntegrate::inumr, NIntegrate::nlim -- 1), 2), 3) Compile, 4), 5) NDSolve, • NDSolve -- 1a), 1b), 2), 3), • NMinimize/NMaximize/FindMinimum/FindMaximum - NMinimize::nnum, FindMinimum::nrnum -- 1) NMinimize/NMaximize, 2) FindMinimum, 3) explanation of the downside of NumericQ, • FindFit/LinearModelFit/NonlinearModelFit 1) • Plotting numeric functions -- Various plot functions try evaluating the function to be plotted symbolically at first. If one is trying to plot a numerical function like NIntegrate, then one has to wrap it in a function whose arguments are protected by ?NumericQ. 1) - There are many answers in which NumericQ figures. Some have long explanations, some just point out the problem, and some show the solution without much comment. Of the ones I could find, I tried to include those with at least some explanation and include a variety of the circumstances in which the problem arises. No doubt others may know of better examples I've missed, and I hope they will improve this answer. Thanks! – Michael E2 May 28 '13 at 22:54 I can't believe this wasn't already on the list. Thanks for adding it, and with lots of references! – Mr.Wizard May 29 '13 at 3:29 # Learn how to use the Documentation Center effectively Mathematica comes with the most comprehensive documentation I have ever seen in a software product. This documentation contains • reference pages for every Mathematica function • tutorials for various topics, which show you step by step how to achieve something • guide pages to give you an overview of functions about a specific topic • a categorised function navigator, to help you find appropriate guide pages and reference pages. • finally, the complete interactive Mathematica book You can always open the Documentation Center by pressing F1. When the cursor (the I-beam) is anywhere near a function, then the help page of this function is opened. E.g. when your cursor is anywhere at the position where the dots are in .I.n.t.e.g.r.a.t.e., you will be directed to the help page of Integrate. ## Reference pages: A reference page is a help page which is dedicated to exactly one Mathematica function (or symbol). In the image below you see the reference page of the Sin function. Usually, some of the sections are open, but here I closed them so you see all parts at once. • In yellow, you see the usage. It gives you instantly information about how many arguments the function expects. Often there is more then one usage. Additionally, a short description is given. • The Details section gives you further information about Options, behavioural details and things which are important to note. In general, this section is only important in a more advanced state. • In some cases, extra information is provided on the mathematical Background of the function explaining the depths of the method, its relation to other functions and its limitations (for example FindHamiltonianCycle). • The Examples section is the most important, because there you have a lot of examples, showing everything starting from simple use cases to very advanced things. Study this section carefully! • See Also gives you a list of functions which are related. Very helpful, when a function does not exactly what you want, because most probably you find help in the referenced pages. • Tutorials shows you tutorials which are related to the function. In the case of Sin it is e.g. the Elementary Transcendental Functions tutorial. • Related Guides gives you a list of related guide pages. • Related Links references to material in the web: Demonstrations, MathWorld pages, etc. In general my recommendation for viewing a help page is the following: 1. Study the usage carefully 2. Look up basic examples. If you don't find what you need, look up all examples 3. Read the Details And of course if you like the how-to style, you should read the referenced tutorials. ## Guide pages: Guide pages collect all functions which belong to a certain topic and they are an excellent resource when you try to find a function you do not know yet. The guide page itself is often divided into several subsections collecting similar functions. In the image above for instance the Trigonometric Functions. Furthermore, you can find links to tutorials, etc. when you open the Learning Resources tab. At the end of each guide page you will find references to related guide pages. ## Function navigator and virtual book: The rest can be explored by just trying and does not need extensive explanation. To reach the function navigator or the book, you can use the buttons on the top of the Documentation Center. The rest is mostly self-explanatory. The virtual book is a very nice resource when you like to read something from the beginning to the end. In this way you can be sure that you at least scraped every functionality of Mathematica, which you probably miss when you hop between the help pages. But be warned, it is a lot of material! ## Final notes: • Since the complete documentation consists of usual Mathematica notebooks, all calculations and examples can be tested inside the help pages. Of course, you cannot destroy the documentation, because everything is reset when you close a help page. • You can always search the documentation by typing into the search bar on top of the Documentation Center: • When coming from a different programming language, and you are not sure that a certain Mathematica function is equivalent to what you are used to, be sure to check the Properties & Relations section in the reference page to get ideas on what other functions could be relevant for your case. - +1 This should be pinned to the top:) – Ajasja Feb 18 '13 at 21:45 F1 works only on Windows and Linux. Documentation Center is accessed on a Mac using command-shift-F. – rhomboidRhipper May 27 '14 at 20:04 @rhomboidRhipper I use Mathematica on two MacBooks Pro and on several MacPro's and on each of them the F1 short-cut is working fine. Is it possible that your system settings required that you need to press a the command shift combination to access the F keys? – halirutan May 27 '14 at 20:14 It should be noted that the V10 documentation works differently. The home page is different and currently the function navigator is missing. – Sjoerd C. de Vries Mar 22 at 19:55 ## Mathematica can be much more than a scratchpad My impression is that Mathematica is predominately used as a super graphical calculator, or as a programming language and sometimes as a mathematical word processor. Although it is in part all of these things, there is a more powerful usage paradigm for Mathematica. Mathematica stackexchange itself tends to be strongly oriented towards specific programming techniques and solutions. The more powerful and broader technique is to think of Mathematica as a piece of paper on which you are developing and writing your mathematical ideas, organizing them, preserving knowledge in an active form, adding textual explanation and perhaps communicating with others through Mathematica itself. This requires familiarity with some of the larger aspects of Mathematica. These suggestions are focused toward new users who are either using Mathematica to learn mathematical material or want to develop new and perhaps specialized material. Most beginners use the notebook interface - but just barely. They should learn how to use Titles, Sections and Text cells. If I was teaching a beginner I would have the first assignment be to write a short essay without any Input/Output cells at all. I would have them learn how to look at the underlying expression of cells, and how to use the ShowGroupOpener option so a notebook could be collapsed to outline form. Most subjects worthy of study or development require extended treatment. This means there may be multiple types of calculation or graphical or dynamic presentations. And multiple is usually simpler for a beginner with Mathematica. Notebooks will be more to the long than the short side. New users should be encouraged to write their own routines when necessary. It certainly pays to make maximum use of built-in routines, and difficult to learn them all, but Mathematica is more like a meta-language from which you can construct useful routines in specific areas. Sometimes it is useful to write routines simply for convenience in usage. It's also worthwhile to think of routines as definitions, axioms, rules and specifications rather than as programs. Perhaps it is just a mindset but it is Mathematica and not C++. Routines can be put in a section at the beginning of a notebook. Again, I would teach new users how to write usage messages, SyntaxInformation statements, and define Options and Attributes for routines. Most new users would probably prefer not to be bothered with this but it represents the difference between ephemeral material and permanent active useful aquired knowledge. Writing useful routines is probably the most difficult part. Using them in longish notebooks will always expose flaws in the initial design. A new user working on a new project should create a folder for the project in the$UserBaseDirectory/Applications folder. This is THE place to gather material on a specific project. Then, if many useful routines have been created in the Routines sections of various notebooks, they could be moved to a package in the same Application folder. Again, it is not very difficult to write packages (especially if the routines have already been written and tested) and this makes the accumulated routines available to all notebooks. If one gets more advanced, style sheets and palettes can be added to the same application, along with an extended folder structure.

None of the things I have discussed here (except writing actual useful routines) is especially difficult to learn. It does provide a stable framework for using Mathematica and accumulating knowledge and experience. It is the present Mathematica paradigm.

-
I am not certain how to make the link above so perhaps someone can help with that. I don't know how to select a specific object to link to. –  David Park Dec 23 '13 at 21:40
Thanks, I already did it :). In the future you can get the link from under your answer (labeled share) –  belisarius Dec 23 '13 at 21:41

## Understand what Set (=) really does

Because WRI's tutorials and documentation encourage the use of =, the infix operator version of Set, in a manner that mimics assignment in other programming languages, newcomers to Mathematica are likely to presume that Set is the equivalent of whatever kind of assignment operator they have previously encountered. It is hard but essential for them to learn that Set actually associates a rewrite rule (an ownvalue) with a symbol. This is a form of symbol binding unlike that in any other programming language in popular use, and eventually leads to shock, dismay, and confusion, when the new user evaluates something like x = x[1]

Mathematica's built-in documentation doesn't do a good job of helping the new user to learn how different its symbol binding really is. The information is all there, but organized almost as if to hide rather than reveal the existence and significance of ownvalues.

What does it mean to say that "Set actually associates a rewrite rule (an ownvalue) with a symbol"? Let's look at what happens when an "assignment" is made to the symbol a; i.e., when Set[a, 40 + 2] is evaluated.

a = 40 + 2


42

The above is just Set[a, 40 + 2] as it is normally written. On the surface all we can see is that the sub-expression 40 + 2 was evaluated to 42 and returned, the binding of a to 42 is a side-effect. In a procedural language, a would now be associated with a chunk of memory containing the value 42. In Mathematica the side effect is to create a new rule called an ownvalue and to associate a with that rule. Mathematica will apply the rule whenever it encounters the symbol a as an atom. Mathematica, being a pretty open system, will let us examine the rule.

OwnValues[a]


{HoldPattern[a] :> 42}

To emphasize how really different this is from procedural assignment, consider

a = a[1]; a


42[1]

Surprised? What happened is the ownvalue we created above caused a to rewritten as 42 on the righthand side of the expression. Then Mathematica made a new ownvalue rule which it used to rewrite the a occurring after the semicolon as 42[1]. Again, we can confirm this:

OwnValues[a]


{HoldPattern[a] :> 42[1]}

An excellent and more detailed explanation of where Mathematica keeps symbol bindings and how it deals with them can be found in the answers to this question. To find out more about this issue within Mathematica's documentation go here.

keywords set assign ownvalue variable-binding

-
+1 But I think the sentence "It is hard but essential to them to learn that Set actually associates a rewrite rule (an ownvalue) with a symbol." deserves further explanation for a new user. –  belisarius Jan 25 '13 at 18:20
Not only does the documentation not do a good job of explaining how different Mathematica is to other languages, but in many cases actually attempts to hand-wave the differences away. A user can have read the documentation thoroughly, but then come to a site like this and realise they don't understand the language at all. For this reason I think resources like Leonid's book that deal with things more directly are really essential resources for the newcomer. –  Oleksandr R. Jan 25 '13 at 18:22
Consider adding a link to this question which explains the distinction between OwnValues, DownValues, etc. –  rcollyer Jan 25 '13 at 18:22
@OleksandrR. The book Power Programming With Mathematica: The Kernel by David B. Wagner also does a good job with this issue. –  m_goldberg Jan 25 '13 at 18:31
a[1] = 2;a = 42;a = a[1]; a –  m_goldberg Jan 27 '13 at 1:24

## Understand that semicolon (;) is not a delimiter

Although it may look to newcomers that semicolons are used in Mathematica as statement terminators as in C or Java, or perhaps as statement separators as in Pascal and its derivatives, in fact, semicolons are the infix form of the function CompoundExpression, just as plus-signs (+) are the infix form of the function Plus.

You can verify this by evaluating

Hold[a; b; c] // FullForm


Hold[CompoundExpression[a, b, c]]

CompoundExpression is necessary to Mathematica because many of the core programming functions such as SetDelayed (:=), Module, Block, and With take only a single expression as their second argument. This second argument is of course the code body and normally requires the evaluation of many expressions. CompoundExpression provides the construct that bundles an indefinite number of expressions into one.

Wolfram Research chose semicolon for the binary operator form of CompoundExpression to make Mathematica code look more like C code, but this is only syntactic sugar.

The only true delimiter in Mathematica is comma (,).

### Update

One often sees code like the following

data = RandomReal[{0., 10.}, {1000, 2}];


The variable data is probably going to be used as test or example data. The semicolon is added to suppress the output from this Set expression because the output is both very large and no one really cares about its details. Because there is no visible output, it would be easy to assume the expression returns nothing, but that is not true. Mathematica expressions always return something, even if it is only the token Null, which does not print in OutputForm. In the case of CompoundExpression, there is an additional twist -- I quote from the Mathematica documentation:

expr1; expr2; returns value Null. If it is given as input, the resulting output will not be printed. Out[n] will nevertheless be assigned to be the value of expr2.

This the only case I know of where evaluating an expression at toplevel doesn't assign its actual output to Out[n].

keywords delimiter terminator separator semicolon compound-expression

-
perhaps a bit more on the actual effect of ;? –  Yves Klett Jan 28 '13 at 14:22
@YvesKlett. I think posts to this CW are meant to be restricted to pitfalls and not meant to be replacements for general documentation. –  m_goldberg Jan 28 '13 at 14:27
But a common pitfall is not to suppress output or improper use of , vs. ; in Module etc. –  Yves Klett Jan 28 '13 at 14:29
Shouldn't binary form be infix form? In fact, CompoundExpression is in general not a binary operation! –  halirutan Jan 28 '13 at 15:39
It should be noted that ; has a lower precedence than almost everything, including both Set and SetDelayed. So, to use them in conjunction with each other, parentheses or a scoping construct needs to be used. –  rcollyer Jan 29 '13 at 21:03

## Why is my picture upside-down?

Sometimes, when moving from data-based representations into image-based representations, odd things happen. For example, the left-most leaf in the rose

img = ColorConvert[Import["ExampleData/rose.gif"], "grayscale"]


points downwards. Yet if we extract the data in the image and plot by another means

imgData = ImageData[img];
ReliefPlot[imgData]


the left-most leaf points upwards. The image is rendered upside-down! This can be seen numerically by contrasting the dimensions of the imageData and the dimensions of the image itself:

ImageDimensions[img]
imgData = ImageData[img]


which return {223, 164} and {164, 223} respectively.

This problem is endemic to all programs that handle images/graphics and as well as data/matrices. Why? Because there are two different coordinate systems in common use. Images, like graphics, use regular Cartesian coordinates. For example, the point (1,2) means one to the right and two up. The point (10, 3) means 10 to the right and 3 up. The origin is effectively in the bottom-left and the two coordinates are indices into the (column, row).

Contrast this with matrices. Here the convention is

 a11 a12 a13
a21 a22 a23
a31 a32 a33


In this arrangement, the origin is effectively at the top left and the two coordinates index into the (row, column). The symptom you see (having to Reverse the ImageData) is a result of this dual-origin problem.

You can see this dual-system at work by clicking on an image. Choose "get coordinates" and the coordinate system for the image has (1,1) in the lower left. But if you choose "get indices" then the coordinate system starts in the top left. Coordinates are the image coordinates, indices index into ImageData. So for instance, ImageValue[img, {1, 1}] gives the bottom left pixel value. The documentation tries to reduce this confusion by using words like "gives the pixel value of image at position {x,y}" (for example, see the help for ImageValue) to refer to image (Cartesian) coordinates, while it uses "row," "column," and "index" when it is using matrix-indices (for example, see the help file for ImageTake).

Fortunately, there is a simple fix: to use the option DataReversed.

imgDataRev = ImageData[img, DataReversed -> True];
ReliefPlot[imgDataRev]


Several other plotting commands require similar processing. For example:

ListPlot3D[1 - imgDataRev]


again requires the datareversal in order to not be turned upside-down.

Two related questions with associated answers can be found here and here.

-

# The displayed form may substantially differ from the internal form

As soon as you discover replacement rules, you are bound to find that they mysteriously fail to replace subexpressions, or replace subexpressions you didn't expect to be replaced.

For example, consider the definition

foo = (a+b)(c+d)(e-f)/Sqrt[2]


which will cause Mathematica output an expression which looks very much like what you entered; approximately: $$\frac{(a+b)(c+d)(e-f)}{\sqrt{2}}$$ Also the InputForm seems to confirm that no transformation has been done to that expression:

((a + b)*(c + d)*(e - f))/Sqrt[2]


Now try to apply some rules on this (from now on I'll give the output in InputForm):

foo /. {x_ + y_ -> x^2 + y^2, x_ - y_ -> x^2 - y^2, Sqrt[2] -> Sqrt[8]}
(*
==> ((a^2 + b^2)*(c^2 + d^2)*(e^2 + f^2))/Sqrt[2]
*)


What is that? We explicitly requested the difference to be replaced with a difference of squares, not a sum! And why wasn't Sqrt[2] replaced at all?

Well, the reason is that Mathematica expressions are not what they look like. To see the real structure of a Mathematica expression, you can use FullForm:

foo // FullForm
(*
==> Times[Power[2, Rational[-1, 2]], Plus[a, b], Plus[c, d],
Plus[e, Times[-1, f]]]
*)


Now, we see why the replacement rules didn't work as expected: e-f is actually e + (-1)*f and thus matched perfectly the first rule (sum of two expressions) which transformed that into e^2 + ((-1)*f)^2 which of course evaluates to e^2+f^2. At the time the second rule is applied, the difference doesn't exist any more. Also, the Sqrt[2] in the denominator is actually a factor of 2^(-1/2). It is also easy to check that Sqrt[2] has Power[2, Rational[1, 2]] (that is, 2^(1/2)) as FullForm. That one is nowhere found in the FullForm of the expression foo evaluates to.

With that knowledge we can correct our replacement rules to work as expected:

foo /. {x_Symbol + y_Symbol -> x^2 + y^2,
x_Symbol - y_Symbol -> x^2 - y^2,
1/Sqrt[2] -> 1/Sqrt[8]}
(*
==> ((a^2 + b^2)*(c^2 + d^2)*(e^2 - f^2))/(2*Sqrt[2])
*)


First, we restricted our + rule to only accept symbols as expressions, so that it doesn't match e-f. For consistency, the same is true for the second rule. Finally, we replaced 1/Sqrt[2] instead of Sqrt[2] (Mathematica correctly evaluated 1/Sqrt[8] to 1/(2 Sqrt[2])).

Note that instead of FullForm you can also use TreeForm, which gives you a nice graphical representation of the internal expression).

-
A very common mistake, indeed (+1) –  belisarius Jul 26 '13 at 17:58

## Attempting to make an assignment to the argument of a function

Quite frequently new users attempt something like this:

foo[bar_, new_] := AppendTo[bar, new]

x = {1};

foo[x, 2]


To be met with:

AppendTo::rvalue: {1} is not a variable with a value, so its value cannot be changed. >>

Or:

f[x_, y_] := (x = x + y; x)

a = 1;
b = 2;

f[a, b]


Set::setraw: Cannot assign to raw object 1. >>

This is because the value of the symbol x, a, etc. is inserted into the right-hand-side definition.

One needs either a Hold attribute for in-place modification:

SetAttributes[foo, HoldFirst]

foo[bar_, new_] := AppendTo[bar, new]

x = {1};

foo[x, 2];

x

{1, 2}


Or a temporary symbol, typically created with Module, for intermediate calculations:

f[x_, y_] := Module[{t}, t = x + y; t]

a = 1;
b = 2;

f[a, b]

3


(This definition is of course highly contrived for such a simple operation.)

Other Hold attributes include: HoldAll, HoldRest, and HoldAllComplete.

Note: Passing held arguments to a function with Attributes is similar to passing arguments by reference in other languages; ByRef keyword in VBA, or passing a pointer or a reference in C++ for example. However note that this similarity is no equivalence; for example, when passing the first element of a list to a reference in C++, only the list member will be passed; in Mathematica, the expression to access the list member will be passed. This can lead to differences if e.g. another item is prepended to the list before accessing the argument: With pass by reference in C++, the argument will refer to the same value, despite it now being the second element; however Mathematica will evaluate the expression only after using the argument, thus giving the new first element:

a={1,2,3};
SetAttributes[foo, HoldFirst]
foo[x_] := (PrependTo[a, 0]; x)
foo[ a[[1]] ]
(*
==> 0
*)

-
Passing held arguments to a function with Attributes is similar to passing arguments by reference in other languages. –  faysou Feb 5 '13 at 9:40
@Faysal If you feel that should be part of the answer feel free to edit it. I'm quite unfamiliar with most other languages so I'll not do that myself. –  Mr.Wizard Feb 5 '13 at 10:42
Surprising from someone of your level ! –  faysou Feb 5 '13 at 11:14

## Understand the difference between Set (or =) and SetDelayed (or :=)

A common misconception is that = is always used to define variables (such as x = 1) and := is used to define functions (such as f[x_] := x^2). However, there really is no explicit distinction in Mathematica as to what constitutes a "variable" and what constitutes a "function" — they're both symbols, which have different rules associated with them.

Without going into heavy details, be aware of the following important differences (follow the links for more details):

• = is an immediate assignment, whereas := is a delayed assignment. In other words, f = x will assign the value of x to f at definition time, whereas f := x will return the value of x at evaluation time, that is every time f is encountered, x will be recalculated. See also: 1, 2, 3
• If you're plotting a function, whose definition depends on the output of another possibly expensive computation (such as Integrate, DSolve, Sum, etc. and their numerical equivalents) use = or use an Evaluate with :=. Failure to do so will redo the computation for every plot point! This is the #1 reason for "slow plotting". See also: 1, 2

At a slightly more advanced level, you should be aware that:

• = holds only its first argument, whereas := holds all its arguments. This does not mean however that Set or SetDelayed don't evaluate their first argument. In fact, they do, in a special way. See also: 1
• =, in combination with :=, can be used for memoization, which can greatly speed up certain kinds of computations. See also: 1

Here is one discussion which illustrates why normally one should use SetDelayed to define functions. Even for interactive work, making systematic use of this practice pays huge dividends.

keywords: set setdelayed assignment definition function variable

-
Nice! Perhaps the behavior of (for example)f = Interpolation[Array[RandomInteger@1000 &, 1000]] with Set and SetDelayedcould be illustrative. –  belisarius Jan 26 '13 at 7:03

## Use Consistent Naming Conventions

This is basic, and good practice in any programming language, but Mathematica's slow-to-fail nature makes it in a sense a less forgiving language than others, so those of us who have in the past gotten away with bad habits may run into trouble. Suppose I have a function

loseMemoriesLikeTearsInRain[]


which I later try to invoke thusly:

loseMemoryLikeTearsInRain[]


In some other languages this would result in a compile error, and is easily spotted, but in Mathematica, what usually happens is either

1. the unevaluated expression loseMemoryLikeTearsInRain[] gets passed on to some other function,
2. Mathematica silently moves on without performing the side effects the function is supposed to perform, or
3. both.

For this reason, I have found it especially important to have a consistent set of conventions for naming things. The exact choice is to some extent a matter of taste, but here are some things that have tripped me up:

1. inconsistent capitalization,
2. starting function names with a capital letter (can conflict with predefined Mathematica functions),
3. inconsistent use of singular and plural (I now try to favor the singular whenever possible),
4. names that do not distinguish between pure functions and those with side effects (I now use noun-clauses and verb-clauses respectively),
5. generally inconsistent, idiosyncratic, or poorly thought out use of terminology,
6. attempts to abbreviate beyond what is reasonable or memorable. (One consistent convention is to drop all vowels other than the first letter of the word, whch mks evrythng lk lk ths.)
-
Autocompletion is useful for this purpose –  belisarius Feb 8 '13 at 14:14
Concerning Mathematica, I would not recommend abbreviating function names. Lengthy function names isn't really a big issue performance-wise, and in my experience it is more important that you remember years later what your function does than to save some typing. Mathematica itself is very eminent on giving informative though long names (think of FrequencySamplingFilterKernel, SymmetrizedIndependentComponents, etc.). –  István Zachar Feb 18 '13 at 20:37

## Using the result of functions that return replacement rules

Most new Mathematica users will at some point encounter the seemingly odd formatting of the output given by functions such as Solve or Root.

Solve[x^2 == 4, x]


{{x -> -2}, {x -> 2}}

You might find this output strange for two reasons. We'll have a look at both.

### What do the arrows mean?

The output that Solve returns, is what is called a replacement rule in Mathematica. A replacement Rule is of the form lhs -> rhs and does not do much on its own. It is used together with other functions that apply the rule to some expression. The arguably most common of these functions is ReplaceAll, which can be written in the short form /.. As the documentation states

expr/.rules

applies a rule or list of rules in an attempt to transform each subpart of an expression expr.

In practice, this looks like the following:

x + 3 /. x -> 2


5

Notice how /. and -> are combined to replace the x in the expression x+3 by 2. And this is also how you can use the Solve output. The simplest form would be:

x /. Solve[x^2 == 4, x]


{-2,2}

Since you will often face more complicated problems and Solve and its ilk might take quite some time to evaluate, it makes sense in theses cases to only calculate the solutions once and save them for later use. Just like many other expressions, replacement rules can be assigned to symbols using Set:

sol = Solve[x^2 == 4, x];
x /. sol


{-2, 2}

### Why the nested structure?

At first glance, the nested structure of the output looks strange and you might ask: why is the output of the form {{x -> -2}, {x -> 2}} when it could just could be {x -> -2, x -> 2}?

To understand this, take a look at the following:

x /. {x -> -2, x -> 2}


-2

Replacement rules can be given in lists to make things like x + y /. {x -> 1, y -> 2} work. When only a single list of rules is given (as in the example above), only one replacement is made for each variable. As the result shows, Mathematica replaces x with the first matching rule it finds. In order to have Mathematica make two (or more) replacements and output a list, the rules have to be given as lists of lists.

The nested structure also makes more sense as soon as you start using Solve and other functions with more than one variable.

Solve[{x + y == 6, x^2 == y}, {x, y}]


{{x -> -3, y -> 9}, {x -> 2, y -> 4}}

You can still apply this list of rules to expressions with either x or y or both. If you only want a certain solution you can acces the element you want either before or after replacement, using functions like First, Last or Part (which is usually written in its postfix form [[...]]):

sol2d = Solve[{x + y == 6, x^2 == y}, {x, y}];
First[x - y /. sol2d]
x - y /. First[sol2d]
Last[x - y /. sol2d]
x - y /. sol2d[[2]]
`

-12

-12

-2

-2

-
This seems more like a guide than a "pitfalls" post. I encourage you to consider posting this under one of the questions that specifically deals with this issue instead, e.g. (3175), (6669), (9035). –  Mr.Wizard Jan 30 '13 at 6:39
The OP asked for things that tend to confuse new users and this certainly confused me. But I totally see your point. (except for the fact that the post about the documentation above e.g. seems more like a guide, too) maybe we can tweak my answer to make it better meet the purpose of this wiki. –  einbandi Jan 30 '13 at 9:48
I see your point after a second read, so +1. Tweaking is fine with me. I commented above partly because you aren't going to get "reputation" for answers in this community-wiki thread as you would if this answer were elsewhere, if that matters to you. –  Mr.Wizard Jan 30 '13 at 9:53