Hot answers tagged

185

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


110

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


99

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


93

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. To make this type of symbol naming possible use Mathematica letter-like form \[LetterSpace], or shorter Esc_Esc, which looks like usual underscore with smaller opacity. Avoid using ...


87

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


81

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


75

Preamble I had a talk devoted specifically to this topic, on Second Russian WTC in 2014. Unfortunately, it is in Russian. But I will try to summarize it here. Since this post is becoming too long, I decided to split it to several smaller ones, each dedicated to some particular set of methods / techniques. This one will contain a general / conceptual ...


73

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


68

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


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

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


59

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


59

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


56

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


53

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


51

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


41

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


41

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


40

Here are some advices from my experience. Explore new ideas with the Mathematica frontend. Don't hesitate to use sections and subsections in the frontend to structure your work and experiment various possibilities. When you have instructions that work, package them into functions, still in the frontend. It's practical to select all the useful ...


37

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


37

Managing the complexity, II: controlling complexity on the smaller scale There are a few things you can do to control and reduce the complexity of your code, even on the small scale - long before you move to packages and split code into several files. Effective use of the core data structures This is probably the first thing to mention. The most important ...


35

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


32

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


30

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


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=3), or ...


28

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


28

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


26

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


26

Managing the complexity III: using powerful abstractions In this section I will list a few techniques which allow one to write more modular code and better separate the concerns, by using certain powerful abstractions provided by or possible to have in the Mathematica. Higher-order functions These are functions which take other functions as arguments. In ...


23

All palette state (i.e., variables which affect the palette and should be remembered between sessions) should be vectored through the palette's TaggingRules option, and its initialization should be done in the palette's NotebookDynamicExpression option. That, plus context isolation of any kernel functions you need to define should solve all of the points ...



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