my Mathematica cheat sheet

collected, maintained by Nasser M. Abbasi

This is my Mathematica cheat sheet. I keep in it useful things I learn about Mathematica, and things I see on the net. If something here is from the net, I try to make sure I put a reference or credit to where I saw it, else it will be something I wrote myself, so all blames to me.

last updated March 3, 2013

Current
Mathematica notebook used to generate this FAQ is here

Table to content

1 How to use Mathematica for signal processing?

2 How to read Mathematica own source code?

Say you want to read source code of LaplaceTransform. First load it

then do

The above will print top level code of the above function.

3 How do pure functions work?

I made this simple diagram to help me understand pure functions.

4 Mathematica directories after installation. Where things are?

I made this diagram to show the installation tree structure to help me figure where things are. Here is an HTML version of the diagram (might be too small to see)

5 How to write a package?

6 How to use context and packages?

6.1 How to find what contexts are loaded?

6.2 How to find what packages are loaded?

to see what contexts are there

to see what packages are loaded

6.3 How to find what packages in one specific context are loaded?

6.4 How to find what contexts are loaded?

6.5 How to load an m file or a package?

Append to the Path the folder name where the package is located in. In this example, assume there is a package control.m located in folder C:\data, then type

6.6 How to find names of functions inside a package ?

must use the ‘*’ above.

6.7 How to load everything from a package?

use Needs

6.8 How to find in which package a function is?

use Context

6.9 How to look at all contexts that belong to a package?

type Contexts[“packageName*”]

6.10 How to remove packages?

todo

7 How to find partial fraction expansion?

8 some keyboard shortcuts

to insert i type esc ii esc.
to enter π type esc p esc
to enter e type esc ee esc
ctrl-6 wil make exponent
ctrl^ will make superscript

9 How to trace a function

10 How to remove the Big O notation at the end of Series expansion?

11 How to plot circle?

12 How to Solve implicit differentiation equations?

Written Feb 20, 2004
Suppose you are give , x=cosh(t), y=cos(s) and asked to find dz/ds

Here, z depends on ‘s’ via x. So z implicitly depends on s.

To find dz/ds in mma, this is the code

another example: Another example, U=x^2 y^3 z, X=sin(s+t), Y=cos(s+t), Z=exp(s t)

Find du/ds and du/dt

13 How to draw the roots on complex equation?

14 On DSolveIntegrals package

Mathematica can handle partial differential equations via the DSolveIntegrals package. These arise in chemical contexts in the 1D wave equation, 3D wave equation, 3D diffusion equation, Time-dependent and Time independent Schrödinger equation.
Hermite showed that the quintic equation could be solved by elliptic functions

15 How to simplify with conditions? (using Assume)

For example, to integrate this below, for n positive integer do

16 How to do replacement? how to use Patterns?

16.1 smart replacement everywhere?

17 How to plot real and imaginary part of a function?

18 How to plot complex numbers?

18.1 How to plot mapping of complex numbers?

This below shows both the ‘z’ domain (which is just the whole complex plane) and the ‘w’ domain, which is the mapping, on the same plot

19 How to save a plot as an EPS?

20 How to extract DSolve solutions?

20.1 one way

21 How to make Mathematica not evaluate its arguments?

22 How to combine more than plot?

23 comparing speed of functional and procedural

From the net

In[1]:=
Timing[For[sum = 0; n = 1,  n < 100001, n++, sum += n]]

Out[1]=
{1.2999999999999998*Second,  Null}

In[2]:=
Timing[Plus @@ Range[10000]]

Out[2]=
{0.009999999999999787*Second, 50005000}

24 How to use subscript variables for function definitions, and use zero as index?

use Notation package

25 How to extract the LHS and RHS of an equation?

By Nasser M. Abbasi, 4/18/2010

26 How to make animated GIF files from Mathematica manipulate?

I could not get Export[] to work on Manipulate, since Export wants list of images to make an animated GIF files. Hence the following is what I do, all on windows. You need the following 4 programs (all free)
1. camStudio to take an AVI movie of the manipulate as it runs
2. VirturalDupMod to take AVI and generate the PNG frames
3. Small
Mathematica code to eliminate files from the above result, as too many PNG files are generated
4. EazyGraphics converter to convert PNG to GIF
5. UNFreeze to convert the GIF files to animated gif.

So the following are the steps. (on windows)
1. Start
Mathematica, start CamStudio, run the Manipulate and record it using camStudio for few seconds, then stop recording and save the resulting AVI file. call it  file.AVI
2. open VirtualDupMod, do File->Open file, and open the above file. Then FILE->SaveImage Sequence, make sure it is set to PNG export, and put the export folder name. Make a new folder for the files so they do not get mixed with other stuff. then do OK to start. Close when done.
3. run the following Mathematica code to remove number of files

The above assumes you have the result of  VirtualDupMod in folder c:\png\ and the code will copy every other 256 file to a new folder called c:\png2. Make sure you SetDirectory[] to c:\png before starting. Adjust the value 256 above to anything else, it depends on how many frames you want to keep. Try to keep the overall animated gif size to less than 400k.
4. open EazyGraphics converter , in settings, set it to 24 bit, and choose GIF to export, and no resize is selected. Now navigate to the folder c:\png2 above, and select “add files”.  select all the files and click OK and START. Set the target folder to say c:\gif to that resulting files are in one folder separate from all others.
5. Now go to folder c:\gif, select all files, using windows build in RESIZE pictures, resize them to 200 by 200. This is only needs to be done if you are making Thumbnail GIF. Else, leave the size as is.
6. Open UnFREEz program, select all the gif files from above, drag them to the little open window, and click generate animated gif file. Type  a name for the animated gif file when asked.
7. To include the animated gif file in latex, I do (the scale below is 1 since I already resized the images in step above). Change as needed.

\documentclass[12pt]{article}
\usepackage{graphicx}
\usepackage{html}
\usepackage{geometry}

\begin{document}

\begin{htmlonly}
\begin{center}
\end{center}
\end{htmlonly}

8. run latex2html and the resulting HTML will have the animation in it.

refrence: http://www.wikihow.com/Convert-a-Video-Into-a-Gif-Animation

27 How to do convolution?

28 How to use Piecewise function?

29 How to make good label for plot?

Example from the net

30 How to do some matrix operations?

note 1: Position and Cases return result that can be used by Extract directly. But can’t be used by Part directly. So, try to use Position or Cases first for the problem.

30.1 How to extract first column in matrix

Using Part:

30.2 How to extract first 3 rows in the first column?

30.3 How to find some matrix rows based on some condition on value in say the first column?

now find rows which has elements in first column say less than 3.
Reference: http://stackoverflow.com/questions/7507092/how-to-extract-rows-from-matrix-based-on-value-in-first-entry
The solution using pattern below (WRech) is interesting since the same pattern can be used by Cases and Position.

a) (me)

b) (Simon)

c) (Asim)

d) (WReach)

e)  (WReach)

30.4 How to generate a diagonal matrix?

Random values on the diagonal

Ones on the diagonal

30.5 How to generate upper diagonal matrix?

one way, using SparseArray

Or using Table. But notice that in SparseArray, the ‘zeros’ are allready the default case, so using SparseArray is simpler.

30.6 How to find the trace of a matrix?

30.7 How to find product of elements on the Trace?

30.8 How to check if a Matrix is diagonal matrix?

By Jon MacLoone

By Paul Abbott

30.9 How to find locations of all zeros (or any other value) in a matrix?

one way

another way

30.10 How to find locations of elements subject to some test?

find all elements between 4 and 8

30.11 How to insert an element in specific position?

Use standard index positions, as in Matlab/Fortran etc..

30.12 How to insert a row into a matrix?

To insert this row in the second row in matrix ‘a’

or just use ‘2’, it will also work

30.13 How to insert a column into a matrix?

To insert this column in the second column position in matrix ‘a’

a)

b)

e)  by Leonid Shifrin

30.14 How to build a large matrix from blocks of smaller matrices?

Given

and I want to make matrix { {a,a},{a,a} }

but now the trick is to use ArrayFlatten (not Flatten)

So, rule of thumb to remember: use standard matrix building, i.e. {{a,a},{a etc...} but in the end, use ArrayFlatten.

30.15 How to apply a function to each element in a 2D matrix?

Given

and was want to apply the this function to it

Then use Map

31 How to find if an expression implies another?

32 How to display matrices in MatrixForm without having to use MatrixForm all the time?

32.1

32.2

Another otpion is to use TraditionalForm. Can change default form fromthe menu, so this way no need to change $PrePrint, to TraditionalForm or type 33 How to make 3D axes normal instead of boxed? 34 How to convert Ax=b to set of equations? Example, This below sets up the M x’’+k x = 0 system and solves for modal frequencies 35 How to use ListPlot on set of x,y data? one way is to use transpose 36 How to do autocorrelation in Matlab, it is >> v=[1,2,3] xcorr(v,v) ans = 3 8 14 8 3 37 How to make a spring? from the net: 38 How to work with directories and files? 38.1 How to list files in a directory? 39 Where is init.m and how to use it? Possible locations for init.m files include the following:$BaseDirectory/Kernel kernel initialization code for all users
$UserBaseDirectory/Kernel kernel initialization code for the currently logged-in user$BaseDirectory/FrontEnd front end initialization code for all users
$UserBaseDirectory/FrontEnd front end initialization code for the currently logged-in user I have my init.m in the following folder C:\Documents and Settings\All Users\Application Data\Mathematica\Kernel\init.m 40 How to make plot range become a slider? 41 On Mathematica accuracy and precision 41.1 From class notes: UC Davis, Dr Rocke: “Precision means the variability between estimates Accuracy means the amount of deviation between the estimate and the “true value” The condition number is the ratio of the output error to the input error . if the condition number is about 10k, then one loses about k digits of accuracy. The main sources of inaccuracy (= error) is truncation error and round-off error. 41.2 From the above dart diagram, then we can say this: a value is accurate if it is near the bull-eye. But if is away from the bull-eye, but it is always away from the bull-eye and in the same place, then it is precise. So something can be precise but not accurate. So precise has to do with repeated values. i.e. one can’t say a value is precise, but must talk about an experiment being precise, it is produced same result each time (or very close results each time). So, it is best of course to be both accurate and precise. So what does it mean to be accurate but not precise? using the above dart diagram, it means values generated from the experiment are always close to the pull eye, but not in the same locations. 41.3 By Andrzej Kozlowski, from Math newsgroup, January 28,2010 “The definition of precision in Mathematica is this. Suppose x is a number known up to an error of epsilon, that is it can be viewed as lying in the interval (x-epsilon/2,x+epsilon/2). Then its precision is -Log[10,epsilon/x]. Its accuracy is -Log[10,epsilon]. The two are related by the equation: Precision[x] - Accuracy[x] == RealExponent[x] The interpretation in terms of digits is only approximate. Both accuracy and precision can be negative - this depends on the scale of the number i.e. RealExponent. A number will have negative accuracy if its absolute error is large. It is easy to produce such numbers by cancellation With[{x = N[10^100, 50] - N[10^100, 50]}, Accuracy[x]] -50.301 On the other hand, since$MinPrecision

0

You won’t normally in Mathematica see numbers with negative Precision.
Precision is the main concept, Accuracy is only used because Precision
is singular at 0 (remember - its relative error).

It’s all perfectly documented so this tired scape goat is not available
this time.

Andrzej Kozlowski”

42 What are some guidelines when writing a Mathematica demonstration?

In math italicize single Roman letters that are variables or
functions  (example, x,y,f(x),t
2. Exception to above is capital letters for points like P and Q in
geometry.
3. Do not italicize Greek letters (example, alpha, gamma, beta, etc..), and units like sec or rad, or  punctuation like ( ).
4. Styling the control labels is optional.
5. Do not use strings with <> for such formatting. Use Row[{    }]
6. put () around units in plot labels. As (sec) or (hz)
7. do not italicize function names longer than one letter. So Style[“exp”,Italic] should just be “exp”
8. The t in delta(t) should be italic--but not the delta, Greek letter are not Italian letters is how I remember that.
9. Log should be log.
10. Is j^2= -1? Better say so in the caption for non EE.

http://demonstrations.wolfram.com/guidelines.html

Example: To put a label on a plot

11. The following note is a general one, from the net by John Fultz (sept 2011) about mixing modules and Manipulate, useful to remember:

Module variables should *never* appear inside Dynamics or Manipulates internal
to that Module.

To be clear with some examples (all using Dynamic, but they could equally well
use Manipulate, which is implemented using Dynamic)...

(* OK *) Dynamic[Module[{a}, a]]
(* OK *) Module[{a},
(* expression involving a*);
Dynamic[(* expression *not* involving a *)]

In fact, this rule is so straightforward and universal, there’s no reason that
we shouldn’t have some advisory syntax highlighting which points out the
badness...I intend to do this for a future release.

Sincerely,

John Fultz
jfu...@wolfram.com
User Interface Group
Wolfram Research, Inc. “

To typeset math for display on the demo use this type of coding

to add invisible space use  ESC is ESC

43 How to make a condition as a pattern to use for search

By Bob Hanlon from math group:

44 How to read Mathematica example data and where is it located?

on windows, V 8, example data is located in C:\Program Files\Wolfram Research\Mathematica\8.0\Documentation\English\System\ExampleData and it can be read like this

45 How to stop 3D plot from changing size of plot when using the mouse to rotate it?

use SphericalRegion→True

46 How to apply a filter on a data?

answer moved to my main HOWTO page

47 How to select elements from a list that satisfy specific condition

This question was posted on the net. Given b:=Table[{x,y},{x,1,6},{y,1,6}] select from it elements {x,y} which satsify x+y>9

48. How to select specific elements from a matrix, and replace those by some other value?

Given a matrix, say which has Indeterminate and we want to change all these entries in the matrix by zero.

another example, given a matrix of values, replace those values which as <0.5 by NULL

49 What are the AppearanceElements names that can be used for Manipulate and other items

It is hard to obtain a list of all the AppearanceElements as there is no one place that contains them. Here is a list of what I know about so far

 1 HideControlsButton 2 SnapshotButton 3 ResetButton 4 UpdateButton 5 ContentResizeArea 6 HideControlsButton 7 ManipulateMenu 8 SnapshotButton 9 BookmarksButton 10 InputField 11 StepLeftButton 12 PlayPauseButton 13 StepRightButton 14 FasterSlowerButtons 15 DirectionButton 16 InlineInputField

50 How to get points from plot once it is plotted

example 1

example 2

51 Notes on dynamics

Useful notes taken from Mathematica documentation. All of these below are from the Mathematica help.

1.    Dynamic is wrapped around the whole expression, so evaluation of the  Table command is delayed until the output is displayed in the notebook. Any time the value of  x is changed, the  Table command will be reevaluated.

2.    Remember that  Dynamic has the effect of delaying evaluation until the expression reaches the front end

3.    Because it has the attribute  HoldFirst,  Dynamic does not evaluate its first argument. This is fundamental to the workings of  Dynamic, but it can lead to a somewhat unexpected behavior

4.    Ordinary variables in Mathematica are owned by the kernel. Their values reside in the kernel, and when you ask Mathematica to display the value in the front end, a transaction is initiated with the kernel to retrieve the value.

5.    Variables declared with  DynamicModule, on the other hand, are owned by the front end. Their values reside in the front end, and when the front end needs a value, it can be retrieved locally with very little overhead.

6.    the most important is the fact that values of all  DynamicModule variables are saved in the file when the notebook is saved.

7.    By default, dynamic outputs triggered by changes in variable values are updated no faster than twenty times per second (this rate can be changed with the  SystemOption  “DynamicUpdateInterval”).

8.    Dynamic outputs are only updated when they are visible on screen.

9.    Remember to add synchorization->False to all dynamics, else will time out. When using Refresh also.

10.    Never make a refresh[] tracks on 2 of my own symbols (not control variables). Use tick, only. Causes major synchronization problems with I update 2 variables inside a refresh, and have the refresh tracks both. Only make one track local variable, such as ticks

11.    Ok, Found out that finishDynamic[] can causes annoying refresh on the UI whenever I move sliders. So removed it.

12.    Remember to use :> and not -> for TrackedSymbols

From John Fultz on math group:

“Module variables should *never* appear inside Dynamics or Manipulates internal
to that Module.

To be clear with some examples (all using Dynamic, but they could equally well
use Manipulate, which is implemented using Dynamic)...

(* OK *) Dynamic[Module[{a}, a]]
(* OK *) Module[{a},
(* expression involving a*);
Dynamic[(* expression *not* involving a *)]

By John Fultz on math group, jan 24/2012

“Generally, you should  construct controls so that they’re not inside Dynamics that will trigger while you’re interacting with those controls, since this can create instability”

By John Fultz on math group, feb 3/2012

“CDF files which you expect to deploy cannot rely on Shift+Enter evaluations to
prime the pump.  You need to make sure that all of the code dependencies are in
the dynamic evaluations somewhere.  Some possible ways of doing this, all of
which have been discussed at various points on MathGroup, include:

* Using the Initialization option of Dynamic, DynamicModule, or Manipulate
* Using the SaveDefinitions option of Manipulate
* Adding code to the NotebookDynamicExpression option of the notebook (if it’s
initialization code, then wrapped in Refresh[#,None]& to prevent it from
evaluating more than once per session).
* Not such a good idea for function definitions, but if you simply have code
that needs to run before Dynamic code runs, nesting a DynamicWrapper around it
might be appropriate, too.”

some useful posts and links on Dynamics
http://stackoverflow.com/questions/1179430/why-wont-this-work-dynamic-in-a-select

52 How to make a struct in Mathematica

See these link for more options:

http://stackoverflow.com/questions/1453006/struct-data-type-in-mathematica
http://stackoverflow.com/questions/7356691/question-on-setting-up-a-struct-in-mathematica-safely
http://stackoverflow.com/questions/8197788/using-a-struct-inside-manipulate-to-help-manage-control-variables-how-to-initia
http://mathematica.stackexchange.com/questions/990/struct-equivalent-in-mathematica

This is one of the major beefs I have with Mathematica. It does not have a struct as a build-in, and integrated basic data structure. This makes it hard to manage variables in a large program so that one can collected related variables into one item, and then pass this one iterm around functions instead of passing all the related variables one by one in a large argument list. Having only a List as the basic struct can be limited at times.

This lack of a struct in Mathematica can lead one to bad programming habits by using global variables to avoid having to pass large number of parameters each time.

One can argue that in functional programming, one is supposed to make small functions, each accepts a minimal number of arguments and hence the need for a struct is not needed. But I do not buy this argument. In hierachical programming, the top level function, before it divides work among a smaller number of functions, would require access to a large number of variables. Hence, at one point, a function, a top level on, would need access to a larger number of variables, than the helper functions.

It easy to make examples, where a function requires large number of arguments to do its work. How about a function that needs to process say a person information, and the person record contains 50 different variables? Before calling smaller helper functions, the main function needs access to all the person record. Hence, if we had a record data struct, this function will accept as input one parameter, the person record, and not 50 different parameters which make up the individual fields in the record.

Any way, currently there are very few choices to make a struct in Mathematica. Each has its limitations. One can to use an indexed object as an emulation. Like this (had its own problems, so not recommended)

53 How to apply a function using 2 arguments from a list?

Can use Apply or @@@ , like this

Or

54 simple examples to show how to use Sow and Reap

Sow and Reap can be confusing to use. I collect here simple examples showing how they are used. See help also for more examples

example 1

55 How to make comments use monospaced fonts?

Thanks to Alexey Popkov for this

56 How to do long division of 2 polynomials?

This came about when I was trying to convert 1/(1-x^2/2) to normal form, i.e. tell Mathematica to change the above to 1+x^2/2.
But doing Simplify[1/(1-x^2/2)] or Expand, does not work:

So the only solution I found is to use Series command, as follows

57 What are common patterns to use for function parameters?

use these in parameter “declaration” of functions to make more robust. From the help center

x_/;NumberQ[x]&&Positive[x]    will match only if x is positive number not complex, since Positive is False for complex)

Another way is like this, using virtual function:

butterd[fs_?(NumberQ[#]&&Positive[#]&)
or
x_Integer?Positive

This is nice, since I do not have to retype the parameter name again and again for each test as when using /;

centerGrid_?(Element[#,Booleans]&)    Match when centerGrid is BOOLEAN. (True or False)

Find out when to use this function definition:

testFunction[f_][x_,y_]:=(Print[f[x,y]];5);

vs

testFunction[f_,x_,y_]:=(Print[f[x,y]];5);

some symbols to use that might simplify things:

bool=(Element[#,Booleans]&)
numeric = (Element[#,Reals]&);
integer = (Element[#,Integers]&);

integerStrictPositive = (IntegerQ[#]&&#>0&);
integerPositive      = (IntegerQ[#]&&#>= 0&);

numericStrictPositive = (Element[#,Reals]&& #>0&);
numericPositive       = (Element[#,Reals]&&#>= 0&);
numericStrictNegative = Element[#,Reals]&&#<0&);
numericNegative       = (Element[#,Reals]&&#<=  0&);

Can also use | to say that the argument must have either Head. like this

WARNING: NumericQ will match a complex number, so better to use Element[#,Reals]

so, use Reals

but not Positive, as postive is not defined for complex

so, one can write

or

or

58 How to add rational polynomials?

59 How to use options in functions?

This below is also a useful post by David Park on the net on options usage in packages

---------------------------------------------------------------------------
“David Park”  wrote in message news:<ch97qo$ff1... Guillermo, If it was part of a notebook, I would write your package something like the following. BeginPackage[“Test1”] fexample1::”usage” = “fexample[x, opts] calculates (a + b) x where a and b are set by options.”; a::usage = “a is an option for fexample that sets its value.”; b::usage = “b is an option for fexample that sets its value.”; Begin[“Private”] Options[fexample1] = {a -> Global A, b -> Global B}; fexample1[x_, opts___Rule] := (a + b) x /. {opts} /. Options[fexample1] End[] EndPackage[] Then ?Test1* gives usage messges for a, b and fexample1 and fexample1[x] (A + B) x Notice that I moved the Options statement to the Private section and I used GlobalA and GlobalB to set the default values of a and b. Also you want to start the usage message with the function name and arguments to get automatic command completion when desired. David Park” --------------------------------------------------- 60 How to replace patterns in expressions Example 1 by Andrzej Kozlowski on math group, July 2010: Suppose in the expression 2/3 I + x/y I you wish to replace all fractions (that is 2/3 and x/y) by r and I by d. Without worrying about evaluation you can do this as follows: If you allow the expression to evaluate the patterns will no longer match. For example, with only one Unevaluated you will get Without any you will get: Example 2 question: I want to replace y for x everywhere except in Exp[x]. Answer by Bob Hanlon on the net: http://mathforum.org/kb/thread.jspa?messageID=7120881&tstart=0 61 How to find which folders are on the trusted path and which are not? Thanks to Mike for these commands, see http://stackoverflow.com/questions/8583521/why-do-i-get-security-warning-message-this-file-contains-potentially-unsafe-dyn Now to find if your current notebook is on the trusted path type and see if the output shows up in the trusted path of not. To add a folder to trusted path go to “Preferences > Advanced > Open Options Inspector”. Then under Global Preferences search for trusted 62 Difference between Block, With and Module In Mathematica, For is slower than the alternative iterator constructs. Try to avoid using For in innermost loops unless it would make for more complicated code. In this example simply changing from For to Do makes a substantial difference. This below from help. I need to add more basic examples showing the difference in use Block and Module have values, the last expression evaluated is their value, we can see this by making a Grid (or just printing)  5  5 But module leaked symbols have$ signs

 x1771  x Modules and Blocks both execute if they are in the path of code, without calling them 63 How to generate symbolic labels for plot from low level functions? use this pattern 64 How to generate table of content using HTML links to sections in a notebook? These are the steps I use to make TOC which is just HTML links to internal tags in the notebook, where these cell tags are sections. This way, when I exprt to HTML, I end up with TOC which is hyperlinks to internal locations within the web page. step 1: create the section as normal. As in right-click the mouse, and select INSERT new cell, and select Section. Now in the new cell, write the section title. 2. Copy, using the mouse the title of the Section you just wrote so that the title is in the buffer. Now go to Cell->Cell tags->Add/remove and in the little window, paste the title of the section there and click Add. 3. Now go to the top of the document itself, where the TOC is located, and also PASTE the name of the section there. It will be plain text now. 4. Now, using the mouse again, select the text you just pasted, and do right-click and select MAKE hyperlink. This will bring up a menu like this 5. Select the option Current notebook from above, and this will bring up a list of all cell tags below. Scroll down looking for the same title there and click on it. This will make the TOC entry HTML link. 6. Now do SAVE AS HTML, and the notebook will be saved as HTML and the TOC will be links to the sections 65 How to extract values in a list of the form {x->value} one way another 66 How to align something inside Framed environment? Use Item 67 How to align an individual row of a grid? use Item  row1,row1 row2 row3  row1,row1 row2 row3 68 How to print a numerical value not in scientific notation? Use NumberForm 69 How to clear the notebook cache from any old symbols? Sometimes I get the case that the notebook retain old definitions and symbols even after I deleted them from the notebook. This happened when I was using a Demonstration stylesheet and had an separate initilization cell, and had added SaveDefinitions->True in the Manipulate cell. To make sure the notebook clears any old symbols, enter this command in the notebook once In addition, I change the preferences like this: 70 Where to put my init.m? possible locations for init.m . On windows, can be in the kernel folder underBaseDirectory

Also  in the kernel folder under $UserBaseDirectory Also can be in FrontEnd folder under$BaseDirectory

Also can be in FrontEnd folder under $UserBaseDirectory Can also put it here: very confusing. Just need to pick on place, and use it. Better to put my init.m in my personal folder, and just read it manually when starting Mathematica, like this 71 What is the difference between RotationMatrix and RotationTransform? 72. How to rotate a vector around a point other than origin? 73. Where to find examples using Mathematica to solve basic engineering problems I have few notes here 74 How to change the head of a list? A list has a Head at its zero index position By changing the head we use Apply. For example, to add the numbers of the above lst, we need to change the Head from List to Plus. There is a command in Mathematica to change the Head, called Apply We could have used the zero index trick, but it is better to use Apply: If we have a list of lists, like this and we want to change the head of each list in it, for example, we want the product of each list shown, then we need to change the head of each list to Times. To do that, the follwing short but might be strange looking command Another way to do the above is to Map the Apply function or, little shorter version of the above: find out about this option Method->{Automatic,”SymbolicProcessing” -> 0} 75 How to display polynomial from higher order to lower order? Mathematica default display of polynomial is reverse the traditional form: use Traditional Form with ParameterVariables to make it appear as in text books 76 How to understand symbol shadwing? 77 How to do OO in Mathematica? I wrote this small note here 78 How to sort a list of numbers? Sort[] sort numbers from small to large by default. By supplying a function, one can change this as needed 79 How to copy and paste code to text forum such as Mathematica Stackexchange or email messages? Follow these steps as an example 80 How to make automatic subscripted matrix notation? 81 How to find all Names in a build-in function context and any options they have? To find say all names in NDSolve and options used by that name if any do (this example is for NDSolve) # Option Options to this option 1 NDSolveAdams  MaxDifferenceOrder→12 VariableStepCoefficients→Automatic 2 NDSolveBaderSequenceFunction {} 3 NDSolveBDF  ImplicitSolver→NDSolveNewton MaxDifferenceOrder→5 VariableStepCoefficients→Automatic 4 NDSolveBootstrapDenseOutput {} 5 NDSolveBulirschSequenceFunction {} 6 NDSolveChasing  Method→Automatic ExtraPrecision→0 ChasingType→LinearChasing 7 NDSolveChebyshevCoefficients {} 8 NDSolveCheckMethodProperty {} 9 NDSolveComposition  Coefficients→Automatic DifferenceOrder→Automatic Method→None 10 NDSolveCompositionCoefficients {} 11 NDSolveConsistentCoefficientsQ {} 12 NDSolveCreateMethodData {} 13 NDSolveCreateWorkspace {} 14 NDSolveCreateWorkspaceList {} 15 NDSolveCubicHermite {} 16 NDSolveDCayleyInverse {} 17 NDSolveDDEFunction {} 18 NDSolveDelayDESteps  Method→Automatic DerivativeEvaluation→Interpolation 19 NDSolveDExpInverse {} 20 NDSolveDExpInverseCoefficients {} 21 NDSolveDiscontinuity {} 22 NDSolveDiscontinuityHandler  Discontinuities→Automatic Method→Automatic 23 NDSolveDoubleStep  LocalExtrapolation→True Method→None StepSizeSafetyFactors→Automatic StiffnessTest→Automatic 24 NDSolveEmbeddedExplicitRungeKuttaCoefficients {} 25 NDSolveEstimateStartingStep {} 26 NDSolveEvent  CheckDerivative→Automatic Direction→All EventCondition→True EventLocationMethod→Automatic WorkingVariables→False 27 NDSolveEventData {} 28 NDSolveEventLocator  Direction→All Event→None EventAction:→StopIntegration EventCondition→True EventLocationMethod→Automatic IncludeDerivatives→Automatic CheckDerivatives→False Method→Automatic 29 NDSolveEventOrderBackward {} 30 NDSolveEventOrderForward {} 31 NDSolveExplicitEuler {} 32 NDSolveExplicitMidpoint {} 33 NDSolveExplicitModifiedMidpoint {} 34 NDSolveExplicitRungeKutta  Coefficients→EmbeddedExplicitRungeKuttaCoefficients DifferenceOrder→Automatic EmbeddedDifferenceOrder→Automatic StepSizeControlParameters→Automatic StepSizeSafetyFactors→Automatic StiffnessTest→Automatic 35 NDSolveExtrapolation  ExtrapolationSequence→Automatic MaxDifferenceOrder→Automatic Method→ExplicitModifiedMidpoint MinDifferenceOrder→Automatic OrderSafetyFactors→Automatic StartingDifferenceOrder→Automatic StepSizeRatioBounds→Automatic StepSizeSafetyFactors→Automatic StiffnessTest→Automatic 36 NDSolveFiniteDifferenceDerivative  DifferenceOrder→4 PeriodicInterpolation→False 37 NDSolveFiniteDifferenceDerivativeFunction {} 38 NDSolveFiniteElement  BoundaryMethod→Automatic BoundaryTolerance→Automatic ElementOrder→Automatic IntegrationOrder→Automatic LinearSolveMethod→Automatic MeshOptions→Automatic 39 NDSolveFixedPoint {} 40 NDSolveFixedStep  Method→None StepSize→Automatic 41 NDSolveGetDefaultDifferenceOrder {} 42 NDSolveGetMethodOptionValues {} 43 NDSolveGMRES  Preconditioner→Automatic OrthogonalizationType→ModifiedGramSchmidt MaxKrylovSubspaceDimension→Automatic MaxKrylovRestarts→Automatic 44 NDSolveHairerOstermannSequenceFunction {} 45 NDSolveHarmonicSequenceFunction {} 46 NDSolveIDA  MaxDifferenceOrder→5 ImplicitSolver→Newton 47 NDSolveImplicitRungeKutta  Coefficients→ImplicitRungeKuttaGaussCoefficients DifferenceOrder→Automatic ImplicitSolver→Newton StepSizeControlParameters→Automatic StepSizeSafetyFactors→Automatic 48 NDSolveImplicitRungeKuttaAdjointCoefficients {} 49 NDSolveImplicitRungeKuttaCoefficients  Solve→Row 50 NDSolveImplicitRungeKuttaGaussCoefficients {} 51 NDSolveImplicitRungeKuttaLobattoIIIACoefficients {} 52 NDSolveImplicitRungeKuttaLobattoIIIBCoefficients {} 53 NDSolveImplicitRungeKuttaLobattoIIICCoefficients {} 54 NDSolveImplicitRungeKuttaRadauIACoefficients {} 55 NDSolveImplicitRungeKuttaRadauIIACoefficients {} 56 NDSolveImpulse  FromDiracDelta→False 57 NDSolveInitialHistory {} 58 NDSolveInitializeMethod {} 59 NDSolveInitializeSubmethod {} 60 NDSolveInitializeSubmethods {} 61 NDSolveIntraStepEvaluationData {} 62 NDSolveInvokeMethod {} 63 NDSolveIterate {} 64 NDSolveJump  SlidingMode→Automatic StepRejectionParameters→Automatic 65 NDSolveKrylovIteration  BasisSize→Automatic MaxIterations→Automatic 66 NDSolveLinearlyImplicitEuler  LinearSolveMethod→Automatic StabilityCheck→True 67 NDSolveLinearlyImplicitMidpoint  LinearSolveMethod→Automatic StabilityCheck→True 68 NDSolveLinearlyImplicitModifiedMidpoint  LinearSolveMethod→Automatic StabilityCheck→True 69 NDSolveLinearStabilityBoundary {} 70 NDSolveLocalInterpolation {} 71 NDSolveLocallyExact  SimplificationFunction→None 72 NDSolveLocalSeries {} 73 NDSolveLSODA  LinearSolveMethod→Automatic MaxDifferenceOrder→12 74 NDSolveMassMatrix  Method→Automatic 75 NDSolveMethodData {} 76 NDSolveMethodOfLines  DifferentiateBoundaryConditions→True DiscretizedMonitorVariables→False ExpandEquationsSymbolically→False Method→Automatic SpatialDiscretization→Automatic TemporalVariable→Automatic 77 NDSolveMethodSymbol {} 78 NDSolveNewton  LinearSolveMethod→Automatic 79 NDSolveNonstiffTest  MaxRepetitions→{2,∞} 80 NDSolveNonstiffTestData {} 81 NDSolveNumericalFunctionToEquations {} 82 NDSolveOptimalRoundingSequenceFunction {} 83 NDSolveOrthogonalChebyshevCoefficients {} 84 NDSolveOrthogonalProjection  Dimensions→{} MaxIterations→Automatic Method→StiffnessSwitching 85 NDSolveProcessEquations  AccuracyGoal→Automatic Compiled→Automatic DependentVariables→Automatic EvaluationMonitor→None InterpolationOrder→Automatic MaxSteps→10000 MaxStepSize→Automatic Method→Automatic NormFunction→Automatic PrecisionGoal→Automatic SolveDelayed→Automatic StartingStepSize→Automatic StepMonitor→None WorkingPrecision→MachinePrecision 86 NDSolveProcessSolutions {} 87 NDSolveProjection  Invariants→None LinearSolveMethod→Cholesky MaxIterations→Automatic Method→StiffnessSwitching 88 NDSolveReinitialize  AccuracyGoal→Automatic EvaluationMonitor→None InterpolationOrder→Automatic MaxSteps→10000 MaxStepSize→Automatic NormFunction→Automatic PrecisionGoal→Automatic StartingStepSize→Automatic StepMonitor→None 89 NDSolveReinitializeVector  AccuracyGoal→Automatic EvaluationMonitor→None InterpolationOrder→Automatic MaxSteps→10000 MaxStepSize→Automatic NormFunction→Automatic PrecisionGoal→Automatic StartingStepSize→Automatic StepMonitor→None 90 NDSolveRombergSequenceFunction {} 91 NDSolveSamePrecisionQ {} 92 NDSolveScaledVectorNorm {} 93 NDSolveSelf {} 94 NDSolveShooting  ImplicitSolver→Automatic MaxIterations→Automatic Method→Automatic StartingInitialConditions→Automatic 95 NDSolveSlidingModeFunction {} 96 NDSolveSpectralRadius  MaxIterations→50 SampleFrequency→Automatic 97 NDSolveSpectralRadiusOptionValues {} 98 NDSolveSplitting  Coefficients→Automatic DifferenceOrder→Automatic Equations→{} Method→None 99 NDSolveStabilizedRungeKutta  Coefficients→OrthogonalChebyshevCoefficients DifferenceOrder→Automatic MaxStages→Automatic SpectralRadius→Automatic StepSizeControlParameters→Automatic StepSizeSafetyFactors→Automatic 100 NDSolveStateData {} 101 NDSolveStepSizeControlData {} 102 NDSolveStiffnessSwitching  NonstiffTest→Automatic Method→{Automatic,Automatic} 103 NDSolveStiffnessTest  MaxRepetitions→{3,5} 104 NDSolveStiffnessTestData {} 105 NDSolveStreamline  Mesh→None Method→Automatic SinkTest→5 106 NDSolveSubspaceIteration  BasisSize→Automatic MaxIterations→Automatic 107 NDSolveSymmetricCompositionCoefficients {} 108 NDSolveSymmetricCompositionSymmetricMethodCoefficients {} 109 NDSolveSymplecticPartitionedRungeKutta  Coefficients→SymplecticPartitionedRungeKuttaCoefficients DifferenceOrder→Automatic PositionVariables→{} 110 NDSolveSymplecticPartitionedRungeKuttaCoefficients {} 111 NDSolveTestImplicitSolver {} 112 NDSolveToSymbol {} 113 NDSolveValidNumericalFunctionQ {} 114 NDSolveValidScaledVectorNormQ {} 115 NDSolveValidStateDataQ {} 116 NDSolveVODE {} 117 NDSolveWhen {} 118 NDSolve$EventSolution {}
119 {NDSolveImplicitRungeKuttaGaussCoefficients,NDSolveImplicitRungeKuttaLobattoIIIACoefficients,NDSolveImplicitRungeKuttaLobattoIIIBCoefficients,NDSolveImplicitRungeKuttaLobattoIIICCoefficients,NDSolveImplicitRungeKuttaRadauIACoefficients,NDSolveImplicitRungeKuttaRadauIIACoefficients} {}
120 4 {}

And for say FindMinimum

# Option Options to this option
 Method→PolakRibiere RestartIterations→∞
2 FindMinimumConstrainedMinimization {}
3 FindMinimumFMsymbol {}
4 FindMinimumInitializeMethod {}
5 FindMinimumInteriorPoint
 CropLambda→True CropMatrix→False AdaptivePenalty→False CompareLastMerit→False Theta→1 SplitFreeVariables→False AugmentedMerit→True LineSearch→BackTracking BarrierUpdate→EveryIteration StartingIteration→1 FeasibilityRestoration→True Scaling→True
6 FindMinimumLevenbergMarquardt
 EvaluationMonitor→Automatic Jacobian→Automatic Residual→Automatic StepControl→TrustRegion
7 FindMinimumNewton
 Hessian→Automatic StepControl→LineSearch
8 FindMinimum`QuasiNewton
 StepControl→LineSearch StepMemory→Automatic

82 How to make escape key to add {} around elements?

if one types in 1,2,3,4 is there is a way to select these and have {} automatically put around them to make a list {1,2,3,4} using escape key shortcut?
Yes. See http://stackoverflow.com/questions/13735497/wrap-text-selection-in-brackets-in-mathematica

Answer by Chris Degnen who wrote this

put it in the init file to load at start-up.

83 How to look for a substring and return first one found inside a larger string

I needed to do this when I was parsing some output. The problem is like this: given a string say “foo[] boo[] more goo[] more” and we want to look for pattern  like this “__[” in otherwords, a letter or more that end with “[“, but we need to find the first one. Hence in the above, we want to find “foo”. 2 ways to do this:

84 How to dynamically change the layout of Manipulate based on another control variable value?

85 What are most common commands?

Map or /@

Takes function and applies it to each element in a list

use when function needs to be called with arguments taken from more than one list, else use Map if argument come from one list

This is only when the lists are one level. For 2 levels we have to use MapThread. This shows the difference

Apply

86 common signature definitions

see tutorial/PatternsOverview
this below from  tutorial/PuttingConstraintsOnPatterns
http://stackoverflow.com/questions/8786389/what-is-the-recommended-way-to-check-that-a-list-is-a-list-of-numbers-in-argumen

From tutorial/FindingExpressionsThatMatchAPattern

idividual integer parameter

integer

integer strictly positive

integer strictly negative

integer zero or positive

integer zero or negative

integer in some range

Real

Real strictly positive

Real strictly negative

Real zero or positive

Real zero or negative

Real in some range

Reals Domain. Values in Reals Domain, (inclues floating points, Integers, Rationals)

general check

reals number strictly less than zero

Reals strictly positive

Reals strictly negative

Reals zero or positive

Real zero or negative

Real in some range

boolean

any numerical parameter

Those that have head meaning a number

complex number

general complex number

lists

general list  (list of any dimension, ragged lists, 1D vectors, 2D, any content)

1D list (i.e. vector)

1D vector of specific types

To check it is a vector, and also that the conent is of some specific type, combine the 2 checks done above. For example, to check it is 1D vector of numbers only

2D matix of numbers

2D matrix numeric but contains no complex numbers

2D matrix of strings

87 How to check for Head of expression

use MatchQ

Or for the above can do

88 How to make different Grids

using just Item

Using just Item but add frame also

89 How to generate animatd GIF files with different sizes from Manipulate

Assuming that variable “m” is the result of running your Manipulate, as in

I could not figure out how to export this as animated gif file. Doing this:

simply created a static image. However, exporting to AVI works as animation. So I eneded up saving it as AVI, then reading the frames and exporting them again as animated gif file as follows

Here, I just wanted black and white so just used first channel

Now we have animated gif file. Here it is

To resize the animated GIF

Reolace the Image command above by this, where here the image is scaled by 50%

Here is the small size animated gif file

90 Common Patterns

from help:

91 Compare Manipulate to DynamicModule

some examples here

92 How to replace the dependent variables and all its derivatives in a differential equation?

Suppose we have u''(t)+u'(t)+u(t)==3 cos(2 t) and we wanted to find a particula solution by replacing u in the differential equation by some guess for a particular solution. Then do