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 Feb 2, 2012

Table to content

1. How to use Mathematica for signal processing?
2.
How to read Mathematica own source code?
3 How do pure functions work?
4 Mathematica directories after installation. Where things are?
5 How to write a package?
6 How to us context and packages?
7 How to find partial fraction expansion?
8 some keyboard shortcuts
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?
13 How to draw the roots on complex equation?
14 On DSolveIntegrals package
15 How to simplify with conditions? (using Assume)
16 How to do replacement? how to use Patterns?
17 How to plot real and imaginary part of a function?
18 How to plot complex numbers?
19 How to save a plot as an EPS?
20 How to extract DSolve solutions?
21 How to make Mathematica not evaluate its arguments?
22 How to combine more than plot?
23 comparing speed of functional and procedural
24 How to use subscript variables for function definitions, and use zero as index?
25 How to extract the LHS and RHS of an equation?
26 How to make animated GIF files from Mathematica manipulate?
27 How to do convolution?
28 How to use Piecewise function?
29 How to make good label for plot?
30 How to do some matrix operations?
31 How to find if an expression implies another?
32 How to display matrices in MatrixForm without having to use MatrixForm all the time?
33 How to make 3D axes normal instead of boxed?
34 How to convert Ax=b to set of equations?
35 How to use ListPlot on set of x,y data?
36 How to do autocorrelation?
37 How to make a spring?
38 How to work with directories and files?
39 Where is init.m and how to use it?
40 How to make plot range become a slider?
41 On Mathematica accuracy and precision
42 What are some guidelines when writing a Mathematica demonstration?
43 How to make a condition as a pattern to use for search?
44 How to read Mathematica example data and where is it located?
45 How to stop 3D plot from changing size of plot when using the mouse to rotate it?
46 How to apply a filter on a data?
47 How to select elements from a list that satisfy specific condition
48. How to select specific elements from a matrix, and replace those by some other value?
49 What are the AppearanceElements names that can be used for Manipulate and other items
50 How to get points from plot once it is plotted
51 Notes on dynamics
52 How to make a struct in Mathematica
53 How to apply a function using 2 arguments from a list?
54 simple examples to show how to use Sow and Reap
55 How to make comments use monospaced fonts?
56 How to do long division of 2 polynomials?
57 What are common patterns to use for function parameters?
58 How to add rational polynomials?
59 How to use options in functions?
60 How to replace patterns in expressions
61 How to find which folders are on the trusted path and which are not?
62 Difference between Block, With and Module
63 How to generate symbolic labels for plot from low level functions?
64 How to generate table of content using HTML links to sections in a notebook?
65 How to extract values in a list of the form {x->value}
66 How to align something inside Framed environment?
67 How to align an individual row of a grid?
68 How to print a numerical value not in scientific notation?
69 How to clear the notebook cache from any old symbols?

1 How to use Mathematica for signal processing?

Here is a link to information about old Mathematica signal processing package.

2 How to read Mathematica own source code?

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

MMA_1.gif

then do

MMA_2.gif

MMA_3.gif

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

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)
MMA_5.gif

5 How to write a package?

I made this small note

6 How to us context and packages?

6.1 How to find what contexts are loaded?

MMA_6.gif

MMA_7.gif

6.2 How to find what packages are loaded?

to see what contexts are there

MMA_8.gif

MMA_9.gif

to see what packages are loaded

MMA_10.gif

MMA_11.gif

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

MMA_12.gif

MMA_13.gif

6.4 How to find what contexts are loaded?

MMA_14.gif

MMA_15.gif

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

MMA_16.gif

6.6 How to find names of functions inside a package ?

MMA_17.gif

MMA_18.gif

MMA_19.gif

MMA_20.gif

must use the ‘*’ above.

6.7 How to load everything from a package?

use Needs

MMA_21.gif

6.8 How to find in which package a function is?

use Context

MMA_22.gif

MMA_23.gif

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

type Contexts[“packageName*”]

MMA_24.gif

MMA_25.gif

MMA_26.gif

MMA_27.gif

6.10 How to remove packages?

todo

7 How to find partial fraction expansion?

MMA_28.gif

MMA_29.gif

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

MMA_30.gif

MMA_31.gif

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

MMA_32.gif

MMA_33.gif

11 How to plot circle?

MMA_34.gif

MMA_35.gif

12 How to Solve implicit differentiation equations?

Written Feb 20, 2004
Suppose you are give MMA_36.gif, 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

MMA_37.gif

MMA_38.gif

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

MMA_39.gif

MMA_40.gif

MMA_41.gif

13 How to draw the roots on complex equation?

MMA_42.gif

MMA_43.gif

MMA_44.gif

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

MMA_45.gif

MMA_46.gif

MMA_47.gif

MMA_48.gif

16 How to do replacement? how to use Patterns?

16.1 smart replacement everywhere?

MMA_49.gif

MMA_50.gif

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

MMA_51.gif

MMA_52.gif

18 How to plot complex numbers?

18.1 How to plot mapping of complex numbers?

MMA_53.gif

MMA_54.gif

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

MMA_55.gif

MMA_56.gif

19 How to save a plot as an EPS?

MMA_57.gif

MMA_58.gif

MMA_59.gif

MMA_60.gif

20 How to extract DSolve solutions?

20.1 one way

MMA_61.gif

MMA_62.gif

MMA_63.gif

MMA_64.gif

21 How to make Mathematica not evaluate its arguments?

MMA_65.gif

MMA_66.gif

MMA_67.gif

MMA_68.gif

22 How to combine more than plot?

MMA_69.gif

MMA_70.gif

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
see also my note on this.

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

By Nasser M. Abbasi, 4/18/2010

MMA_71.gif

MMA_72.gif

MMA_73.gif

MMA_74.gif

MMA_75.gif

MMA_76.gif

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

MMA_77.gif

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}
\htmladdnormallink{\includegraphics[scale=1]{final_animation}}{final_animation.gif}
\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?

MMA_78.gif

28 How to use Piecewise function?

MMA_79.gif

29 How to make good label for plot?

Example from the net

MMA_80.gif

Graphics:64Cycles in FIFO

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

MMA_82.gif

MMA_83.gif

Using Part:

MMA_84.gif

MMA_85.gif

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

MMA_86.gif

MMA_87.gif

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

MMA_88.gif

MMA_89.gif

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)

MMA_90.gif

MMA_91.gif

MMA_92.gif

MMA_93.gif

b) (Simon)

MMA_94.gif

MMA_95.gif

MMA_96.gif

MMA_97.gif

c) (Asim)

MMA_98.gif

MMA_99.gif

d) (WReach)

MMA_100.gif

MMA_101.gif

e)  (WReach)

MMA_102.gif

MMA_103.gif

MMA_104.gif

30.4 How to generate a diagonal matrix?

Random values on the diagonal

MMA_105.gif

MMA_106.gif

Ones on the diagonal

MMA_107.gif

MMA_108.gif

30.5 How to generate upper diagonal matrix?

one way, using SparseArray

MMA_109.gif

MMA_110.gif

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

MMA_111.gif

MMA_112.gif

30.6 How to find the trace of a matrix?

MMA_113.gif

MMA_114.gif

MMA_115.gif

MMA_116.gif

MMA_117.gif

MMA_118.gif

30.7 How to find product of elements on the Trace?

MMA_119.gif

MMA_120.gif

MMA_121.gif

MMA_122.gif

30.8 How to check if a Matrix is diagonal matrix?

By Jon MacLoone

MMA_123.gif

MMA_124.gif

MMA_125.gif

MMA_126.gif

MMA_127.gif

MMA_128.gif

MMA_129.gif

MMA_130.gif

MMA_131.gif

MMA_132.gif

By Paul Abbott

MMA_133.gif

MMA_134.gif

MMA_135.gif

MMA_136.gif

MMA_137.gif

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

MMA_138.gif

MMA_139.gif

one way

MMA_140.gif

MMA_141.gif

another way

MMA_142.gif

MMA_143.gif

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

find all elements between 4 and 8

MMA_144.gif

MMA_145.gif

MMA_146.gif

MMA_147.gif

MMA_148.gif

MMA_149.gif

30.11 How to insert an element in specific position?

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

MMA_150.gif

MMA_151.gif

MMA_152.gif

MMA_153.gif

30.12 How to insert a row into a matrix?

MMA_154.gif

MMA_155.gif

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

MMA_156.gif

MMA_157.gif

MMA_158.gif

or just use ‘2’, it will also work

MMA_159.gif

MMA_160.gif

30.13 How to insert a column into a matrix?

MMA_161.gif

MMA_162.gif

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

MMA_163.gif

a)

MMA_164.gif

MMA_165.gif

b)

MMA_166.gif

MMA_167.gif

c) by Leonid Shifrin http://stackoverflow.com/questions/7537401/how-to-insert-a-column-into-a-matrix-the-correct-mathematica-way

MMA_168.gif

MMA_169.gif

e)  by Leonid Shifrin

MMA_170.gif

MMA_171.gif

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

Given

MMA_172.gif

MMA_173.gif

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

MMA_174.gif

MMA_175.gif

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

MMA_176.gif

MMA_177.gif

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

MMA_178.gif

MMA_179.gif

and was want to apply the this function to it

MMA_180.gif

Then use Map

MMA_181.gif

MMA_182.gif

31 How to find if an expression implies another?

MMA_183.gif

MMA_184.gif

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

32.1

MMA_185.gif

MMA_186.gif

MMA_187.gif

MMA_188.gif

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

MMA_189.gif

MMA_190.gif

MMA_191.gif

MMA_192.gif

33 How to make 3D axes normal instead of boxed?

MMA_193.gif

MMA_194.gif

34 How to convert Ax=b to set of equations?

MMA_195.gif

MMA_196.gif

Example, This below sets up the M x’’+k x = 0 system and solves for modal frequencies

MMA_197.gif

MMA_198.gif

MMA_199.gif

MMA_200.gif

35 How to use ListPlot on set of x,y data?

one way is to use transpose

MMA_201.gif

MMA_202.gif

36 How to do autocorrelation

MMA_203.gif

MMA_204.gif

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:

MMA_205.gif

MMA_206.gif

38 How to work with directories and files?

38.1 How to list files in a directory?

MMA_207.gif

MMA_208.gif

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?

MMA_209.gif

MMA_210.gif

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”
MMA_211.gif

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

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.

see also
http://demonstrations.wolfram.com/guidelines.html
MMA_212.gif

MMA_213.gif

Example: To put a label on a plot
MMA_214.gif

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 *)]
(* BAD *) Module[{a}, Dynamic[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. “

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

By Bob Hanlon from math group:

MMA_215.gif

MMA_216.gif

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

MMA_217.gif

MMA_218.gif

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

use SphericalRegion→True

MMA_219.gif

46 How to apply a filter on a data?

Suppose we want to apply say an average filter on a list. Say we have a list of numbers, and we want to replace each value in the list by the average 3 values around each value (a smoothing filter).  Then we can use ListConvolve

MMA_220.gif

MMA_221.gif

This example below, the Laplacian in 2D is applied on a grid.

MMA_222.gif

MMA_223.gif

MMA_224.gif

MMA_225.gif

MMA_226.gif

MMA_227.gif

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
my answer

MMA_228.gif

MMA_229.gif

Adriano Pascoletti answer

MMA_230.gif

MMA_231.gif

Bill Row answer

MMA_232.gif

MMA_233.gif

Murray Eisenberg  answer

MMA_234.gif

MMA_235.gif

MMA_236.gif

MMA_237.gif

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.

MMA_238.gif

MMA_239.gif

MMA_240.gif

MMA_241.gif

MMA_242.gif

MMA_243.gif

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

MMA_244.gif

MMA_245.gif

MMA_246.gif

MMA_247.gif

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

MMA_248.gif

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

MMA_249.gif

MMA_250.gif

MMA_251.gif

example 2

MMA_252.gif

MMA_253.gif

MMA_254.gif

MMA_255.gif

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 *)]
(* BAD *) Module[{a}, Dynamic[a]]”

From 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”

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)

MMA_256.gif

MMA_257.gif

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

Can use Apply or @@@ , like this

MMA_258.gif

MMA_259.gif

Or

MMA_260.gif

MMA_261.gif

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

MMA_262.gif

MMA_263.gif

55 How to make comments use monospaced fonts?

Thanks to Alexey Popkov for this

MMA_264.gif

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:

MMA_265.gif

MMA_266.gif

MMA_267.gif

MMA_268.gif

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

MMA_269.gif

MMA_270.gif

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
MMA_271.gif
MMA_272.gif

Also I made these notes

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 /;

x/;Boole[x]     matches x when it is True or False only

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);

For Boolean, use

Clear[f];
f[x_/;Element[x,Booleans]]:=Print[“yes”];

(Element[#,Booleans]&) = (Element[#,Booleans]&);
numeric = (NumericQ[#]&&Im[#]==0&);

integer = (IntegerQ[#]&&Im[#]==0&);
ntegerStrictPositive = (IntegerQ[#]&&Im[#]==0&&Re[#]>0&);
integerPositive      = (IntegerQ[#]&&Im[#]==0&&Re[#]>= 0&);

numericStrictPositive = (NumericQ[#]&&Im[#]==0&& Re[#]>0&);
numericPositive       = (NumericQ[#]&&Im[#]==0&& Re[#]>= 0&);
numericStrictNegative = (NumericQ[#]&&Im[#]==0&& Re[#]<0&);
numericNegative       = (NumericQ[#]&&Im[#]==0&& Re[#]<=  0&);

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

MMA_273.gif

MMA_274.gif

MMA_275.gif

MMA_276.gif

MMA_277.gif

so, one can write

MMA_278.gif

MMA_279.gif

or

MMA_280.gif

MMA_281.gif

or

MMA_282.gif

MMA_283.gif

58 How to add rational polynomials?

MMA_284.gif

MMA_285.gif

59 How to use options in functions?

MMA_286.gif

MMA_287.gif

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 Global`A and
Global`B 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:

MMA_288.gif

MMA_289.gif


If you allow the expression to evaluate the patterns will no longer match. For example, with only one Unevaluated you will get

MMA_290.gif

MMA_291.gif

Without any you will get:

MMA_292.gif

MMA_293.gif

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

MMA_294.gif

MMA_295.gif

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

MMA_296.gif

MMA_297.gif

MMA_298.gif

MMA_299.gif

Now to find if your current notebook is on the trusted path type

MMA_300.gif

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

MMA_301.gif

MMA_302.gif

MMA_303.gif

MMA_304.gif

  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

MMA_305.gif

Block and Module have values, the last expression evaluated is their value, we can see this by making a Grid (or just printing)

MMA_306.gif

5

MMA_307.gif

5

But module leaked symbols have $ signs

MMA_308.gif

x$1771

MMA_309.gif

x

Modules and Blocks both execute if they are in the path of code, without calling them

MMA_310.gif

MMA_311.gif

MMA_312.gif

MMA_313.gif

63 How to generate symbolic labels for plot from low level functions?

use this pattern

MMA_314.gif

MMA_315.gif

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 MMA_316.gif
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}

MMA_317.gif

one way

MMA_318.gif

MMA_319.gif

another

MMA_320.gif

MMA_321.gif

66 How to align something inside Framed environment?

Use Item

MMA_322.gif

MMA_323.gif

67 How to align an individual row of a grid?

use Item

MMA_324.gif

row1,row1
row2
row3

MMA_325.gif

row1,row1
row2
row3

68 How to print a numerical value not in scientific notation?

Use NumberForm

MMA_326.gif

MMA_327.gif

MMA_328.gif

MMA_329.gif

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

MMA_330.gif

In addition, I change the preferences like this:
MMA_331.gif

Spikey Created with Wolfram Mathematica 8.0