Hot answers tagged

165

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


101

I'll just throw in a few random thoughts in no particular order, but this will be a rather high-level view on things. This is necessarily a subjective exposition, so treat it as such. Typical use cases In my opinion, Compile as an efficiency-boosting device is effective in two kinds of situations (and their mixes): The problem is solved most efficiently ...


93

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


82

Basic syntax issues Mathematica is case-sensitive. sin is not the same as Sin. Symbol names cannot contain underscore. _ is a reserved character used for pattern matching. 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 ...


78

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


74

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. Let's start with the follwing simple example: Solve[x^2 == 4, x] {{x -> -2}, {x -> 2}} You might find this output strange for two reasons. We'll have ...


70

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


66

The main change since that time seems to be that the modern way of using options is associated with OptionsPattern[] - OptionValue commands. A typical way of defining a function would be: Options[f] = { FirstOption -> 1, SecondOption ->2 } f[x_,y_,opts:OptionsPattern[]]:= Print[{x,y,OptionValue[FirstOption],OptionValue[SecondOption]}] ...


64

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


61

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


53

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


53

Assuming commands will have side effects when 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 ...


52

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


49

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


48

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


37

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


35

Here is a practical example from a StackOverflow question. I hope that it gives a good overview of the basic methods. Question What would be the best way to make a function out of the below code ? It would take a dataList as well as some graphical options (such as colors) as arguments and return a customized tabular representation as shown ...


35

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


32

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


29

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


27

Setting SetSystemOptions[ "CompileOptions" -> "CompileReportExternal"->True] will emit a message when parts of your function do not get compiled. After compilation, Needs["CompiledFunctionTools`"] followed by CompilePrint[cF] (with cF the function you have compiled will display some bytecode; looking for CopyTensor or MainEvaluate in that helps locate ...


27

Don't leave 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 such as massive memory usage, peculiar evaluation leaks, and broken ...


24

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


23

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


23

Basic proposal There are a number of options and their attractiveness will depend on the scenario for their use, therefore it is difficult to make any broad recommendations of best practice. I will say that generally it is not recommended to rely on global assignments as in your first example, because this method scales poorly and because it is easy to ...


23

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


22

Part of what you are asking is of course a matter of taste and habits, but here are my 2 cents: 1) if you want Mathematica to find your package files with a Needs or Get their context names must agree with the hierarchy of directories and filenames. I don't see any good reasons to diverge from that standard convention. For complex packages with many files ...


22

You can try Maxima. It is small, free and closest look alike to Mathematica and install easily in both Windows and Linux. But if you want to strictly impose "which produce equal or even better functionality" condition, I am afraid, I have to withdraw my answer. Honestly speaking, I think there would not be any answer at all. Big List You can find a big ...


22

Sage. It is a great project using a nice and clean programming language (Python). Many parts of its functionality comes from other free software. The usual stuff you are expecting (integration, ODEs, solving equations) is implemented using Maxima. For example for specialised group theory GAP is used.


21

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



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