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?
3 How do pure functions work?
4 Mathematica directories after installation. Where things are?
5 How to write a package?
6 How to use 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?
70 Where to put my init.m?
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?
74 How to change the head of a list?
75 How to display polynomial from higher order to lower order?
76 How to understand symbol shadwing?
77 How to do OO in Mathematica?
78 How to sort a list of numbers?
79 How to copy and paste code to text forum such as Mathematica Stackexchange?
80 How to make automatic subscripted matrix notation?
81 How to find all Names in a buildin function context and any options they have?
82 How to make escape key to add {} around elements?
83 How to look for a substring and return first one found inside a larger string
84 How to dynamically change the layout of Manipulate based on another control variable value?
85 What are most common commands?
86 common signature definitions
87 How to check for Head of expression
88 How to make different Grids
89 How to generate animatd GIF files with different sizes from Manipulate
90 Common Patterns
91 Compare Manipulate to DynamicModule
92 How to replace the dependent variables and all its derivatives in a differential equation?
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
then do
The above will print top level code of the above function.
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)
I made this small note
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?
to insert i type esc ii esc.
to enter π type esc p esc
to enter e type esc ee esc
ctrl6 wil make exponent
ctrl^ will make superscript
10 How to remove the Big O notation at the end of Series expansion?
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?
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, Timedependent 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
see also my note on this.
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}
\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/ConvertaVideoIntoaGifAnimation
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/howtoextractrowsfrommatrixbasedonvalueinfirstentry
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)
c) by Leonid Shifrin http://stackoverflow.com/questions/7537401/howtoinsertacolumnintoamatrixthecorrectmathematicaway
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
in Matlab, it is
>> v=[1,2,3]
xcorr(v,v)
ans =
3 8 14 8 3
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 loggedin user
$BaseDirectory/FrontEnd front end initialization code for all users
$UserBaseDirectory/FrontEnd front end initialization code for the currently loggedin 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 roundoff error.
41.2
From the above dart diagram, then we can say this: a value is accurate if it is near the bulleye. But if is away from the bulleye, but it is always away from the bulleye 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 (xepsilon/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 italicbut 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
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 *)]
(* 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. “
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
my answer
Adriano Pascoletti answer
Bill Row answer
Murray Eisenberg answer
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
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]]”
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/whywontthisworkdynamicinaselect
52 How to make a struct in Mathematica
See these link for more options:
http://stackoverflow.com/questions/1453006/structdatatypeinmathematica
http://stackoverflow.com/questions/7356691/questiononsettingupastructinmathematicasafely
http://stackoverflow.com/questions/8197788/usingastructinsidemanipulatetohelpmanagecontrolvariableshowtoinitia
http://mathematica.stackexchange.com/questions/990/structequivalentinmathematica
This is one of the major beefs I have with Mathematica. It does not have a struct as a buildin, 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/(1x^2/2) to normal form, i.e. tell Mathematica to change the above to 1+x^2/2.
But doing Simplify[1/(1x^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
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 /;
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 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:
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/whydoigetsecuritywarningmessagethisfilecontainspotentiallyunsafedyn
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
x$1771 
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 rightclick 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 rightclick 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:
possible locations for init.m . On windows, can be in the kernel folder under $BaseDirectory
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?
see this article by David Wagner http://www.mathematicajournal.com/issue/v6i2/columns/wagner/wagner62.pdf
and http://mathematica.stackexchange.com/questions/3294/whyaresomefunctionnamesred
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 buildin 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  NDSolve`Adams 


2  NDSolve`BaderSequenceFunction  {}  
3  NDSolve`BDF 


4  NDSolve`BootstrapDenseOutput  {}  
5  NDSolve`BulirschSequenceFunction  {}  
6  NDSolve`Chasing 


7  NDSolve`ChebyshevCoefficients  {}  
8  NDSolve`CheckMethodProperty  {}  
9  NDSolve`Composition 


10  NDSolve`CompositionCoefficients  {}  
11  NDSolve`ConsistentCoefficientsQ  {}  
12  NDSolve`CreateMethodData  {}  
13  NDSolve`CreateWorkspace  {}  
14  NDSolve`CreateWorkspaceList  {}  
15  NDSolve`CubicHermite  {}  
16  NDSolve`DCayleyInverse  {}  
17  NDSolve`DDEFunction  {}  
18  NDSolve`DelayDESteps 


19  NDSolve`DExpInverse  {}  
20  NDSolve`DExpInverseCoefficients  {}  
21  NDSolve`Discontinuity  {}  
22  NDSolve`DiscontinuityHandler 


23  NDSolve`DoubleStep 


24  NDSolve`EmbeddedExplicitRungeKuttaCoefficients  {}  
25  NDSolve`EstimateStartingStep  {}  
26  NDSolve`Event 


27  NDSolve`EventData  {}  
28  NDSolve`EventLocator 


29  NDSolve`EventOrderBackward  {}  
30  NDSolve`EventOrderForward  {}  
31  NDSolve`ExplicitEuler  {}  
32  NDSolve`ExplicitMidpoint  {}  
33  NDSolve`ExplicitModifiedMidpoint  {}  
34  NDSolve`ExplicitRungeKutta 


35  NDSolve`Extrapolation 


36  NDSolve`FiniteDifferenceDerivative 


37  NDSolve`FiniteDifferenceDerivativeFunction  {}  
38  NDSolve`FiniteElement 


39  NDSolve`FixedPoint  {}  
40  NDSolve`FixedStep 


41  NDSolve`GetDefaultDifferenceOrder  {}  
42  NDSolve`GetMethodOptionValues  {}  
43  NDSolve`GMRES 


44  NDSolve`HairerOstermannSequenceFunction  {}  
45  NDSolve`HarmonicSequenceFunction  {}  
46  NDSolve`IDA 


47  NDSolve`ImplicitRungeKutta 


48  NDSolve`ImplicitRungeKuttaAdjointCoefficients  {}  
49  NDSolve`ImplicitRungeKuttaCoefficients 


50  NDSolve`ImplicitRungeKuttaGaussCoefficients  {}  
51  NDSolve`ImplicitRungeKuttaLobattoIIIACoefficients  {}  
52  NDSolve`ImplicitRungeKuttaLobattoIIIBCoefficients  {}  
53  NDSolve`ImplicitRungeKuttaLobattoIIICCoefficients  {}  
54  NDSolve`ImplicitRungeKuttaRadauIACoefficients  {}  
55  NDSolve`ImplicitRungeKuttaRadauIIACoefficients  {}  
56  NDSolve`Impulse 


57  NDSolve`InitialHistory  {}  
58  NDSolve`InitializeMethod  {}  
59  NDSolve`InitializeSubmethod  {}  
60  NDSolve`InitializeSubmethods  {}  
61  NDSolve`IntraStepEvaluationData  {}  
62  NDSolve`InvokeMethod  {}  
63  NDSolve`Iterate  {}  
64  NDSolve`Jump 


65  NDSolve`KrylovIteration 


66  NDSolve`LinearlyImplicitEuler 


67  NDSolve`LinearlyImplicitMidpoint 


68  NDSolve`LinearlyImplicitModifiedMidpoint 


69  NDSolve`LinearStabilityBoundary  {}  
70  NDSolve`LocalInterpolation  {}  
71  NDSolve`LocallyExact 


72  NDSolve`LocalSeries  {}  
73  NDSolve`LSODA 


74  NDSolve`MassMatrix 


75  NDSolve`MethodData  {}  
76  NDSolve`MethodOfLines 


77  NDSolve`MethodSymbol  {}  
78  NDSolve`Newton 


79  NDSolve`NonstiffTest 


80  NDSolve`NonstiffTestData  {}  
81  NDSolve`NumericalFunctionToEquations  {}  
82  NDSolve`OptimalRoundingSequenceFunction  {}  
83  NDSolve`OrthogonalChebyshevCoefficients  {}  
84  NDSolve`OrthogonalProjection 


85  NDSolve`ProcessEquations 


86  NDSolve`ProcessSolutions  {}  
87  NDSolve`Projection 


88  NDSolve`Reinitialize 


89  NDSolve`ReinitializeVector 


90  NDSolve`RombergSequenceFunction  {}  
91  NDSolve`SamePrecisionQ  {}  
92  NDSolve`ScaledVectorNorm  {}  
93  NDSolve`Self  {}  
94  NDSolve`Shooting 


95  NDSolve`SlidingModeFunction  {}  
96  NDSolve`SpectralRadius 


97  NDSolve`SpectralRadiusOptionValues  {}  
98  NDSolve`Splitting 


99  NDSolve`StabilizedRungeKutta 


100  NDSolve`StateData  {}  
101  NDSolve`StepSizeControlData  {}  
102  NDSolve`StiffnessSwitching 


103  NDSolve`StiffnessTest 


104  NDSolve`StiffnessTestData  {}  
105  NDSolve`Streamline 


106  NDSolve`SubspaceIteration 


107  NDSolve`SymmetricCompositionCoefficients  {}  
108  NDSolve`SymmetricCompositionSymmetricMethodCoefficients  {}  
109  NDSolve`SymplecticPartitionedRungeKutta 


110  NDSolve`SymplecticPartitionedRungeKuttaCoefficients  {}  
111  NDSolve`TestImplicitSolver  {}  
112  NDSolve`ToSymbol  {}  
113  NDSolve`ValidNumericalFunctionQ  {}  
114  NDSolve`ValidScaledVectorNormQ  {}  
115  NDSolve`ValidStateDataQ  {}  
116  NDSolve`VODE  {}  
117  NDSolve`When  {}  
118  NDSolve`$EventSolution  {}  
119  {NDSolve`ImplicitRungeKuttaGaussCoefficients,NDSolve`ImplicitRungeKuttaLobattoIIIACoefficients,NDSolve`ImplicitRungeKuttaLobattoIIIBCoefficients,NDSolve`ImplicitRungeKuttaLobattoIIICCoefficients,NDSolve`ImplicitRungeKuttaRadauIACoefficients,NDSolve`ImplicitRungeKuttaRadauIIACoefficients}  {}  
120  4  {} 
And for say FindMinimum
#  Option  Options to this option  
1  FindMinimum`ConjugateGradient 


2  FindMinimum`ConstrainedMinimization  {}  
3  FindMinimum`FMsymbol  {}  
4  FindMinimum`InitializeMethod  {}  
5  FindMinimum`InteriorPoint 


6  FindMinimum`LevenbergMarquardt 


7  FindMinimum`Newton 


8  FindMinimum`QuasiNewton 

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/wraptextselectioninbracketsinmathematica
Answer by Chris Degnen who wrote this
put it in the init file to load at startup.
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
Thread
use when function needs to be called with arguments taken from more than one list, else use Map if argument come from one list
MapThread
In this case gives the same answer as using Thread
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/whatistherecommendedwaytocheckthatalistisalistofnumbersinargumen
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 head (floating point number)
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
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