General Tips on Mathematica

Posted on Apr 25, 2013 in Computer Science

Things under legendu.net/outdated are outdated technologies that the author does not plan to update any more. Please look for better alternatives.

** Things on this page are fragmentary and immature notes/thoughts of the author. It is not meant to readers but rather for convenient reference of the author and future improvement. **

  1. Mathematica is very a powerful symbolic computing system. It is the best among all these symbol computing software that I've used (including Mathematica, Maxima and MATLAB). You can even do algebraic computing on pictures imported or graphs generated by Mathematica. Mathematica will just treat them as symbols.

  2. Mathematica use full names for the names of functions, which make it easy for us to find the functions you need. Many times you can guess out the name of a function you want to use.

  3. Mathematica has a complete set of built-in functions. Whenever you want function, you'd better check the help document of Mathematica first, because usually what you want is already there. You do not want to waste time in redoing what has already been done. By the way, never fail afraid to using the help document of Mathematica. It is very easy to find what you want in the help document. As I said before, usually you can dope out the name of the built-in functions you want. I have to say that the help document of Mathematica is the best among all programming software that I've ever used, but unfortunately the help document of R (which is another programming language I like very much) is the worst among all these programming software that I have ever used.

Work Easy

  1. One thing I like very much about Mathematica is that there are some alternative ways (given next to the function in the help document if exists) to pass arguments to functions. For example, instead of writing f[expr], you can use expr//f; instead of writing Map[f,expr], you can use f/@expr; instead of writing f[expr1,expr2], you can use expr1$\sim$f$\sim$expr2. These alternative ways can make things convenient in many situations. Because whenever you use a compound function, people usually think from the function most inside while you have to write from the function most outside in tradition way. With the help of // and $\sim$, you can write down a compound function easily without switching the cursor back to the beginning of our code.

  2. These alternative symbols for functions have a higher computing priority than //, e.g. f/@expr//Length is equivalent to

    Length[Map[f,expr]]
    

Configuration

  1. You can use function Directory to get the current working directory of Mathematica. To change the working directory, you can use function SetDirectory. To add a new path to the search path of Mathematica, you can modify variable Path.

Rules

  1. Since all variables you defined in a Mathematica session (not variables that you defined in function Module or Block and so on) are global variables, you can use them any where including user-defined functions. It can easily screw up your program if there are too many global variables in Mathematica workspace, so you're not encouraged to use global variables. You can always use function Clear to clear values and definitions for symbols. If you also want to properties associated (e.g. attributes and defaults) with the symbols, you can use function ClearAll. However, function Clear and ClearAll won't remove these symbols defined from the Mathematica workspace, i.e. Mathematica still recognized them even if there are no value or definitions (or just nothing if function ClearAll was used) associated with them. If you want to completely remove a symbol from the Mathematica workspace so that Mathematica can no longer recognize the symbol, you can use function Remove. Notice that all these 3 functions accept wild cards in their arguments. Keep defining and removing symbols is not handy. You can avoid define symbols using rules. To be clearer, you can use rules to replace symbols with values or other expressions. For example, to calculate \(sin 5 + cos 5\), you can use command

    Sin[x] + Cos[x] /. x -> 5
    

    instead of using

    x = 5;
    Sin[x] + Cos[x]
    
  2. The results of many functions in Mathematica are rules, but many times you want numerical values instead. To change a rule to number(s), you can simply apply the rule to symbols associated with it. For example, if you have a rule x->2, y->3 named r, you can simply use command {x,y}/.r to extract numbers in these rules. If the symbols in a rule are the same, for example if you have a rule x->2, x->3 named r, then you can use command x/.#&/@r to extract numbers in the rule.

Input and Output

  1. By default, the output in Mathematica is in standard form. If the results are strings, then it's hard for us tell whether the result is as expected or not if you read the output in standard form. A way to check whether the output is as expected is to change the output to input form suing function InputForm.

  2. InputForm[expr] prints as a version of expr suitable for input to Mathematica.

  3. OutputForm[expr] prints as a two-dimensional representation of expr using only keyboard characters.

  4. TeXForm[expr] prints as a Tex version of expr. Also you can type in expressions in Mathematica using Tex format using ToExpression. For example, to type in \(\alpha\) in Mathematica using Tex format, you can use command ToExpression["$\alpha$",TeXForm].

  5. TraditionalForm[expr] prints as an approximation to the traditional mathematical notation for expr.

  6. StandardForm[expr] prints as the standard Mathematica two-dimensional representation of expr.

  7. Format[expr,form] gives a format for the specified form of output.

  8. Function ReadList can read data from a file into a list of specified patterns.

  9. Function Import and Export are very powerful. They support all kinds of data format. File extensions are important when you use these two functions. Different file extensions might get different result when you use these two functions.

    data_Om_2030 = Import["/path/to/rms_20_30_1.bin", "real64"];
    
  10. Splice["file"] splices Mathematica output into an external file. It takes text enclosed between <* and *> in the file, evaluates the text as Mathematica input, and replaces the text with the resulting Mathematica output. It's similar to Sweave in R.

  11. $$Alpha] gives the Greek symbol \(\alpha\), and others are similar.

  12. FileNameJoin[{"name1","name2",...}] joins the strings together into a file name suitable for your current operating system.

Characters

  1. While character _ can be used in function names in many programming languages, it's reserved in Mathematica. Special characters that can be used in function names in Mathematica include _, $, etc.

  2. You can use function Symbol to get the value of an object from it's string expression. Conversely, you can use function Hold to to change an object into an expression and then use function ToString to change it into a string.

  3. Unlike R, numbers in Mathematica cannot be use as strings directly, instead, you must use ToString to convert numbers to string.

Vector, Matrix, Array and List

  1. There's only one data structure in Mathematica, which is list. A vector in Mathematica is just a list of depth 1; a matrix in mathematica is a nested list of depth 2; a multi-dimensional array in Mathematica is a nested list with a depth greater than 2.

  2. A vector (a list nested once, which is also an 1-dim array) in Mathematica can be treated either as a column vector or a row vector, which to use depends on conventions. For example, if w and v are two vectors then w.v calculates the inner product of w and v. Sometimes, instead of calculating the inner product of the two vectors, you might you want to calculate the matrix production of the column vectors times the row vector. To achieve this, you can use Outer[Times, w, v].

  3. Similar to R, a vector (a list with depth 1) is different from a matrix in Mathematica. But unlike R, you can not perform transpose operation on a vector to get a matrix of one row. However, by putting the vector into {} you turn it into a matrix of one row. And by transposing the resulting matrix, you get a matrix of one column.

  4. To take out an element (or some elements) from a list (vector, matrix, multi-dimensional array or any list) in Mathematica, you use [[]] (or function Part[]), which is different from almost all other languages. For example, to take out an element (or some elements) of a vector, a matrix or a data frame in R, you use []; to take out an element from an 1-D array in C/C++ and Java you use [] and [][] for taking out an element from a 2-D array.

  5. Function Flatten[list] flattens out a nested list, i.e. it decreases the depth of a list. By contrary, function Partition can split a list into sub lists, which increase the depth of a list. So function Partition is useful to reshape a vector to a matrix or a multi-dimensional array. To change a vector x into a matrix (2-D array) of n columns, you can simply use Partition[x,n]; to change vector x into a 3-D array, you can use result=Partition[Partition[x,m],n]. The resulting 3-D array result is a list with \(n\times m\) matrices as its elements[^1]. Sometimes you might want to transpose each element of the resulting 3-D array result, e.g. if the data was exported from some 3-D array in R using default setting[^2]. To achieve this, you can use Map[Transpose,result] or use the alternative way Transpose/@result.

  6. You should use vector operations as much as possible because it's not only faster but also more convenient to write the code. Many functions in Mathematica support vector/list operations, however, some functions in Mathematica might not behave in the way you expect if you pass a list/vector to it. A more general and powerful way to carry out vector/list operation is to use function Map[^3]. An alternative way for command Map[f,expr] is f/@expr.

  7. Tuples[list,n] generates a list of all possible n-tuples of elements from list.

  8. Position[expr,pattern] (similar to function which in R)gives a list of the positions at which objects matching pattern appear in expr.

  9. DeleteDuplicates[list] deletes all duplicates from list.

  10. Riffle in Mathematica is similar to function paste in R.

  11. Function Join can join vectors, matrices, arrays or lists together in a specified way.

Graphics and Animation

  1. Mathematica is very powerful at plotting graphics and presenting animations. It can do almost everything that you can think about. Just give it a try if you come across a hard situation in other software.

Integral

  1. Mathematica的求导功能是无与伦比的,但是Mathematica的积分功能却不尽令人如意。 当然这其中也包括其他一些功能,比如说化简功能。 有时候人一眼就能看出的答案用Mathematica却不能得到很好的结果。 这是为什么呢?并不是Mathematica比较傻,而是Mathematica考虑的比常人多,尤其是非数学学着。 通常Mathematica会把变量的范围放大到复数范围内,而不是局限在实数范围内。 这就是Mathematica有时候会很慢而且给出的结果不尽令人如意的原因。 通常解决的方法有两种,一种是给参数限定条件,另外一种是人工化简分解问题, 给出Mathematica比较容易就能解决的问题。然后再把这些部分合起来从而得到结果。

Optimization

  1. Function Maximize and Minimize carries out exact global optimizations. And function NMaximize and NMinimize carries out global optimization numerically. There're also many other functions in Mathematica which do global or local optimizations.

Useful Functions

  1. 函数Series可以进行Taylor或者是洛朗级数展开,非常有用。而级数对于求数列的通项是非常Powerful的。

  2. 函数Apart可以将有理多项式分解开成方便积分的几个部分,这在进行一些复杂的有理多项式的积分中是相当有用的。

  3. FunctionInverse

Programming

  1. In Mathematica you use comma to separate different parts of a For loop, which is different from most other programming languages.

  2. You have to be aware that all open notebooks in Mathematica share the same workspace, which means that the running result in a notebooks affects the running results in other notebooks. This can be handy in many situations, because you don't want to put everything in a single notebook oftentimes. However, you have to be careful about this. Because if you forget to define some local variable in a Module while there exists a global variable with the same name, the module define won't gives us warning messages. This will probably lead us to wrong results that are hardly noticeable. To avoid this problem, you can either use function Clear[] to clear all global variables before you running modules you wrote, or you can quit the kernel first and then running these modules. A better way to solve this problem is to always make these variables used in a Module local.

  3. You should always be careful about the If function in mathematica. There're 3 branches in this function corresponding to True, False and Null respectively. In most programming languages, you only have two branches. If you only specify branches corresponding to True and False for If function, it doesn't do anything if it cannot decide whether given condition is True or False. This might result tricky bugs sometimes. So if the program does not behave like what you expect, you might want to check whether some If function in your code has a condition that doesn't yield a boolean value.

  4. A shoddy thing about programming with Mathematica is that the arguments of a Module are kind of like constants, which means that you cannot change them in your code. In many cases, you want to give some arguments of a function some default values, and you might want to change their values later. Unfortunately, this is not supported in Mathematica. To achieve this, you have to create new local variables in the Module, assign the values of the arguments to these variables, and then treat these variables as the arguments of the Module.

Parallel Computing

  1. Parallel computing in Mathematica is even more convenient than parallel computing in MATLAB, because Mathematica automate many things for you. However, as a side effect, parallel computing in MATLAB is not as efficient as parallel computing in MATLAB.

  2. For an expression which contains only built-in functions and contains loops essentially (e.g. code contains Table or Map), you can parallelize them simply by putting them into Parallelize. There's no need for you to launch kernels or to distribute definitions in Mathematica 8 or later. They will be taken care of automatically by Mathematica (8 or later).

  3. Many functions in mathematica have parallel versions, e.g. Map has a parallel version ParallelMap, Table has a parallel version ParallelTable, and Do has a parallel version ParallelDo. You can use these parallel versions functions directly with no extra work in Mathematica 8 or later.

  4. For user-defined functions, even if it contains loops (essentially) which are parallelizable, you cannot parallelize it by just putting it into Parallelize, instead, you must parallelize code which contains loops (essentially) in the function by yourself, e.g., you can parallel versions for functions that are parallelizable.

  5. If you have to run jobs each of which is not parallelizable, you can still benefit from parallel computing by submitting them parallel using ParallelSubmit and WaitAll. However, you have to distribute definitions of user-defined functions manually first (at least before Mathematica 8).

Compile

  1. Compile, tensor, array, must be explicit

Send Email

  1. You can use the built-in SendMail to send email in Mathematica. The following command gives a simple example[^4].

    SendMail[
        "From" -> "firedragon.du@gmail.com",
        "To" -> "dclong@iastate.edu",
        "Subject" -> "Sending Email from Mathematica",
        "Body" -> "Just have a try",
        "Server" -> "mailhub.iastate.edu"
    ]
    
  2. The options that SendMail can use include: "To", "Cc", "Bcc", "Subject", "Body", "Attachments", "From", "Server","EncryptionProtocol", "Fullname", "PortNumber", "ReplyTo", "ServerAuthentication", "UserName".

  3. You can insert object(s) in mathematica workspace into the email body directly when you use SendMail to send emails, which is very convenient if you want to send the running results of mathmatica via email.

不太清楚地方:

  1. 前面提到过Mathematica在进行操作时总是从复数范围出发, 从而在进行一些积分或者是化简操作时, 给出限定条件就显得特别重要,而这个方面我不是很清楚。

The first partition combine m elements into a sublist which act as a new element for the resulting list, and then the second partition go further to combine n sublists together to form a matrix of \(m\times n\) which acts the a new element of the final resulting list.

By default, a matrix in R is filled by columns and is stretched to a vector by columns, while when you use function Partition, the matrices which are elements of the final resulting list/3-D array are filled by row

Similar to function apply in R, but you cannot pass extra parameters to the function which is to be applied over the list.

I'm not very sure how to send Gmail in Mathematica. I've tried many different ways, but none of them worked.

  1. <> joins two strings together, StringJoin, + in python, Java, etc. A missing <> not necesarry cause error but of course give you wrong answer, so be careful!!!

  2. You can write program in plain text (and save it as .m file). You can import the functions in the file using Import[file_path]. This is the suggested way for you to manager your own Mathematica code.

  3. You can specify scope of notebook "Evaluation -> Notebook's Default Context" and then select one of the options.

  4. Be careful when you save your notebook as .m file. The stupid software comments out every line!!! You can just save it as plain text or copy and paste it into a .m file.

  5. The stupid Mathematica 9 screws up scopes. Even if you have run the definition of a function in a notebook that is set as global, it's not seen in other notebooks!!!

  6. check whether a plain text file can also be imported!!!!

    a. mathematics Mathematics MATHEMATICS

  7. just use ?FunName to get help of a function. If you are not sure whether a function is defined or not, this also helps.

  8. the result of ParallelTable is the same as Table except for side effect of computation.

  9. parallize[table[]]

  10. use "" for string instead of ‘’

  11. missing semicolon is a common mistake

  12. cannot use _ in variable names, cause error message: Set::write: Tag Times in 1 x_ is Protected. >>

  13. f[x_Real] := x^2; pass integer to it won't work!!!

  14. f[x_Real:3.] = x^2 default parameter

  15. nohup math -run "<<../mle_2_10.m" & do not quote
    in Mathematica you use <<"../mle_2_10.m", but here quote <<../mle_2_10.m instead of the file name.

  16. Get[file_path] << file_path Import[file_path]

  17. nohup matlab -nodesktop -nosplash file.m (don't put & as it cause matlab not to start)

  18. SetDirectory["/home/dclong/simulation"] Directory[] FileNames[]

  19. it is suggested that you use java camelCase style to name variables in Mathematica which can distinguish them from functions

  20. integer cannot be use in string concatenation directly, must use ToString to convert it to a String first.

  21. mle /. Rule -> (#2 &)

  22. Export[output, result, "Table"];

common mistakes

  1. forget {}, in Module

IO

  1. put and PutAppends

  2. >> and >>> similar to Linux bash > and >>